syd 3.41.7

rock-solid application kernel
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
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
//
// Syd: rock-solid application kernel
// src/config.rs: Static configuration, edit & recompile!
//
// Copyright (c) 2023, 2024, 2025 Ali Polatel <alip@chesswob.org>
// Based in part upon HardenedBSD's sys/hardenedbsd/hbsd_pax_segvguard.c which is:
//   Copyright (c) 2006 Elad Efrat <elad@NetBSD.org>
//   Copyright (c) 2013-2017, by Oliver Pinter <oliver.pinter@hardenedbsd.org>
//   Copyright (c) 2014, by Shawn Webb <shawn.webb@hardenedbsd.org>
//   Copyright (c) 2014, by Danilo Egea Gondolfo <danilo at FreeBSD.org>
//   All rights reserved.
//   SPDX-License-Identifier: BSD-3-Clause
// Based in part upon gVisor's kvm_const*.go which is:
//   Copyright 2018 The gVisor Authors.
//   SPDX-License-Identifier: Apache-2.0
// Based in part upon kvm-ioctls' kvm-ioctls.rs which is:
//   Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//   SPDX-License-Identifier: Apache-2.0 OR MIT
//
// SPDX-License-Identifier: GPL-3.0

use std::{
    os::{
        fd::{AsRawFd, BorrowedFd, RawFd},
        unix::ffi::OsStrExt,
    },
    sync::{LazyLock, OnceLock},
    time::Duration,
};

use btoi::btoi;
use nix::{
    errno::Errno,
    fcntl::OFlag,
    sys::{personality::Persona, stat::Mode},
    unistd::{close, sysconf, Gid, SysconfVar, Uid},
};

use crate::{
    compat::{STATX_MNT_ID, STATX_MNT_ID_UNIQUE, STATX_MODE},
    confine::check_cross_memory_attach,
    fs::{is_dev_null, FileMap, FileMapEntry, FileType},
    fstatx, info,
    path::{XPath, XPathBuf},
    proc::proc_mmap_min_addr,
    rng::{duprand, randint},
    sandbox::Version,
    sysinfo::RandTimer,
};

// Convenience type to list {io,pr}ctls with their names.
type KeyValue<'a> = (&'a str, u64);

/// Path to /etc.
pub const PATH_ETC: &[u8] = b"/etc";

/// The default shell to execute.
/// Change this if your system doesn't have /bin/sh,
/// or set the environment variable SYD_SHELL.
pub const SYD_SH: &str = "/bin/sh";

/// The contents of the file `esyd.sh`.
pub const ESYD_SH: &str = include_str!("esyd.sh");

/// The contents of the file `syd.el`.
pub const SYD_EL: &str = include_str!("syd.el");

/// The environment variable to override the host Linux kernel version.
pub const ENV_ASSUME_KERNEL: &str = "SYD_ASSUME_KERNEL";
/// The environment variable to read the default shell from.
pub const ENV_SH: &str = "SYD_SHELL";
/// The environment variable to read the log level from.
pub const ENV_LOG: &str = "SYD_LOG";
/// The environment variable to set to log to a different fd than standard error.
pub const ENV_LOG_FD: &str = "SYD_LOG_FD";
/// The environment variable to read the syslog(2) capacity from.
pub const ENV_LOG_BUF_LEN: &str = "SYD_LOG_BUF_LEN";
/// The environment variable to set the number of core syscall handler threads.
pub const ENV_NPROC: &str = "SYD_NPROC";
/// The environment variable to set the number of maximum syscall handler threads.
pub const ENV_NPROC_MAX: &str = "SYD_NPROC_MAX";
/// The environment variable to read the pid filename from.
pub const ENV_PID_FN: &str = "SYD_PID_FN";
/// The environment variable to force RESOLVE_NO_XDEV at open(2) boundary.
pub const ENV_FORCE_NOXDEV: &str = "SYD_FORCE_NOXDEV";
/// The environment variable to force randomized fds.
///
/// Setting this environment variable is equivalent to setting trace/force_rand_fd:1.
pub const ENV_FORCE_RANDFD: &str = "SYD_FORCE_RANDFD";
/// The environment variable to force TTY output.
pub const ENV_FORCE_TTY: &str = "SYD_FORCE_TTY";
/// The environment variable to quiet TTY output.
pub const ENV_QUIET_TTY: &str = "SYD_QUIET_TTY";

/// The environment variable to hold the PTY child fd (used internally).
pub const ENV_PTY_FD: &str = "SYD_PTY_FD";

/// The environment variable to set ipc socket.
pub const ENV_IPC: &str = "SYD_IPC";

/// The environment variable to hold the IPC epoll fd (used internally).
pub const ENV_IPC_POLL_FD: &str = "SYD_IPC_POLL_FD";
/// The environment variable to hold the IPC UNIX socket (used internally).
pub const ENV_IPC_UNIX_FD: &str = "SYD_IPC_UNIX_FD";

/// The environment variable to read the default external address from.
pub const ENV_PROXY_HOST: &str = "SYD_PROXY_HOST";
/// The environment variable to read the default external port from.
pub const ENV_PROXY_PORT: &str = "SYD_PROXY_PORT";
/// The environment variable to read the default external unix socket from.
pub const ENV_PROXY_UNIX: &str = "SYD_PROXY_UNIX";

/// The environment variable to set to disable cross memory attach, and fallback to /proc/pid/mem.
pub const ENV_NO_CROSS_MEMORY_ATTACH: &str = "SYD_NO_CROSS_MEMORY_ATTACH";

/// The environment variable to set to fallback to /proc/pid/mem if
/// process_vm_{read,write}v(2) is not available (ie returns ENOSYS).
/// The environment variable `ENV_NO_CROSS_MEMORY_ATTACH` has precedence
/// over this variable.
pub const ENV_PROC_PID_MEM_FALLBACK: &str = "SYD_PROC_PID_MEM_FALLBACK";

/// The environment variable to dump seccomp filters.
pub const ENV_DUMP_SCMP: &str = "SYD_DUMP_SCMP";

/// The environment variable to skip seccomp confinement of Syd threads.
pub const ENV_SKIP_SCMP: &str = "SYD_SKIP_SCMP";

/// The environment variable to set for quick boot.
///
/// This makes Syd startup noticeably faster,
/// however it removes a layer of defense against some container breaks.
/// Use this if you frequently re-execute syd{,-oci} such as we do on
/// Exherbo during Paludis' generate metadata phase.
pub const ENV_QUICK_BOOT: &str = "SYD_QUICK_BOOT";

/// The environment variable to save AT_RANDOM bytes at boot.
///
/// This is only intended for internal use and the user MUST not set it.
pub const ENV_RAND: &str = "SYD_RAND";

/// The environment variable to track log beginner Syd quote.
///
/// This is only intended for internal use and the user MUST not set it.
pub const ENV_SING: &str = "SYD_SING";

/// The environment variable to save Syd sandbox random ID.
///
/// If this variable is not set by the user,
/// Syd generates it by hashing AT_RANDOM bytes with SHA3-512.
pub const ENV_ID: &str = "SYD_ID";

/// The environment variable to make syd-oci skip configuration parsing.
///
/// This is primarily intended for testing.
pub const ENV_OCI_NO_CONFIG: &str = "SYD_OCI_NO_CONFIG";

/// The environment variable to read the parent-death signal from.
pub const ENV_PDS: &str = "SYD_PDS";

/// SafeSetID does not allow UID transitions for UIDs less than or equal to UID_MIN.
/// 11 is typically the `operator` user.
pub const UID_MIN: Uid = Uid::from_raw(11);

/// SafeSetID does not allow GID transitions for GIDs less than or equal to GID_MIN.
/// 14 is typically the `uucp` group.
pub const GID_MIN: Gid = Gid::from_raw(14);

/// Path prefix for magic stat commands.
pub const MAGIC_PREFIX: &[u8] = b"/dev/syd";

/// syd version
pub static VERSION: LazyLock<&'static str> = LazyLock::new(|| {
    if env!("SYD_GIT_HEAD").is_empty() {
        env!("CARGO_PKG_VERSION")
    } else {
        env!("SYD_GIT_HEAD")
    }
});

/// Api version of the syd(2) configuration.
pub const API_VERSION: Version = Version::new(3, 1);

/// Api major version of the syd(2) configuration.
pub const API_MAJOR_VERSION: &str = env!("CARGO_PKG_VERSION_MAJOR");

/// Api minor version of the syd(2) configuration.
pub const API_MINOR_VERSION: &str = "1";

/// Api version for the IPC service.
pub const IPC_MINOR_VERSION: &str = "1";

/// File format marker for Crypt sandboxing.
pub const CRYPT_MAGIC: &[u8] = &[0x7F, b'S', b'Y', b'D', 3];

/// Path to the file which will be used as file status for magic stat commands.
pub const MAGIC_FILE: &[u8] = b"/dev/null";

/// Limit on the maximum number of path components for path canonicalization.
pub const PATH_MAX_COMP: usize = 128;

/// Default buffer size for directory entries.
///
/// We use the same default as musl, see:
/// https://git.musl-libc.org/cgit/musl/tree/src/dirent/__dirent.h#n10
/// GNU libc uses 32k:
/// https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/unix/sysv/linux/opendir.c;h=48e3dc4fdbdf219c9f354f9c8bc30108ec7046c4;hb=84977600dace5a7cfcb0918e6757939fd4969839#l106
pub const DIRENT_BUF_SIZE: usize = 2048;

/// System page size
#[expect(clippy::cast_sign_loss)]
pub static PAGE_SIZE: LazyLock<u64> = LazyLock::new(|| {
    sysconf(SysconfVar::PAGE_SIZE)
        .unwrap_or(Some(4096))
        .unwrap_or(4096) as u64
});

/// The system-inherent limit for the size of one zero-copy operation
/// is 16 pages. If more data is to be sent to AF_ALG, user space
/// must slice the input into segments with a maximum size of 16
/// pages.
pub const KCAPI_SIZE: usize = 16 * libc::PIPE_BUF;

/// Pipe buffer size.
///
/// Before Linux 2.6.11, the capacity of a pipe was the same as the
/// system page size (e.g., 4096 bytes on i386). Since Linux 2.6.11,
/// the pipe capacity is 16 pages (i.e., 65,536 bytes in a system
/// with a page size of 4096 bytes). Since Linux 2.6.35, the default
/// pipe capacity is 16 pages, but the capacity can be queried and set
/// using the fcntl(2) F_GETPIPE_SZ and F_SETPIPE_SZ operations.
pub const PIPE_BUF: usize = 16 * libc::PIPE_BUF;

/// A version of `PIPE_BUF` that is safe to use with `AF_ALG` sockets.
///
/// This is slightly smaller than `PIPE_BUF` to let kernel some space.
pub const PIPE_BUF_ALG: usize = 15 * libc::PIPE_BUF;

/// Number of CPUs on the system.
pub static NPROC: LazyLock<usize> = LazyLock::new(num_cpus::get);

/// The size of the syscall handler thread pool.
///
/// Note, the pool is self-growing/shrinking, and this constant defines
/// the number of core threads that are always alive and do not get
/// reaped-off even if they're idle.
#[expect(clippy::disallowed_methods)]
pub static EMU_POOL_SIZE: LazyLock<usize> = LazyLock::new(|| {
    let n = std::env::var_os(ENV_NPROC)
        .map(|val| btoi::<usize>(val.as_bytes()).expect("SYD_NPROC"))
        .unwrap_or_else(|| *NPROC);
    assert!(n >= 1, "SYD_NPROC must be at least 1!");
    n
});

/// The absolute maximum number of workers. This corresponds to the
/// maximum value that can be stored within half the bits of u64, as two
/// counters (total workers and busy workers) are stored in one
/// AtomicU64.
#[expect(clippy::disallowed_methods)]
pub static EMU_MAX_SIZE: LazyLock<usize> = LazyLock::new(|| {
    let n = std::env::var_os(ENV_NPROC_MAX)
        .map(|val| btoi::<usize>(val.as_bytes()).expect("SYD_NPROC_MAX"))
        .unwrap_or(usize::MAX);
    assert!(
        n > *EMU_POOL_SIZE,
        "SYD_NPROC_MAX must be greater than SYD_NPROC!"
    );
    n
});

/// Specify the duration in milliseconds for which additional threads
/// outside the core pool remain alive while not receiving any work
/// before giving up and terminating.
/// Defaults to 3 seconds.
pub const EMU_KEEP_ALIVE: u16 = 3;

/// Specify the graceful wait time for the monitor thread.
/// Defaults to 250 milliseconds.
pub const MON_GRACE_TIME: Duration = Duration::from_millis(250);

/// Specify the cycle period of the monitor thread.
/// Defaults to 25 milliseconds.
pub const MON_CYCLE_TIME: Duration = Duration::from_millis(25);

/// Specify the cycle period of the interrupt thread.
/// Defaults to 10 milliseconds.
pub const INT_CYCLE_TIME: Duration = Duration::from_millis(10);

/// Stack size for the syscall handler threads.
/// Defaults to 208k.
pub const EMU_STACK_SIZE: usize = 208 * 1024;

/// Stack size for the syscall monitor thread.
/// Defaults to 128k.
pub const MON_STACK_SIZE: usize = 128 * 1024;

/// Stack size for the syscall interrupt thread.
/// Defaults to 128k.
pub const INT_STACK_SIZE: usize = 128 * 1024;

/// Stack size for the IPC thread.
/// Defaults to 256k.
pub const IPC_STACK_SIZE: usize = 256 * 1024;

/// Stack size for the AES encryption threads.
/// Defaults to 96k.
pub const AES_STACK_SIZE: usize = 96 * 1024;

/// Stack size for the short-lived micro-threads Syd spawns during
/// system call emulation.
/// Defaults to 8k.
pub const MINI_STACK_SIZE: usize = 8 * 1024;

/// Stack size for the initial _clone_(2) to spawn the sandbox process.
/// Defaults to 2M.
pub const CHLD_STACK_SIZE: usize = 2 * 1024 * 1024;

// Syslog(2) defaults

#[cfg(target_arch = "x86_64")]
const SYSLOG_CAPSHIFT: usize = 18;
#[cfg(target_arch = "x86")]
const SYSLOG_CAPSHIFT: usize = 18;
#[cfg(target_arch = "aarch64")]
const SYSLOG_CAPSHIFT: usize = 14;
#[cfg(target_arch = "arm")]
const SYSLOG_CAPSHIFT: usize = 13;
#[cfg(target_arch = "riscv64")]
const SYSLOG_CAPSHIFT: usize = 14;
#[cfg(any(target_arch = "powerpc", target_arch = "powerpc64"))]
const SYSLOG_CAPSHIFT: usize = 18;
#[cfg(target_arch = "s390x")]
const SYSLOG_CAPSHIFT: usize = 17;

#[cfg(not(any(
    target_arch = "x86_64",
    target_arch = "x86",
    target_arch = "aarch64",
    target_arch = "arm",
    target_arch = "s390x",
    target_arch = "riscv64",
    target_arch = "powerpc",
    target_arch = "powerpc64",
)))]
const SYSLOG_CAPSHIFT: usize = 14;

/// Default static capacity for syslog(2) stack mode.
///
/// This is the default mode unless a capacity has been specified
/// at startup using the environment variable `SYD_LOG_BUF_LEN`.
///
/// Quoting syslog(2):
/// In early kernels, LOG_BUF_LEN had the value 4096; from Linux 1.3.54,
/// it was 8192; from Linux 2.1.113, it was 16384; since Linux
/// 2.4.23/2.6, the value is a kernel configuration option
/// (CONFIG_LOG_BUF_SHIFT, default value dependent on the architecture).
/// Since Linux 2.6.6, the size can be queried with command type 10 (see
/// below).
pub const SYSLOG_STACK_SIZE: usize = 1 << SYSLOG_CAPSHIFT;

/// The ring buffer capacity for Syslog.
///
/// Note this buffer is allocated on the heap.
/// Defaults to 2M.
pub const SYSLOG_CAPACITY: usize = 2 * 1024 * 1024;

// SegvGuard Defaults

/// SegvGuard entry expiry timeout.
pub const SEGVGUARD_EXPIRY: Duration = Duration::from_secs(2 * 60);
/// SegvGuard entry suspension timeout.
pub const SEGVGUARD_SUSPENSION: Duration = Duration::from_secs(10 * 60);
/// SegvGuard max number of crashes before expiry.
pub const SEGVGUARD_MAXCRASHES: u8 = 5;

// Sandbox Restrictions

/// List of allowlisted personality(2) flags.
///
/// This is consistent with podman(1) and docker(1)
pub const SAFE_PERSONAS: &[KeyValue] = &[
    ("PER_LINUX", 0x0000),
    ("PER_LINUX32", 0x0800000),
    ("UNAME26", 0x0020000),
    ("PER_LINUX32|UNAME26", 0x0800000 | 0x0020000),
    ("GET_PERSONALITY", 0xffffffff),
];

/// List of unsafe personality(2) flags.
pub const UNSAFE_PERSONAS: &[Persona] = &[Persona::READ_IMPLIES_EXEC, Persona::ADDR_NO_RANDOMIZE];

/// List of allowlisted madvise(2) advices.
pub const ALLOWLIST_MADVISE: &[KeyValue] = &[
    ("MADV_NORMAL", libc::MADV_NORMAL as u64),
    ("MADV_SEQUENTIAL", libc::MADV_SEQUENTIAL as u64),
    ("MADV_DONTNEED", libc::MADV_DONTNEED as u64),
    ("MADV_REMOVE", libc::MADV_REMOVE as u64),
    ("MADV_HUGEPAGE", libc::MADV_HUGEPAGE as u64),
    ("MADV_NOHUGEPAGE", libc::MADV_NOHUGEPAGE as u64),
    ("MADV_DONTDUMP", libc::MADV_DONTDUMP as u64),
    // Libc does not define MADV_COLLAPSE for musl.
    ("MADV_COLLAPSE", 25),
    ("MADV_POPULATE_READ", libc::MADV_POPULATE_READ as u64),
    ("MADV_POPULATE_WRITE", libc::MADV_POPULATE_WRITE as u64),
    // Libc does not yet define MADV_GUARD_{INSTALL,REMOVE}.
    ("MADV_GUARD_INSTALL", 102),
    ("MADV_GUARD_REMOVE", 103),
];

/// List of no-opped madvise(2) advices.
pub const NOOP_MADVISE: &[u64] = &[
    libc::MADV_RANDOM as u64,
    libc::MADV_WILLNEED as u64,
    libc::MADV_DONTFORK as u64,
    libc::MADV_DOFORK as u64,
    libc::MADV_MERGEABLE as u64,
    libc::MADV_UNMERGEABLE as u64,
    libc::MADV_SOFT_OFFLINE as u64,
    libc::MADV_DODUMP as u64,
    libc::MADV_FREE as u64,
    libc::MADV_WIPEONFORK as u64,
    libc::MADV_KEEPONFORK as u64,
    libc::MADV_COLD as u64,
    libc::MADV_PAGEOUT as u64,
];

/// List of denied madvise(2) advices.
pub const DENY_MADVISE: &[u64] = &[libc::MADV_HWPOISON as u64];

/// List of allowed madvise(2) advices for Syd threads.
pub const SYD_MADVISE: &[u64] = &[
    libc::MADV_DONTNEED as u64,
    libc::MADV_FREE as u64,
    libc::MADV_HUGEPAGE as u64,
    // Libc does not yet define MADV_GUARD_{INSTALL,REMOVE}.
    102, // MADV_GUARD_INSTALL
    103, // MADV_GUARD_REMOVE
];

/// List of allowlisted prctl(2) requests.
pub const ALLOWLIST_PRCTL: &[KeyValue] = &[
    ("PR_SET_PDEATHSIG", 1),
    ("PR_GET_PDEATHSIG", 2),
    ("PR_GET_DUMPABLE", 3),
    ("PR_SET_DUMPABLE", 4),
    ("PR_GET_ALIGN", 5),
    ("PR_GET_SETALIGN", 6),
    ("PR_GET_KEEPCAPS", 7),
    ("PR_SET_KEEPCAPS", 8),
    ("PR_GET_FPEMU", 9),
    ("PR_SET_FPEMU", 10),
    ("PR_GET_FPEXC", 11),
    ("PR_SET_FPEXC", 12),
    ("PR_GET_TIMING", 13),
    ("PR_SET_TIMING", 14),
    ("PR_SET_NAME", 15),
    ("PR_GET_NAME", 16),
    ("PR_GET_ENDIAN", 19),
    ("PR_SET_ENDIAN", 20),
    ("PR_GET_SECCOMP", 21), // Disallowed unless trace/allow_unsafe_cbpf:1
    ("PR_SET_SECCOMP", 22), // Disallowed unless trace/allow_unsafe_cbpf:1
    ("PR_CAPBSET_READ", 23),
    ("PR_CAPBSET_DROP", 24),
    ("PR_GET_TSC", 25),
    ("PR_SET_TSC", 26),
    ("PR_GET_SECUREBITS", 27),
    ("PR_SET_SECUREBITS", 28),
    ("PR_SET_TIMERSLACK", 29),
    ("PR_GET_TIMERSLACK", 30),
    ("PR_TASK_PERF_EVENTS_DISABLE", 31), // Disallowed unless trace/allow_unsafe_perf:1
    ("PR_TASK_PERF_EVENTS_ENABLE", 32),  // Disallowed unless trace/allow_unsafe_perf:1
    ("PR_MCE_KILL", 33),
    ("PR_MCE_KILL_GET", 34),
    // SAFETY: no self modifying executables! PR_SET_MM
    // SAFETY: no ptrace! PR_SET_PTRACER
    ("PR_SET_CHILD_SUBREAPER", 36),
    ("PR_GET_CHILD_SUBREAPER", 37),
    ("PR_SET_NO_NEW_PRIVS", 38),
    ("PR_GET_NO_NEW_PRIVS", 39),
    ("PR_GET_TID_ADDRESS", 40),
    ("PR_SET_THP_DISABLE", 41),
    ("PR_GET_THP_DISABLE", 42),
    // SAFETY: unimplemented! PR_MPX_ENABLE_MANAGEMENT
    // SAFETY: unimplemented! PR_MPX_DISABLE_MANAGEMENT
    ("PR_SET_FP_MODE", 45),
    ("PR_GET_FP_MODE", 46),
    ("PR_CAP_AMBIENT", 47),
    ("PR_SVE_SET_VL", 50),
    ("PR_SVE_GET_VL", 51),
    ("PR_GET_SPECULATION_CTRL", 52), // Disallowed unless trace/allow_unsafe_exec_speculative:1
    ("PR_SET_SPECULATION_CTRL", 53), // Disallowed unless trace/allow_unsafe_exec_speculative:1
    ("PR_PAC_RESET_KEYS", 54),
    ("PR_SET_TAGGED_ADDR_CTRL", 55),
    ("PR_GET_TAGGED_ADDR_CTRL", 56),
    ("PR_SET_IO_FLUSHER", 57),
    ("PR_GET_IO_FLUSHER", 58),
    ("PR_SET_SYSCALL_USER_DISPATCH", 59),
    ("PR_PAC_SET_ENABLED_KEYS", 60),
    ("PR_PAC_GET_ENABLED_KEYS", 61),
    ("PR_SCHED_CORE", 62),
    ("PR_SET_MDWE", 65),
    ("PR_GET_MDWE", 66),
    ("PR_SET_VMA", 0x53564d41),
];

/// Equivalent to the list of environment variables that glibc/musl remove
/// for programs running under secure-execution mode.
pub const UNSAFE_ENV: &[&[u8]] = &[
    b"GCONV_PATH",
    b"GETCONF_DIR",
    b"GLIBC_TUNABLES",
    b"HOSTALIASES",
    b"LD_AOUT_LIBRARY_PATH",
    b"LD_AOUT_PRELOAD",
    b"LD_AUDIT",
    b"LD_BIND_NOT",
    b"LD_DEBUG",
    b"LD_DEBUG",
    b"LD_DEBUG_OUTPUT",
    b"LD_DYNAMIC_WEAK",
    b"LD_DYNAMIC_WEAK",
    b"LD_ELF_HINTS_PATH",
    b"LD_HWCAP_MASK",
    b"LD_LIBMAP",
    b"LD_LIBMAP_DISABLE",
    b"LD_LIBRARY_PATH",
    b"LD_LIBRARY_PATH_FDS",
    b"LD_LIBRARY_PATH_RPATH",
    b"LD_LOADFLTR",
    b"LD_ORIGIN_PATH",
    b"LD_PREFER_MAP_32BIT_EXEC",
    b"LD_PRELOAD",
    b"LD_PRELOAD_FDS",
    b"LD_PROFILE",
    b"LD_SHOW_AUXV",
    b"LD_USE_LOAD_BIAS",
    b"LOCALDOMAIN",
    b"LOCPATH",
    b"MALLOC_TRACE",
    b"MUSL_LOCPATH",
    b"NIS_PATH",
    b"NLSPATH",
    b"RESOLV_HOST_CONF",
    b"RES_OPTIONS",
    b"TMPDIR",
    b"TZ",
    b"TZDIR",
    b"LANG",
    b"LC_CTYPE",
    b"LC_NUMERIC",
    b"LC_TIME",
    b"LC_COLLATE",
    b"LC_MONETARY",
    b"LC_MESSAGES",
    b"LC_PAPER",
    b"LC_NAME",
    b"LC_ADDRESS",
    b"LC_TELEPHONE",
    b"LC_MEASUREMENT",
    b"LC_IDENTIFICATION",
    b"LC_ALL",
];

/// Default ioctl allow/denylist.
/// false -> allow, true -> deny.
/*
 * Quotes from Landlock ioctl access helpers
 * is_masked_device_ioctl and is_masked_device_ioctl_compat:
 *
 * 1. FIOCLEX, FIONCLEX, FIONBIO and FIOASYNC manipulate the FD's
 *    close-on-exec and the file's buffered-IO and async flags.
 *    These operations are also available through fcntl(2),
 *    and are unconditionally permitted in Landlock.
 * 2. FIOQSIZE queries the size of a regular file, directory, or link.
 *    We still permit it, because it always returns -ENOTTY for
 *    other file types.
 * 3. FIFREEZE and FITHAW freeze and thaw the file system which the
 *    given file belongs to. Requires CAP_SYS_ADMIN.
 *    These commands operate on the file system's superblock rather
 *    than on the file itself. The same operations can also be
 *    done through any other file or directory on the same file
 *    system, so it is safe to permit these.
 * 4. FS_IOC_FIEMAP queries information about the allocation of
 *    blocks within a file.
 *    This IOCTL command only makes sense for regular files and is
 *    not implemented by devices. It is harmless to permit.
 * 5. FIGETBSZ queries the file system's block size for a file or
 *    directory.
 *    This command operates on the file system's superblock rather
 *    than on the file itself. The same operation can also be done
 *    through any other file or directory on the same file system,
 *    so it is safe to permit it.
 * 6. FICLONE, FICLONERANGE and FIDEDUPERANGE make files share
 *    their underlying storage ("reflink") between source and
 *    destination FDs, on file systems which support that.
 *    These IOCTL commands only apply to regular files
 *    and are harmless to permit for device files.
 * 7. FS_IOC_GETFSUUID and FS_IOC_GETFSSYSFSPATH both operate on
 *    the file system superblock, not on the specific file, so
 *    these operations are available through any other file on the
 *    same file system as well.
 * 8. FIONREAD, FS_IOC_GETFLAGS, FS_IOC_SETFLAGS, FS_IOC_FSGETXATTR and
 *    FS_IOC_FSSETXATTR are forwarded to device implementations.
 * 9. file_ioctl() commands (FIBMAP, FS_IOC_RESVSP, FS_IOC_RESVSP64,
 *    FS_IOC_UNRESVSP, FS_IOC_UNRESVSP64 and FS_IOC_ZERO_RANGE) are
 *    forwarded to device implementations, so not permitted.
 * 10. FICLONE is permitted, same as in the non-compat variant.
 * 11. CONFIG_X86_64: FS_IOC_RESVSP_32, FS_IOC_RESVSP64_32, FS_IOC_UNRESVSP_32,
 *     FS_IOC_UNRESVSP64_32, FS_IOC_ZERO_RANGE_32: not blanket-permitted,
 *     for consistency with their non-compat variants.
 * 12. FS_IOC32_GETFLAGS, FS_IOC32_SETFLAGS are forwarded to their device
 *     implementations.
 * 13. RNDGETENTCNT is the single ioctl(2) request for /dev/{u,}random
 *     which does not require CAP_SYS_ADMIN. The other ioctl(2) requests
 *     of the same interface RNDADDTOENTCNT, RNDGETPOOL, RNDADDENTROPY,
 *     RNDZAPENTCNT, and RNDCLEARPOOL are privileged.
 */
pub const DEFAULT_IOCTL: &[(&str, bool)] = &[
    ("FIOCLEX", false),
    ("FIONCLEX", false),
    ("FIONBIO", false),
    ("FIONREAD", false),
    ("FIOASYNC", false),
    ("FIOQSIZE", false),
    ("FIFREEZE", true),      // CAP_SYS_ADMIN!
    ("FITHAW", true),        // ditto!
    ("FS_IOC_FIEMAP", true), // Leaks on-disk layout.
    ("FIGETBSZ", true),      // ditto!
    ("FICLONE", false),
    ("FICLONERANGE", false),
    ("FIDEDUPERANGE", false),
    ("FS_IOC_GETFSUUID", true),      // Leaks on-disk layout.
    ("FS_IOC_GETFSSYSFSPATH", true), // ditto!
    ("FIBMAP", true),                // ditto!
    ("KDSETKEYCODE", true),
    ("KDSIGACCEPT", true),
    ("TIOCSETD", true),
    ("TIOCSTI", true),
    ("TIOCCONS", true),
    ("TIOCLINUX", true),
    ("FS_IOC_FSGETXATTR", true), // (SAFETY: xattr restrictions)
    ("FS_IOC_FSSETXATTR", true), // ditto!
    ("FS_IOC_SETFLAGS", true),   // To deny immutable & append-only flag changes
    ("RNDGETENTCNT", false),     // unprivileged.
    ("RNDADDTOENTCNT", true),    // requires CAP_SYS_ADMIN.
    ("RNDGETPOOL", true),        // ditto.
    ("RNDADDENTROPY", true),     // ditto.
    ("RNDZAPENTCNT", true),      // ditto.
    ("RNDCLEARPOOL", true),      // ditto.
    ("SECCOMP_IOCTL_NOTIF_RECV", true),
    ("SECCOMP_IOCTL_NOTIF_SEND", true),
    ("SECCOMP_IOCTL_NOTIF_ID_VALID", true),
    ("SECCOMP_IOCTL_NOTIF_ADDFD", true),
    ("SECCOMP_IOCTL_NOTIF_SET_FLAGS", true),
];

// Sandboxing profiles

/// Off sandboxing profile.
/// Used as shorthand to turn all sandboxing off.
pub const PROFILE_OFF: &[&str] = &["sandbox/all:off", "sandbox/net,mem,pid,pty,force,tpe:off"];

/// Libsyd helper sandboxing profile.
/// Turns all sandboxing off and set sandbox lock to Exec.
/// Useful to configure syd in the application via libsyd.
pub const PROFILE_LIB: &[&str] = &["include_profile off", "lock:exec"];

/// Quiet sandboxing profile.
pub const PROFILE_QUIET: &[&str] = &[
    "default/all:filter",
    "default/net,block,mem,pid,force,segvguard,tpe:filter",
];

/// Trace sandboxing profile, used by pandora(1).
pub const PROFILE_TRACE: &[&str] = &[
    "log/level:info",
    "sandbox/force:on",
    "default/all,force,tpe:warn",
];

/// OCI default sandboxing profile, used by syd-oci(1).
pub const PROFILE_OCI: &[&str] = &[
    "include_profile nopie", // most containers ship non-pie binaries...
    "include_profile trace",
    "lock:off", // allow esyd.
    "trace/allow_safe_syslog:true",
];

/// Enforce profile, used to practically undo `oci` and `trace` profiles at runtime.
pub const PROFILE_ENFORCE: &[&str] = &[
    "default/all,net,force,tpe:deny",
    "trace/allow_safe_syslog:false",
    "trace/allow_unsafe_exec_nopie:false",
    "lock:exec", // keep esyd.
];

/// No ipv4 sandboxing profile.
pub const PROFILE_NOIPV4: &[&str] = &[
    "sandbox/net:on",
    "allow/cnet+any6!0-65535",
    "deny/cnet+any4!0-65535",
];

/// No ipv6 sandboxing profile.
pub const PROFILE_NOIPV6: &[&str] = &[
    "sandbox/net:on",
    "allow/cnet+any4!0-65535",
    "deny/cnet+any6!0-65535",
];

/// Privileged sandboxing profile.
pub const PROFILE_PRIVILEGED: &[&str] = &["trace/allow_unsafe_caps:true"];

/// No core dump restrictions profile.
pub const PROFILE_CORE: &[&str] = &["trace/allow_unsafe_prlimit:true"];

/// Debug sandboxing profile.
pub const PROFILE_DEBUG: &[&str] = &[
    "trace/allow_unsafe_dumpable:true",    // PR_SET_DUMPABLE!
    "trace/allow_unsafe_magiclinks:true",  // allow /proc/$pid/mem access.
    "trace/allow_unsafe_exec_memory:true", // allow W^X memory.
    "trace/allow_unsafe_prctl:true",       // allow changing process name.
    "trace/allow_unsafe_prlimit:true",     // enable coredumps.
    "trace/allow_unsafe_ptrace:true",      // strace -f syd
];

/// No memory restrictions sandboxing profile.
pub const PROFILE_NOMEM: &[&str] = &["trace/allow_unsafe_exec_memory:true"];

/// No PIE sandboxing profile.
pub const PROFILE_NOPIE: &[&str] = &["trace/allow_unsafe_exec_nopie:true"];

/// Random sandboxing profile, activated with:
/// `syd --profile rand`.
pub const PROFILE_RAND: &[&str] = &["trace/force_rand_fd:true"];

/// Firefox sandboxing profile.
/// `syd --profile firefox`
pub const PROFILE_FIREFOX: &[&str] = &[
    "sandbox/pty:off",                     // firefox(1) is not a console application
    "trace/allow_unsafe_exec_libc:true",   // Allow preloading libmozsandbox.so
    "trace/allow_unsafe_exec_memory:true", // W^X memory required for JIT
    "trace/allow_unsafe_page_cache:true",  // mincore(2) may be needed for DRM
];

/// Readonly sandboxing profile.
/// `syd --profile ro`
pub const PROFILE_READONLY: &[&str] = &["deny/cpath,wpath+/***"];

/// Container sandboxing profile, activated with:
/// `syd --profile container`
pub const PROFILE_CONTAINER: &[&str] = &[
    "unshare/all:true",
    "allow/lpath,rpath+/proc/uptime", // time-ns aware
];

/// Immutable container sandboxing profile, activated with:
/// `syd --profile immutable`
pub const PROFILE_IMMUTABLE: &[&str] = &[
    "include_profile container",
    "bind+/opt:/opt:ro,nodev,nosuid,nosymfollow",
    "bind+/usr:/usr:ro,nodev,nosuid,nosymfollow",
    "bind+/etc:/etc:ro,nodev,nosuid,noexec,nosymfollow",
    "bind+/mnt:/mnt:ro,nodev,nosuid,noexec,nosymfollow",
    "bind+/srv:/srv:ro,nodev,nosuid,noexec,nosymfollow",
    "bind+/home:/home:ro,nodev,nosuid,noexec,nosymfollow",
    "bind+tmpfs:/boot:ro,nodev,nosuid,noexec,nosymfollow,mode=0",
    "bind+tmpfs:/run:nodev,nosuid,nosymfollow,mode=1777",
    "bind+tmpfs:/tmp:nodev,nosuid,nosymfollow,mode=1777",
    "bind+tmpfs:/dev/shm:nodev,nosuid,noexec,nosymfollow,mode=1777",
];

/// Landlock sandboxing profile, activated with:
/// `syd --profile landlock`.
pub const PROFILE_LANDLOCK: &[&str] = &[
    "sandbox/lock:on",
    "allow/lock/rpath+/dev",
    "allow/lock/rpath,exec+/etc",
    "allow/lock/rpath,exec+/bin",
    "allow/lock/rpath,exec+/sbin",
    "allow/lock/rpath,exec+/lib",
    "allow/lock/rpath,exec+/opt",
    "allow/lock/rpath,exec+/usr",
    // /proc is always allowed.
    "allow/lock/rpath+/run",
    "allow/lock/rpath+/var",
    // /dev/null is always allowed.
    "allow/lock/read,ioctl,write+/dev/full",
    "allow/lock/read,ioctl+/dev/random",
    "allow/lock/read,ioctl+/dev/urandom",
    "allow/lock/read,ioctl+/dev/zero",
    // As of version 3.39.0, Linux profile omits bnet, exec, ioctl,
    // spath and fown access for public directories.
    // Paludis profile overrides this as it may be needed
    // during package testing.
    "allow/lock/rpath,cpath,wpath,tpath+/dev/shm",
    "allow/lock/rpath,cpath,wpath,tpath+/var/tmp",
    "allow/lock/rpath,cpath,wpath,tpath+/tmp",
];

/// Paludis sandboxing profile, activated with:
/// `syd --profile paludis`.
pub const PROFILE_PALUDIS: &[&str] = &[
    "include_profile linux",
    "include_profile tty",
    "default/lock:warn", // set Landlock compat-level to best-effort when stacked with Landlock profile.
    "allow/lock/rpath+/sys", // Relax Landlock to allow /sys when stacked with Landlock profile.
    "lock:exec",         // esandbox
    "mask^",             // do not inherit the default mask-list from linux profile.
    "sandbox/pty:off",   // Paludis creates a PTY on its own.
    "trace/memory_access:0", // fallback to unsafe proc_pid_mem(5) if cross memory attach fails.
    "trace/allow_safe_bind:true",
    "trace/allow_safe_kcapi:true",
    "trace/allow_unsafe_cbpf:true",     // stacked seccomp cbpf filters
    "trace/allow_unsafe_chroot:true",   // glibc uses this in src_install
    "trace/allow_unsafe_dumpable:true", // allows strace -f syd
    "trace/allow_unsafe_env:true",
    "trace/allow_unsafe_exec_libc:true",
    "trace/allow_unsafe_exec_memory:true",
    "trace/allow_unsafe_exec_nopie:true",
    "trace/allow_unsafe_exec_null:true",
    "trace/allow_unsafe_exec_stack:true",
    "trace/allow_unsafe_exec_script:true", // Do not set SECBIT_EXEC_RESTRICT_FILE_LOCKED.
    "trace/allow_unsafe_exec_interactive:true", // Do not set SECBIT_EXEC_DENY_INTERACTIVE_LOCKED.
    "trace/allow_unsafe_exec_speculative:true", // Do not enable Speculative Execution mitigation.
    "trace/allow_unsafe_filename:true",    // sydbox#118
    "trace/allow_unsafe_create:true",      // poppler-data src_install fails without this.
    "trace/allow_unsafe_hardlinks:true",   // gnulib linkat test fails without this.
    "trace/allow_unsafe_magiclinks:true",  // tests love to access /proc/1.
    "trace/allow_unsafe_symlinks:true",    // git's tests fail without this.
    "trace/allow_unsafe_machine_id:true",  // make machine-id(5) visible to Paludis.
    "trace/allow_unsafe_memfd:true",       // executable memory-fds are OK.
    "trace/allow_unsafe_mkbdev:true",      // dev-python/backports-tarfile's tests need this.
    "trace/allow_unsafe_mkcdev:true",      // ditto.
    "trace/allow_unsafe_msgsnd:true",
    "trace/allow_unsafe_nice:true",
    "trace/allow_unsafe_nocookie:true", // syscookies are a mitigation against compromised Syd.
    "trace/allow_unsafe_nomseal:true",  // mseal(2) is a mitigation against compromised Syd.
    "trace/allow_unsafe_open_path:true",
    "trace/allow_unsafe_page_cache:true",
    "trace/allow_unsafe_perf:true",
    "trace/allow_unsafe_personality:true", // gawk tests require ADDR_NO_RANDOMIZE.
    "trace/allow_unsafe_ptrace:true",
    "trace/allow_unsafe_prctl:true", // perl tests want to set process name.
    "trace/allow_unsafe_prlimit:true",
    "trace/allow_unsafe_proc_files:true", // builds typically use /proc/cpuinfo and more.
    "trace/allow_unsafe_proc_pid_status:true", // proc_pid_status(5) hardening is for malware-analysis.
    "trace/allow_unsafe_shm:true",             // perl tests map executable shared memory.
    "trace/allow_unsafe_sigreturn:true",
    "trace/allow_unsafe_socket:true",
    "trace/allow_unsafe_sysinfo:true", // disables sysinfo(2) randomizer, >3.23.4
    "trace/allow_unsupp_socket:true",
    "trace/allow_unsafe_time:true",
    "trace/allow_unsafe_xattr:true", // setcap requires access to security.capability.*
    // Avoid annoying open(/, O_DIRECTORY) failures.
    // See: #208, #212, and #219.
    // no-op unless Landlock is enabled.
    "allow/lock/readdir+/",
    // Allow FS_IOC_SETFLAGS (used by libarchive, cpio, tar etc.)
    // Use `!` suffix as this ioctl request doesn't exist on i686, x32 etc.
    "ioctl/deny-FS_IOC_SETFLAGS!", // needed because it's denied by default.
    "ioctl/allow+FS_IOC_SETFLAGS!",
    // Turned on by esandbox in metadata phase.
    "sandbox/exec:off",
    // TPE is unnecessary for package builds.
    "sandbox/tpe:off",
    // Filter noisy systemd access.
    "filter/cnet+/run/systemd/userdb/io.systemd.DynamicUser",
    // Defaults for /selinux.
    "allow/lpath,rpath+/selinux",
    "allow/lpath,rpath+/selinux/context",
    "allow/lpath,rpath,write+/selinux/context/**",
    // Defaults for sysfs.
    "allow/lpath,rpath+/sys",
    "allow/lpath,rpath+/sys/devices",
    "allow/lpath,rpath+/sys/devices/system",
    "allow/lpath,rpath+/sys/devices/system/cpu",
    "allow/lpath,rpath+/sys/devices/system/cpu/isolated",
    "allow/lpath,rpath+/sys/devices/system/cpu/kernel_max",
    "allow/lpath,rpath+/sys/devices/system/cpu/online",
    "allow/lpath,rpath+/sys/devices/system/cpu/offline",
    "allow/lpath,rpath+/sys/devices/system/cpu/possible",
    "allow/lpath,rpath+/sys/devices/system/cpu/present",
    "allow/lpath,rpath+/sys/fs",
    "allow/lpath,rpath+/sys/fs/cgroup/***",
    "allow/lpath,rpath+/sys/kernel",
    "allow/lpath,rpath+/sys/kernel/mm",
    "allow/lpath,rpath+/sys/kernel/mm/transparent_hugepage/***",
    "allow/lpath,rpath+/sys/kernel/security",
    "allow/lpath,rpath+/sys/kernel/security/apparmor/***",
    // Defaults for procfs.
    "allow/lpath,rpath,rename+/proc/crypto",
    "allow/lpath,rpath,rename+/proc/cpuinfo",
    "allow/lpath,rpath,rename+/proc/loadavg",
    "allow/lpath,rpath,rename+/proc/meminfo",
    "allow/lpath,rpath,rename+/proc/stat",
    "allow/lpath,rpath,rename+/proc/uptime",
    "allow/lpath,rpath,rename+/proc/version",
    // SAFETY: We allow relaxed stat access (/proc wide).
    // This must be combined with trace/allow_unsafe_magiclinks:1.
    "allow/lpath,rpath,rename+/proc/[0-9]*/stat",
    "allow/lpath,rpath,rename+/proc/[0-9]*/task/[0-9]*/stat",
    // SAFETY: Allow /proc PID traversals.
    // Tests often assume they can identify fellow processes
    // by readdir'ing /proc hence we allow it here but deny
    // in the default secure `linux` profile.
    "allow/lpath,rpath,rename+/proc/[0-9]*",
    "allow/lpath,rpath,rename+/proc/filesystems",
    // SAFETY:
    // 1. proc_pid_maps(5) access allows an attacker
    //    to easily circumvent ASLR, therefore the two rules
    //    below have been moved from Linux to Paludis profile.
    // 2. Access to proc_pid_smaps(5) and proc_pid_pagemap(5)
    //    have similar security characteristics.
    // 3. smaps has a `*` at the end to also allow smaps_rollup.
    // 4. ioctl(2) access is needed for PROCMAP_QUERY.
    "allow/lpath,rpath,rename,ioctl+/proc/self/maps",
    "allow/lpath,rpath,rename,ioctl+/proc/self/task/[0-9]*/maps",
    "allow/lpath,rpath,rename+/proc/self/smaps*",
    "allow/lpath,rpath,rename+/proc/self/task/[0-9]*/smaps*",
    "allow/lpath,rpath,rename+/proc/self/pagemap",
    "allow/lpath,rpath,rename+/proc/self/task/[0-9]*/pagemap",
    "allow/lpath,rpath,rename+/proc/mounts", // symlink to self/mounts
    "allow/lpath,rpath,rename+/proc/self/mounts",
    "allow/lpath,rpath,rename+/proc/self/task/[0-9]*/mounts",
    "allow/lpath,rpath,rename+/proc/self/mountinfo",
    "allow/lpath,rpath,rename+/proc/self/task/[0-9]*/mountinfo",
    "allow/lpath,rpath,rename+/proc/self/attr/***",
    "allow/lpath,rpath,rename+/proc/self/task/[0-9]*/attr/***",
    "allow/lpath,rpath,rename+/proc/self/cgroup",
    "allow/lpath,rpath,rename+/proc/self/task/[0-9]*/cgroup",
    "allow/lpath,rpath,rename+/proc/sys",
    "allow/lpath,rpath,rename+/proc/sys/fs/***",
    "allow/lpath,rpath,rename+/proc/sys/kernel/***",
    "allow/lpath,rpath,rename+/proc/sys/net/***",
    "allow/lpath,rpath,rename+/proc/sys/vm/***",
    // Allow /dev/shm, /var/tmp and /tmp for Paludis builds.
    // As of version 3.39.0, Linux profile omits bnet, exec, ioctl,
    // spath and fown access for public directories which we re-add here.
    "allow/exec,ioctl,spath,bnet,fown+/dev/shm/**",
    "allow/exec,ioctl,spath,bnet,fown+/var/tmp/**",
    "allow/exec,ioctl,spath,bnet,fown+/tmp/**",
    // Allow wider permissions for public directories.
    // no-op unless Landlock is enabled.
    "allow/lock/exec,ioctl,spath,bnet+/dev/shm",
    "allow/lock/exec,ioctl,spath,bnet+/var/tmp",
    "allow/lock/exec,ioctl,spath,bnet+/tmp",
    // Allow /var/cache for Paludis builds.
    "allow/lpath,rpath,mktemp+/var/cache/***",
    "allow/lpath,rpath,wpath,cpath,spath,tpath,exec,ioctl,bnet,fown,fattr+/var/cache/**",
    "allow/lock/rpath,wpath,cpath,spath,tpath,exec,ioctl,bnet+/var/cache",
    // Defaults for network sandboxing.
    "allow/bnet+loopback!0",
    "allow/bnet+loopback!1024-65535",
    // Defaults for Landlock networking which is ABI>=4.
    "allow/lock/bnet+0",
    "allow/lock/bnet+1024-65535",
    "allow/lock/cnet+1024-65535",
    // Allow interaction with memory file descriptors.
    "allow/exec,lpath,rpath,wpath,cpath+!memfd:**",
    "allow/exec,lpath,rpath,wpath,cpath+!memfd-hugetlb:**",
    "allow/exec,lpath,rpath,wpath,cpath+/proc/self/fd/!memfd:**",
    "allow/exec,lpath,rpath,wpath,cpath+/proc/self/fd/!memfd-hugetlb:**",
    // Repository directory
    "allow/lpath,rpath+/var/db",
    "allow/lpath,rpath+/var/db/paludis/***",
];

/// LTP sandboxing profile, activated with:
/// `syd --profile ltp`
///
/// This profile allows wide filesystem & network access,
/// and it should only be used with LTP tests!
pub const PROFILE_LTP: &[&str] = &[
    "include_profile paludis",
    "trace/allow_unsafe_chroot:false", // LTP chroot tests break if chroot is no-op.
    "trace/allow_unsafe_deprecated:true", // LTP has remap_file_pages(2) tests.
    "trace/allow_unsafe_keyring:true", // LTP tests for add_key.
    "trace/allow_unsafe_madvise:true", // LTP has madvise(2) tests.
    "trace/allow_unsafe_mbind:true",   // LTP has mbind(2) tests.
    "trace/allow_unsafe_oob:true",     // LTP recvmsg tests break with MSG_OOB restriction.
    "trace/allow_unsafe_stat_bdev:true", // LTP inotify tests break with this restriction.
    "trace/allow_unsafe_stat_cdev:true", // ditto.
    "allow/all+/***",
    "allow/net+@**",
    "allow/net+any!0-65535",
    "ioctl/deny-FIGETBSZ",
];

/// NIX sandboxing profile, activated with:
/// `syd --profile nix`
///
/// This profile allows wide filesystem & network access,
/// and it should only be used with NIX crate tests!
pub const PROFILE_NIX: &[&str] = &[
    "include_profile paludis",
    "trace/allow_unsafe_madvise:true",  // NIX has madvise(2) tests.
    "trace/allow_unsafe_mqueue:true",   // NIX has mqueue(2) tests.
    "trace/allow_unsafe_vmsplice:true", // NIX has vmsplice(2) tests.
    "allow/all+/***",
    "allow/net+@**",
    "allow/net+any!0-65535",
];

/// User sandboxing profile, activated with:
/// `syd --profile user`.
/// Syd sets the environment variables
/// UID, GID, USER, and HOME before parsing this
/// profile.
pub const PROFILE_USER: &[&str] = &[
    "include_profile linux",
    "include_profile rand",
    "include_profile tty",
    // dmesg(8)
    "trace/allow_safe_syslog:true",
    // TPE
    "tpe/negate:1",
    "tpe/user_owned:1",
    "tpe/gid:${SYD_GID}",
    // Enforce strict file modes:
    // Disallow executable bits to enhance W^X.
    // Disallow s{u,g}id bits on files.
    // Disallow setting group+other bits.
    "trace/force_umask:7177",
    // /home
    // 1. We allow read(${HOME}) but not write(${HOME}),
    //    read|write(${HOME}/**) is ok, i.e. the user can not delete
    //    their home directory under the sandbox which is a nice and
    //    funny protection.
    // 2. We disallow all dotfiles except history.
    // 3. We mark shell-history files as append-only.
    "allow/all+${HOME}/**",
    "allow/lpath,rpath+${HOME}/***",
    "deny/all+${HOME}/**/.*/***",
    "allow/all+${HOME}/**/.*history*",
    "append+${HOME}/.*history",
    // /run/user/uid
    "allow/all+/run/user/${SYD_UID}/**",
    "allow/lpath,rpath+/run/user/${SYD_UID}/***",
];

/// Common Linux system profile, used by oci, paludis and user profiles.
pub const PROFILE_LINUX: &[&str] = &[
    // List root is safe.
    "allow/stat,chdir,readdir+/",
    // Safe defaults for Exec sandboxing
    "allow/lpath,rpath,exec+/bin/***",
    "allow/lpath,rpath,exec+/sbin/***",
    "allow/lpath,rpath,exec+/lib*/***",
    "allow/lpath,rpath,exec+/usr/***",
    "allow/lpath,rpath,exec+/opt/***",
    // SAFETY: Do not leak kernel config/module information.
    // This overrides the lib rule above.
    "deny/lpath,rpath,exec+/lib*/modules/***",
    // Safe defaults for Network sandboxing
    "allow/net/link+route", // allow NETLINK_ROUTE.
    "allow/cnet+/run/nscd/socket",
    "allow/cnet+/var/run/nscd/socket",
    "allow/cnet+/var/lib/sss/pipes/nss",
    "allow/cnet+loopback!65535", // getaddrinfo() with AI_ADDRCONFIG on musl.
    // /dev
    "allow/lpath,rpath+/dev",
    "allow/lpath,rpath+/dev/fd",
    // As of version 3.39.0, Linux profile omits bnet, exec, ioctl,
    // spath and fown access for public directories.
    // Paludis profile overrides this as it may be needed
    // during package testing.
    "allow/lpath,rpath,mktemp+/dev/shm/***",
    "allow/lpath,rpath,mktemp+/var/tmp/***",
    "allow/lpath,rpath,mktemp+/tmp/***",
    "allow/lpath,rpath,wpath,cpath,tpath,fattr+/dev/shm/**",
    "allow/lpath,rpath,wpath,cpath,tpath,fattr+/var/tmp/**",
    "allow/lpath,rpath,wpath,cpath,tpath,fattr+/tmp/**",
    "allow/lpath,rpath,wpath,ioctl+/dev/full",
    "allow/lpath,rpath,wpath,ioctl+/dev/zero",
    "allow/lpath,rpath,wpath,ioctl+/dev/null",
    "allow/lpath,rpath,wpath+/dev/stdin",
    "allow/lpath,rpath,wpath+/dev/stdout",
    "allow/lpath,rpath,wpath+/dev/stderr",
    "allow/lpath,rpath,wpath,ioctl+/dev/random",
    "allow/lpath,rpath,wpath,ioctl+/dev/urandom",
    // /proc
    //
    // SAFETY: Note we allow readdir to `/proc`,
    // however we do _not_ allow PID traversals,
    // ie identifying fellow processing by readdir'ing `/proc`.
    // Notably, this is allowed in the `paludis` profile.
    "allow/lpath,rpath+/proc",
    // SAFETY: We allow basic stat access (not global but per-process and per-task).
    // trace/allow_unsafe_magiclinks:0 default is another layer of
    // protection against potential malicious activity with proc
    // magiclinks. Paludis profile allows global stat access for /proc/stat.
    "allow/lpath,rpath+/proc/self/stat",
    "allow/lpath,rpath+/proc/self/task/[0-9]*/stat",
    "allow/lpath,rpath+/proc/self/statm",
    "allow/lpath,rpath+/proc/self/task/[0-9]*/statm",
    "allow/lpath,rpath+/proc/self/status",
    "allow/lpath,rpath+/proc/self/task/[0-9]*/status",
    // SAFETY: Mask global info/stat paths as an extra layer such as:
    // /proc/buddyinfo, /proc/cpuinfo, /proc/meminfo, /proc/pagetypeinfo,
    // /proc/slabinfo, /proc/vmallocinfo, /proc/zoneinfo,
    // /proc/diskstats, /proc/schedstat, /proc/stat, /proc/vmstat etc.
    "mask+/proc/*info*/***:/dev/null:/var/empty",
    "mask+/proc/*stat*/***:/dev/null:/var/empty",
    // SAFETY: We provide an empty file in place of /proc/cmdline
    // for compatibility rather than denying outright. In any case,
    // syd does not leak the contents of this file to the sandbox
    // process. See: https://gitlab.exherbo.org/sydbox/sydbox/-/issues/106
    "allow/lpath,rpath+/proc/cmdline",
    "mask+/proc/cmdline",
    // SAFETY: Provide an empty file in place of /proc/version.
    // This is consistent with uname(2) restrictions.
    "allow/lpath,rpath+/proc/version",
    "mask+/proc/version",
    // SAFETY: Further masking for sa{f,n}e defaults.
    "mask+/proc/interrupts",
    "mask+/proc/kcore",
    "mask+/proc/keys",
    "mask+/proc/acpi/***:/dev/null:/var/empty",
    "mask+/proc/asound/***:/dev/null:/var/empty",
    "mask+/proc/bus/***:/dev/null:/var/empty",
    "mask+/proc/driver/***:/dev/null:/var/empty",
    // /proc/dynamic_debug
    // SAFETY: Provide wider debug glob for future-safety.
    "mask+/proc/*debug*/***:/dev/null:/var/empty",
    "mask+/proc/fs/***:/dev/null:/var/empty",
    "mask+/proc/irq/***:/dev/null:/var/empty",
    // /proc/latency_stats, /proc/timer_list, /proc/timer_stats etc.
    "mask+/proc/latency_*/***:/dev/null:/var/empty",
    "mask+/proc/timer_*/***:/dev/null:/var/empty",
    "mask+/proc/*_stats/***:/dev/null:/var/empty",
    "mask+/proc/pressure/***:/dev/null:/var/empty",
    // /proc/schedstat, /proc/sched_debug etc.
    "mask+/proc/sched*/***:/dev/null:/var/empty",
    "mask+/proc/scsi/***:/dev/null:/var/empty",
    // SAFETY: Modification of /proc/sys/kernel/modprobe requires no
    // capabilities (can cause arbitrary code to be inserted into the
    // kernel via a replacement modprobe)!
    // https://forums.grsecurity.net/viewtopic.php?f=7&t=2522
    //
    // As of 3.36.0 we extend this to protect more such as:
    // /proc/sys, /proc/sysvipc, /proc/sysrq-trigger etc.
    "mask+/proc/sys*/***:/dev/null:/var/empty",
    "mask+/proc/tty/***:/dev/null:/var/empty",
    // SAFETY: Mask boot_id with random UUID.
    // This prevents leaking host boot id unintentionally.
    // getrandom(2) is already in VDSO so allowing random UUID
    // file does not give any more power to the attacker.
    "allow/lpath,rpath+/proc/sys",
    "allow/lpath,rpath+/proc/sys/kernel",
    "allow/lpath,rpath+/proc/sys/kernel/random",
    "allow/lpath,rpath+/proc/sys/kernel/random/*id",
    "mask+/proc/sys/kernel/random/boot_id:/proc/sys/kernel/random/uuid",
    "mask+/proc/sys/kernel/random/uuid:/proc/sys/kernel/random/uuid",
    // Done /proc masking, move on!
    //
    // Wait, there is more!
    // SAFETY: Mask critical /sys paths as an extra layer.
    // Extra layer because this profile allows no access
    // to the sysfs directory otherwise.
    "mask+/sys/dev/***:/dev/null:/var/empty",
    "mask+/sys/devices/***:/dev/null:/var/empty",
    "mask+/sys/firmware/***:/dev/null:/var/empty",
    "mask+/sys/fs/***:/dev/null:/var/empty",
    // SAFETY: Provide an empty file in place of /sys/kernel/notes.
    // See: https://lwn.net/Articles/962782/
    // As of 3.36.0, we extend it to the directory recursively.
    "mask+/sys/kernel/***:/dev/null:/var/empty",
    // Done /sys masking, move on!
    "allow/lpath,rpath+/proc/self",
    "allow/lpath,rpath+/proc/thread-self",
    "allow/lpath,rpath+/proc/self/comm",
    "allow/lpath,rpath+/proc/self/task/[0-9]*/comm",
    "allow/lpath,rpath+/proc/self/cmdline",
    "allow/lpath,rpath+/proc/self/task/[0-9]*/cmdline",
    "allow/lpath,rpath+/proc/self/fd",
    "allow/lpath,rpath+/proc/self/fdinfo",
    "allow/lpath,rpath+/proc/self/task",
    "allow/lpath,rpath+/proc/self/task/[0-9]*",
    "allow/lpath,rpath+/proc/self/task/[0-9]*/fd",
    "allow/lpath,rpath+/proc/self/task/[0-9]*/fdinfo",
    // SAFETY: Avoid assigning wpath and ioctl sets
    // on /proc/self/{cwd,exe,root} magic symlinks
    // to provide hardening against container breaks.
    "allow/lpath,rpath+/proc/self/cwd",
    "allow/lpath,rpath+/proc/self/task/[0-9]*/cwd",
    "allow/lpath,rpath+/proc/self/exe",
    "allow/lpath,rpath+/proc/self/task/[0-9]*/exe",
    "allow/lpath,rpath+/proc/self/root",
    "allow/lpath,rpath+/proc/self/task/[0-9]*/root",
    "allow/lpath,rpath+/proc/self/fdinfo/[0-9]*",
    "allow/lpath,rpath+/proc/self/task/[0-9]*/fdinfo/[0-9]*",
    "allow/lpath,rpath,wpath,ioctl+/proc/self/fd/[0-9]*",
    "allow/lpath,rpath,wpath,ioctl+/proc/self/task/[0-9]*/fd/[0-9]*",
    r"allow/lpath,rpath,wpath,ioctl+/proc/self/fd/anon_inode:\[pidfd\]",
    r"allow/lpath,rpath,wpath,ioctl+/proc/self/fd/pipe:\[[0-9]*\]",
    r"allow/lpath,rpath,wpath,ioctl+/proc/self/fd/socket:\[[0-9]*\]",
    r"allow/lpath,rpath,wpath,ioctl+/proc/self/task/[0-9]*/fd/anon_inode:\[pidfd\]",
    r"allow/lpath,rpath,wpath,ioctl+/proc/self/task/[0-9]*/fd/pipe:\[[0-9]*\]",
    r"allow/lpath,rpath,wpath,ioctl+/proc/self/task/[0-9]*/fd/socket:\[[0-9]*\]",
    // /run
    "allow/lpath,rpath+/run",
    "allow/lpath,rpath+/run/systemd",
    "allow/lpath,rpath+/run/systemd/resolve",
    "allow/lpath,rpath+/run/systemd/resolve/*.conf",
    // /var
    "allow/lpath,rpath+/var",
    "allow/lpath,rpath+/var/lib/sss/mc/passwd", // Required for LDAP.
    "allow/lpath,rpath+/var/lib/sss/mc/group",  // ditto.
    "allow/lpath,rpath,chroot+/var/empty",      // Allow daemons to chroot.
    // /etc
    "allow/lpath,rpath+/etc",
    "allow/lpath,rpath+/etc/DIR_COLORS",
    "allow/lpath,rpath+/etc/GREP_COLORS",
    "allow/lpath,rpath+/etc/bash*/***",
    "allow/lpath,rpath+/etc/alternatives/***",
    "allow/lpath,rpath+/etc/ca-certificates/***",
    "allow/lpath,rpath+/etc/env.d/***",
    "allow/lpath,rpath+/etc/groff/***",
    "allow/lpath,rpath+/etc/ld.so.conf.d/***",
    "allow/lpath,rpath+/etc/environment",
    "allow/lpath,rpath+/etc/ethertypes",
    "allow/lpath,rpath+/etc/group",
    "allow/lpath,rpath+/etc/hosts",
    "allow/lpath,rpath+/etc/inputrc",
    "allow/lpath,rpath+/etc/issue",
    "allow/lpath,rpath+/etc/ld*",
    "allow/lpath,rpath+/etc/locale.alias",
    "allow/lpath,rpath+/etc/locale.conf",
    "allow/lpath,rpath+/etc/localtime",
    "mask+/etc/localtime:/usr/share/zoneinfo/UTC", // prevent leaking the timezone.
    "mask+/usr/share/zoneinfo/**:/usr/share/zoneinfo/UTC:/var/empty", // ditto.
    "allow/lpath,rpath+/etc/machine-id", // randomized, unless trace/allow_unsafe_machine_id:1.
    "allow/lpath,rpath+/etc/hostid",     // ditto.
    "allow/lpath,rpath+/var/adm/hostid", // ditto.
    "allow/lpath,rpath+/etc/man_db.conf",
    "allow/lpath,rpath+/etc/nanorc",
    "allow/lpath,rpath+/etc/**/nsswitch.conf",
    "allow/lpath,rpath+/etc/passwd",
    "allow/lpath,rpath+/etc/profile*/***",
    "allow/lpath,rpath+/etc/services",
    "allow/lpath,rpath+/etc/*-release",
    "allow/lpath,rpath+/etc/protocols",
    "allow/lpath,rpath+/etc/resolv.conf",
    "allow/lpath,rpath+/etc/skel/***",
    "allow/stat,chdir,readdir+/etc/ssl",
    "allow/lpath,rpath+/etc/ssl/certs/***",
    "allow/lpath,rpath+/etc/ssl/misc/***",
    "allow/lpath,rpath+/etc/ssl/openssl.cnf",
    "allow/lpath,rpath+/etc/terminfo/***",
    "allow/lpath,rpath+/etc/zsh/***",
    // /home
    //
    // Do _not_ allow readdir which allows enumerating other users!
    "allow/lpath,chdir+/home",
    // Defaults for Network sandboxing:
    //
    // Allow network access to unnamed UNIX sockets.
    "allow/net+!unnamed",
];

/// Profile to allowlist TTY ioctls without path check, used by oci,
/// paludis and user profiles.
/// Syd sets the environment variable TTY before parsing this profile.
pub const PROFILE_TTY: &[&str] = &[
    // Allow safe ioctl requests without path check.
    "include_profile tty_native",
    // TTY lock rules to be used with Landlock.
    "allow/lock/read,ioctl,write+/dev/ptmx",
    "allow/lock/read,ioctl,write+/dev/tty",
    "allow/lock/read,ioctl,write+${SYD_TTY}",
    "allow/lock/rpath,ioctl,write+/dev/pts",
    // TTY seccomp rules to act as the second layer.
    "allow/lpath,rpath,wpath,ioctl+/dev/ptmx",
    "allow/lpath,rpath,wpath,ioctl+/dev/tty",
    "allow/lpath,rpath,wpath,ioctl+${SYD_TTY}",
    "allow/lpath,rpath,wpath,ioctl+/dev/pts/ptmx",
    "allow/lpath,rpath,wpath,ioctl+/dev/pts/[0-9]*/***",
];

/// Profile to allowlist TTY-native ioctls without path check.
pub const PROFILE_TTY_NATIVE: &[&str] = &[
    "ioctl/allow+TIOCGPGRP",
    "ioctl/allow+TIOCSPGRP",
    "ioctl/allow+TIOCGSID",
    "ioctl/allow+TCFLSH",
    "ioctl/allow+TCGETA",
    "ioctl/allow+TCGETS",
    "ioctl/allow+TCGETS2",
    "ioctl/allow+TCGETX",
    "ioctl/allow+TCSETA",
    "ioctl/allow+TCSETAF",
    "ioctl/allow+TCSETAW",
    "ioctl/allow+TCSETS",
    "ioctl/allow+TCSETS2",
    "ioctl/allow+TCSETSF",
    "ioctl/allow+TCSETSF2",
    "ioctl/allow+TCSETSW",
    "ioctl/allow+TCSETSW2",
    "ioctl/allow+TCSETX",
    "ioctl/allow+TCSETXF",
    "ioctl/allow+TCSETXW",
    "ioctl/allow+TCXONC",
    "ioctl/allow+TIOCGLCKTRMIOS",
    "ioctl/allow+TIOCSLCKTRMIOS",
    "ioctl/allow+TIOCGWINSZ",
    "ioctl/allow+TIOCSWINSZ",
    "ioctl/allow+TIOCGDEV",
    "ioctl/allow+TIOCGEXCL",
    "ioctl/allow+TIOCGPKT",
    "ioctl/allow+TIOCGPTLCK",
    "ioctl/allow+TIOCGPTN",
    "ioctl/allow+TIOCGPTPEER",
    "ioctl/allow+TIOCSCTTY",
    "ioctl/allow+TIOCSIG",
    "ioctl/allow+TIOCVHANGUP",
    "ioctl/allow+TIOCGPKT",
    "ioctl/allow+TIOCGPTLCK",
    "ioctl/allow+TIOCGPTPEER",
    "ioctl/allow+TIOCPKT",
    "ioctl/allow+TIOCSPTLCK",
];

/// Profile to allowlist KVM ioctls without path check.
/// Read: https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt
pub const PROFILE_KVM: &[&str] = &[
    "allow/wpath,ioctl+/dev/kvm",
    "include_profile kvm_native",
    "ioctl/allow+KVM_GET_API_VERSION",
    "ioctl/allow+KVM_CREATE_VM",
    "ioctl/allow+KVM_GET_VCPU_MMAP_SIZE",
    "ioctl/allow+KVM_CREATE_VCPU",
    "ioctl/allow+KVM_GET_DIRTY_LOG",
    "ioctl/allow+KVM_SET_TSS_ADDR",
    "ioctl/allow+KVM_RUN",
    "ioctl/allow+KVM_NMI",
    "ioctl/allow+KVM_CHECK_EXTENSION",
    "ioctl/allow+KVM_GET_TSC_KHZ",
    "ioctl/allow+KVM_SET_TSC_KHZ",
    "ioctl/allow+KVM_INTERRUPT",
    "ioctl/allow+KVM_SET_MSRS",
    "ioctl/allow+KVM_SET_USER_MEMORY_REGION",
    "ioctl/allow+KVM_SET_REGS",
    "ioctl/allow+KVM_SET_SREGS",
    "ioctl/allow+KVM_GET_MSRS",
    "ioctl/allow+KVM_GET_REGS",
    "ioctl/allow+KVM_GET_SREGS",
    "ioctl/allow+KVM_GET_SUPPORTED_CPUID",
    "ioctl/allow+KVM_GET_EMULATED_CPUID",
    "ioctl/allow+KVM_SET_CPUID2",
    "ioctl/allow+KVM_SET_SIGNAL_MASK",
    "ioctl/allow+KVM_GET_VCPU_EVENTS",
    "ioctl/allow+KVM_SET_VCPU_EVENTS",
    "ioctl/allow+KVM_SET_DEVICE_ATTR",
    "ioctl/allow+KVM_SET_IDENTITY_MAP_ADDR",
    "ioctl/allow+KVM_CREATE_IRQCHIP",
    "ioctl/allow+KVM_IRQ_LINE",
    "ioctl/allow+KVM_REGISTER_COALESCED_MMIO",
    "ioctl/allow+KVM_UNREGISTER_COALESCED_MMIO",
    "ioctl/allow+KVM_SET_GSI_ROUTING",
    "ioctl/allow+KVM_IRQFD",
    "ioctl/allow+KVM_IOEVENTFD",
    "ioctl/allow+KVM_GET_MP_STATE",
    "ioctl/allow+KVM_SET_MP_STATE",
    "ioctl/allow+KVM_SIGNAL_MSI",
    "ioctl/allow+KVM_SET_GUEST_DEBUG",
    "ioctl/allow+KVM_CREATE_DEVICE",
    "ioctl/allow+KVM_SET_DEVICE_ATTR",
    "ioctl/allow+KVM_GET_DEVICE_ATTR",
    "ioctl/allow+KVM_HAS_DEVICE_ATTR",
];

/// Profile to allowlist KVM arch-native ioctls without path check.
#[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
pub const PROFILE_KVM_NATIVE: &[&str] = &[
    "ioctl/allow+0x4680aea3",         // _KVM_ENABLE_CAP
    "ioctl/allow+0x4010aeab",         // _KVM_GET_ONE_REG
    "ioctl/allow+0x4010aeac",         // _KVM_SET_ONE_REG
    "ioctl/allow+0xc008aeb0",         // _KVM_GET_REG_LIST
    "ioctl/allow+5",                  // _KVM_ARM_TARGET_GENERIC_V8
    "ioctl/allow+0x8020aeaf",         // _KVM_ARM_PREFERRED_TARGET
    "ioctl/allow+0x4020aeae",         // _KVM_ARM_VCPU_INIT
    "ioctl/allow+0x4040aec2",         // _KVM_ARM_VCPU_FINALIZE
    "ioctl/allow+0x6030000000100042", // _KVM_ARM64_REGS_PSTATE
    "ioctl/allow+0x6030000000100044", // _KVM_ARM64_REGS_SP_EL1
    "ioctl/allow+0x6030000000100000", // _KVM_ARM64_REGS_R0
    "ioctl/allow+0x6030000000100002", // _KVM_ARM64_REGS_R1
    "ioctl/allow+0x6030000000100004", // _KVM_ARM64_REGS_R2
    "ioctl/allow+0x6030000000100006", // _KVM_ARM64_REGS_R3
    "ioctl/allow+0x6030000000100010", // _KVM_ARM64_REGS_R8
    "ioctl/allow+0x6030000000100024", // _KVM_ARM64_REGS_R18
    "ioctl/allow+0x6030000000100040", // _KVM_ARM64_REGS_PC
    "ioctl/allow+0x603000000013c510", // _KVM_ARM64_REGS_MAIR_EL1
    "ioctl/allow+0x603000000013c102", // _KVM_ARM64_REGS_TCR_EL1
    "ioctl/allow+0x603000000013c100", // _KVM_ARM64_REGS_TTBR0_EL1
    "ioctl/allow+0x603000000013c101", // _KVM_ARM64_REGS_TTBR1_EL1
    "ioctl/allow+0x603000000013c080", // _KVM_ARM64_REGS_SCTLR_EL1
    "ioctl/allow+0x603000000013c082", // _KVM_ARM64_REGS_CPACR_EL1
    "ioctl/allow+0x603000000013c600", // _KVM_ARM64_REGS_VBAR_EL1
    "ioctl/allow+0x603000000013df1a", // _KVM_ARM64_REGS_TIMER_CNT
    "ioctl/allow+0x603000000013df00", // _KVM_ARM64_REGS_CNTFRQ_EL0
    "ioctl/allow+0x6030000000138012", // _KVM_ARM64_REGS_MDSCR_EL1
    "ioctl/allow+0x603000000013c708", // _KVM_ARM64_REGS_CNTKCTL_EL1
    "ioctl/allow+0x603000000013c684", // _KVM_ARM64_REGS_TPIDR_EL1
];

/// Profile to allowlist KVM arch-native ioctls without path check.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub const PROFILE_KVM_NATIVE: &[&str] = &[
    "ioctl/allow+0x0",        // _KVM_VCPU_TSC_CTRL
    "ioctl/allow+0x0",        // _KVM_VCPU_TSC_OFFSET
    "ioctl/allow+0xc004ae02", // _KVM_GET_MSR_INDEX_LIST
    "ioctl/allow+0xc004ae0a", // _KVM_GET_MSR_FEATURE_INDEX_LIST
    "ioctl/allow+0x4040ae77", // _KVM_CREATE_PIT2
    "ioctl/allow+0xc208ae62", // _KVM_GET_IRQCHIP
    "ioctl/allow+0x4208ae63", // _KVM_SET_IRQCHIP
    "ioctl/allow+0x4030ae7b", // _KVM_SET_CLOCK
    "ioctl/allow+0x8030ae7c", // _KVM_GET_CLOCK
    "ioctl/allow+0x8070ae9f", // _KVM_GET_PIT2
    "ioctl/allow+0x4070aea0", // _KVM_SET_PIT2
    "ioctl/allow+0xc008aeba", // _KVM_MEMORY_ENCRYPT_OP
    "ioctl/allow+0x8010aebb", // _KVM_MEMORY_ENCRYPT_REG_REGION
    "ioctl/allow+0x8010aebc", // _KVM_MEMORY_ENCRYPT_UNREG_REGION
    "ioctl/allow+0xc018ae85", // _KVM_TRANSLATE
    "ioctl/allow+0x81a0ae8c", // _KVM_GET_FPU
    "ioctl/allow+0x41a0ae8d", // _KVM_SET_FPU
    "ioctl/allow+0x8400ae8e", // _KVM_GET_LAPIC
    "ioctl/allow+0x4400ae8f", // _KVM_SET_LAPIC
    "ioctl/allow+0x4008ae90", // _KVM_SET_CPUID2
    "ioctl/allow+0xc008ae91", // _KVM_GET_CPUID2
    "ioctl/allow+0x8080aea1", // _KVM_GET_DEBUGREGS
    "ioctl/allow+0x4080aea2", // _KVM_SET_DEBUGREGS
    "ioctl/allow+0x9000aea4", // _KVM_GET_XSAVE
    "ioctl/allow+0x5000aea5", // _KVM_SET_XSAVE
    "ioctl/allow+0x8188aea6", // _KVM_GET_XCRS
    "ioctl/allow+0x4188aea7", // _KVM_SET_XCRS
    "ioctl/allow+0xaead",     // _KVM_KVMCLOCK_CTRL
];

/// Profile to allowlist KVM arch-native ioctls without path check.
#[cfg(not(any(
    target_arch = "arm",
    target_arch = "x86",
    target_arch = "x86_64",
    target_arch = "aarch64"
)))]
pub const PROFILE_KVM_NATIVE: &[&str] = &[];

/// The list of eBPF family syscalls
pub const EBPF_SYSCALLS: &[&str] = &["bpf", "uretprobe"];

/// The list of mount family syscalls
pub const MOUNT_SYSCALLS: &[&str] = &[
    "fsconfig",
    "fsmount",
    "fsopen",
    "fspick",
    "listmount",
    "mount",
    "mount_setattr",
    "open_tree",
    "open_tree_attr",
    "statmount",
    "umount",
    "umount2",
];

/// The list of process, i/o priority changing system calls.
pub const NICE_SYSCALLS: &[&str] = &[
    "ioprio_set",
    "sched_setattr",
    "sched_setscheduler",
    "sched_setparam",
    "setpriority",
];

/// The list of page cache system calls.
pub const PAGE_CACHE_SYSCALLS: &[&str] = &["cachestat", "mincore"];

/// The list of perf/debugging system calls.
pub const PERF_SYSCALLS: &[&str] = &[
    "lookup_dcookie",
    "perf_event_open",
    "rtas",
    "s390_runtime_instr",
    "sys_debug_setcontext",
];

/// The list of ptrace system calls.
pub const PTRACE_SYSCALLS: &[&str] = &[
    "kcmp",
    "pidfd_getfd",
    "ptrace",
    "process_madvise",
    "process_vm_readv",
    "process_vm_writev",
];

/// The list of system calls which are of epoll family.
pub const EPOLL_SYSCALLS: &[&str] = &[
    // SAFETY: epoll fd is created once at startup,
    // before the seccomp filters have been loaded.
    // "epoll_create",
    // "epoll_create1",
    "epoll_ctl",
    "epoll_ctl_old",
    "epoll_wait",
    "epoll_wait_old",
    "epoll_pwait",
    "epoll_pwait2",
];

/// The list of system calls which are of UTS family.
pub const UTS_SYSCALLS: &[&str] = &["setdomainname", "sethostname"];

/// The list of system calls which are of the getid family.
pub const GET_ID_SYSCALLS: &[&str] = &[
    "getuid",
    "getuid32",
    "getgid",
    "getgid32",
    "geteuid",
    "geteuid32",
    "getegid",
    "getegid32",
    "getresuid",
    "getresuid32",
    "getresgid",
    "getresgid32",
    "getgroups",
    "getgroups32",
];

/// The list of system calls which are of the fadvise family.
pub const FADVISE_SYSCALLS: &[&str] = &["arm_fadvise64_64", "fadvise64", "fadvise64_64"];

/// The list of system calls which are of the futex family.
pub const FUTEX_SYSCALLS: &[&str] = &[
    "futex",
    "futex_requeue",
    "futex_time64",
    "futex_wait",
    "futex_waitv",
    "futex_wake",
    "swapcontext",
    "sys_debug_swapcontext",
];

/// The list of system calls which are of the setid family.
pub const SET_ID_SYSCALLS: &[&str] = &[
    "setuid",
    "setuid32",
    "setgid",
    "setgid32",
    "setreuid",
    "setreuid32",
    "setregid",
    "setregid32",
    "setresuid",
    "setresuid32",
    "setresgid",
    "setresgid32",
];

/// SAFETY: We do not support diverging FsID from Effective ID.
/// SAFETY: We do not support setgroups (due to pointer deref -> TOCTOU vector)
pub const UNSAFE_ID_SYSCALLS: &[&str] = &["setgroups", "setgroups32"];

/// The list of system calls which are in vDSO.
///
/// This set is always allowed for backwards compatibility.
pub const VDSO_SYSCALLS: &[&str] = &[
    "clock_getres",
    "clock_getres_time64",
    "clock_gettime",
    "clock_gettime64",
    "getcpu",
    "getrandom",
    "gettimeofday",
    "time",
];

/// The list of system calls which syd has a `UNotify` callback for
pub const HOOK_SYSCALLS: &[&str] = &[
    "accept",
    "accept4",
    "bind",
    "connect",
    "getpeername",
    "getsockname",
    "getsockopt",
    "recvfrom",
    "recvmsg",
    "recvmmsg",
    "recvmmsg_time64",
    "sendto",
    "sendmsg",
    "sendmmsg",
    "socket",
    "socketcall",
    "socketpair",
    "execve",
    "execveat",
    "getdents64",
    "stat",
    "access",
    "fstat",
    "fstat64",
    "fstatat64",
    "lstat",
    "newfstatat",
    "stat64",
    "statx",
    "faccessat",
    "faccessat2",
    "chdir",
    "fchdir",
    "chmod",
    "fchmod",
    "fchmodat",
    "fchmodat2",
    "fchown",
    "fchown32",
    "chown",
    "lchown",
    "fchownat",
    "creat",
    "link",
    "symlink",
    "unlink",
    "linkat",
    "symlinkat",
    "unlinkat",
    "mkdir",
    "rmdir",
    "mkdirat",
    "mknod",
    "mknodat",
    "open",
    "openat",
    "openat2",
    "rename",
    "renameat",
    "renameat2",
    "utime",
    "utimes",
    "futimesat",
    "utimensat",
    "truncate",
    "truncate64",
    "ftruncate",
    "ftruncate64",
    "getxattr",
    "getxattrat",
    "fgetxattr",
    "lgetxattr",
    "setxattr",
    "setxattrat",
    "fsetxattr",
    "lsetxattr",
    "listxattr",
    "listxattrat",
    "flistxattr",
    "llistxattr",
    "removexattr",
    "removexattrat",
    "fremovexattr",
    "lremovexattr",
    "ioctl",
    "prctl",
    "kill",
    "tkill",
    "tgkill",
    "rt_sigqueueinfo",
    "rt_tgsigqueueinfo",
    "pidfd_open",
    "brk",
    "mmap",
    "mmap2",
    "mremap",
    "setrlimit",
    "prlimit64",
    "statfs",
    "statfs64",
    "fstatfs",
    "fstatfs64",
    "fallocate",
    "uname",
    "fanotify_mark",
    "inotify_add_watch",
    "memfd_create",
    "fcntl",
    "fcntl64",
    "sysinfo",
    "sigaction",
    "rt_sigaction",
    "chroot",
    "syslog",
];

// The list of socketcall(2) subcalls to hook for sandboxing.
//
// This list must be sorted because it's binary searched.
pub(crate) const HOOK_SCKCALLS: &[u8] = &[
    0x1,  // socket
    0x2,  // bind
    0x3,  // connect
    0x5,  // accept
    0x6,  // getsockname
    0x7,  // getpeername
    0x8,  // socketpair
    0x9,  // send
    0xb,  // sendto
    0xc,  // recvfrom
    0xf,  // getsockopt
    0x10, // sendmsg
    0x11, // recvmsg
    0x12, // accept4
    0x13, // recvmmsg
    0x14, // sendmmsg
];

/// The list of system calls which are confined by the Stat sandboxing category.
///
/// Note, this list _must_ be sorted!
pub const STAT_SYSCALLS: &[&str] = &[
    "access",
    "faccessat",
    "faccessat2",
    "fanotify_mark",
    "fgetxattr",
    "flistxattr",
    "fstatat64",
    "fstatfs",
    "fstatfs64",
    "getxattr",
    "getxattrat",
    "inotify_add_watch",
    "lgetxattr",
    "listxattr",
    "listxattrat",
    "llistxattr",
    "lstat",
    "lstat64",
    "newfstatat",
    "stat",
    "stat64",
    "statfs",
    "statfs64",
    "statx",
];

/// The list of system calls which are confined by the Rename sandboxing category.
///
/// Note, this list _must_ be sorted!
pub const RENAME_SYSCALLS: &[&str] = &["link", "linkat", "rename", "renameat", "renameat2"];

/// The list of system calls which are confined by the Truncate sandboxing category.
///
/// Note, this list _must_ be sorted!
pub const TRUNCATE_SYSCALLS: &[&str] = &[
    "fallocate",
    "ftruncate",
    "ftruncate64",
    "truncate",
    "truncate64",
];

/// The list of system calls which are confined by the Connect network sandboxing category.
///
/// Note, this list _must_ be sorted!
pub const CONNECT_SYSCALLS: &[&str] = &["connect", "sendmmsg", "sendmsg", "sendto"];

/// The list of system calls which are for CPU emulation functionality.
pub const CPU_SYSCALLS: &[&str] = &[
    "modify_ldt",
    "subpage_prot",
    "switch_endian",
    "vm86",
    "vm86old",
];

/// The list of system calls which are for Kernel keyring access.
pub const KEYRING_SYSCALLS: &[&str] = &["add_key", "keyctl", "request_key"];

/// The list of system calls which are used for memory protection keys.
pub const PKEY_SYSCALLS: &[&str] = &["pkey_alloc", "pkey_free", "pkey_mprotect"];

/// The list of system calls which are deprecated.
pub const DEPRECATED_SYSCALLS: &[&str] = &[
    "_sysctl",
    //"oldfstat",    // fstat(2) is provided by Syd.
    //"oldolduname", // uname(2) is provided by Syd.
    //"olduname",    // ditto.
    "remap_file_pages",
    "setfsgid",
    "setfsgid32",
    "setfsuid",
    "setfsuid32",
    "stime",
    "uselib",
    "ustat",
];

/// The list of system calls which are part of time/clock adjustment.
pub const TIME_SYSCALLS: &[&str] = &[
    "adjtimex",
    "clock_adjtime",
    "clock_adjtime64",
    "clock_settime",
    "clock_settime64",
    "settimeofday",
    //"stime", deprecated.
];

/// The list of system calls for filesystem sync.
/// SAFETY: By default sync(2), syncfs(2) are no-ops to prevent potential local DoS.
pub const SYNC_SYSCALLS: &[&str] = &["sync", "syncfs"];

/// The list of system calls which are part of the io_uring interface.
pub const IOURING_SYSCALLS: &[&str] = &["io_uring_enter", "io_uring_register", "io_uring_setup"];

#[cfg(feature = "prof")]
/// The list of system calls which are used by gperf for profiling.
///
/// Empty in case `prof` feature is disabled.
/// Note we also allow open(2), openat(2), lstat(2), stat(2), and
/// write(2) syscalls for the main thread if profiling is enabled.
pub const PROF_SYSCALLS: &[&str] = &["setitimer"];

#[cfg(not(feature = "prof"))]
/// The list of system calls which are used by gperf for profiling.
///
/// Empty in case `prof` feature is disabled.
/// Note we also allow open(2), openat(2), lstat(2), stat(2), and
/// write(2) syscalls for the main thread if profiling is enabled.
pub const PROF_SYSCALLS: &[&str] = &[];

/// The list of system calls which are allowlisted without any filtering.
pub const SAFE_SYSCALLS: &[&str] = &[
    "_llseek",
    "_newselect",
    //"_sysctl", deprecated
    //"accept",
    //"accept4",
    //"acct", // CAP_SYS_PACCT
    //add_key, restrictions applied, see setup_seccomp.
    //adjtimex, restrictions applied, see setup_seccomp.
    //afs_syscall, unimplemented
    "alarm",
    "arch_prctl", // Used during platform-specific initialization by ld-linux.so.
    "arm_fadvise64_64",
    "arm_sync_file_range",
    "atomic_barrier",
    "atomic_cmpxchg_32",
    //"bpf", restrictions applied, see setup_seccomp.
    "breakpoint", // arm
    //"brk",
    //"cachestat", // moved to page_cache syscalls as of 3.35.2.
    "cacheflush", // arm
    "capget",
    "capset",
    //"chdir",
    //"chroot",
    //clock_adjtime, restrictions applied, see setup_seccomp.
    //clock_adjtime64, restrictions applied, see setup_seccomp.
    //"clock_getres", part of vDSO-syscalls.
    //"clock_getres_time64", ditto.
    //"clock_gettime", ditto.
    //"clock_gettime64", ditto.
    "clock_nanosleep",
    "clock_nanosleep_time64",
    //"clock_settime", restrictions applied, see setup_seccomp.
    //"clock_settime64", ditto
    "clone", // CLONE_NEW* is restricted in parent filter.
    // "clone3", // unsafe because namespaces cannot be restricted.
    "close",
    "close_range",
    "copy_file_range",
    //create_module
    //delete_module
    "dup",
    "dup2",
    "dup3",
    "epoll_create",
    "epoll_create1",
    "epoll_ctl",
    "epoll_ctl_old",
    "epoll_pwait",
    "epoll_pwait2",
    "epoll_wait",
    "epoll_wait_old",
    "eventfd",
    "eventfd2",
    "exit",
    "exit_group",
    "fadvise64",
    "fadvise64_64",
    //"fallocate",
    "fanotify_init",
    //"fanotify_mark", device side-channel mitigations
    //"fchdir",
    //"fchmod",
    //"fchown",
    //"fchown32",
    //"fcntl", restrictions applied for appendonly!
    //"fcntl64", ditto
    "fdatasync",
    //finit_module
    "flock",
    "fork",
    //fsconfig
    //fsmount
    //fsopen
    //fspick
    //"fstat",
    //"fstat64",
    //"oldfstat",
    //"fstatfs",
    //"fstatfs64",
    "fsync",
    //"ftruncate",
    //"ftruncate64",
    // "futex", See: FUTEX_SYSCALLS for futex family.
    //get_kernel_syms
    "getpagesize",
    "get_mempolicy",
    "get_robust_list",
    "get_thread_area",
    //"getcpu", part of vDSO-syscalls.
    "getcwd",
    //"getdents",
    //"getdents64",
    //"getegid",
    //"getegid32",
    //"geteuid",
    //"geteuid32",
    //"getgid",
    //"getgid32",
    "getgroups",
    "getgroups32",
    "getitimer",
    //"getpeername",
    "getpgid",
    "getpgrp",
    "getpid",
    "getpmsg",
    "getppid",
    "getpriority",
    //"getrandom", part of vDSO-syscalls.
    "getresgid",
    "getresuid",
    "getrlimit",
    "getrusage",
    "getsid",
    // "getuid", See: GET_ID_SYSCALLS for getid family.
    //"getsockname",
    //"getsockopt",
    "gettid",
    //"gettimeofday", part of vDSO-syscalls.
    //init_module
    //"inotify_add_watch",
    "inotify_init",
    "inotify_init1",
    "inotify_rm_watch",
    "io_cancel",
    "io_destroy",
    "io_getevents",
    "io_pgetevents",
    "io_pgetevents_time64",
    "io_setup",
    "io_submit",
    /*
     * io-uring: restrictions applied, see setup_seccomp.
    "io_uring_enter",
    "io_uring_register",
    "io_uring_setup",
    */
    //"ioctl", restrictions applied, see setup_seccomp.
    //"ioperm", // CAP_SYS_RAWIO
    //"iopl", // CAP_SYS_RAWIO
    "ioprio_get",
    //"ioprio_set", restrictions applied, see setup_seccomp.
    //"kcmp", part of PTRACE_SYSCALLS now as of 3.33.0.
    //kexec_file_load,
    //kexec_load,
    //keyctl, restrictions applied, see setup_seccomp.
    //"kill", restrictions applied, see setup_seccomp.
    "landlock_add_rule",
    "landlock_create_ruleset",
    "landlock_restrict_self",
    "listen",
    //"lookup_dcookie", restrictions applied, see setup_seccomp.
    "lseek",
    //"madvise", restrictions applied, see setup_seccomp.
    "map_shadow_stack",
    //"mbind", restrictions applied, see setup_seccomp.
    "membarrier",
    //"memfd_create",
    //"memfd_secret",
    //"migrate_pages",
    //"mincore", NO! https://arxiv.org/pdf/1901.01161
    "mlock",
    "mlock2",
    "mlockall",
    //"mmap",
    //"mmap2",
    //"modify_ldt", restrictions applied, see setup_seccomp.
    //"mount", restrictions applied, see setup_seccomp.
    //"mount_setattr", // ditto
    //"move_pages",
    "mprotect",
    "mq_getsetattr",
    "mq_notify",
    //"mq_open", restrictions applied, see setup_seccomp.
    "mq_timedreceive",
    "mq_timedreceive_time64",
    "mq_timedsend",
    "mq_timedsend_time64",
    "mq_unlink",
    //"mremap",
    "mseal",
    //"msgctl", restrictions applied, see setup_seccomp.
    //"msgget", restrictions applied, see setup_seccomp.
    "msgrcv",
    //"msgsnd", restrictions applied, see setup_seccomp.
    "msync",
    "munlock",
    "munlockall",
    "munmap",
    //name_to_handle_at
    "nanosleep",
    //nfsservctl,
    //"open_by_handle_at",
    //open_tree
    "pause",
    //"perf_event_open", restrictions applied see load_seccomp_parent and setup_seccomp.
    //"personality", restrictions applied, see setup_seccomp.
    //"pidfd_getfd", added to ptrace set as of 3.35.2.
    //"pidfd_open", restrictions applied, see setup_seccomp.
    "pidfd_send_signal",
    "pipe",
    //"pipe2", restrictions applied, see setup_seccomp.
    //pivot_root,
    //"pkey_alloc", restrictions applied, see setup_seccomp.
    //"pkey_free", ditto
    //"pkey_mprotect", ditto
    "poll",
    "ppoll",
    "ppoll_time64",
    // "prctl", restrictions applied, see setup_seccomp.
    "pread64",
    "preadv",
    "preadv2",
    //"prlimit64",
    //"process_madvise", added to ptrace set as of 3.35.2.
    "process_mrelease",
    //process_vm_readv // restrictions applied, see setup_seccomp.
    //process_vm_writev // ditto.
    "pselect6",
    "pselect6_time64",
    //"ptrace", // restrictions applied see load_seccomp_parent and setup_seccomp.
    //"putpmsg",
    "pwrite64",
    "pwritev",
    //"pwritev2", // restrictions applied see setup_seccomp.
    //query_module,
    //quotactl
    //quotactl_fd
    "read",
    "readahead",
    "readlink",
    "readlinkat",
    "readv",
    //reboot
    "recv",
    //"recvfrom", // hooked for informational purposes.
    //"recvmmsg", // ditto
    //"recvmmsg_time64", // ditto
    //"recvmsg", // ditto
    //"remap_file_pages", // deprecated, prot _must_ be 0, not security critical.
    //request_key, restrictions applied, see setup_seccomp.
    "restart_syscall",
    "riscv_flush_icache",
    //"riscv_hwprobe", info leak, see: https://www.kernel.org/doc/html/v6.6/riscv/hwprobe.html
    //"rseq", restrictions applied, see setup_seccomp.
    //"rt_sigaction", SA_RESTART tracking.
    "rt_sigpending",
    "rt_sigprocmask",
    //"rt_sigqueueinfo", restrictions applied, see setup_seccomp.
    //"rt_sigreturn", SROP mitigations
    "rt_sigsuspend",
    "rt_sigtimedwait",
    "rt_sigtimedwait_time64",
    //"rt_tgsigqueueinfo", restrictions applied, see setup_seccomp.
    "s390_pci_mmio_read",
    "s390_pci_mmio_write",
    "s390_runtime_instr",
    "sched_get_priority_max",
    "sched_get_priority_min",
    "sched_getaffinity",
    "sched_getattr",
    "sched_rr_get_interval",
    "sched_rr_get_interval_time64",
    "sched_getparam",
    "sched_getscheduler",
    "sched_setaffinity",
    //"sched_setattr", restrictions applied, see setup_seccomp.
    //"sched_setscheduler", restrictions applied, see setup_seccomp.
    //"sched_setparam", restrictions applied, see setup_seccomp.
    "sched_yield",
    //"seccomp", restrictions applied, see setup_seccomp.
    //security, unimplemented
    "select",
    //"semctl", restrictions applied, see setup_seccomp.
    //"semget", restrictions applied, see setup_seccomp.
    "semop",
    "semtimedop",
    "semtimedop_time64",
    "send",
    "sendfile",
    "sendfile64",
    //"sendmmsg", emulated.
    //"sendmsg", emulated.
    "set_mempolicy",
    "set_mempolicy_home_node",
    "set_robust_list",
    "set_thread_area",
    "set_tid_address",
    //"setdomainname", added to uts set as of 3.35.2.
    //"setfsgid",
    //"setfsgid32",
    //"setfsuid",
    //"setfsuid32",
    //"setgid",
    //"setgid32",
    //"setgroups",
    //"setgroups32",
    //"sethostname", added to uts set as of 3.35.2.
    "setitimer",
    "setns", // restrictions applied in load_seccomp_parent.
    "setpgid",
    //"setpriority", restrictions applied, see setup_seccomp.
    //"setregid",
    //"setregid32",
    //"setresgid",
    //"setresgid32",
    //"setresuid",
    //"setresuid32",
    //"setreuid",
    //"setreuid32",
    //"setrlimit",
    "setsid",
    "setsockopt",
    //"settimeofday"
    //"setuid",
    //"setuid32",
    "set_tls", // arm
    //"sgetmask", // x86, OBSOLETE!
    //"ssetmask", // x86, OBSOLETE!
    //"shmat", restrictions applied, see setup_seccomp.
    //"shmctl", restrictions applied, see setup_seccomp.
    "shmdt",
    //"shmget", restrictions applied, see setup_seccomp.
    "shutdown",
    "signal",
    //"sigaction", SA_RESTART tracking.
    "sigaltstack",
    "signalfd",
    "signalfd4",
    "sigpending",
    "sigprocmask",
    "sigsuspend",
    //"sigreturn", SROP mitigations
    //"socket",
    //"socketpair",
    "splice",
    //"statfs",
    //"statfs64",
    //swapoff
    //swapon
    //"sync",
    "sync_file_range",
    "sync_file_range2", // arm & ppc
    //"syncfs",
    //"sysinfo", information-leak, see setup_seccomp.
    //"syslog",
    "tee",
    //"tgkill", restrictions applied, see setup_seccomp.
    //"time", part of vDSO-syscalls.
    "timer_create",
    "timer_delete",
    "timer_getoverrun",
    "timer_gettime",
    "timer_gettime64",
    "timer_settime",
    "timer_settime64",
    "timerfd_create",
    "timerfd_gettime",
    "timerfd_gettime64",
    "timerfd_settime",
    "timerfd_settime64",
    "times",
    //"tkill", an obsolete predecessor to tgkill, should be avoided.
    //tuxcall, // unimplemented
    "ugetrlimit",
    "umask",
    //"uname", restrictions applied, see setup_seccomp.
    //olduname, deprecated
    //oldolduname, deprecated
    //"umount", restrictions applied, see setup_seccomp.
    //"umount2", // ditto
    "unshare", // restrictions applied in load_seccomp_parent.
    //"uretprobe", restrictions applied, see setup_seccomp.
    //"uselib", deprecated
    // Added in Linux-4.3
    // (Ab)used by most Project Zero Linux kernel exploits.
    //"userfaultfd",
    //"ustat", deprecated
    "vfork",
    //"vhangup", // CAP_SYS_TTY_CONFIG
    //"vmsplice", // restrictions applied, see setup_seccomp.
    //vserver, unimplemented
    "wait4",
    "waitid",
    "waitpid",
    "write",
    "writev",
];

/// System calls allowed for emulator threads.
pub const EMU_SYSCALLS: &[&str] = &[
    "_llseek",
    //"accept4", protected with syscall argument cookies.
    //"bind", protected with syscall argument cookies.
    "brk",
    //"clock_gettime", part of vDSO-syscalls.
    //"clock_gettime64", part of vDSO-syscalls.
    "clock_nanosleep",
    //"clone", // CLONE_NEW* flags are restricted.
    //"clone3", // never allowed due to struct-pointer CLONE_NEW* bypass.
    "close",
    //"connect", protected with syscall argument cookies.
    "exit",
    "exit_group",
    "fallocate", // TODO: protect with syscall cookies!
    "fanotify_mark",
    "fchdir",
    "fchmod",
    "fchown",
    "fgetxattr",
    "flistxattr",
    "fremovexattr",
    "fsetxattr",
    "fstat",
    "fstat64",
    "fstatfs",
    "fstatfs64",
    //"ftruncate", protected with syscall argument cookies.
    //"ftruncate64", ditto.
    // "futex", See: FUTEX_SYSCALLS for futex family.
    "get_robust_list",
    "getdents64",
    "getpgid",
    "getpgrp",
    "getpid",
    //"getrandom", part of vDSO-syscalls.
    "getsockname",
    "getsockopt",
    "gettid",
    "getxattrat",
    "inotify_add_watch",
    "kcmp",
    "landlock_create_ruleset",
    "landlock_restrict_self",
    "lgetxattr",
    //linkat, protected with syscall argument cookies.
    "listxattrat",
    "llistxattr",
    "lremovexattr",
    "lseek",
    "lsetxattr",
    "lstat",
    //"madvise", advices are confined.
    //"memfd_create", protected with syscall argument cookies.
    "mlock",
    "mmap",
    "mmap2",
    "mprotect",
    "mremap",
    "munlock",
    "munmap",
    "nanosleep",
    "pidfd_getfd",
    "pidfd_open",
    "pidfd_send_signal",
    //"pipe2", flags are confined, protected with syscall argument cookies.
    //"prctl", see EMU_PRCTL_OPS for permitted operations.
    "process_mrelease", // Used by kill action when signal is SIGKILL.
    "process_vm_readv",
    "process_vm_writev",
    "read",
    "readv",
    "recv",
    "recvfrom",
    "recvmsg",
    "recvmmsg",
    "recvmmsg_time64",
    "removexattrat",
    "restart_syscall",
    "rseq",
    "rt_sigprocmask",
    "rt_sigtimedwait",        // Used by interrupt handling.
    "rt_sigtimedwait_time64", // ditto.
    "sched_getaffinity",
    //"sched_setaffinity", we use sync seccomp rather than CPU pinning as of 3.37.6.
    "sched_yield",
    "send",
    "sendmsg",
    "sendto",
    "set_robust_list",
    "setxattrat",
    "sigaltstack",
    "sigprocmask",
    //"socket", protected with syscall argument cookies.
    //"socketpair", ditto.
    "splice",
    "symlinkat", // TODO: protect with syscall cookies!
    "tee",
    "tgkill",
    "tkill",
    "timer_create",    // needed to unblock idle helper threads.
    "timer_delete",    // ditto.
    "timer_settime",   // ditto.
    "timer_settime64", // ditto.
    //"truncate", protected with syscall argument cookies.
    //"truncate64", ditto.
    "umask",
    //"uname", protected with syscall argument cookies.
    "waitid",
    // Required to unblock FIFOs.
    "sigreturn",
    "rt_sigreturn",
    //"sigaction", installing new signal handlers is not permitted.
    //"rt_sigaction", ditto.
    // fd calls
    "faccessat2",
    "fchmodat",  // TODO: protect with syscall cookies!
    "fchmodat2", // TODO: ditto.
    "fchownat",  // TODO: ditto.
    "mkdirat",   // TODO: ditto.
    "mknodat",   // TODO: ditto.
    "newfstatat",
    //"openat2", protected with syscall argument cookies.
    "readlinkat",
    //"renameat2", protected with syscall argument cookies.
    "statx",
    //"unlinkat", protected with syscall argument cookies.
    "utimensat",
    // used by logging, peer_inode, and proc_pid_status(5) masking.
    "write",
];

/// Fcntl operations allowed for emulator threads.
pub const EMU_FCNTL_OPS: &[u64] = &[
    libc::F_GETFD as u64,
    libc::F_SETFD as u64,
    libc::F_GETFL as u64,
    libc::F_SETFL as u64,
    libc::F_OFD_SETLK as u64,
    libc::F_OFD_SETLKW as u64,
    libc::F_ADD_SEALS as u64,
];

/// Prctl operations allowed for emulator threads.
pub const EMU_PRCTL_OPS: &[KeyValue] = &[
    ("PR_SET_NAME", 15),        // used by syd_{mon->emu}
    ("PR_SET_VMA", 0x53564d41), // used by mimalloc
];

/// Prctl operations allowed for emulator threads when SafeSetID is on.
pub const EMU_PRCTL_OPS_SAFESETID: &[KeyValue] = &[("PR_CAP_AMBIENT", 47), ("PR_CAPBSET_DROP", 24)];

/// System calls allowed for Interrupter thread.
pub const INT_SYSCALLS: &[&str] = &[
    "clock_nanosleep",
    "close",
    "exit",
    "exit_group", // to exit if inter-thread signaling does not work.
    //"clock_gettime", part of vDSO-syscalls.
    //"clock_gettime64", ditto.
    // "futex", See: FUTEX_SYSCALLS for futex family.
    "getpid",
    "gettid",
    // can {{dr}e,}allocate memory.
    // mmap{,2} and mprotect are further confined to disable PROT_EXEC.
    "brk",
    //"madvise", advices are confined.
    "mremap",
    "munmap",
    "nanosleep",
    "lseek",   // seek in /proc/$pid/status file.
    "_llseek", // ditto.
    //"prctl", see INT_PRCTL_OPS for permitted operations.
    "read",
    "restart_syscall",
    "rt_sigprocmask",
    "rseq",
    "sched_yield",
    "sigaltstack", // rare but necessary.
    "sigprocmask", // ditto.
];

/// Fcntl operations allowed for Interrupter thread.
pub const INT_FCNTL_OPS: &[u64] = &[
    libc::F_GETFD as u64,
    libc::F_SETFD as u64,
    libc::F_OFD_SETLK as u64,
    libc::F_OFD_SETLKW as u64,
];

/// Prctl operations allowed for Interrupter thread.
pub const INT_PRCTL_OPS: &[KeyValue] = &[("PR_SET_VMA", 0x53564d41)];

/// System calls allowed for the IPC thread.
///
/// We do not protect system calls of this thread with system call argument cookies,
/// because `syd_ipc` thread exits as soon as the sandbox is locked
/// therefore this mitigation was deemed unnecessary.
pub const IPC_SYSCALLS: &[&str] = &[
    "close",
    "exit",
    //"clock_gettime",   // part of vDSO-syscalls.
    //"clock_gettime64", // ditto.
    // "futex", See: FUTEX_SYSCALLS for futex family.
    "getpid",
    "gettid",
    //"getrandom", part of vDSO-syscalls.
    "getsockopt",
    "accept4",
    "recvmsg",
    "sendmsg",
    // can {{dr}e,}allocate and seal memory.
    // mmap{,2} and mprotect are further confined to disable PROT_EXEC.
    "brk",
    //"madvise", advices are confined.
    "mremap",
    "mseal",
    "munmap",
    //"prctl", see INT_PRCTL_OPS for permitted operations.
    "restart_syscall",
    "rt_sigprocmask",
    "rseq",
    "sched_yield",
    "sigaltstack", // rare but necessary.
    "sigprocmask", // ditto.
];

/// Fcntl operations allowed for IPC thread.
pub const IPC_FCNTL_OPS: &[u64] = &[
    libc::F_GETFD as u64,
    libc::F_SETFD as u64,
    libc::F_OFD_SETLK as u64,
    libc::F_OFD_SETLKW as u64,
];

/// Prctl operations allowed for Interrupter thread.
pub const IPC_PRCTL_OPS: &[KeyValue] = &[("PR_SET_VMA", 0x53564d41)];

/// System calls allowed for AES threads.
pub const AES_SYSCALLS: &[&str] = &[
    "_llseek",
    //"accept4", protected with syscall argument cookies.
    "brk",
    //"clock_gettime", part of vDSO-syscalls.
    //"clock_gettime64", ditto.
    "clock_nanosleep",
    //"clone", // CLONE_NEW* flags are restricted.
    //"clone3", // never allowed due to struct-pointer CLONE_NEW* bypass.
    "close",
    "exit",
    //"fadvise64", See: FADVISE_SYSCALLS for allowed fadvise syscalls.
    //"fcntl", See: AES_FCNTL_OPS for allowed fcntl operations.
    //"fcntl64",
    "fremovexattr",
    //"ftruncate", Protected with syscall argument cookies.
    //"ftruncate64", ditto.
    // "futex", See: FUTEX_SYSCALLS for futex family.
    "get_robust_list",
    "getpid",
    //"getrandom", part of vDSO-syscalls.
    "getsockopt",
    "gettid",
    "landlock_create_ruleset",
    "landlock_restrict_self",
    "lseek",
    //"madvise", advices are confined.
    "mlock",
    "mmap",
    "mmap2",
    "mprotect",
    "mremap",
    "munlock",
    "munmap",
    "nanosleep",
    //"pipe2", flags are confined, protected with syscall argument cookies.
    //"prctl", see AES_PRCTL_OPS for permitted operations.
    "recvmsg",
    "restart_syscall",
    "rseq",
    "rt_sigprocmask",
    "sched_getaffinity",
    "sched_yield",
    "send",    // TODO: protect with syscall cookies!
    "sendmsg", // TODO: protect with syscall cookies!
    "sendto",  // TODO: protect with syscall cookies!
    "set_robust_list",
    "sigaltstack",
    "sigprocmask",
    "splice",
    "tee",
    //"sigaction", installing new signal handlers is not permitted.
    //"rt_sigaction", ditto.
];

/// Fcntl operations allowed for AES threads.
pub const AES_FCNTL_OPS: &[u64] = &[
    libc::F_GETFD as u64,
    libc::F_SETFD as u64,
    libc::F_ADD_SEALS as u64,
    libc::F_OFD_SETLK as u64, // used by syd::log::LockedWriter.
    libc::F_OFD_SETLKW as u64,
];

/// Prctl operations allowed for AES threads.
pub const AES_PRCTL_OPS: &[KeyValue] = &[
    ("PR_SET_NAME", 15),        // used by syd_aes spawns
    ("PR_SET_VMA", 0x53564d41), // used by mimalloc
];

/// System calls allowed for main wait thread.
pub const MAIN_SYSCALLS: &[&str] = &[
    "_llseek",
    "brk",
    //"clock_gettime", part of vDSO-syscalls.
    //"clock_gettime64", ditto.
    "clock_nanosleep",
    "close",
    "exit_group",
    "fstat",
    "fstat64",
    "fstatfs",
    "fstatfs64",
    // "futex", See: FUTEX_SYSCALLS for futex family.
    "get_robust_list",
    "getdents64", // used by pid-limiter.
    "getpgid",
    "getpgrp",
    "getpid",
    //"getrandom", part of vDSO-syscalls.
    "gettid",
    "kill", // used by pid-limiter.
    "lseek",
    //"madvise", advices are confined.
    "mmap",
    "mmap2",
    "mprotect",
    "mremap",
    "munlock",
    "munmap",
    "nanosleep",
    "pidfd_open",
    "pidfd_getfd",
    "pidfd_send_signal",
    //"prctl", see MAIN_PRCTL_OPS for permitted operations.
    "process_mrelease",  // Used by kill action when signal is SIGKILL.
    "process_vm_readv",  // needed to get AT_{RANDOM,SECURE}.
    "process_vm_writev", // needed to set AT_SECURE.
    "ptrace",
    "read",
    "readv",
    "restart_syscall",
    "rseq",
    "rt_sigprocmask",
    "sched_getaffinity",
    //"sched_setaffinity", set before confinement, unneeded after.
    "sched_yield",
    "set_robust_list",
    "sigaltstack",
    "sigprocmask",
    "statx",
    "sysinfo", // used by pid-limiter.
    "tgkill",
    "tkill",
    "waitid",
    //"sigaction", installing new signal handlers is not permitted.
    //"rt_sigaction", ditto.
    // fd-calls
    "faccessat2",
    "newfstatat",
    //"openat2", protected with syscall argument cookies.
    "readlinkat",
];

/// Fcntl operations allowed for main wait thread.
pub const MAIN_FCNTL_OPS: &[u64] = &[
    libc::F_GETFD as u64,
    libc::F_SETFD as u64,
    libc::F_GETFL as u64,
    libc::F_SETFL as u64,
    libc::F_OFD_SETLK as u64,
    libc::F_OFD_SETLKW as u64,
];

/// Prctl operations allowed for main wait thread.
pub const MAIN_PRCTL_OPS: &[KeyValue] = &[("PR_SET_VMA", 0x53564d41)];

/// System calls that must be specifically allowed for syd-oci.
///
/// Note, this list _must_ be sorted!
pub const OCI_SYSCALLS: &[&str] = &[
    "kcmp",
    "pidfd_getfd",
    "process_mrelease",
    "process_vm_readv",
    "process_vm_writev",
    "ptrace",
    "syslog",
    "unshare",
];

/// Define a static (global) LazyLock value for the kernel version.
///
/// As of version 3.36.1, this can be overriden using SYD_ASSUME_KERNEL
/// environment variable.
#[expect(clippy::disallowed_methods)]
pub static KERNEL_VERSION: LazyLock<(u32, u32)> = LazyLock::new(|| {
    use std::os::unix::ffi::OsStrExt;

    use btoi::btoi;
    use memchr::memchr;
    use nix::sys::utsname::uname;

    // As of version 3.36.1 we allow overriding kernel version with SYD_ASSUME_KERNEL.
    let version = if let Some(version) = std::env::var_os(ENV_ASSUME_KERNEL) {
        version.as_bytes().to_owned()
    } else {
        let version = uname().unwrap();
        version.release().as_bytes().to_owned()
    };
    let nextdot = memchr(b'.', &version).expect("BUG: Invalid kernel version!");
    let major = btoi::<u32>(&version[..nextdot]).expect("BUG: Invalid kernel version!");
    let version = &version[nextdot + 1..];
    let nextdot = memchr(b'.', version).unwrap_or(version.len());
    let minor = btoi::<u32>(&version[..nextdot]).expect("BUG: Invalid kernel version!");

    (major, minor)
});

/// Kernel version string derived from `KERNEL_VERSION`, used by uname(2).
///
/// # Safety
///
/// 1. If version string is longer than 65 characters, it'll be truncated.
/// 2. Micro version is randomized to prevent information leaks.
#[expect(clippy::disallowed_methods)]
pub static KERNEL_VERSION_STR: LazyLock<String> = LazyLock::new(|| {
    let (major, minor) = *KERNEL_VERSION;
    let micro = randint(0u8..=u8::MAX).expect("BUG: Failed to randomize kernel micro version!");
    format!("{major}.{minor}.{micro}")
});

/// Check for MFD_NOEXEC_SEAL support (Linux 6.3 or newer).
pub static HAVE_MFD_NOEXEC_SEAL: LazyLock<bool> = LazyLock::new(|| {
    let (major, minor) = *KERNEL_VERSION;
    major > 6 || (major == 6 && minor >= 3)
});

/// Returns MFD_NOEXEC_SEAL on Linux>=6.3 and MFD_ALLOW_SEALING on older Linux.
pub static SAFE_MFD_FLAGS: LazyLock<libc::c_uint> = LazyLock::new(|| {
    if *HAVE_MFD_NOEXEC_SEAL {
        libc::MFD_NOEXEC_SEAL
    } else {
        libc::MFD_ALLOW_SEALING
    }
});

/// Check for PIDFD_THREAD support (Linux-6.9 or newer).
pub static HAVE_PIDFD_THREAD: LazyLock<bool> = LazyLock::new(|| {
    let (major, minor) = *KERNEL_VERSION;
    major > 6 || (major == 6 && minor >= 9)
});

/// Check for SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP support (Linux-6.6 or newer).
pub static HAVE_SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP: LazyLock<bool> = LazyLock::new(|| {
    let (major, minor) = *KERNEL_VERSION;
    major > 6 || (major == 6 && minor >= 6)
});

/// Check for STATX_MNT_ID_UNIQUE support (Linux-6.8 or newer).
pub(crate) static HAVE_STATX_MNT_ID_UNIQUE: LazyLock<bool> = LazyLock::new(|| {
    let (major, minor) = *KERNEL_VERSION;
    major > 6 || (major == 6 && minor >= 8)
});

/// Check for AT_EXECVE_CHECK support (Linux-6.14 or newer).
pub static HAVE_AT_EXECVE_CHECK: LazyLock<bool> = LazyLock::new(|| {
    let (major, minor) = *KERNEL_VERSION;
    major > 6 || (major == 6 && minor >= 14)
});

/// Check for PROCMAP_QUERY ioctl(2) (Linux-6.11 or newer).
pub static HAVE_PROCMAP_QUERY: LazyLock<bool> = LazyLock::new(|| {
    let (major, minor) = *KERNEL_VERSION;
    major > 6 || (major == 6 && minor >= 11)
});

/// Check for MADV_GUARD_{INSTALL,REMOVE} madvise(2) (Linux-6.13 or newer).
pub static HAVE_MADV_GUARD: LazyLock<bool> = LazyLock::new(|| {
    let (major, minor) = *KERNEL_VERSION;
    major > 6 || (major == 6 && minor >= 13)
});

/// Check for CONFIG_CROSS_MEMORY_ATTACH support.
pub static HAVE_CROSS_MEMORY_ATTACH: LazyLock<bool> = LazyLock::new(check_cross_memory_attach);

/// Check for stat.st_size support in /proc/$pid/fd (Linux-6.2 or newer).
pub static HAVE_PROC_PID_FD_STAT_SIZE: LazyLock<bool> = LazyLock::new(|| {
    let (major, minor) = *KERNEL_VERSION;
    major > 6 || (major == 6 && minor >= 2)
});

/// Check for RWF_NOAPPEND support for pwritev2(2) (Linux-6.9 or newer).
pub static HAVE_RWF_NOAPPEND: LazyLock<bool> = LazyLock::new(|| {
    let (major, minor) = *KERNEL_VERSION;
    major > 6 || (major == 6 && minor >= 9)
});

/// Check if kernel/pid_max sysctl is namespaced (Linux-6.14 or newer).
pub static HAVE_NAMESPACED_PID_MAX: LazyLock<bool> = LazyLock::new(|| {
    let (major, minor) = *KERNEL_VERSION;
    major > 6 || (major == 6 && minor >= 14)
});

//
// Below is internal territory, you have been warned.

/// Unsafe mode mask for SHM hardening.
pub(crate) const SHM_UNSAFE_MASK: u64 = 0o177;

/// Name prefix for memory file descriptors.
/// This is used in access control.
pub const MFD_NAME_PREFIX: &[u8] = b"!memfd:";

/// Name prefix for hugetlbfs memory file descriptors.
/// This is used in access control.
pub const MFD_HUGETLB_NAME_PREFIX: &[u8] = b"!memfd-hugetlb:";

/// BIGTCP maximum for loopback:
///
/// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=d6f938ce52f9adb23f4c31cc371654a5f18ff328
pub const LOOPBACK_BIGTCP_MAX: u32 = 0x30d40;

/// Determine minimum allowed mmap(2) address by reading `/proc/sys/vm/mmap_min_addr`.
///
/// Enforce OpenBSD's hard-coded minimum mmap(2) address by capping at PAGE_SIZE;
/// See: https://github.com/openbsd/src/blob/94a7e27d04f23871848a8f225ef286e84969197a/sys/uvm/uvm_map.c#L235
pub static MMAP_MIN_ADDR: LazyLock<u64> =
    LazyLock::new(|| proc_mmap_min_addr().unwrap_or(*PAGE_SIZE).max(*PAGE_SIZE));

// Trace data for ptrace(2) hooked system calls.
//
// This we we don't rely on system call number
// which is architecture/personality specific.
pub(crate) const PTRACE_DATA_CHDIR: u16 = 0;
pub(crate) const PTRACE_DATA_EXECVE: u16 = 1;
pub(crate) const PTRACE_DATA_EXECVEAT: u16 = 2;
pub(crate) const PTRACE_DATA_SIGRETURN: u16 = 3;
pub(crate) const PTRACE_DATA_RT_SIGRETURN: u16 = 4;

/// Returns a new randomized timer.
pub(crate) static _RAND_TIMER: OnceLock<RandTimer> = OnceLock::new();

/// Returns a reference to the static randomized timer.
///
/// Calling this before `timer_init` will panic!
#[expect(clippy::disallowed_methods)]
#[expect(non_snake_case)]
#[inline(always)]
pub(crate) fn RAND_TIMER() -> &'static RandTimer {
    _RAND_TIMER.get().unwrap()
}

/// Initialize randomized timer.
pub fn timer_init() -> Result<(), Errno> {
    let timer = RandTimer::new()?;

    info!("ctx": "run", "op": "sysinfo_init_timer",
        "msg": "initialized internal sysinfo(2) randomized timer",
        "off": [timer.uptime_offset, timer.idle_offset]);
    _RAND_TIMER.set(timer).or(Err(Errno::EAGAIN))?;

    Ok(())
}

/// Returns a reference to the static `/` dirfd.
///
/// Calling this before calling `proc_init` will panic!
#[expect(clippy::disallowed_methods)]
#[expect(non_snake_case)]
#[inline(always)]
pub(crate) fn ROOT_FD() -> RawFd {
    *_ROOT_FD.get().unwrap()
}

/// Returns a reference to the static `/` mode.
///
/// Calling this before calling `proc_init` will panic!
#[expect(clippy::disallowed_methods)]
#[expect(non_snake_case)]
#[inline(always)]
pub(crate) fn ROOT_F_MODE() -> u16 {
    *_ROOT_F_MODE.get().unwrap()
}

/// Returns a reference to the static `/` unique mount id.
///
/// Calling this before calling `proc_init` will panic!
#[expect(clippy::disallowed_methods)]
#[expect(non_snake_case)]
#[inline(always)]
pub(crate) fn ROOT_MNT_ID() -> u64 {
    *_ROOT_MNT_ID.get().unwrap()
}

/// Returns a reference to the static `/` dirfd.
///
/// Calling this before calling `proc_init` will panic!
#[expect(non_snake_case)]
#[inline(always)]
pub(crate) fn ROOT_FILE() -> BorrowedFd<'static> {
    // SAFETY: `proc_init' is called beforehand.
    unsafe { BorrowedFd::borrow_raw(ROOT_FD()) }
}

/// Returns a reference to the static `/proc` dirfd.
///
/// Calling this before calling `proc_init` will panic!
#[expect(clippy::disallowed_methods)]
#[expect(non_snake_case)]
#[inline(always)]
pub(crate) fn PROC_FD() -> RawFd {
    *_PROC_FD.get().unwrap()
}

/// Returns a reference to the static `/proc` mode.
///
/// Calling this before calling `proc_init` will panic!
#[expect(clippy::disallowed_methods)]
#[expect(non_snake_case)]
#[inline(always)]
pub(crate) fn PROC_F_MODE() -> u16 {
    *_PROC_F_MODE.get().unwrap()
}

/// Returns a reference to the static `/proc` unique mount id.
///
/// Calling this before calling `proc_init` will panic!
#[expect(clippy::disallowed_methods)]
#[expect(non_snake_case)]
#[inline(always)]
pub(crate) fn PROC_MNT_ID() -> u64 {
    *_PROC_MNT_ID.get().unwrap()
}

/// Returns a reference to the static `/proc` dirfd.
///
/// Calling this before calling `proc_init` will panic!
#[expect(non_snake_case)]
#[inline(always)]
pub(crate) fn PROC_FILE() -> BorrowedFd<'static> {
    // SAFETY: `proc_init' is called beforehand.
    unsafe { BorrowedFd::borrow_raw(PROC_FD()) }
}

/// Returns a reference to the static `/dev/null` fd.
///
/// Calling this before calling `proc_init` will panic!
#[expect(clippy::disallowed_methods)]
#[expect(non_snake_case)]
#[inline(always)]
pub(crate) fn NULL_FD() -> RawFd {
    *_NULL_FD.get().unwrap()
}

/// Returns a reference to the static `/dev/null` mode.
///
/// Calling this before calling `proc_init` will panic!
#[expect(clippy::disallowed_methods)]
#[expect(non_snake_case)]
#[inline(always)]
pub(crate) fn NULL_F_MODE() -> u16 {
    *_NULL_F_MODE.get().unwrap()
}

/// Returns a reference to the static `/dev/null` unique mount id.
///
/// Calling this before calling `proc_init` will panic!
#[expect(clippy::disallowed_methods)]
#[expect(non_snake_case)]
#[inline(always)]
pub(crate) fn NULL_MNT_ID() -> u64 {
    *_NULL_MNT_ID.get().unwrap()
}

/*
/// Returns a reference to the static `/dev/null` fd.
///
/// Calling this before calling `proc_init` will panic!
#[expect(clippy::disallowed_methods)]
#[expect(non_snake_case)]
#[inline(always)]
pub(crate) fn NULL_FILE() -> BorrowedFd<'static> {
    // SAFETY: `proc_init' is called beforehand.
    unsafe { BorrowedFd::borrow_raw(NULL_FD()) }
}
*/

/// File descriptor to `/`, ie the root file system.
pub(crate) static _ROOT_FD: OnceLock<RawFd> = OnceLock::new();

/// Mode to `/`, ie the root file system.
pub(crate) static _ROOT_F_MODE: OnceLock<u16> = OnceLock::new();

/// Unique mount id to `/`, ie the root file system.
pub(crate) static _ROOT_MNT_ID: OnceLock<u64> = OnceLock::new();

/// File descriptor to /proc file system.
pub(crate) static _PROC_FD: OnceLock<RawFd> = OnceLock::new();

/// Mode to the /proc file system.
pub(crate) static _PROC_F_MODE: OnceLock<u16> = OnceLock::new();

/// Unique mount id to /proc file system.
pub(crate) static _PROC_MNT_ID: OnceLock<u64> = OnceLock::new();

/// File descriptor to /dev/null character device.
pub(crate) static _NULL_FD: OnceLock<RawFd> = OnceLock::new();

/// Mode to the /dev/null character device.
pub(crate) static _NULL_F_MODE: OnceLock<u16> = OnceLock::new();

/// Unique mount id to /dev/null character device.
pub(crate) static _NULL_MNT_ID: OnceLock<u64> = OnceLock::new();

/// Initialize static file descriptors for use by syd::proc any friends.
#[expect(clippy::cast_possible_truncation)]
#[expect(clippy::cognitive_complexity)]
#[expect(clippy::disallowed_methods)]
pub fn proc_init() -> Result<(), Errno> {
    let mut mask = STATX_MODE;
    mask |= if *HAVE_STATX_MNT_ID_UNIQUE {
        STATX_MNT_ID_UNIQUE
    } else {
        STATX_MNT_ID
    };

    let fd_root = nix::fcntl::open(
        "/",
        OFlag::O_PATH | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC,
        Mode::empty(),
    )?;
    let (f_mode_root, mnt_id_root) = fstatx(&fd_root, mask)
        .map(|stx| (stx.stx_mode & !(libc::S_IFMT as u16), stx.stx_mnt_id))?;

    // SAFETY: To make this file descriptor harder to spot by an
    // attacker we duplicate it to a random fd number.
    let fd_root = duprand(fd_root.as_raw_fd(), OFlag::O_CLOEXEC)?;

    info!("ctx": "run", "op": "opendir_root",
        "msg": "opened root directory",
        "fd": fd_root,
        "f_mode": f_mode_root,
        "mnt_id": mnt_id_root);
    _ROOT_FD.set(fd_root).or(Err(Errno::EAGAIN))?;
    _ROOT_F_MODE.set(f_mode_root).or(Err(Errno::EAGAIN))?;
    _ROOT_MNT_ID.set(mnt_id_root).or(Err(Errno::EAGAIN))?;

    // SAFETY: fd_root is a valid fd for process lifetime.
    let fd_root = unsafe { BorrowedFd::borrow_raw(fd_root) };

    // Note, we may call getdents64(2) on /proc for PID sandboxing,
    // therefore we open it without O_PATH here.
    let fd_proc = nix::fcntl::openat(
        fd_root,
        XPath::from_bytes(b"proc"),
        OFlag::O_DIRECTORY | OFlag::O_CLOEXEC,
        Mode::empty(),
    )?;
    let (f_mode_proc, mnt_id_proc) = fstatx(&fd_proc, mask)
        .map(|stx| (stx.stx_mode & !(libc::S_IFMT as u16), stx.stx_mnt_id))?;

    // SAFETY: To make this file descriptor harder to spot by an
    // attacker we duplicate it to a random fd number.
    let fd_proc = duprand(fd_proc.as_raw_fd(), OFlag::O_CLOEXEC)?;

    info!("ctx": "run", "op": "opendir_proc",
        "msg": "opened /proc directory",
        "fd": fd_proc,
        "f_mode": f_mode_proc,
        "mnt_id": mnt_id_proc);
    _PROC_FD.set(fd_proc).or(Err(Errno::EAGAIN))?;
    _PROC_F_MODE.set(f_mode_proc).or(Err(Errno::EAGAIN))?;
    _PROC_MNT_ID.set(mnt_id_proc).or(Err(Errno::EAGAIN))?;

    let fd_null = nix::fcntl::openat(
        fd_root,
        XPath::from_bytes(b"dev/null"),
        OFlag::O_PATH | OFlag::O_CLOEXEC,
        Mode::empty(),
    )?;
    let (f_mode_null, mnt_id_null) = fstatx(&fd_null, mask)
        .map(|stx| (stx.stx_mode & !(libc::S_IFMT as u16), stx.stx_mnt_id))?;

    // SAFETY: Validate what we've opened is indeed `/dev/null`.
    if !is_dev_null(&fd_null).unwrap_or(false) {
        return Err(Errno::ENODEV);
    }

    // SAFETY: To make this file descriptor harder to spot by an
    // attacker we duplicate it to a random fd number.
    let fd_null = duprand(fd_null.as_raw_fd(), OFlag::O_CLOEXEC)?;

    info!("ctx": "run", "op": "opendev_null",
        "msg": "opened /dev/null",
        "fd": fd_null,
        "f_mode": f_mode_null,
        "mnt_id": mnt_id_null);
    _NULL_FD.set(fd_null).or(Err(Errno::EAGAIN))?;
    _NULL_F_MODE.set(f_mode_null).or(Err(Errno::EAGAIN))?;
    _NULL_MNT_ID.set(mnt_id_null).or(Err(Errno::EAGAIN))?;

    Ok(())
}

/// Close static file descriptors for use by syd::proc and friends.
pub fn proc_close() {
    if let Some(fd) = _ROOT_FD.get() {
        let _ = close(*fd);
    }

    if let Some(fd) = _PROC_FD.get() {
        let _ = close(*fd);
    }

    if let Some(fd) = _NULL_FD.get() {
        let _ = close(*fd);
    }
}

// FileMap populated with static FDs.
// safe_canonicalize clones this on each call.
pub(crate) static FILEMAP: LazyLock<FileMap> = LazyLock::new(|| {
    let mut filemap: FileMap = FileMap::with_capacity(FILECAP);

    let entry = FileMapEntry::new(
        ROOT_FD().into(),
        Some(FileType::Dir),
        Some(ROOT_F_MODE()),
        Some(ROOT_MNT_ID()),
        None,
    );
    filemap.0.insert(XPathBuf::from("/"), entry);

    let entry = FileMapEntry::new(
        PROC_FD().into(),
        Some(FileType::Dir),
        Some(PROC_F_MODE()),
        Some(PROC_MNT_ID()),
        None,
    );
    filemap.0.insert(XPathBuf::from("/proc"), entry);

    let entry = FileMapEntry::new(
        NULL_FD().into(),
        Some(FileType::Chr),
        Some(NULL_F_MODE()),
        Some(NULL_MNT_ID()),
        None,
    );
    filemap.0.insert(XPathBuf::from("/dev/null"), entry);

    filemap
});

// FileMap default capacity.
pub(crate) const FILECAP: usize = 8;

// Warn at compile time if this crate is built with `panic=unwind`.
#[cfg(panic = "unwind")]
#[deprecated(
    note = "Built with panic=unwind. This configuration is not supported; you have been warned."
)]
#[expect(dead_code)]
const SYD_PANIC_UNWIND_BUILD: () = ();

// Force a use of the deprecated item so the warning is actually emitted.
#[cfg(panic = "unwind")]
const _: () = {
    let _ = SYD_PANIC_UNWIND_BUILD;
};

/// Pink Floyd easter egg.
pub const PINK_FLOYD: &str = concat!(
    "\x1b[01;35m",
    "       ..uu.                               \n",
    "       ?$\"\"`?i           z'              \n",
    "       `M  .@\"          x\"               \n",
    "       'Z :#\"  .   .    f 8M              \n",
    "       '&H?`  :$f U8   <  MP   x#'         \n",
    "       d#`    XM  $5.  $  M' xM\"          \n",
    "     .!\">     @  'f`$L:M  R.@!`           \n",
    "    +`  >     R  X  \"NXF  R\"*L           \n",
    "        k    'f  M   \"$$ :E  5.           \n",
    "        %%    `~  \"    `  'K  'M          \n",
    "            .uH          'E   `h           \n",
    "         .x*`             X     `          \n",
    "      .uf`                *                \n",
    "    .@8     .                              \n",
    "   'E9F  uf\"          ,     ,             \n",
    "     9h+\"   $M    eH. 8b. .8    .....     \n",
    "    .8`     $'   M 'E  `R;'   d?\"\"\"`\"# \n",
    "   ` E      @    b  d   9R    ?*     @     \n",
    "     >      K.zM `%%M'   9'    Xf   .f     \n",
    "    ;       R'          9     M  .=`       \n",
    "    t                   M     Mx~          \n",
    "    @                  lR    z\"           \n",
    "    @                  `   ;\"             \n",
    "                          `                \n",
    "\x1b[0m",
);

/// See Emily Play easter egg.
pub const SEE_EMILY_PLAY: &str = concat!(
    "\x1b[0;1;35;95mTh",
    "\x1b[0;1;31;91mer",
    "\x1b[0;1;33;93me",
    "\x1b[0m ",
    "\x1b[0;1;32;92mis",
    "\x1b[0m ",
    "\x1b[0;1;36;96mn",
    "\x1b[0;1;34;94mo",
    "\x1b[0m ",
    "\x1b[0;1;35;95mot",
    "\x1b[0;1;31;91mhe",
    "\x1b[0;1;33;93mr",
    "\x1b[0m ",
    "\x1b[0;1;32;92mda",
    "\x1b[0;1;36;96my",
    "\x1b[0m",
    "\n",
    "\x1b[0;1;35;95mLe",
    "\x1b[0;1;31;91mt'",
    "\x1b[0;1;33;93ms",
    "\x1b[0m ",
    "\x1b[0;1;32;92mtr",
    "\x1b[0;1;36;96my",
    "\x1b[0m ",
    "\x1b[0;1;34;94mit",
    "\x1b[0m ",
    "\x1b[0;1;35;95ma",
    "\x1b[0;1;31;91mno",
    "\x1b[0;1;33;93mth",
    "\x1b[0;1;32;92mer",
    "\x1b[0m ",
    "\x1b[0;1;36;96mw",
    "\x1b[0;1;34;94may",
    "\x1b[0m",
    "\n",
    "\x1b[0;1;35;95mYo",
    "\x1b[0;1;31;91mu'",
    "\x1b[0;1;33;93mll",
    "\x1b[0m ",
    "\x1b[0;1;32;92ml",
    "\x1b[0;1;36;96mos",
    "\x1b[0;1;34;94me",
    "\x1b[0m ",
    "\x1b[0;1;35;95myo",
    "\x1b[0;1;31;91mur",
    "\x1b[0m ",
    "\x1b[0;1;33;93mm",
    "\x1b[0;1;32;92min",
    "\x1b[0;1;36;96md",
    "\x1b[0m ",
    "\x1b[0;1;34;94man",
    "\x1b[0;1;35;95md",
    "\x1b[0m ",
    "\x1b[0;1;31;91mpl",
    "\x1b[0;1;33;93may",
    "\x1b[0m",
    "\n",
    "\x1b[0;1;35;95mFr",
    "\x1b[0;1;31;91mee",
    "\x1b[0m \x1b[0;1;33;93mg",
    "\x1b[0;1;32;92mam",
    "\x1b[0;1;36;96mes",
    "\x1b[0m ",
    "\x1b[0;1;34;94mf",
    "\x1b[0;1;35;95mor",
    "\x1b[0m ",
    "\x1b[0;1;31;91mm",
    "\x1b[0;1;33;93may",
    "\x1b[0m",
    "\n",
    "\x1b[0;1;35;95mSe",
    "\x1b[0;1;31;91me",
    "\x1b[0m ",
    "\x1b[0;1;33;93mEm",
    "\x1b[0;1;32;92mil",
    "\x1b[0;1;36;96my",
    "\x1b[0m ",
    "\x1b[0;1;34;94mpl",
    "\x1b[0;1;35;95may",
    "\x1b[0m",
    "\n",
);

/// The Piper easter egg.
pub const THE_PIPER: &str = concat!(
    "Helper and healer, I cheer\n",
    "Small waifs in the woodland wet\n",
    "Strays I find in it, wounds I bind in it\n",
    "Bidding them all forget!\n",
);