syd 3.52.0

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
3235
3236
3237
3238
3239
3240
3241
3242
3243
//
// Syd: rock-solid application kernel
// src/fd.rs: File descriptor utilities
//
// Copyright (c) 2025, 2026 Ali Polatel <alip@chesswob.org>
// SPDX-License-Identifier: GPL-3.0

//! Set of functions to manage file descriptors.

use std::{
    convert::Infallible,
    fmt,
    fs::{Metadata, Permissions},
    io,
    mem::ManuallyDrop,
    os::{
        fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd},
        unix::{fs::FileExt, net::UnixStream},
    },
    sync::OnceLock,
};

use btoi::btoi;
use libc::{
    c_int, c_long, c_uint, c_ulong, syscall, SYS_ioctl, SYS_kcmp, SYS_pidfd_getfd, SYS_pidfd_open,
    SYS_pidfd_send_signal, EBADF, O_NONBLOCK,
};
use nix::{
    errno::Errno,
    fcntl::{fcntl, AtFlags, FcntlArg, FdFlag, OFlag, SealFlag},
    sched::CloneFlags,
    sys::{
        socket::{
            getsockopt,
            sockopt::{PeerCredentials, ReceiveTimeout, SendTimeout},
            SockFlag, SockaddrStorage, UnixCredentials,
        },
        stat::Mode,
    },
    unistd::{lseek64, read, write, AccessFlags, Pid, Whence},
};

use crate::{
    compat::{
        fstatx, getdents64, openat2, pread64, pwrite64, recvmsg, sendmsg, statx, AddressFamily,
        Cmsg, CmsgOwned, CmsgSpace, FsType, MsgFlags, MsgHdr, ResolveFlag, SockType,
        STATX_BASIC_STATS, STATX_INO, STATX_MNT_ID, STATX_MNT_ID_UNIQUE, STATX_MODE, STATX_SIZE,
        TIOCEXCL, TIOCGEXCL, TIOCNXCL,
    },
    config::{
        DIRENT_BUF_SIZE, HAVE_AT_EXECVE_CHECK, HAVE_PIDFD_THREAD, HAVE_PROC_PID_FD_STAT_SIZE,
        HAVE_STATX_MNT_ID_UNIQUE,
    },
    cookie::{safe_close, safe_close_range, safe_execve_check, safe_faccess, safe_socket},
    fs::{oflag_accmode, readlinkat},
    hash::SydHashSet,
    info,
    lookup::safe_open_how,
    path::{XPath, XPathBuf},
    proc::proc_tgid,
    retry::retry_on_eintr,
    rng::duprand,
};

/// SAFETY: AT_BADFD to be used a safe alternative to AT_FDCWD.
pub const AT_BADFD: BorrowedFd<'static> = unsafe { BorrowedFd::borrow_raw(-EBADF) };

/// An owned file descriptor that uses cookified close(2) on drop.
///
/// This is functionally identical to [`OwnedFd`] but calls
/// [`safe_close`] (which embeds syscall argument cookies) instead of
/// `libc::close` when the descriptor is dropped. This ensures that
/// every close(2) issued by Syd passes through the sealed cookie pool,
/// making it verifiable by the seccomp(2) BPF filter.
///
/// # Safety invariants
///
/// The inner `fd` is a valid, open file descriptor owned exclusively
/// by this handle. It will be closed exactly once, on drop.
#[derive(Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(transparent)]
pub struct SafeOwnedFd {
    fd: RawFd,
}

impl Drop for SafeOwnedFd {
    #[inline(always)]
    fn drop(&mut self) {
        // This panics on EBADF.
        let _ = close(self.fd);
    }
}

impl fmt::Debug for SafeOwnedFd {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SafeOwnedFd").field("fd", &self.fd).finish()
    }
}

impl AsRawFd for SafeOwnedFd {
    fn as_raw_fd(&self) -> RawFd {
        self.fd
    }
}

impl AsFd for SafeOwnedFd {
    fn as_fd(&self) -> BorrowedFd<'_> {
        // SAFETY: `SafeOwnedFd` owns the fd and it stays valid for the
        // lifetime of `&self`.
        unsafe { BorrowedFd::borrow_raw(self.fd) }
    }
}

impl SafeOwnedFd {
    /// View a slice of owned fds as borrowed fds.
    pub fn as_borrowed_slice(fds: &[SafeOwnedFd]) -> &[BorrowedFd<'_>] {
        // SAFETY: SafeOwnedFd and BorrowedFd are both repr(transparent)
        // over RawFd. The fds remain valid for the lifetime of the slice.
        unsafe { std::slice::from_raw_parts(fds.as_ptr().cast(), fds.len()) }
    }
}

impl IntoRawFd for SafeOwnedFd {
    fn into_raw_fd(self) -> RawFd {
        let fd = self.fd;
        std::mem::forget(self);
        fd
    }
}

impl FromRawFd for SafeOwnedFd {
    /// Constructs a new `SafeOwnedFd` from the given raw file
    /// descriptor.
    ///
    /// # Safety
    ///
    /// The `fd` must be a valid, open file descriptor that the caller
    /// transfers ownership of. It must not require any cleanup other
    /// than close(2).
    ///
    /// # Panics
    ///
    /// Panics if `fd` is negative.
    /// Panics if `set_cloexec` fails on the given `fd`.
    unsafe fn from_raw_fd(fd: RawFd) -> Self {
        assert!(
            fd >= 0,
            "SafeOwnedFd::from_raw_fd: fd must be non-negative, got {fd}"
        );

        let fd_tmp = BorrowedFd::borrow_raw(fd);
        #[expect(clippy::disallowed_methods)]
        set_cloexec(fd_tmp, true).expect("set_cloexec");

        SafeOwnedFd { fd }
    }
}

#[expect(clippy::disallowed_types)]
impl From<std::os::fd::OwnedFd> for SafeOwnedFd {
    /// Converts an `OwnedFd` into a `SafeOwnedFd`, transferring
    /// ownership.
    ///
    /// The file descriptor will henceforth be closed via `safe_close`
    /// (cookified close) on drop.
    #[inline]
    fn from(owned: std::os::fd::OwnedFd) -> Self {
        SafeOwnedFd {
            fd: owned.into_raw_fd(),
        }
    }
}

#[expect(clippy::disallowed_types)]
impl From<SafeOwnedFd> for std::os::fd::OwnedFd {
    /// Converts a `SafeOwnedFd` back into an `OwnedFd`, transferring
    /// ownership.
    ///
    /// The file descriptor will henceforth be closed via `libc::close`
    /// on drop.
    fn from(safe: SafeOwnedFd) -> Self {
        // SAFETY: SafeOwnedFd guarantees a valid fd >= 0.
        unsafe { std::os::fd::OwnedFd::from_raw_fd(safe.into_raw_fd()) }
    }
}

#[expect(clippy::disallowed_types)]
impl From<std::fs::File> for SafeOwnedFd {
    /// Takes ownership of a [`File`](std::fs::File)'s underlying file
    /// descriptor.
    ///
    /// The file descriptor will henceforth be closed via `safe_close`
    /// (cookified close) on drop.
    fn from(file: std::fs::File) -> Self {
        SafeOwnedFd::from(std::os::fd::OwnedFd::from(file))
    }
}

#[expect(clippy::disallowed_types)]
impl From<SafeOwnedFd> for std::fs::File {
    /// Returns a [`File`](std::fs::File) that takes ownership of the
    /// given safe file descriptor.
    fn from(safe: SafeOwnedFd) -> Self {
        std::fs::File::from(std::os::fd::OwnedFd::from(safe))
    }
}

#[expect(clippy::disallowed_types)]
impl From<UnixStream> for SafeOwnedFd {
    /// Takes ownership of a
    /// [`UnixStream`](std::os::unix::net::UnixStream)'s underlying file
    /// descriptor.
    ///
    /// The file descriptor will henceforth be closed via `safe_close`
    /// (cookified close) on drop.
    fn from(stream: UnixStream) -> Self {
        SafeOwnedFd::from(std::os::fd::OwnedFd::from(stream))
    }
}

#[expect(clippy::disallowed_types)]
impl From<SafeOwnedFd> for UnixStream {
    /// Returns a [`UnixStream`](std::os::unix::net::UnixStream) that
    /// takes ownership of the given safe file descriptor.
    fn from(safe: SafeOwnedFd) -> Self {
        UnixStream::from(std::os::fd::OwnedFd::from(safe))
    }
}

impl io::Read for SafeOwnedFd {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        nix::unistd::read(self.as_fd(), buf).map_err(io::Error::from)
    }
}

impl io::Write for SafeOwnedFd {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        nix::unistd::write(self, buf).map_err(io::Error::from)
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(()) // No-op, same as OwnedFd.
    }
}

impl io::Seek for SafeOwnedFd {
    fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
        #[expect(clippy::cast_possible_wrap)]
        let (offset, whence) = match pos {
            io::SeekFrom::Start(n) => (n as libc::off64_t, Whence::SeekSet),
            io::SeekFrom::End(n) => (n as libc::off64_t, Whence::SeekEnd),
            io::SeekFrom::Current(n) => (n as libc::off64_t, Whence::SeekCur),
        };
        #[expect(clippy::cast_sign_loss)]
        lseek64(self.as_fd(), offset, whence)
            .map(|r| r as u64)
            .map_err(io::Error::from)
    }
}

impl FileExt for SafeOwnedFd {
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
        let offset = offset
            .try_into()
            .or(Err(Errno::EOVERFLOW))
            .map_err(io::Error::from)?;
        pread64(self.as_fd(), buf, offset).map_err(io::Error::from)
    }

    fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
        let offset = offset
            .try_into()
            .or(Err(Errno::EOVERFLOW))
            .map_err(io::Error::from)?;
        pwrite64(self.as_fd(), buf, offset).map_err(io::Error::from)
    }
}

impl SafeOwnedFd {
    /// Creates a new `SafeOwnedFd` instance that shares the same
    /// underlying file description as the existing `SafeOwnedFd`
    /// instance.
    pub fn try_clone(&self) -> Result<Self, Errno> {
        // Use F_DUPFD_CLOEXEC to atomically duplicate and set CLOEXEC.
        // Avoid using file descriptors below 3 as they are used for stdio(3).
        let fd = fcntl(self.as_fd(), FcntlArg::F_DUPFD_CLOEXEC(3))?;
        Ok(Self { fd })
    }

    /// Queries metadata about the underlying file.
    pub fn metadata(&self) -> io::Result<Metadata> {
        // SAFETY:
        // self.as_raw_fd() returns a valid file descriptor.
        // ManuallyDrop prevents double closure.
        #[expect(clippy::disallowed_types)]
        let file = ManuallyDrop::new(unsafe { std::fs::File::from_raw_fd(self.as_raw_fd()) });
        file.metadata()
    }

    /// Changes the permissions on the underlying file.
    pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
        // SAFETY:
        // self.as_raw_fd() returns a valid file descriptor.
        // ManuallyDrop prevents double closure.
        #[expect(clippy::disallowed_types)]
        let file = ManuallyDrop::new(unsafe { std::fs::File::from_raw_fd(self.as_raw_fd()) });
        file.set_permissions(perm)
    }
}

/// Sets or clears the append (O_APPEND) flag on a file descriptor.
pub fn set_append<Fd: AsFd>(fd: Fd, state: bool) -> Result<(), Errno> {
    let flags = fcntl(&fd, FcntlArg::F_GETFL)?;

    let mut new_flags = flags;
    if state {
        new_flags |= OFlag::O_APPEND.bits();
    } else {
        new_flags &= !OFlag::O_APPEND.bits();
    }

    fcntl(&fd, FcntlArg::F_SETFL(OFlag::from_bits_truncate(new_flags))).map(drop)
}

/// Returns `true` if the given file descriptor is set to non-blocking mode.
pub fn get_nonblock<Fd: AsFd>(fd: Fd) -> Result<bool, Errno> {
    fcntl(fd, FcntlArg::F_GETFL).map(|flags| flags & O_NONBLOCK != 0)
}

/// Sets or clears the non-blocking (O_NONBLOCK) flag on a file descriptor.
pub fn set_nonblock<Fd: AsFd>(fd: Fd, state: bool) -> Result<(), Errno> {
    let flags = fcntl(&fd, FcntlArg::F_GETFL)?;

    let mut new_flags = flags;
    if state {
        new_flags |= OFlag::O_NONBLOCK.bits();
    } else {
        new_flags &= !OFlag::O_NONBLOCK.bits();
    }

    fcntl(&fd, FcntlArg::F_SETFL(OFlag::from_bits_truncate(new_flags))).map(drop)
}

/// Sets or clears the close-on-exec (FD_CLOEXEC) flag on a file descriptor.
pub fn set_cloexec<Fd: AsFd>(fd: Fd, state: bool) -> Result<(), Errno> {
    let flags = fcntl(&fd, FcntlArg::F_GETFD)?;

    let mut new_flags = flags;
    if state {
        new_flags |= FdFlag::FD_CLOEXEC.bits();
    } else {
        new_flags &= !FdFlag::FD_CLOEXEC.bits();
    }

    fcntl(
        &fd,
        FcntlArg::F_SETFD(FdFlag::from_bits_truncate(new_flags)),
    )
    .map(drop)
}

/// Closes the given file descriptor, panics on `Err(Errno::EBADF)`.
#[inline(always)]
pub fn close<Fd: IntoRawFd>(fd: Fd) -> Result<(), Errno> {
    let fd = fd.into_raw_fd();

    // Use safe_close which embeds syscall argument cookies.
    match safe_close(fd) {
        Ok(_) => Ok(()),
        Err(Errno::EBADF) => panic!("BUG: Attempt to close bad fd:{fd}, report a bug!"),
        Err(errno) => Err(errno),
    }
}

/// Safe wrapper for close_range(2).
#[inline(always)]
pub fn close_range(first: c_uint, last: c_uint, flags: c_uint) -> Result<(), Errno> {
    safe_close_range(first, last, flags)
}

/// Close all file descriptors >= `fd`, equivalent to BSD's closefrom(2).
///
/// # Errors
///
/// Propagates any error returned by `close_range`.
pub fn closefrom(fd: c_uint) -> Result<(), Errno> {
    close_range(fd, RawFd::MAX as c_uint, 0)
}

/// Close all file descriptors in `close`.
///
/// `closefds` must be sorted ascending and contain no duplicates;
/// otherwise returns `Err(Errno::EINVAL)`.
///
/// # Errors
///
/// Returns on the first syscall error encountered, or
/// `Err(Errno::EINVAL)` if `close` is not strictly ascending.
pub fn closeall(closefds: &[c_uint]) -> Result<(), Errno> {
    // no-op if close is empty.
    if closefds.is_empty() {
        return Ok(());
    }

    // Validate that `close` is strictly ascending and unique.
    if closefds.windows(2).any(|w| w[0] >= w[1]) {
        return Err(Errno::EINVAL);
    }

    let mut first = closefds[0];
    let mut last = first;

    #[expect(clippy::arithmetic_side_effects)]
    for &fd in &closefds[1..] {
        if fd != last + 1 {
            close_range(first, last, 0)?;
            first = fd;
        }
        last = fd;
    }
    close_range(first, last, 0)
}

/// Close all file descriptors except those in `exceptions`.
///
/// `exceptions` must be sorted ascending and contain no duplicates;
/// otherwise returns `Err(Errno::EINVAL)`.
///
/// Uses `close_range(2)` under the hood to efficiently close the
/// non-exempt descriptors.
///
/// # Errors
///
/// Returns on the first syscall error encountered, or
/// `Err(Errno::EINVAL)` if `exceptions` is not strictly ascending.
pub fn closeexcept(exceptions: &[c_uint]) -> Result<(), Errno> {
    // Validate that `exceptions` is strictly ascending and unique.
    if exceptions.windows(2).any(|w| w[0] >= w[1]) {
        return Err(Errno::EINVAL);
    }

    // If no exceptions, close everything.
    if exceptions.is_empty() {
        return closefrom(0);
    }

    // Use a wider integer for range computations to avoid overflow.
    let mut next: u64 = 0;

    for &ex_fd in exceptions {
        let ex_fd = u64::from(ex_fd);

        // Close [next .. ex_fd - 1], if non-empty.
        if next < ex_fd {
            let first = c_uint::try_from(next).or(Err(Errno::EOVERFLOW))?;
            let last = c_uint::try_from(ex_fd.checked_sub(1).ok_or(Errno::EOVERFLOW)?)
                .or(Err(Errno::EOVERFLOW))?;
            close_range(first, last, 0)?;
        }

        // Skip the exception itself.
        next = ex_fd.saturating_add(1);
    }

    // Finally close [next .. MAX_FD], if any remain.
    if next <= RawFd::MAX as u64 {
        let first = c_uint::try_from(next).or(Err(Errno::EOVERFLOW))?;
        closefrom(first)?;
    }

    Ok(())
}

const KCMP_FILE: c_long = 0;

/// Check if the given file descriptor is open for the given process.
pub fn is_open_fd(pid: Pid, fd: RawFd) -> Result<bool, Errno> {
    #[expect(clippy::cast_lossless)]
    #[expect(clippy::cast_possible_wrap)]
    #[expect(clippy::cast_sign_loss)]
    // SAFETY: There's no libc wrapper for kcmp.
    match Errno::result(unsafe {
        syscall(
            SYS_kcmp,
            pid.as_raw() as c_long,
            pid.as_raw() as c_long,
            KCMP_FILE,
            fd as c_ulong as c_long,
            fd as c_ulong as c_long,
        )
    }) {
        Ok(_) => Ok(true),
        Err(Errno::EBADF) => Ok(false),
        Err(errno) => Err(errno),
    }
}

/// Check two fds point to the same open file description for the given processes.
pub fn is_same_fd(pid1: Pid, pid2: Pid, fd1: RawFd, fd2: RawFd) -> Result<bool, Errno> {
    if pid1 == pid2 && fd1 == fd2 {
        // We do not check for open/valid FD in this function,
        // so we short-circuit here for efficiency.
        return Ok(true);
    }

    // SAFETY: There's no libc wrapper for kcmp.
    #[expect(clippy::cast_lossless)]
    #[expect(clippy::cast_possible_wrap)]
    #[expect(clippy::cast_sign_loss)]
    Ok(Errno::result(unsafe {
        syscall(
            SYS_kcmp,
            pid1.as_raw() as c_long,
            pid2.as_raw() as c_long,
            KCMP_FILE,
            fd1 as c_ulong as c_long,
            fd2 as c_ulong as c_long,
        )
    })? == 0)
}

/// Check if file resides on a hugetlbfs (e.g. memfds with MFD_HUGETLB)
pub fn is_huge_file<Fd: AsFd>(fd: Fd) -> Result<bool, Errno> {
    FsType::get(fd).map(|fs_type| fs_type.is_huge_file())
}

/// Check if file resides inside procfs(5).
pub fn is_proc<Fd: AsFd>(fd: Fd) -> Result<bool, Errno> {
    FsType::get(fd).map(|fs_type| fs_type.is_proc())
}

/// Check if file resides inside secret memory created by memfd_secret(2).
pub fn is_secretmem<Fd: AsFd>(fd: Fd) -> Result<bool, Errno> {
    FsType::get(fd).map(|fs_type| fs_type.is_secretmem())
}

/// Check if file is the /dev/null character device.
pub fn is_dev_null<Fd: AsFd>(fd: Fd) -> Result<bool, Errno> {
    const NULL_MAJOR: u32 = 1;
    const NULL_MINOR: u32 = 3;
    is_char_dev(fd, NULL_MAJOR, NULL_MINOR)
}

/// Check if file is the AMD KFD character device (/dev/kfd).
pub fn is_dev_kfd<Fd: AsFd>(fd: Fd) -> Result<bool, Errno> {
    const KFD_MAJOR: u32 = 238;
    const KFD_MINOR: u32 = 0;
    is_char_dev(fd, KFD_MAJOR, KFD_MINOR)
}

/// Check if file is the /dev/ptmx character device.
pub fn is_dev_ptmx<Fd: AsFd>(fd: Fd) -> Result<bool, Errno> {
    const PTMX_MAJOR: u32 = 5;
    const PTMX_MINOR: u32 = 2;
    is_char_dev(fd, PTMX_MAJOR, PTMX_MINOR)
}

/// Check if file is a character device with the given major/minor numbers.
pub fn is_char_dev<Fd: AsFd>(fd: Fd, major: u32, minor: u32) -> Result<bool, Errno> {
    #[expect(clippy::cast_possible_truncation)]
    const S_IFCHR: u16 = libc::S_IFCHR as u16;
    #[expect(clippy::cast_possible_truncation)]
    const S_IFMT: u16 = libc::S_IFMT as u16;

    let statx = fstatx(fd, STATX_BASIC_STATS)?;

    // Check if file is a character device,
    // and its device major/minor numbers
    // match the given parameters.
    Ok(statx.stx_mode & S_IFMT == S_IFCHR
        && statx.stx_rdev_major == major
        && statx.stx_rdev_minor == minor)
}

/// Check if the given file is a regular file.
pub fn is_file<Fd: AsFd>(fd: Fd) -> Result<bool, Errno> {
    #[expect(clippy::cast_possible_truncation)]
    const S_IFREG: u16 = libc::S_IFREG as u16;
    #[expect(clippy::cast_possible_truncation)]
    const S_IFMT: u16 = libc::S_IFMT as u16;

    let statx = fstatx(&fd, STATX_BASIC_STATS)?;

    Ok(statx.stx_mode & S_IFMT == S_IFREG)
}

/// Check if the given file is a regular empty file.
pub fn is_empty_file<Fd: AsFd>(fd: Fd) -> Result<bool, Errno> {
    #[expect(clippy::cast_possible_truncation)]
    const S_IFREG: u16 = libc::S_IFREG as u16;
    #[expect(clippy::cast_possible_truncation)]
    const S_IFMT: u16 = libc::S_IFMT as u16;

    let statx = fstatx(&fd, STATX_BASIC_STATS)?;

    Ok(statx.stx_size == 0 && statx.stx_mode & S_IFMT == S_IFREG)
}

/// Check if the given file is a memory file descriptor.
///
/// This function requires proc(5) mounted.
pub fn is_memfd<Fd: AsFd>(fd: Fd) -> Result<bool, Errno> {
    let pfd = XPathBuf::from_self_fd(fd.as_fd().as_raw_fd())?;
    let lnk = readlinkat(PROC_FILE(), &pfd)?;
    Ok(lnk.starts_with(b"/memfd:") && lnk.ends_with(b" (deleted)"))
}

/// Parse a FD from a Path.
pub fn parse_fd(path: &XPath) -> Result<RawFd, Errno> {
    btoi::<RawFd>(path.as_bytes()).or(Err(Errno::EBADF))
}

/// Seals the memfd for write, grow, shrink and future seals.
pub fn seal_memfd_all<Fd: AsFd>(fd: Fd) -> Result<(), Errno> {
    seal_memfd(
        fd,
        SealFlag::F_SEAL_SEAL
            | SealFlag::F_SEAL_WRITE
            | SealFlag::F_SEAL_SHRINK
            | SealFlag::F_SEAL_GROW,
    )
}

/// Seals memfd with the given `SealFlag`.
///
/// Returns `Err(Errno::EINVAL)` if `flags` is empty.
pub fn seal_memfd<Fd: AsFd>(fd: Fd, flags: SealFlag) -> Result<(), Errno> {
    // Guard against nonsensical use.
    if flags.is_empty() {
        return Err(Errno::EINVAL);
    }

    // Seal memory fd.
    fcntl(fd, FcntlArg::F_ADD_SEALS(flags)).map(drop)
}

/// Set pipe max size of the given pipe.
pub fn set_pipemax<Fd: AsFd>(fd: Fd, size: c_int) -> Result<usize, Errno> {
    #[expect(clippy::cast_sign_loss)]
    fcntl(fd, FcntlArg::F_SETPIPE_SZ(size)).map(|r| r as usize)
}

/// Get exclusive mode for the given terminal.
pub fn get_exclusive<Fd: AsFd>(fd: Fd) -> Result<bool, Errno> {
    let mut set: c_int = 0;
    let fd = fd.as_fd().as_raw_fd();

    // SAFETY: TIOCGEXCL takes an int* to return 0 or nonzero.
    Errno::result(unsafe { syscall(SYS_ioctl, fd, TIOCGEXCL, std::ptr::addr_of_mut!(set)) })
        .map(|_| set != 0)
}

/// Set given terminal to exclusive mode, or disable exclusive mode.
pub fn set_exclusive<Fd: AsFd>(fd: Fd, enable: bool) -> Result<(), Errno> {
    let fd = fd.as_fd().as_raw_fd();
    let req = if enable { TIOCEXCL } else { TIOCNXCL };

    // SAFETY: TIOC{E,N}XCL take no extra arguments.
    Errno::result(unsafe { syscall(SYS_ioctl, fd, req) }).map(drop)
}

/// Checks if the given file descriptor has a send timeout set.
pub fn has_send_timeout<F: AsFd>(fd: &F) -> Result<bool, Errno> {
    let tv = getsockopt(fd, SendTimeout)?;
    Ok(tv.tv_sec() != 0 || tv.tv_usec() != 0)
}

/// Checks if the given file descriptor has a receive timeout set.
pub fn has_recv_timeout<F: AsFd>(fd: &F) -> Result<bool, Errno> {
    let tv = getsockopt(fd, ReceiveTimeout)?;
    Ok(tv.tv_sec() != 0 || tv.tv_usec() != 0)
}

/// Returns the inode for the given file descriptor.
pub fn fd_inode<Fd: AsFd>(fd: Fd) -> Result<u64, Errno> {
    retry_on_eintr(|| fstatx(&fd, STATX_INO)).map(|statx| statx.stx_ino)
}

/// Returns the mode for the given file descriptor.
pub fn fd_mode<Fd: AsFd>(fd: Fd) -> Result<Mode, Errno> {
    retry_on_eintr(|| fstatx(&fd, STATX_MODE))
        .map(|statx| statx.stx_mode)
        .map(u32::from)
        .map(Mode::from_bits_retain)
}

/// Returns true if the given file descriptor is active.
pub fn is_active_fd<Fd: AsFd>(fd: Fd) -> bool {
    fcntl(fd, FcntlArg::F_GETFD).is_ok()
}

/// Returns true if the given file descriptor is syntactically valid.
///
/// Negative values, including AT_FDCWD, are not syntactically valid.
pub fn is_valid_fd(fd: u64) -> bool {
    to_valid_fd(fd).map(|fd| fd >= 0).unwrap_or(false)
}

/// Converts a system call argument to a RawFd.
///
/// Negative values, excluding AT_FDCWD, return an error.
#[expect(clippy::cast_possible_truncation)]
pub fn to_valid_fd(fd: u64) -> Result<RawFd, Errno> {
    let fd = fd as RawFd;

    if fd == libc::AT_FDCWD || fd >= 0 {
        Ok(fd)
    } else {
        Err(Errno::EBADF)
    }
}

/// Converts a system call argument to a RawFd.
///
/// Negative values, including AT_FDCWD, return an error.
#[expect(clippy::cast_possible_truncation)]
pub fn to_fd(fd: u64) -> Result<RawFd, Errno> {
    let fd = fd as RawFd;

    if fd >= 0 {
        Ok(fd)
    } else {
        Err(Errno::EBADF)
    }
}

/// Returns file access mode in status flags.
pub fn fd_status_flags<Fd: AsFd>(fd: Fd) -> Result<OFlag, Errno> {
    fcntl(fd, FcntlArg::F_GETFL).map(OFlag::from_bits_truncate)
}

/// Returns true if file is writable.
pub fn is_writable_fd<Fd: AsFd>(fd: Fd) -> Result<bool, Errno> {
    fd_status_flags(fd)
        .map(oflag_accmode)
        .map(|mode| !mode.is_empty())
}

/// Get number of open file descriptors.
pub fn fd_count(pid: Option<Pid>) -> Result<u64, Errno> {
    let mut pfd = XPathBuf::from("/proc");
    if let Some(pid) = pid {
        pfd.push_pid(pid);
    } else {
        pfd.push(b"thread-self");
    }
    pfd.push(b"fd");

    if *HAVE_PROC_PID_FD_STAT_SIZE {
        let stx = statx(AT_BADFD, &pfd, 0, STATX_SIZE)?;
        return Ok(stx.stx_size);
    }

    #[expect(clippy::disallowed_methods)]
    let fd = nix::fcntl::openat(
        AT_BADFD,
        &pfd,
        OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC,
        Mode::empty(),
    )?;
    let mut nfds: u64 = 0;
    loop {
        match getdents64(&fd, DIRENT_BUF_SIZE) {
            Ok(entries) => {
                nfds = nfds
                    .checked_add(entries.count() as u64)
                    .ok_or(Errno::ERANGE)?
            }
            Err(Errno::ECANCELED) => break, // EOF or empty directory.
            Err(errno) => return Err(errno),
        };
    }

    Ok(nfds.saturating_sub(2))
}

// execveat(2): Only perform a check if execution would be allowed.
// Requires Linux>=6.14.
pub(crate) const AT_EXECVE_CHECK: AtFlags = AtFlags::from_bits_retain(0x10000);

/// Return true if the given File is executable.
pub fn is_executable<Fd: AsFd>(file: Fd) -> bool {
    check_executable(file).is_ok()
}

/// Check if the given File is executable.
pub fn check_executable<Fd: AsFd>(file: Fd) -> Result<(), Errno> {
    if *HAVE_AT_EXECVE_CHECK {
        safe_execve_check(file)
    } else {
        safe_faccess(file, AccessFlags::X_OK, crate::compat::AT_EACCESS)
    }
}

/// PIDFD_THREAD flag for pidfd_open(2).
#[expect(clippy::cast_sign_loss)]
pub const PIDFD_THREAD: u32 = OFlag::O_EXCL.bits() as u32;

/// PIDFD_NONBLOCK flag for pidfd_open(2).
pub const PIDFD_NONBLOCK: u32 = libc::O_NONBLOCK as u32;

/// Safe wrapper for pidfd_open(2).
///
/// This function requires Linux 5.3+.
pub fn pidfd_open(pid: Pid, mut flags: u32) -> Result<SafeOwnedFd, Errno> {
    // Use PIDFD_THREAD if available, pass-through PIDFD_NONBLOCK.
    let pid = if *HAVE_PIDFD_THREAD || flags & PIDFD_THREAD == 0 {
        pid
    } else {
        flags &= !PIDFD_THREAD;
        proc_tgid(pid)?
    };

    // SAFETY: libc does not have a pidfd_open(2) wrapper yet.
    #[expect(clippy::cast_possible_truncation)]
    Errno::result(unsafe { syscall(SYS_pidfd_open, pid.as_raw(), flags) }).map(|fd| {
        // SAFETY: pidfd_open(2) returned success, fd is valid.
        unsafe { SafeOwnedFd::from_raw_fd(fd as RawFd) }
    })
}

/// Safe wrapper for pidfd_getfd(2).
///
/// This function requires Linux 5.6+.
pub fn pidfd_getfd<Fd: AsFd>(pid_fd: Fd, remote_fd: RawFd) -> Result<SafeOwnedFd, Errno> {
    // SAFETY: libc does not have a pidfd_getfd(2) wrapper yet.
    #[expect(clippy::cast_possible_truncation)]
    Errno::result(unsafe { syscall(SYS_pidfd_getfd, pid_fd.as_fd().as_raw_fd(), remote_fd, 0) })
        .map(|fd| {
            // SAFETY: pidfd_getfd(2) returned success, fd is valid.
            unsafe { SafeOwnedFd::from_raw_fd(fd as RawFd) }
        })
}

/// Safe wrapper for pidfd_send_signal(2).
///
/// This function requires Linux 5.1+.
pub fn pidfd_send_signal<Fd: AsFd>(pid_fd: Fd, sig: i32) -> Result<(), Errno> {
    // SAFETY: libc does not have a wrapper for pidfd_send_signal yet.
    Errno::result(unsafe { syscall(SYS_pidfd_send_signal, pid_fd.as_fd().as_raw_fd(), sig, 0, 0) })
        .map(drop)
}

/// Safe wrapper for pidfd_send_signal(2) with signal 0.
///
/// This function requires Linux 5.1+.
pub fn pidfd_is_alive<Fd: AsFd>(pid_fd: Fd) -> Result<(), Errno> {
    pidfd_send_signal(pid_fd, 0)
}

/// Raw `clone(2)` with `CLONE_PIDFD` and NULL stack (COW semantics).
///
/// `CLONE_VM` must not be set.
#[expect(unreachable_code)]
pub fn fdclone<F: FnOnce() -> Infallible>(
    func: F,
    flags: CloneFlags,
    signal: Option<c_int>,
) -> Result<(SafeOwnedFd, Pid), Errno> {
    if flags.contains(CloneFlags::CLONE_VM) {
        return Err(Errno::EINVAL);
    }

    let mut pid_fd: libc::c_int = -1;
    let clone_flags = flags.bits() | signal.unwrap_or(0) | libc::CLONE_PIDFD;

    // SAFETY:
    // Arch-specific argument order; see kernel/fork.c.
    // CLONE_BACKWARDS2 (s390): newsp, flags, &parent_tid, &child_tid, tls
    // CLONE_BACKWARDS / default: flags, newsp, &parent_tid, tls, &child_tid
    let child = Errno::result(unsafe {
        #[cfg(target_arch = "s390x")]
        {
            syscall(
                libc::SYS_clone,
                0,
                clone_flags,
                std::ptr::addr_of_mut!(pid_fd) as c_long,
                0,
                0,
            )
        }
        #[cfg(not(target_arch = "s390x"))]
        {
            syscall(
                libc::SYS_clone,
                clone_flags,
                0,
                std::ptr::addr_of_mut!(pid_fd) as c_long,
                0,
                0,
            )
        }
    })?;

    if child == 0 {
        func(); // never returns.
    }

    #[expect(clippy::cast_possible_truncation)]
    Ok((
        // SAFETY: clone(2) succeeded, pid_fd is a valid file descriptor.
        unsafe { SafeOwnedFd::from_raw_fd(pid_fd) },
        Pid::from_raw(child as libc::pid_t),
    ))
}

/// Send bytes and file descriptors over a Unix stream socket.
///
/// Returns the number of bytes sent on success.
pub fn send_with_fd<Fd: AsFd>(sock: Fd, bytes: &[u8], fds: &[RawFd]) -> Result<usize, Errno> {
    let iov = [io::IoSlice::new(bytes)];

    // SAFETY:
    // 1. fds are valid file descriptors.
    // 2. BorrowedFd is repr(transparent) over RawFd, so transmuting a
    //    &[RawFd] to &[BorrowedFd] is layout-safe when the fds are
    //    valid.
    let borrowed: &[BorrowedFd<'_>] =
        unsafe { std::slice::from_raw_parts(fds.as_ptr().cast(), fds.len()) };
    let cmsgs: &[Cmsg<'_>] = if fds.is_empty() {
        &[]
    } else {
        &[Cmsg::ScmRights(borrowed)]
    };
    sendmsg::<_, SockaddrStorage>(&sock, &iov, cmsgs, MsgFlags::empty(), None)
}

/// Receive bytes and file descriptors from a Unix stream socket.
///
/// Returns `(bytes_received, fds_received)` on success.
pub fn recv_with_fd<Fd: AsFd>(
    sock: Fd,
    bytes: &mut [u8],
    fds: &mut [RawFd],
) -> Result<(usize, usize), Errno> {
    let mut iov = [io::IoSliceMut::new(bytes)];

    let cmsg_siz = RawFd::cmsg_space()
        .checked_mul(fds.len())
        .ok_or(Errno::EOVERFLOW)?;
    let mut cmsg_buf = vec![0u8; cmsg_siz];

    let mut hdr = MsgHdr::default();
    hdr.set_iov_mut(&mut iov);
    if !fds.is_empty() {
        hdr.set_control(&mut cmsg_buf);
    }
    let msg = recvmsg(&sock, &mut hdr, MsgFlags::empty())?;

    let mut fd_count = 0;
    if let Ok(cmsgs) = msg.cmsgs() {
        for cmsg in cmsgs {
            if let CmsgOwned::ScmRights(recv_fds) = cmsg {
                for fd in recv_fds {
                    if fd_count < fds.len() {
                        fds[fd_count] = fd.into_raw_fd();
                        fd_count = fd_count.checked_add(1).ok_or(Errno::EOVERFLOW)?;
                    }
                }
            }
        }
    }

    Ok((msg.bytes, fd_count))
}

/// Get peer credentials for the given UNIX socket.
pub fn peer_creds<Fd: AsFd>(fd: Fd) -> Result<UnixCredentials, Errno> {
    getsockopt(&fd, PeerCredentials)
}

/// Netlink alignment helper: nlmsg_align.
#[expect(clippy::arithmetic_side_effects)]
pub fn nlmsg_align(v: usize) -> usize {
    (v + 3) & !3usize
}

/// Netlink alignment helper: nla_align.
#[expect(clippy::arithmetic_side_effects)]
pub fn nla_align(v: usize) -> usize {
    (v + 3) & !3usize
}

// Constants:
// SOCK_DIAG_BY_FAMILY is 20 in the kernel uapi.
const SOCK_DIAG_BY_FAMILY: u16 = 20;

// Netlink special message types.
#[expect(clippy::cast_possible_truncation)]
const NLMSG_DONE: u16 = libc::NLMSG_DONE as u16;
#[expect(clippy::cast_possible_truncation)]
const NLMSG_ERROR: u16 = libc::NLMSG_ERROR as u16;

// nlmsghdr (16) + unix_diag_req (24) = 40 bytes.
const NL_HDR_LEN: usize = 16;
const UD_REQ_LEN: usize = 24;
#[expect(clippy::cast_possible_truncation)]
const NL_MSG_LEN: u32 = (NL_HDR_LEN + UD_REQ_LEN) as u32;

// udiag flags / attributes
const UNIX_DIAG_VFS: u16 = 1;
const UNIX_DIAG_PEER: u16 = 2;
const UDIAG_SHOW_VFS: u32 = 0x0000_0002;
const UDIAG_SHOW_PEER: u32 = 0x0000_0004;

/// Return the peer socket inode (low 32 bits zero-extended) for a UNIX-domain
/// socket with the given `inode`. Uses NETLINK_SOCK_DIAG / unix diag and requests the
/// peer attribute. If peer socket inode is not available, returns local socket
/// inode as fallback. Requires Linux kernel to be configured with `CONFIG_UNIX_DIAG`.
#[expect(clippy::arithmetic_side_effects)]
#[expect(clippy::cast_possible_truncation)]
pub fn peer_inode(inode: u64) -> Result<u64, Errno> {
    // Get local inode to filter diag results.
    let local_ino = inode;
    let local_ino32 = (local_ino & 0xffff_ffff) as u32;

    // Open NETLINK_SOCK_DIAG socket.
    let nl = safe_socket(
        AddressFamily::Netlink,
        SockType::Datagram,
        SockFlag::SOCK_CLOEXEC,
        libc::NETLINK_SOCK_DIAG,
    )?;

    // Build request into a stack buffer.
    let mut req = [0u8; NL_HDR_LEN + UD_REQ_LEN];

    // Fill nlmsghdr.
    let mut p = 0usize;
    req[p..p + 4].copy_from_slice(&NL_MSG_LEN.to_ne_bytes()); // nlmsg_len
    p += 4;
    req[p..p + 2].copy_from_slice(&SOCK_DIAG_BY_FAMILY.to_ne_bytes()); // nlmsg_type
    p += 2;
    let nl_flags = (libc::NLM_F_REQUEST | libc::NLM_F_ROOT | libc::NLM_F_MATCH) as u16;
    req[p..p + 2].copy_from_slice(&nl_flags.to_ne_bytes()); // nlmsg_flags
    p += 2;
    req[p..p + 4].copy_from_slice(&1u32.to_ne_bytes()); // nlmsg_seq
    p += 4;
    req[p..p + 4].copy_from_slice(&0u32.to_ne_bytes()); // nlmsg_pid
    p += 4;

    // Fill unix_diag_req.
    req[p] = libc::AF_UNIX as u8;
    p += 1; // sdiag_family
    req[p] = 0u8;
    p += 1; // sdiag_protocol
    req[p..p + 2].copy_from_slice(&0u16.to_ne_bytes());
    p += 2; // pad
    req[p..p + 4].copy_from_slice(&u32::MAX.to_ne_bytes());
    p += 4; // udiag_states
    req[p..p + 4].copy_from_slice(&local_ino32.to_ne_bytes());
    p += 4; // udiag_ino
    req[p..p + 4].copy_from_slice(&UDIAG_SHOW_PEER.to_ne_bytes());
    p += 4; // udiag_show
    req[p..p + 4].copy_from_slice(&0u32.to_ne_bytes());
    p += 4; // cookie[0]
    req[p..p + 4].copy_from_slice(&0u32.to_ne_bytes());
    p += 4; // cookie[1]
    assert_eq!(p, req.len());

    // Send loop: Retry short writes until full message sent.
    let mut sent_total = 0usize;
    while sent_total < req.len() {
        let slice = &req[sent_total..];
        let sent = retry_on_eintr(|| write(&nl, slice))?;
        if sent == 0 {
            return Err(Errno::EIO);
        }
        sent_total = sent_total.saturating_add(sent);
    }

    // Recv loop: Parse netlink messages until we find UNIX_DIAG_PEER or finish.
    //
    // Quoting https://docs.kernel.org/userspace-api/netlink/intro.html
    // Netlink expects that the user buffer will be at least 8kB or a page size
    // of the CPU architecture, whichever is bigger. Particular Netlink families
    // may, however, require a larger buffer. 32kB buffer is recommended for most
    // efficient handling of dumps (larger buffer fits more dumped objects and
    // therefore fewer recvmsg() calls are needed).
    let mut rbuf = [0u8; 0x8000];
    loop {
        let n = retry_on_eintr(|| read(&nl, &mut rbuf))?;
        if n == 0 {
            return Err(Errno::EIO);
        }
        let mut off = 0usize;
        while off + NL_HDR_LEN <= n {
            // Read nlmsg_len (u32) and nlmsg_type (u16) safely.
            let nlmsg_len = {
                let b: [u8; 4] = rbuf[off..off + 4].try_into().or(Err(Errno::EOVERFLOW))?;
                u32::from_ne_bytes(b) as usize
            };
            if nlmsg_len == 0 || off + nlmsg_len > n {
                return Err(Errno::EIO);
            }
            let nlmsg_type = {
                let b: [u8; 2] = rbuf[off + 4..off + 6]
                    .try_into()
                    .or(Err(Errno::EOVERFLOW))?;
                u16::from_ne_bytes(b)
            };

            if nlmsg_type == NLMSG_DONE {
                //
                // return Err(Errno::ENODATA);
                //
                // Best effort, return local inode.
                return Ok(local_ino);
            } else if nlmsg_type == NLMSG_ERROR {
                if nlmsg_len >= NL_HDR_LEN + 4 {
                    let err_b: [u8; 4] = rbuf[off + NL_HDR_LEN..off + NL_HDR_LEN + 4]
                        .try_into()
                        .or(Err(Errno::EOVERFLOW))?;
                    let nl_err = i32::from_ne_bytes(err_b);
                    // nlmsgerr.error is negative errno.
                    return Err(Errno::from_raw(-nl_err));
                } else {
                    return Err(Errno::EIO);
                }
            } else if nlmsg_type == SOCK_DIAG_BY_FAMILY {
                let payload_off = off + NL_HDR_LEN;
                let ud_min = 16usize;
                if payload_off + ud_min > off + nlmsg_len {
                    return Err(Errno::EIO);
                }
                // udiag_ino at payload_off + 4 (u32)
                let found_ino32 = {
                    let b: [u8; 4] = rbuf[payload_off + 4..payload_off + 8]
                        .try_into()
                        .or(Err(Errno::EOVERFLOW))?;
                    u64::from(u32::from_ne_bytes(b))
                };
                if (found_ino32 & 0xffff_ffff) != (local_ino & 0xffff_ffff) {
                    off = nlmsg_align(off + nlmsg_len);
                    continue;
                }

                // Parse attributes.
                let mut attr_off = payload_off + ud_min;
                while attr_off + 4 <= off + nlmsg_len {
                    let nla_len = {
                        let b: [u8; 2] = rbuf[attr_off..attr_off + 2]
                            .try_into()
                            .or(Err(Errno::EOVERFLOW))?;
                        u16::from_ne_bytes(b) as usize
                    };
                    let nla_type = {
                        let b: [u8; 2] = rbuf[attr_off + 2..attr_off + 4]
                            .try_into()
                            .or(Err(Errno::EOVERFLOW))?;
                        u16::from_ne_bytes(b)
                    };
                    if nla_len < 4 {
                        break;
                    }
                    let payload_start = attr_off + 4;
                    let payload_len = nla_len - 4;
                    if payload_start + payload_len > off + nlmsg_len {
                        break;
                    }

                    if nla_type == UNIX_DIAG_PEER && payload_len >= 4 {
                        let peer_b: [u8; 4] = rbuf[payload_start..payload_start + 4]
                            .try_into()
                            .or(Err(Errno::EOVERFLOW))?;
                        let peer_ino = u64::from(u32::from_ne_bytes(peer_b));
                        return Ok(peer_ino);
                    }

                    attr_off = attr_off.saturating_add(nla_align(nla_len));
                }
            }

            off = nlmsg_align(off + nlmsg_len);
        }
        // Continue read loop for multipart replies.
    }
}

/// Return device ID and inode of the socket file on disk for a
/// UNIX-domain socket with the given `inode`. Uses NETLINK_SOCK_DIAG
/// with UDIAG_SHOW_VFS. Requires Linux kernel to be configured with
/// `CONFIG_UNIX_DIAG`.
#[expect(clippy::arithmetic_side_effects)]
#[expect(clippy::cast_possible_truncation)]
pub fn unix_vfs_id(inode: u64) -> Result<(u32, u32), Errno> {
    let local_ino32 = (inode & 0xffff_ffff) as u32;

    let nl = safe_socket(
        AddressFamily::Netlink,
        SockType::Datagram,
        SockFlag::SOCK_CLOEXEC,
        libc::NETLINK_SOCK_DIAG,
    )?;

    let mut req = [0u8; NL_HDR_LEN + UD_REQ_LEN];
    let mut p = 0usize;
    req[p..p + 4].copy_from_slice(&NL_MSG_LEN.to_ne_bytes());
    p += 4;
    req[p..p + 2].copy_from_slice(&SOCK_DIAG_BY_FAMILY.to_ne_bytes());
    p += 2;
    let nl_flags = (libc::NLM_F_REQUEST | libc::NLM_F_ROOT | libc::NLM_F_MATCH) as u16;
    req[p..p + 2].copy_from_slice(&nl_flags.to_ne_bytes());
    p += 2;
    req[p..p + 4].copy_from_slice(&1u32.to_ne_bytes());
    p += 4;
    req[p..p + 4].copy_from_slice(&0u32.to_ne_bytes());
    p += 4;

    req[p] = libc::AF_UNIX as u8;
    p += 1;
    req[p] = 0u8;
    p += 1;
    req[p..p + 2].copy_from_slice(&0u16.to_ne_bytes());
    p += 2;
    req[p..p + 4].copy_from_slice(&u32::MAX.to_ne_bytes());
    p += 4;
    req[p..p + 4].copy_from_slice(&local_ino32.to_ne_bytes());
    p += 4;
    req[p..p + 4].copy_from_slice(&UDIAG_SHOW_VFS.to_ne_bytes());
    p += 4;
    req[p..p + 4].copy_from_slice(&0u32.to_ne_bytes());
    p += 4;
    req[p..p + 4].copy_from_slice(&0u32.to_ne_bytes());
    p += 4;
    assert_eq!(p, req.len());

    let mut sent_total = 0usize;
    while sent_total < req.len() {
        let sent = retry_on_eintr(|| write(&nl, &req[sent_total..]))?;
        if sent == 0 {
            return Err(Errno::EIO);
        }
        sent_total = sent_total.saturating_add(sent);
    }

    let mut rbuf = [0u8; 0x8000];
    loop {
        let n = retry_on_eintr(|| read(&nl, &mut rbuf))?;
        if n == 0 {
            return Err(Errno::EIO);
        }
        let mut off = 0usize;
        while off + NL_HDR_LEN <= n {
            let nlmsg_len = {
                let b: [u8; 4] = rbuf[off..off + 4].try_into().or(Err(Errno::EOVERFLOW))?;
                u32::from_ne_bytes(b) as usize
            };
            if nlmsg_len == 0 || off + nlmsg_len > n {
                return Err(Errno::EIO);
            }
            let nlmsg_type = {
                let b: [u8; 2] = rbuf[off + 4..off + 6]
                    .try_into()
                    .or(Err(Errno::EOVERFLOW))?;
                u16::from_ne_bytes(b)
            };

            if nlmsg_type == NLMSG_DONE {
                return Err(Errno::ENODATA);
            } else if nlmsg_type == NLMSG_ERROR {
                if nlmsg_len >= NL_HDR_LEN + 4 {
                    let err_b: [u8; 4] = rbuf[off + NL_HDR_LEN..off + NL_HDR_LEN + 4]
                        .try_into()
                        .or(Err(Errno::EOVERFLOW))?;
                    return Err(Errno::from_raw(-i32::from_ne_bytes(err_b)));
                }
                return Err(Errno::EIO);
            } else if nlmsg_type == SOCK_DIAG_BY_FAMILY {
                let payload_off = off + NL_HDR_LEN;
                let ud_min = 16usize;
                if payload_off + ud_min > off + nlmsg_len {
                    return Err(Errno::EIO);
                }
                let found_ino32 = {
                    let b: [u8; 4] = rbuf[payload_off + 4..payload_off + 8]
                        .try_into()
                        .or(Err(Errno::EOVERFLOW))?;
                    u64::from(u32::from_ne_bytes(b))
                };
                if (found_ino32 & 0xffff_ffff) != (inode & 0xffff_ffff) {
                    off = nlmsg_align(off + nlmsg_len);
                    continue;
                }

                // Parse attributes looking for UNIX_DIAG_VFS.
                let mut attr_off = payload_off + ud_min;
                while attr_off + 4 <= off + nlmsg_len {
                    let nla_len = {
                        let b: [u8; 2] = rbuf[attr_off..attr_off + 2]
                            .try_into()
                            .or(Err(Errno::EOVERFLOW))?;
                        u16::from_ne_bytes(b) as usize
                    };
                    let nla_type = {
                        let b: [u8; 2] = rbuf[attr_off + 2..attr_off + 4]
                            .try_into()
                            .or(Err(Errno::EOVERFLOW))?;
                        u16::from_ne_bytes(b)
                    };
                    if nla_len < 4 {
                        break;
                    }
                    let payload_start = attr_off + 4;
                    let payload_len = nla_len - 4;
                    if payload_start + payload_len > off + nlmsg_len {
                        break;
                    }

                    // struct unix_diag_vfs { u32 udiag_vfs_ino; u32 udiag_vfs_dev; }
                    if nla_type == UNIX_DIAG_VFS && payload_len >= 8 {
                        let vfs_ino = {
                            let b: [u8; 4] = rbuf[payload_start..payload_start + 4]
                                .try_into()
                                .or(Err(Errno::EOVERFLOW))?;
                            u32::from_ne_bytes(b)
                        };
                        let vfs_dev = {
                            let b: [u8; 4] = rbuf[payload_start + 4..payload_start + 8]
                                .try_into()
                                .or(Err(Errno::EOVERFLOW))?;
                            u32::from_ne_bytes(b)
                        };
                        return Ok((vfs_dev, vfs_ino));
                    }

                    attr_off = attr_off.saturating_add(nla_align(nla_len));
                }
            }

            off = nlmsg_align(off + nlmsg_len);
        }
    }
}

/// Returns a set of all UNIX domain sockets using NETLINK_SOCK_DIAG.
#[expect(clippy::arithmetic_side_effects)]
#[expect(clippy::cast_possible_truncation)]
pub fn unix_inodes() -> Result<SydHashSet<u64>, Errno> {
    // Open NETLINK_SOCK_DIAG socket.
    let nl = safe_socket(
        AddressFamily::Netlink,
        SockType::Datagram,
        SockFlag::SOCK_CLOEXEC,
        libc::NETLINK_SOCK_DIAG,
    )?;

    // Build request into a stack buffer.
    let mut req = [0u8; NL_HDR_LEN + UD_REQ_LEN];

    // Fill nlmsghdr.
    let mut p = 0usize;
    req[p..p + 4].copy_from_slice(&NL_MSG_LEN.to_ne_bytes()); // nlmsg_len
    p += 4;
    req[p..p + 2].copy_from_slice(&SOCK_DIAG_BY_FAMILY.to_ne_bytes()); // nlmsg_type
    p += 2;
    let nl_flags = (libc::NLM_F_REQUEST | libc::NLM_F_ROOT | libc::NLM_F_MATCH) as u16;
    req[p..p + 2].copy_from_slice(&nl_flags.to_ne_bytes()); // nlmsg_flags
    p += 2;
    req[p..p + 4].copy_from_slice(&1u32.to_ne_bytes()); // nlmsg_seq
    p += 4;
    req[p..p + 4].copy_from_slice(&0u32.to_ne_bytes()); // nlmsg_pid
    p += 4;

    // Fill unix_diag_req for a full dump of AF_UNIX sockets.
    req[p] = libc::AF_UNIX as u8;
    p += 1; // sdiag_family
    req[p] = 0u8;
    p += 1; // sdiag_protocol
    req[p..p + 2].copy_from_slice(&0u16.to_ne_bytes());
    p += 2; // pad
    req[p..p + 4].copy_from_slice(&u32::MAX.to_ne_bytes());
    p += 4; // udiag_states (all)
    req[p..p + 4].copy_from_slice(&0u32.to_ne_bytes());
    p += 4; // udiag_ino (0 => no inode filter; dump)
    req[p..p + 4].copy_from_slice(&UDIAG_SHOW_VFS.to_ne_bytes());
    p += 4; // udiag_show (no attributes needed)
    req[p..p + 4].copy_from_slice(&0u32.to_ne_bytes());
    p += 4; // cookie[0]
    req[p..p + 4].copy_from_slice(&0u32.to_ne_bytes());
    p += 4; // cookie[1]
    assert_eq!(p, req.len());

    // Send loop: retry short writes until full message is sent.
    let mut sent_total = 0usize;
    while sent_total < req.len() {
        let slice = &req[sent_total..];
        let sent = retry_on_eintr(|| write(&nl, slice))?;
        if sent == 0 {
            return Err(Errno::EIO);
        }
        sent_total = sent_total.saturating_add(sent);
    }

    // Recv loop: collect all udiag_ino values directly into a HashSet.
    //
    // Quoting https://docs.kernel.org/userspace-api/netlink/intro.html :
    // Use at least an 8kB buffer; 32kB recommended for dumps.
    let mut rbuf = [0u8; 0x8000];
    let mut iset = SydHashSet::default();
    'recv: loop {
        let n = retry_on_eintr(|| read(&nl, &mut rbuf))?;
        if n == 0 {
            return Err(Errno::EIO);
        }

        let mut off = 0usize;
        while off + NL_HDR_LEN <= n {
            // Read nlmsg_len (u32) and nlmsg_type (u16) safely.
            let nlmsg_len = {
                let b: [u8; 4] = rbuf[off..off + 4].try_into().or(Err(Errno::EOVERFLOW))?;
                u32::from_ne_bytes(b) as usize
            };
            if nlmsg_len == 0 || off + nlmsg_len > n {
                return Err(Errno::EIO);
            }
            let nlmsg_type = {
                let b: [u8; 2] = rbuf[off + 4..off + 6]
                    .try_into()
                    .or(Err(Errno::EOVERFLOW))?;
                u16::from_ne_bytes(b)
            };

            if nlmsg_type == NLMSG_DONE {
                break 'recv;
            } else if nlmsg_type == NLMSG_ERROR {
                if nlmsg_len >= NL_HDR_LEN + 4 {
                    let err_b: [u8; 4] = rbuf[off + NL_HDR_LEN..off + NL_HDR_LEN + 4]
                        .try_into()
                        .or(Err(Errno::EOVERFLOW))?;
                    let nl_err = i32::from_ne_bytes(err_b);
                    // nlmsgerr.error is negative errno.
                    return Err(Errno::from_raw(-nl_err));
                } else {
                    return Err(Errno::EIO);
                }
            } else if nlmsg_type == SOCK_DIAG_BY_FAMILY {
                // unix_diag_msg minimal payload is 16 bytes.
                let payload_off = off + NL_HDR_LEN;
                let ud_min = 16usize;
                if payload_off + ud_min > off + nlmsg_len {
                    return Err(Errno::EIO);
                }

                // udiag_ino (u32) at payload_off + 4
                let ino32 = {
                    let b: [u8; 4] = rbuf[payload_off + 4..payload_off + 8]
                        .try_into()
                        .or(Err(Errno::EOVERFLOW))?;
                    u32::from_ne_bytes(b)
                };

                // Walk NLAs; presence of UNIX_DIAG_VFS => path-based socket.
                let mut has_vfs = false;
                let mut attr_off = payload_off + ud_min;
                let attrs_end = off + nlmsg_len;
                while attr_off + 4 <= attrs_end {
                    let nla_len = {
                        let b: [u8; 2] = rbuf[attr_off..attr_off + 2]
                            .try_into()
                            .or(Err(Errno::EOVERFLOW))?;
                        u16::from_ne_bytes(b) as usize
                    };
                    let nla_type = {
                        let b: [u8; 2] = rbuf[attr_off + 2..attr_off + 4]
                            .try_into()
                            .or(Err(Errno::EOVERFLOW))?;
                        u16::from_ne_bytes(b)
                    };

                    if nla_len < 4 {
                        // Malformed NLA header;
                        // Stop parsing this message to avoid overrun.
                        break;
                    }

                    // Bounds-check this attribute's payload region. If it would overflow
                    // this message, break the attribute loop to skip the rest of this
                    // message safely (staying synchronized with the outer message parser).
                    let payload_start = attr_off + 4;
                    let payload_len = nla_len - 4;
                    if payload_start > attrs_end || payload_start + payload_len > attrs_end {
                        // Malformed/overrun; skip remainder of this message
                        break;
                    }

                    if nla_type == UNIX_DIAG_VFS {
                        has_vfs = true;
                        break;
                    }

                    // Advance to next attribute (aligned).
                    let next = attr_off.saturating_add(nla_align(nla_len));
                    if next <= attr_off {
                        break;
                    } // overflow guard
                    attr_off = next;
                }

                // Insert path-based sockets into the set.
                if has_vfs {
                    iset.try_reserve(1).or(Err(Errno::ENOMEM))?;
                    let _ = iset.insert(ino32.into());
                }
            }

            off = nlmsg_align(off + nlmsg_len);
        }
        // Continue read loop for multipart replies.
    }

    Ok(iset)
}

/// Open static file descriptors for use by syd::proc and friends.
pub fn open_static_files() -> Result<(), Errno> {
    open_static_root()?;
    open_static_proc()?;
    open_static_null()
}

/// Close static file descriptors for use by syd::proc and friends.
pub fn close_static_files() {
    close_static_root();
    close_static_proc();
    close_static_null();
}

/// Open static `/` directory file descriptor.
#[expect(clippy::disallowed_methods)]
pub fn open_static_root() -> Result<(), Errno> {
    if ROOT_FD_OK() {
        return Ok(());
    }

    let mut mask = STATX_MODE;
    mask |= if *HAVE_STATX_MNT_ID_UNIQUE {
        STATX_MNT_ID_UNIQUE
    } else {
        STATX_MNT_ID
    };

    let how = safe_open_how(OFlag::O_PATH | OFlag::O_DIRECTORY, ResolveFlag::empty())
        .resolve(ResolveFlag::RESOLVE_NO_MAGICLINKS | ResolveFlag::RESOLVE_NO_SYMLINKS);
    let fd_root = retry_on_eintr(|| openat2(AT_BADFD, "/", how))?;
    #[expect(clippy::cast_possible_truncation)]
    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))?;

    // Duplicate to a random number to make reuse harder.
    let fd_root = duprand(fd_root.as_raw_fd(), OFlag::O_CLOEXEC)?.into_raw_fd();

    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))?;

    Ok(())
}

/// Open static `/proc` directory file descriptor.
#[expect(clippy::disallowed_methods)]
pub fn open_static_proc() -> Result<(), Errno> {
    if PROC_FD_OK() {
        return Ok(());
    }

    let mut mask = STATX_MODE;
    mask |= if *HAVE_STATX_MNT_ID_UNIQUE {
        STATX_MNT_ID_UNIQUE
    } else {
        STATX_MNT_ID
    };

    // Open without O_PATH, getdents64(2) needed for PID sandboxing.
    let fd_proc = if ROOT_FD_OK() {
        let how = safe_open_how(OFlag::O_RDONLY | OFlag::O_DIRECTORY, ResolveFlag::empty());
        retry_on_eintr(|| openat2(ROOT_FILE(), c"proc", how))
    } else {
        let how = safe_open_how(OFlag::O_RDONLY | OFlag::O_DIRECTORY, ResolveFlag::empty())
            // Drop RESOLVE_BENEATH from resolve flags.
            .resolve(ResolveFlag::RESOLVE_NO_MAGICLINKS | ResolveFlag::RESOLVE_NO_SYMLINKS);
        retry_on_eintr(|| openat2(AT_BADFD, c"/proc", how))
    }?;

    // Validate what we've opened is procfs(5).
    if !is_proc(&fd_proc).unwrap_or(false) {
        return Err(Errno::ENODEV);
    }

    #[expect(clippy::cast_possible_truncation)]
    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))?;

    // Duplicate to a random number to make reuse harder.
    let fd_proc = duprand(fd_proc.as_raw_fd(), OFlag::O_CLOEXEC)?.into_raw_fd();

    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))?;

    Ok(())
}

/// Open static `/dev/null` file descriptor.
#[expect(clippy::disallowed_methods)]
pub fn open_static_null() -> Result<(), Errno> {
    if NULL_FD_OK() {
        return Ok(());
    }

    let mut mask = STATX_MODE;
    mask |= if *HAVE_STATX_MNT_ID_UNIQUE {
        STATX_MNT_ID_UNIQUE
    } else {
        STATX_MNT_ID
    };

    let fd_null = if ROOT_FD_OK() {
        let how = safe_open_how(OFlag::O_PATH, ResolveFlag::empty());
        retry_on_eintr(|| openat2(ROOT_FILE(), c"dev/null", how))
    } else {
        let how = safe_open_how(OFlag::O_PATH, ResolveFlag::empty())
            // Drop RESOLVE_BENEATH from resolve flags.
            .resolve(ResolveFlag::RESOLVE_NO_MAGICLINKS | ResolveFlag::RESOLVE_NO_SYMLINKS);
        retry_on_eintr(|| openat2(AT_BADFD, c"/dev/null", how))
    }?;

    // Validate what we've opened is indeed `/dev/null`.
    if !is_dev_null(&fd_null).unwrap_or(false) {
        return Err(Errno::ENODEV);
    }
    #[expect(clippy::cast_possible_truncation)]
    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))?;

    // Duplicate to a random number to make reuse harder.
    let fd_null = duprand(fd_null.as_raw_fd(), OFlag::O_CLOEXEC)?.into_raw_fd();

    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 `/` directory file descriptor.
pub fn close_static_root() {
    if let Some(fd) = _ROOT_FD.get() {
        let _ = close(*fd);
    }
}

/// Close static `/proc` directory file descriptor.
pub fn close_static_proc() {
    if let Some(fd) = _PROC_FD.get() {
        let _ = close(*fd);
    }
}

/// Close static `/dev/null` file descriptor.
pub fn close_static_null() {
    if let Some(fd) = _NULL_FD.get() {
        let _ = close(*fd);
    }
}

/// 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 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 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 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 fn ROOT_FILE() -> BorrowedFd<'static> {
    // SAFETY: `proc_init' is called beforehand.
    unsafe { BorrowedFd::borrow_raw(ROOT_FD()) }
}

/// Returns true if the static `/` dirfd is open.
#[expect(non_snake_case)]
#[inline(always)]
pub fn ROOT_FD_OK() -> bool {
    _ROOT_FD.get().is_some()
}

/// 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 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 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 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 fn PROC_FILE() -> BorrowedFd<'static> {
    // SAFETY: `proc_init' is called beforehand.
    unsafe { BorrowedFd::borrow_raw(PROC_FD()) }
}

/// Returns true if the static `/proc` dirfd is open.
#[expect(non_snake_case)]
#[inline(always)]
pub fn PROC_FD_OK() -> bool {
    _PROC_FD.get().is_some()
}

/// 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 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 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 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(non_snake_case)]
#[inline(always)]
pub fn NULL_FILE() -> BorrowedFd<'static> {
    // SAFETY: `proc_init' is called beforehand.
    unsafe { BorrowedFd::borrow_raw(NULL_FD()) }
}

/// Returns true if the static `/dev/null` fd is open.
#[expect(non_snake_case)]
#[inline(always)]
pub fn NULL_FD_OK() -> bool {
    _NULL_FD.get().is_some()
}

static _ROOT_FD: OnceLock<RawFd> = OnceLock::new();
static _ROOT_F_MODE: OnceLock<u16> = OnceLock::new();
static _ROOT_MNT_ID: OnceLock<u64> = OnceLock::new();
static _PROC_FD: OnceLock<RawFd> = OnceLock::new();
static _PROC_F_MODE: OnceLock<u16> = OnceLock::new();
static _PROC_MNT_ID: OnceLock<u64> = OnceLock::new();
static _NULL_FD: OnceLock<RawFd> = OnceLock::new();
static _NULL_F_MODE: OnceLock<u16> = OnceLock::new();
static _NULL_MNT_ID: OnceLock<u64> = OnceLock::new();

#[cfg(test)]
mod tests {
    use std::{
        fs::{File, OpenOptions},
        io::ErrorKind,
        os::unix::{
            ffi::OsStrExt,
            fs::OpenOptionsExt,
            net::{UnixListener, UnixStream},
        },
        sync::mpsc,
        thread,
        time::Duration,
    };

    use libc::c_uint;
    use nix::{
        fcntl::{open, AT_FDCWD},
        sys::socket::{accept, bind, connect, listen, Backlog, SockFlag, UnixAddr},
        unistd::{dup, pipe, read, write},
    };
    use tempfile::NamedTempFile;

    use super::*;
    use crate::{
        compat::SockType,
        confine::check_unix_diag,
        cookie::{safe_socket, safe_socketpair},
    };

    fn tempdir() -> Result<XPathBuf, Box<dyn std::error::Error>> {
        let tmp = tempfile::Builder::new()
            .disable_cleanup(true)
            .tempdir_in(".")?;
        let _ = OpenOptions::new()
            .write(true)
            .create(true)
            .mode(0o600)
            .open(tmp.path().join("test"))?;
        Ok(tmp
            .path()
            .to_path_buf()
            .file_name()
            .unwrap()
            .as_bytes()
            .into())
    }

    #[test]
    fn test_nlmsg_align_1() {
        assert_eq!(nlmsg_align(0), 0);
    }

    #[test]
    fn test_nlmsg_align_2() {
        assert_eq!(nlmsg_align(1), 4);
    }

    #[test]
    fn test_nlmsg_align_3() {
        assert_eq!(nlmsg_align(4), 4);
    }

    #[test]
    fn test_nlmsg_align_4() {
        assert_eq!(nlmsg_align(5), 8);
    }

    #[test]
    fn test_nla_align_1() {
        assert_eq!(nla_align(0), 0);
    }

    #[test]
    fn test_nla_align_2() {
        assert_eq!(nla_align(1), 4);
    }

    #[test]
    fn test_nla_align_3() {
        assert_eq!(nla_align(4), 4);
    }

    #[test]
    fn test_nla_align_4() {
        assert_eq!(nla_align(5), 8);
    }

    #[test]
    fn test_to_fd_1() {
        assert_eq!(to_fd(0), Ok(0));
    }

    #[test]
    fn test_to_fd_2() {
        assert_eq!(to_fd(5), Ok(5));
    }

    #[test]
    fn test_to_fd_3() {
        // to_fd rejects AT_FDCWD (negative).
        let at_fdcwd = libc::AT_FDCWD as u64;
        assert_eq!(to_fd(at_fdcwd), Err(Errno::EBADF));
    }

    #[test]
    fn test_to_fd_4() {
        let neg = (-2i32) as u64;
        assert_eq!(to_fd(neg), Err(Errno::EBADF));
    }

    #[test]
    fn test_to_valid_fd_1() {
        assert!(is_valid_fd(0));
    }

    #[test]
    fn test_to_valid_fd_2() {
        assert!(is_valid_fd(42));
    }

    #[test]
    fn test_to_valid_fd_3() {
        // u64 values that truncate to negative i32 are invalid.
        assert!(!is_valid_fd(u64::MAX));
    }

    #[test]
    fn test_to_valid_fd_4() {
        // AT_FDCWD is negative, so is_valid_fd returns false
        // (it checks fd >= 0 after to_valid_fd).
        let at_fdcwd = libc::AT_FDCWD as u64;
        assert!(!is_valid_fd(at_fdcwd));
    }

    #[test]
    fn test_to_valid_fd_5() {
        assert_eq!(to_valid_fd(0), Ok(0));
    }

    #[test]
    fn test_to_valid_fd_6() {
        assert_eq!(to_valid_fd(3), Ok(3));
    }

    #[test]
    fn test_to_valid_fd_7() {
        let at_fdcwd = libc::AT_FDCWD as u64;
        assert_eq!(to_valid_fd(at_fdcwd), Ok(libc::AT_FDCWD));
    }

    #[test]
    fn test_to_valid_fd_8() {
        // -1 as u64
        let neg = (-1i32) as u64;
        assert_eq!(to_valid_fd(neg), Err(Errno::EBADF));
    }

    #[test]
    fn test_parse_fd_1() {
        let path = XPath::from_bytes(b"0");
        assert_eq!(parse_fd(path).unwrap(), 0);
    }

    #[test]
    fn test_parse_fd_2() {
        let path = XPath::from_bytes(b"42");
        assert_eq!(parse_fd(path).unwrap(), 42);
    }

    #[test]
    fn test_parse_fd_3() {
        let path = XPath::from_bytes(b"2147483647");
        assert_eq!(parse_fd(path).unwrap(), i32::MAX);
    }

    #[test]
    fn test_parse_fd_4() {
        let path = XPath::from_bytes(b"not_a_number");
        assert_eq!(parse_fd(path).unwrap_err(), Errno::EBADF);
    }

    #[test]
    fn test_parse_fd_5() {
        let path = XPath::from_bytes(b"");
        assert_eq!(parse_fd(path).unwrap_err(), Errno::EBADF);
    }

    #[test]
    fn test_parse_fd_6() {
        let path = XPath::from_bytes(b"/dev/null");
        assert_eq!(parse_fd(path).unwrap_err(), Errno::EBADF);
    }

    #[test]
    fn test_parse_fd_7() {
        let path = XPath::from_bytes(b"-1");
        assert_eq!(parse_fd(path).unwrap(), -1);
    }

    #[test]
    fn test_is_dev_null_1() {
        let file = OpenOptions::new().read(true).open("/dev/null").unwrap();
        assert!(is_dev_null(&file).unwrap());
    }

    #[test]
    fn test_is_dev_null_2() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        assert!(!is_dev_null(&file).unwrap());
    }

    #[test]
    fn test_is_file_1() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        assert!(is_file(&file).unwrap());
    }

    #[test]
    fn test_is_file_2() {
        let file = OpenOptions::new().read(true).open("/dev/null").unwrap();
        assert!(!is_file(&file).unwrap());
    }

    #[test]
    fn test_is_empty_file_1() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        assert!(is_empty_file(&file).unwrap());
    }

    #[test]
    fn test_is_empty_file_2() {
        use std::io::Write;
        let mut temp = NamedTempFile::new().unwrap();
        temp.write_all(b"data").unwrap();
        temp.flush().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        assert!(!is_empty_file(&file).unwrap());
    }

    #[test]
    fn test_is_empty_file_3() {
        let file = OpenOptions::new().read(true).open("/dev/null").unwrap();
        assert!(!is_empty_file(&file).unwrap());
    }

    #[test]
    fn test_set_cloexec_1() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        set_cloexec(&file, true).unwrap();
        let flags = fcntl(&file, FcntlArg::F_GETFD).unwrap();
        assert!(flags & FdFlag::FD_CLOEXEC.bits() != 0);
    }

    #[test]
    fn test_set_cloexec_2() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        set_cloexec(&file, true).unwrap();
        set_cloexec(&file, false).unwrap();
        let flags = fcntl(&file, FcntlArg::F_GETFD).unwrap();
        assert!(flags & FdFlag::FD_CLOEXEC.bits() == 0);
    }

    #[test]
    fn test_get_nonblock() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        assert!(!get_nonblock(&file).unwrap());
    }

    #[test]
    fn test_set_nonblock_1() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        set_nonblock(&file, true).unwrap();
        assert!(get_nonblock(&file).unwrap());
    }

    #[test]
    fn test_set_nonblock_2() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        set_nonblock(&file, true).unwrap();
        set_nonblock(&file, false).unwrap();
        assert!(!get_nonblock(&file).unwrap());
    }

    #[test]
    fn test_set_append_1() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().write(true).open(temp.path()).unwrap();
        set_append(&file, true).unwrap();
        let flags = fd_status_flags(&file).unwrap();
        assert!(flags.contains(OFlag::O_APPEND));
    }

    #[test]
    fn test_set_append_2() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().write(true).open(temp.path()).unwrap();
        set_append(&file, true).unwrap();
        set_append(&file, false).unwrap();
        let flags = fd_status_flags(&file).unwrap();
        assert!(!flags.contains(OFlag::O_APPEND));
    }

    #[test]
    fn test_fd_status_flags_1() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        let flags = fd_status_flags(&file).unwrap();

        assert!(!flags.contains(OFlag::O_WRONLY));
        assert!(!flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_fd_status_flags_2() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().write(true).open(temp.path()).unwrap();
        let flags = fd_status_flags(&file).unwrap();

        assert!(flags.contains(OFlag::O_WRONLY));
        assert!(!flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_fd_status_flags_3() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .open(temp.path())
            .unwrap();
        let flags = fd_status_flags(&file).unwrap();

        assert!(flags.contains(OFlag::O_RDWR));
        assert!(!flags.contains(OFlag::O_WRONLY));
    }

    #[test]
    fn test_fd_status_flags_4() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        let owned_fd = unsafe { SafeOwnedFd::from_raw_fd(file.as_raw_fd()) };
        std::mem::forget(file);

        let flags = fd_status_flags(&owned_fd).unwrap();
        assert!(!flags.contains(OFlag::O_WRONLY));
        assert!(!flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_fd_status_flags_5() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().write(true).open(temp.path()).unwrap();
        let owned_fd = unsafe { SafeOwnedFd::from_raw_fd(file.as_raw_fd()) };
        std::mem::forget(file);

        let flags = fd_status_flags(&owned_fd).unwrap();
        assert!(flags.contains(OFlag::O_WRONLY));
        assert!(!flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_fd_status_flags_6() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .open(temp.path())
            .unwrap();
        let owned_fd = unsafe { SafeOwnedFd::from_raw_fd(file.as_raw_fd()) };
        std::mem::forget(file);

        let flags = fd_status_flags(&owned_fd).unwrap();
        assert!(flags.contains(OFlag::O_RDWR));
        assert!(!flags.contains(OFlag::O_WRONLY));
    }

    #[test]
    fn test_fd_status_flags_7() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        let borrowed_fd = file.as_fd();

        let flags = fd_status_flags(borrowed_fd).unwrap();
        assert!(!flags.contains(OFlag::O_WRONLY));
        assert!(!flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_fd_status_flags_8() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().write(true).open(temp.path()).unwrap();
        let borrowed_fd = file.as_fd();

        let flags = fd_status_flags(borrowed_fd).unwrap();
        assert!(flags.contains(OFlag::O_WRONLY));
        assert!(!flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_fd_status_flags_9() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .open(temp.path())
            .unwrap();
        let borrowed_fd = file.as_fd();

        let flags = fd_status_flags(borrowed_fd).unwrap();
        assert!(flags.contains(OFlag::O_RDWR));
        assert!(!flags.contains(OFlag::O_WRONLY));
    }

    #[test]
    fn test_fd_status_flags_10() {
        let file = OpenOptions::new().read(true).open("/dev/null").unwrap();
        let flags = fd_status_flags(&file).unwrap();

        assert!(!flags.contains(OFlag::O_WRONLY));
        assert!(!flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_fd_status_flags_11() {
        let file = OpenOptions::new().write(true).open("/dev/null").unwrap();
        let flags = fd_status_flags(&file).unwrap();

        assert!(flags.contains(OFlag::O_WRONLY));
        assert!(!flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_fd_status_flags_12() {
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .open("/dev/null")
            .unwrap();
        let flags = fd_status_flags(&file).unwrap();

        assert!(flags.contains(OFlag::O_RDWR));
        assert!(!flags.contains(OFlag::O_WRONLY));
    }

    #[test]
    fn test_fd_status_flags_13() {
        let (read_fd, _) = pipe().unwrap();

        let flags = fd_status_flags(&read_fd).unwrap();
        assert!(!flags.contains(OFlag::O_WRONLY));
        assert!(!flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_fd_status_flags_14() {
        let (_, write_fd) = pipe().unwrap();

        let flags = fd_status_flags(&write_fd).unwrap();
        assert!(flags.contains(OFlag::O_WRONLY));
        assert!(!flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_fd_status_flags_15() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new()
            .write(true)
            .append(true)
            .open(temp.path())
            .unwrap();
        let flags = fd_status_flags(&file).unwrap();

        assert!(flags.contains(OFlag::O_WRONLY));
        assert!(flags.contains(OFlag::O_APPEND));
    }

    #[test]
    fn test_fd_status_flags_16() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new()
            .write(true)
            .create(true)
            .open(temp.path())
            .unwrap();
        let flags = fd_status_flags(&file).unwrap();

        assert!(flags.contains(OFlag::O_WRONLY));
    }

    #[test]
    fn test_fd_status_flags_17() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(temp.path())
            .unwrap();
        let flags = fd_status_flags(&file).unwrap();

        assert!(flags.contains(OFlag::O_WRONLY));
    }

    #[test]
    fn test_fd_status_flags_18() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new()
            .read(true)
            .append(true)
            .open(temp.path())
            .unwrap();
        let flags = fd_status_flags(&file).unwrap();

        assert!(flags.contains(OFlag::O_RDWR));
        assert!(flags.contains(OFlag::O_APPEND));
    }

    #[test]
    fn test_fd_status_flags_19() {
        let temp = NamedTempFile::new().unwrap();
        std::fs::remove_file(temp.path()).unwrap();
        let file = OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(temp.path())
            .unwrap();
        let flags = fd_status_flags(&file).unwrap();

        assert!(flags.contains(OFlag::O_WRONLY));
    }

    #[test]
    fn test_fd_status_flags_20() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        let file_ref = &file;

        let flags = fd_status_flags(file_ref).unwrap();
        assert!(!flags.contains(OFlag::O_WRONLY));
        assert!(!flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_fd_status_flags_21() {
        let temp = NamedTempFile::new().unwrap();
        let mut file = OpenOptions::new().write(true).open(temp.path()).unwrap();
        let file_ref = &mut file;

        let flags = fd_status_flags(file_ref).unwrap();
        assert!(flags.contains(OFlag::O_WRONLY));
        assert!(!flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_fd_status_flags_22() {
        let temp = NamedTempFile::new().unwrap();
        let file = Box::new(OpenOptions::new().read(true).open(temp.path()).unwrap());

        let flags = fd_status_flags(&file).unwrap();
        assert!(!flags.contains(OFlag::O_WRONLY));
        assert!(!flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_fd_status_flags_23() {
        use std::sync::Arc;
        let temp = NamedTempFile::new().unwrap();
        let file = Arc::new(OpenOptions::new().read(true).open(temp.path()).unwrap());

        let flags = fd_status_flags(&file).unwrap();
        assert!(!flags.contains(OFlag::O_WRONLY));
        assert!(!flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_fd_status_flags_24() {
        use std::rc::Rc;
        let temp = NamedTempFile::new().unwrap();
        let file = Rc::new(OpenOptions::new().read(true).open(temp.path()).unwrap());

        let flags = fd_status_flags(&file).unwrap();
        assert!(!flags.contains(OFlag::O_WRONLY));
        assert!(!flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_fd_status_flags_25() {
        let result = fd_status_flags(AT_BADFD);

        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), Errno::EBADF);
    }

    #[test]
    fn test_fd_status_flags_26() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .open(temp.path())
            .unwrap();

        let flags1 = fd_status_flags(&file).unwrap();
        let flags2 = fd_status_flags(&file).unwrap();
        let flags3 = fd_status_flags(&file).unwrap();

        assert_eq!(flags1, flags2);
        assert_eq!(flags2, flags3);
    }

    #[test]
    fn test_fd_status_flags_27() {
        let temp = NamedTempFile::new().unwrap();
        let file1 = OpenOptions::new().write(true).open(temp.path()).unwrap();
        let file2 = OpenOptions::new().write(true).open("/dev/null").unwrap();

        let flags1 = fd_status_flags(&file1).unwrap();
        let flags2 = fd_status_flags(&file2).unwrap();

        assert!(flags1.contains(OFlag::O_WRONLY));
        assert!(flags2.contains(OFlag::O_WRONLY));
    }

    #[test]
    fn test_fd_status_flags_28() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        let duped_fd = dup(&file).unwrap();

        let flags = fd_status_flags(&duped_fd).unwrap();
        assert!(!flags.contains(OFlag::O_WRONLY));
        assert!(!flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_is_writable_fd_1() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        let result = is_writable_fd(&file).unwrap();

        assert!(!result);
    }

    #[test]
    fn test_is_writable_fd_2() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().write(true).open(temp.path()).unwrap();
        let result = is_writable_fd(&file).unwrap();

        assert!(result);
    }

    #[test]
    fn test_is_writable_fd_3() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .open(temp.path())
            .unwrap();
        let result = is_writable_fd(&file).unwrap();

        assert!(result);
    }

    #[test]
    fn test_is_writable_fd_4() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        let owned_fd = unsafe { SafeOwnedFd::from_raw_fd(file.as_raw_fd()) };
        std::mem::forget(file);

        let result = is_writable_fd(&owned_fd).unwrap();
        assert!(!result);
    }

    #[test]
    fn test_is_writable_fd_5() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().write(true).open(temp.path()).unwrap();
        let owned_fd = unsafe { SafeOwnedFd::from_raw_fd(file.as_raw_fd()) };
        std::mem::forget(file);

        let result = is_writable_fd(&owned_fd).unwrap();
        assert!(result);
    }

    #[test]
    fn test_is_writable_fd_6() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .open(temp.path())
            .unwrap();
        let owned_fd = unsafe { SafeOwnedFd::from_raw_fd(file.as_raw_fd()) };
        std::mem::forget(file);

        let result = is_writable_fd(&owned_fd).unwrap();
        assert!(result);
    }

    #[test]
    fn test_is_writable_fd_7() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        let borrowed_fd = file.as_fd();

        let result = is_writable_fd(borrowed_fd).unwrap();
        assert!(!result);
    }

    #[test]
    fn test_is_writable_fd_8() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().write(true).open(temp.path()).unwrap();
        let borrowed_fd = file.as_fd();

        let result = is_writable_fd(borrowed_fd).unwrap();
        assert!(result);
    }

    #[test]
    fn test_is_writable_fd_9() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .open(temp.path())
            .unwrap();
        let borrowed_fd = file.as_fd();

        let result = is_writable_fd(borrowed_fd).unwrap();
        assert!(result);
    }

    #[test]
    fn test_is_writable_fd_10() {
        let file = OpenOptions::new().read(true).open("/dev/null").unwrap();
        let result = is_writable_fd(&file).unwrap();

        assert!(!result);
    }

    #[test]
    fn test_is_writable_fd_11() {
        let file = OpenOptions::new().write(true).open("/dev/null").unwrap();
        let result = is_writable_fd(&file).unwrap();

        assert!(result);
    }

    #[test]
    fn test_is_writable_fd_12() {
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .open("/dev/null")
            .unwrap();
        let result = is_writable_fd(&file).unwrap();

        assert!(result);
    }

    #[test]
    fn test_is_writable_fd_13() {
        let (read_fd, _) = pipe().unwrap();

        let result = is_writable_fd(&read_fd).unwrap();
        assert!(!result);
    }

    #[test]
    fn test_is_writable_fd_14() {
        let (_, write_fd) = pipe().unwrap();

        let result = is_writable_fd(&write_fd).unwrap();
        assert!(result);
    }

    #[test]
    fn test_is_writable_fd_15() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new()
            .write(true)
            .append(true)
            .open(temp.path())
            .unwrap();
        let result = is_writable_fd(&file).unwrap();

        assert!(result);
    }

    #[test]
    fn test_is_writable_fd_16() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new()
            .write(true)
            .create(true)
            .open(temp.path())
            .unwrap();
        let result = is_writable_fd(&file).unwrap();

        assert!(result);
    }

    #[test]
    fn test_is_writable_fd_17() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(temp.path())
            .unwrap();
        let result = is_writable_fd(&file).unwrap();

        assert!(result);
    }

    #[test]
    fn test_is_writable_fd_18() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new()
            .read(true)
            .append(true)
            .open(temp.path())
            .unwrap();
        let result = is_writable_fd(&file).unwrap();

        assert!(result);
    }

    #[test]
    fn test_is_writable_fd_19() {
        let temp = NamedTempFile::new().unwrap();
        std::fs::remove_file(temp.path()).unwrap();
        let file = OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(temp.path())
            .unwrap();
        let result = is_writable_fd(&file).unwrap();

        assert!(result);
    }

    #[test]
    fn test_is_writable_fd_20() {
        let temp = NamedTempFile::new().unwrap();
        let file = open(
            temp.path(),
            OFlag::O_RDONLY | OFlag::O_CREAT | OFlag::O_TRUNC,
            Mode::empty(),
        )
        .map(File::from)
        .unwrap();
        let result = is_writable_fd(&file).unwrap();

        assert!(!result);
    }

    #[test]
    fn test_is_writable_fd_21() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        let file_ref = &file;

        let result = is_writable_fd(file_ref).unwrap();
        assert!(!result);
    }

    #[test]
    fn test_is_writable_fd_22() {
        let temp = NamedTempFile::new().unwrap();
        let mut file = OpenOptions::new().write(true).open(temp.path()).unwrap();
        let file_ref = &mut file;

        let result = is_writable_fd(file_ref).unwrap();
        assert!(result);
    }

    #[test]
    fn test_is_writable_fd_23() {
        let temp = NamedTempFile::new().unwrap();
        let file = Box::new(OpenOptions::new().read(true).open(temp.path()).unwrap());

        let result = is_writable_fd(&file).unwrap();
        assert!(!result);
    }

    #[test]
    fn test_is_writable_fd_24() {
        use std::sync::Arc;
        let temp = NamedTempFile::new().unwrap();
        let file = Arc::new(OpenOptions::new().read(true).open(temp.path()).unwrap());

        let result = is_writable_fd(&file).unwrap();
        assert!(!result);
    }

    #[test]
    fn test_is_writable_fd_25() {
        use std::rc::Rc;
        let temp = NamedTempFile::new().unwrap();
        let file = Rc::new(OpenOptions::new().read(true).open(temp.path()).unwrap());

        let result = is_writable_fd(&file).unwrap();
        assert!(!result);
    }

    #[test]
    fn test_is_writable_fd_26() {
        let result = is_writable_fd(AT_BADFD);

        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), Errno::EBADF);
    }

    #[test]
    fn test_is_writable_fd_27() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .open(temp.path())
            .unwrap();

        let result1 = is_writable_fd(&file).unwrap();
        let result2 = is_writable_fd(&file).unwrap();
        let result3 = is_writable_fd(&file).unwrap();

        assert_eq!(result1, result2);
        assert_eq!(result2, result3);
    }

    #[test]
    fn test_is_writable_fd_28() {
        let temp = NamedTempFile::new().unwrap();
        let file1 = OpenOptions::new().write(true).open(temp.path()).unwrap();
        let file2 = OpenOptions::new().write(true).open("/dev/null").unwrap();

        let result1 = is_writable_fd(&file1).unwrap();
        let result2 = is_writable_fd(&file2).unwrap();

        assert!(result1);
        assert!(result2);
    }

    #[test]
    fn test_is_writable_fd_29() {
        let temp = NamedTempFile::new().unwrap();
        let file = OpenOptions::new().read(true).open(temp.path()).unwrap();
        let duped_fd = dup(&file).unwrap();

        let result = is_writable_fd(&duped_fd).unwrap();
        assert!(!result);
    }

    #[test]
    fn test_closeall_1() {
        let (r1, w1) = pipe().unwrap();
        let (r2, w2) = pipe().unwrap();
        let (r3, w3) = pipe().unwrap();

        let fds = vec![
            r1.as_raw_fd() as c_uint,
            w1.as_raw_fd() as c_uint,
            r2.as_raw_fd() as c_uint,
            w2.as_raw_fd() as c_uint,
            r3.as_raw_fd() as c_uint,
            w3.as_raw_fd() as c_uint,
        ];

        // Prevent double-close.
        std::mem::forget(r1);
        std::mem::forget(w1);
        std::mem::forget(r2);
        std::mem::forget(w2);
        std::mem::forget(r3);
        std::mem::forget(w3);

        // Ensure fds are sorted.
        let mut sorted_fds = fds.clone();
        sorted_fds.sort();

        // This should close all fds.
        assert!(closeall(&sorted_fds).is_ok());
    }

    #[test]
    fn test_closeall_2() {
        let (r, w) = pipe().unwrap();
        let r_fd = r.as_raw_fd() as c_uint;
        let w_fd = w.as_raw_fd() as c_uint;

        // Unsorted input.
        let mut unsorted = vec![w_fd, r_fd];
        if unsorted[0] < unsorted[1] {
            unsorted.swap(0, 1);
        }

        assert_eq!(closeall(&unsorted), Err(Errno::EINVAL));

        // Duplicate input.
        let dup = vec![r_fd, r_fd];
        assert_eq!(closeall(&dup), Err(Errno::EINVAL));
    }

    #[test]
    fn test_send_recv_with_fd_1() {
        let (l, r) = UnixStream::pair().unwrap();
        let (read_fd, _write_fd) = pipe().unwrap();
        let sent_bytes = b"hello";
        let sent_fds = [read_fd.as_raw_fd()];

        let n = send_with_fd(&l, sent_bytes, &sent_fds).unwrap();
        assert_eq!(n, sent_bytes.len());

        let mut recv_bytes = [0u8; 64];
        let mut recv_fds = [0i32; 4];
        let (nbytes, nfds) = recv_with_fd(&r, &mut recv_bytes, &mut recv_fds).unwrap();
        assert_eq!(nbytes, sent_bytes.len());
        assert_eq!(nfds, 1);
        assert_eq!(&recv_bytes[..nbytes], sent_bytes);
        assert_ne!(recv_fds[0], sent_fds[0]);
    }

    #[test]
    fn test_send_recv_with_fd_2() {
        let (l, r) = UnixStream::pair().unwrap();
        let (r1, w1) = pipe().unwrap();
        let (r2, w2) = pipe().unwrap();
        let sent_bytes = b"multi";
        let sent_fds = [
            r1.as_raw_fd(),
            w1.as_raw_fd(),
            r2.as_raw_fd(),
            w2.as_raw_fd(),
        ];

        let n = send_with_fd(&l, sent_bytes, &sent_fds).unwrap();
        assert_eq!(n, sent_bytes.len());

        let mut recv_bytes = [0u8; 64];
        let mut recv_fds = [0i32; 8];
        let (nbytes, nfds) = recv_with_fd(&r, &mut recv_bytes, &mut recv_fds).unwrap();
        assert_eq!(nbytes, sent_bytes.len());
        assert_eq!(nfds, 4);
        assert_eq!(&recv_bytes[..nbytes], sent_bytes);
    }

    #[test]
    fn test_send_recv_with_fd_3() {
        let (l, r) = UnixStream::pair().unwrap();
        let sent_bytes = b"data only";

        let n = send_with_fd(&l, sent_bytes, &[]).unwrap();
        assert_eq!(n, sent_bytes.len());

        let mut recv_bytes = [0u8; 64];
        let mut recv_fds = [0i32; 4];
        let (nbytes, nfds) = recv_with_fd(&r, &mut recv_bytes, &mut recv_fds).unwrap();
        assert_eq!(nbytes, sent_bytes.len());
        assert_eq!(nfds, 0);
        assert_eq!(&recv_bytes[..nbytes], sent_bytes);
    }

    #[test]
    fn test_send_recv_with_fd_4() {
        let (l, _r) = UnixStream::pair().unwrap();
        let sent_bytes = b"bad";
        let bad_fds = [RawFd::MAX];

        let result = send_with_fd(&l, sent_bytes, &bad_fds);
        assert!(result.is_err());
    }

    #[test]
    fn test_send_recv_with_fd_5() {
        let (l, r) = UnixStream::pair().unwrap();
        let (pipe_r, pipe_w) = pipe().unwrap();
        let sent_bytes = b"x";
        let sent_fds = [pipe_w.as_raw_fd()];

        send_with_fd(&l, sent_bytes, &sent_fds).unwrap();

        let mut recv_bytes = [0u8; 4];
        let mut recv_fds = [0i32; 2];
        let (_, nfds) = recv_with_fd(&r, &mut recv_bytes, &mut recv_fds).unwrap();
        assert_eq!(nfds, 1);

        // Write through the received fd.
        let recv_pipe_w = unsafe { SafeOwnedFd::from_raw_fd(recv_fds[0]) };
        write(&recv_pipe_w, b"hello").unwrap();
        drop(recv_pipe_w);
        drop(pipe_w);

        // Read from the original pipe read end.
        let mut buf = [0u8; 16];
        let n = read(pipe_r, &mut buf).unwrap();
        assert_eq!(&buf[..n], b"hello");
    }

    #[test]
    fn test_peer_inode_1() {
        if !check_unix_diag().unwrap_or(false) {
            eprintln!("UNIX socket diagnostics are not supported, skipping!");
            return;
        }

        // Create socketpair.
        let (a_fd, b_fd) = safe_socketpair(
            AddressFamily::Unix,
            SockType::Stream,
            0,
            SockFlag::SOCK_CLOEXEC,
        )
        .unwrap();

        // Expected peer inode (low 32 bits).
        let b_ino = fd_inode(&b_fd).unwrap();
        let expected = (b_ino & 0xffff_ffff) as u64;

        // Call peer_inode on the other side and compare.
        let got = fd_inode(&a_fd).and_then(peer_inode).unwrap();
        assert_eq!(got, expected);
    }

    #[test]
    fn test_peer_inode_2() {
        if !check_unix_diag().unwrap_or(false) {
            eprintln!("UNIX socket diagnostics are not supported, skipping!");
            return;
        }

        // Create a temporary directory for a unique socket path.
        let td = tempdir().unwrap();
        let sock_path = td.as_path().join("peer_inode.sock");

        // Spawn server thread:
        // bind, listen, accept, compute peer_inode on accepted socket and send it back.
        let (tx_ready, rx_ready) = mpsc::channel::<()>();
        let (tx_peer, rx_peer) = mpsc::channel::<u64>();
        let sock_path_clone = sock_path.clone();
        let server = thread::spawn(move || {
            // bind & listen to get a UnixListener.
            let listener = UnixListener::bind(&sock_path_clone).unwrap();
            // Inform main thread we're listening.
            tx_ready.send(()).unwrap();
            // Accept one connection (blocking).
            let (accepted, _addr) = listener.accept().unwrap();
            // Call peer_inode on accepted stream.
            let peer = fd_inode(&accepted).and_then(peer_inode).unwrap();
            // Send result back.
            tx_peer.send(peer).unwrap();
        });

        // Wait for server to be ready.
        rx_ready.recv_timeout(Duration::from_secs(10)).unwrap();

        // Connect client to socket path (retries briefly as necessary).
        let client = loop {
            match UnixStream::connect(&sock_path) {
                Ok(s) => break s,
                Err(e) => {
                    if e.kind() == ErrorKind::NotFound || e.kind() == ErrorKind::ConnectionRefused {
                        thread::sleep(Duration::from_millis(10));
                        continue;
                    } else {
                        panic!("connect failed: {e:?}");
                    }
                }
            }
        };

        // Compute expected from client fd.
        let client_ino = fd_inode(&client).unwrap();
        let expected = (client_ino & 0xffff_ffff) as u64;

        // Receive peer inode computed by server.
        let got = rx_peer.recv_timeout(Duration::from_secs(10)).unwrap();

        assert_eq!(got, expected);
        server.join().unwrap();
    }

    #[test]
    fn test_peer_inode_3() {
        if !check_unix_diag().unwrap_or(false) {
            eprintln!("UNIX socket diagnostics are not supported, skipping!");
            return;
        }

        // Create an abstract socket name (no filesystem path).
        let name = b"peer_inode_test_abstract_12345";

        // Create server socket.
        let srv_fd = safe_socket(
            AddressFamily::Unix,
            SockType::Stream,
            SockFlag::SOCK_CLOEXEC,
            0,
        )
        .unwrap();

        // Construct abstract address and bind/listen.
        let sockaddr = UnixAddr::new_abstract(name).unwrap();
        bind(srv_fd.as_raw_fd(), &sockaddr).unwrap();
        listen(&srv_fd, Backlog::new(1).unwrap()).unwrap();

        // Create client socket and connect.
        let cli_fd = safe_socket(
            AddressFamily::Unix,
            SockType::Stream,
            SockFlag::SOCK_CLOEXEC,
            0,
        )
        .unwrap();
        connect(cli_fd.as_raw_fd(), &sockaddr).unwrap();

        // Server accept.
        let acc_fd = accept(srv_fd.as_raw_fd()).unwrap();
        let acc_fd = unsafe { SafeOwnedFd::from_raw_fd(acc_fd) };

        // Expected is client's inode low 32 bits.
        let cli_ino = fd_inode(&cli_fd).unwrap();
        let expected = (cli_ino & 0xffff_ffff) as u64;

        // Call peer_inode on the accepted/server side.
        let got = fd_inode(&acc_fd).and_then(peer_inode).unwrap();

        assert_eq!(got, expected);
    }

    #[test]
    fn test_peer_inode_4() {
        if !check_unix_diag().unwrap_or(false) {
            eprintln!("UNIX socket diagnostics are not supported, skipping!");
            return;
        }

        // Create socketpair and verify mutual mapping.
        let (a_fd, b_fd) = safe_socketpair(
            AddressFamily::Unix,
            SockType::Stream,
            0,
            SockFlag::SOCK_CLOEXEC,
        )
        .unwrap();

        // Expected low-32 inodes.
        let a_ino = fd_inode(&a_fd).unwrap();
        let b_ino = fd_inode(&b_fd).unwrap();
        let expected_a = (a_ino & 0xffff_ffff) as u64;
        let expected_b = (b_ino & 0xffff_ffff) as u64;

        let got_from_a = peer_inode(a_ino).unwrap();
        let got_from_b = peer_inode(b_ino).unwrap();

        assert_eq!(got_from_a, expected_b);
        assert_eq!(got_from_b, expected_a);
    }

    #[test]
    fn test_unix_vfs_id_1() {
        if !check_unix_diag().unwrap_or(false) {
            eprintln!("UNIX socket diagnostics are not supported, skipping!");
            return;
        }

        // Create a temporary directory for a unique socket path.
        let td = tempdir().unwrap();
        let sock_path = td.as_path().join("vfs_test.sock");

        // Bind a UNIX socket to the filesystem path.
        let srv_fd = safe_socket(
            AddressFamily::Unix,
            SockType::Stream,
            SockFlag::SOCK_CLOEXEC,
            0,
        )
        .unwrap();

        let sockaddr = UnixAddr::new(&sock_path).unwrap();
        bind(srv_fd.as_raw_fd(), &sockaddr).unwrap();
        listen(&srv_fd, Backlog::new(1).unwrap()).unwrap();

        // Get sockfs inode.
        let sockfs_ino = fd_inode(&srv_fd).unwrap();

        // Call unix_vfs_id on the sockfs inode.
        let (vfs_dev, vfs_ino) = unix_vfs_id(sockfs_ino).unwrap();

        // Cross-check with statx(2) on the socket file path.
        // Kernel's udiag_vfs_dev uses MKDEV(major, minor) = (major << 20 | minor).
        let stx = statx(AT_FDCWD, sock_path.as_path(), 0, STATX_INO).unwrap();
        let expected_ino = stx.stx_ino as u32;
        let stat_major = stx.stx_dev_major;
        let stat_minor = stx.stx_dev_minor;
        // Kernel MKDEV format: major << 20 | minor
        let vfs_major = vfs_dev >> 20;
        let vfs_minor = vfs_dev & 0xfffff;

        assert_eq!(vfs_ino, expected_ino, "VFS inode mismatch");
        assert_eq!(vfs_major, stat_major, "VFS device major mismatch");
        assert_eq!(vfs_minor, stat_minor, "VFS device minor mismatch");
    }

    #[test]
    fn test_unix_vfs_id_2() {
        if !check_unix_diag().unwrap_or(false) {
            eprintln!("UNIX socket diagnostics are not supported, skipping!");
            return;
        }

        // socketpair(2) has no filesystem path,
        // so unix_vfs_id should return ENODATA.
        let (fd_a, _fd_b) = safe_socketpair(
            AddressFamily::Unix,
            SockType::Stream,
            0,
            SockFlag::SOCK_CLOEXEC,
        )
        .unwrap();

        let ino_a = fd_inode(&fd_a).unwrap();
        assert_eq!(unix_vfs_id(ino_a), Err(Errno::ENODATA));
    }

    #[test]
    fn test_unix_vfs_id_3() {
        if !check_unix_diag().unwrap_or(false) {
            eprintln!("UNIX socket diagnostics are not supported, skipping!");
            return;
        }

        // Abstract sockets have no VFS path,
        // so unix_vfs_id should return ENODATA.
        let name = b"unix_vfs_id_test_abstract_12345";

        let srv_fd = safe_socket(
            AddressFamily::Unix,
            SockType::Stream,
            SockFlag::SOCK_CLOEXEC,
            0,
        )
        .unwrap();

        let sockaddr = UnixAddr::new_abstract(name).unwrap();
        bind(srv_fd.as_raw_fd(), &sockaddr).unwrap();
        listen(&srv_fd, Backlog::new(1).unwrap()).unwrap();

        let srv_ino = fd_inode(&srv_fd).unwrap();
        assert_eq!(unix_vfs_id(srv_ino), Err(Errno::ENODATA));
    }

    #[test]
    fn test_unix_vfs_id_4() {
        if !check_unix_diag().unwrap_or(false) {
            eprintln!("UNIX socket diagnostics are not supported, skipping!");
            return;
        }

        // Bind two sockets in two different directories with the same basename.
        // Their VFS identities should differ.
        let td_a = tempdir().unwrap();
        let td_b = tempdir().unwrap();
        let path_a = td_a.as_path().join("socket");
        let path_b = td_b.as_path().join("socket");

        let sock_a = safe_socket(
            AddressFamily::Unix,
            SockType::Stream,
            SockFlag::SOCK_CLOEXEC,
            0,
        )
        .unwrap();
        let sock_b = safe_socket(
            AddressFamily::Unix,
            SockType::Stream,
            SockFlag::SOCK_CLOEXEC,
            0,
        )
        .unwrap();

        let addr_a = UnixAddr::new(&path_a).unwrap();
        let addr_b = UnixAddr::new(&path_b).unwrap();

        bind(sock_a.as_raw_fd(), &addr_a).unwrap();
        bind(sock_b.as_raw_fd(), &addr_b).unwrap();

        listen(&sock_a, Backlog::new(1).unwrap()).unwrap();
        listen(&sock_b, Backlog::new(1).unwrap()).unwrap();

        let ino_a = fd_inode(&sock_a).unwrap();
        let ino_b = fd_inode(&sock_b).unwrap();

        let vfs_a = unix_vfs_id(ino_a).unwrap();
        let vfs_b = unix_vfs_id(ino_b).unwrap();
        assert_ne!(vfs_a, vfs_b);
    }
}