snare 3.4.0

Ergonomic in-process network testing on top of snare-interpose: write the code under test against std, describe the peer with a tester builder
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
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
//! An in-memory TCP fabric behind [`snare_interpose::Net`]. The code under test uses ordinary
//! `std::net` types; their socket calls land here and are serviced from process memory. A
//! [`Listener`] registered by a tester is the peer side of a connection.
//!
//! [`Fabric`] owns a table of virtual descriptors ([`Sock`]): TCP sockets through their
//! fresh → connecting → stream / listener life, UDP and `AF_UNIX` datagram sockets, `socketpair`
//! ends, and the readiness objects (Linux eventfd and epoll, macOS kqueue) and raw L2 endpoints
//! (Linux `AF_PACKET`, macOS `/dev/bpf*`) that event loops and EtherCAT masters open. Each
//! descriptor is a real fd `dup`ed from `/dev/null`, so its number is unique in the process and is
//! freed by the real `close`. Every [`Net`]/[`Fs`] method returns `None` to decline an fd or call
//! it does not model, which passes the call on to the next backend or the OS.
//!
//! Per-`Sim` state that testers also reach (the listener and datagram address maps) lives in
//! [`Registries`], installed per thread by [`enter`] and [`ScopeLayer`]. Link policy, routing,
//! capture and socket accounting live in [`SimShared`]; byte streams in [`Pipe`].
//!
//! Lock order: [`Fabric::socks`], then a connect's `ConnectAttempt`, then the `Registries` maps,
//! then per-object locks (`Listener::pending`, `DgramQueue::packets`, pipe state). The global
//! [`Readiness`](crate::readiness::Readiness) state sits outside all of them: `wait_until` runs
//! its predicate (which takes `socks`) under that state, so nothing may bump readiness or block
//! while holding `socks` — every method copies what it needs out of the table and drops the guard
//! first.
//! Tester-facing entry points run under [`snare_interpose::real`], so their own waits on these
//! locks are not counted as blocked threads by quiescence detection.

use std::collections::{BTreeSet, VecDeque};
use std::ffi::c_int;
use std::io;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::ops::ControlFlow;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};

use snare_interpose::{Fs, Net, NetResult, Restart};

use crate::{HashMap, HashSet};

#[cfg(target_os = "macos")]
mod mac_shutdown;

#[derive(Clone)]
enum Payload {
    Inline { bytes: [u8; 128], len: u8 },
    Heap(Vec<u8>),
}

impl Payload {
    fn copy_from(data: &[u8]) -> Self {
        if data.len() <= 128 {
            let mut bytes = [0; 128];
            bytes[..data.len()].copy_from_slice(data);
            Self::Inline {
                bytes,
                len: data.len() as u8,
            }
        } else {
            Self::Heap(data.to_vec())
        }
    }

    fn into_vec(self) -> Vec<u8> {
        match self {
            Self::Inline { bytes, len } => bytes[..len as usize].to_vec(),
            Self::Heap(data) => data,
        }
    }
}

impl std::ops::Deref for Payload {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        match self {
            Self::Inline { bytes, len } => &bytes[..*len as usize],
            Self::Heap(data) => data,
        }
    }
}

/// One received datagram: its payload and the source address a `recvfrom` reports back.
#[derive(Clone)]
pub(crate) struct Datagram {
    /// The sender's address; [`UNNAMED`] for a datagram from a `socketpair` end.
    src: SocketAddr,
    /// The whole payload. A datagram is received whole or truncated, never split.
    data: Payload,
    /// Still in flight until then (link latency); `None` arrived on sending.
    arrives: Option<Deadline>,
    /// The link it crosses and that link's down epoch when it was sent.
    via: Option<(Arc<LinkState>, u64)>,
    /// When it reaches the socket (its send time plus its delay), for receive timestamps.
    stamp: Stamp,
    #[cfg(target_os = "linux")]
    rx_fallback: Arc<std::sync::OnceLock<Duration>>,
    /// The smallest MTU on its path ([`crate::netif::Copy::mtu`]).
    mtu: Option<u32>,
    /// Its IP header fields and receiving interface, for the receiver's control messages.
    ip: crate::ancillary::Header,
    sequence: u64,
}

/// What the receive-buffer accounting in [`RxQueue`] needs to know of a datagram.
impl Arrival for Datagram {
    fn src(&self) -> SocketAddr {
        self.src
    }

    fn payload(&self) -> usize {
        self.data.len()
    }

    fn arrives(&self) -> Option<Deadline> {
        self.arrives
    }

    /// Whether the link it crosses went down while it was still in flight, which loses it.
    fn lost(&self) -> bool {
        match (&self.via, self.arrives) {
            (Some((link, epoch)), Some(at)) => link.lost_in_flight(*epoch, at.instant()),
            _ => false,
        }
    }

    fn path_mtu(&self) -> Option<u32> {
        self.mtu
    }
}

/// A datagram socket's receive queue. Shared (behind an `Arc`) between the owning [`Sock::Dgram`]
/// and the per-`Sim` address registry, so a `sendto` on one socket can enqueue onto a peer's queue
/// by looking up its bound address. Blocking receives park on the sim's
/// [`Readiness`](crate::readiness::Readiness) channel (giving them quiescence detection), so no
/// per-queue condvar is needed.
#[derive(Default)]
pub(crate) struct DgramQueue {
    /// The datagrams, in flight or arrived, with the receive-buffer limits applied as they land.
    packets: Mutex<RxQueue<Datagram>>,
    /// The code under test's socket this queue belongs to; `None` for a tester endpoint.
    rec: Option<Arc<SockRec>>,
    next_port: AtomicU64,
}

impl DgramQueue {
    /// A queue for the code under test's socket `rec`, registered as that socket's [`RxProbe`] so
    /// its record can report queued bytes (`FIONREAD`, socket stats) without knowing the queue.
    /// The probe is weak: the record never keeps a closed socket's queue alive.
    fn for_socket(rec: &Arc<SockRec>) -> Arc<Self> {
        let queue = Arc::new(DgramQueue {
            packets: Mutex::default(),
            rec: Some(rec.clone()),
            next_port: AtomicU64::new(0),
        });
        rec.set_probe(Arc::downgrade(&queue) as std::sync::Weak<dyn RxProbe>);
        queue
    }

    /// Queues a datagram that becomes receivable `delay` from now (its link latency). A delayed
    /// arrival is registered as a wake-up point first, so a receiver blocked on the virtual clock
    /// is woken (and the quiescence time-skip can jump) when it lands. `via` is the link it
    /// crosses and that link's down epoch at sending, for [`Arrival::lost`]; `sent` when it left,
    /// which with `delay` stamps it; `mtu` its path's smallest MTU. Bumps readiness for `domain`,
    /// the key of the sim the queue belongs to, so it must not be called holding `Fabric::socks`.
    #[allow(clippy::too_many_arguments)]
    fn push_after(
        &self,
        src: SocketAddr,
        data: &[u8],
        delay: Duration,
        via: Option<(Arc<LinkState>, u64)>,
        sent: Stamp,
        mtu: Option<u32>,
        ip: crate::ancillary::Header,
        domain: usize,
    ) {
        let arrives = (!delay.is_zero()).then(|| Deadline::after(delay));
        if let Some(arrives) = arrives {
            arrives.wake_waiters_then();
        }
        let dg = Datagram {
            src,
            data: Payload::copy_from(data),
            arrives,
            via,
            stamp: sent.later(delay),
            #[cfg(target_os = "linux")]
            rx_fallback: Arc::default(),
            mtu,
            ip,
            sequence: readiness_sequence(),
        };
        self.packets.lock().unwrap().push(dg, self.rec.as_deref());
        if let Some(rec) = &self.rec {
            readiness().bump_keys(domain, &[rec.wake_key()]);
        } else {
            readiness().bump_keys(domain, &[]);
        }
    }

    /// Pops the earliest-arrived datagram whose source passes `accept` (a connected socket only
    /// accepts from its peer), with the drop count it carries. `None` when nothing acceptable has
    /// arrived yet.
    fn pop(&self, accept: impl Fn(SocketAddr) -> bool) -> Option<(Datagram, u32)> {
        self.packets
            .lock()
            .unwrap()
            .pop(accept, self.rec.as_deref())
    }

    /// A copy of the datagram [`pop`](Self::pop) would take, left queued: what `MSG_PEEK` reads.
    fn peek(&self, accept: impl Fn(SocketAddr) -> bool) -> Option<(Datagram, u32)> {
        self.packets
            .lock()
            .unwrap()
            .peek(accept, self.rec.as_deref())
    }

    fn readiness_metadata(&self) -> Option<(Duration, u64, usize)> {
        self.packets
            .lock()
            .unwrap()
            .first_matching(|_| true, self.rec.as_deref())
            .map(|(d, _)| (d.stamp.mono, d.sequence, d.data.len()))
    }

    /// Whether a datagram whose source passes `accept` has arrived, without taking it.
    fn has(&self, accept: impl Fn(SocketAddr) -> bool) -> bool {
        self.packets
            .lock()
            .unwrap()
            .has(accept, self.rec.as_deref())
    }

    /// How many datagrams have landed so far: the socket's read wakes (see [`Wakes`]).
    fn landed(&self) -> u64 {
        self.packets.lock().unwrap().landed(self.rec.as_deref())
    }

    /// [`has`](Self::has) any datagram, then [`landed`](Self::landed).
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    fn readable_landed(&self) -> (bool, u64) {
        let mut packets = self.packets.lock().unwrap();
        let rec = self.rec.as_deref();
        (packets.has(|_| true, rec), packets.landed(rec))
    }
}

/// Lets the socket's record see into this queue: landing in-flight datagrams whose time has come,
/// and the queued counts and next datagram length that `FIONREAD` and socket stats report.
impl RxProbe for DgramQueue {
    fn pending_time(&self) -> bool {
        self.packets.lock().unwrap().pending_time()
    }

    fn land(&self) {
        self.packets.lock().unwrap().land(self.rec.as_deref());
    }

    fn queued(&self) -> (usize, usize) {
        self.packets.lock().unwrap().queued()
    }

    fn next_len(&self) -> Option<usize> {
        self.packets.lock().unwrap().next_len(self.rec.as_deref())
    }
}

/// A bidirectional connection. The connecting side is `A`, the accepting side `B`: a tester, or
/// a socket of the code under test accepted from its listener.
///
/// Shared by both ends' descriptors (and every `dup` of them) and by the tester holding the peer
/// side; it lives until the last of them lets go. Closing one end closes only its write pipe.
pub(crate) struct Conn {
    /// Bytes the connecting side writes and the accepting side reads.
    a_to_b: Arc<Pipe>,
    /// Bytes the accepting side writes and the connecting side reads.
    b_to_a: Arc<Pipe>,
    /// The connecting side's address ([`UNNAMED`] for a socketpair).
    pub(crate) client: SocketAddr,
    /// The accepting side's address ([`UNNAMED`] for a socketpair).
    pub(crate) server: SocketAddr,
    /// The sim's registries, for the link policy (latency) on this connection's bytes.
    regs: Arc<Registries>,
    /// The interface the connection crosses, if it leaves the host.
    hop: Option<Hop>,
    /// The two unnamed ends of a `socketpair`: no addresses, and no link policy between them.
    pair: bool,
    /// The socketpair's process-wide identity (see [`ProcessPairs`]); 0 for a connection.
    pair_id: u64,
    /// The pcapng capture this connection's segments are written to, when capture is on.
    tap: Option<TcpTap>,
    /// For each direction (by the writing end's [`End::index`]), the chunks written and not yet
    /// read, each with when it reaches the reader: what a receive timestamp of the bytes read
    /// reports.
    stamps: [Mutex<VecDeque<(usize, Stamp)>>; 2],
    write_delays: [AtomicU64; 2],
    #[cfg(target_os = "macos")]
    mac_shutdown: Mutex<mac_shutdown::State>,
}

/// Which side of a [`Conn`] a descriptor is.
#[derive(Clone, Copy, PartialEq)]
enum End {
    A,
    B,
}

impl Conn {
    /// Writes what the window has room for from `end`; `None` once that direction is closed.
    /// The bytes arrive after the link policy's TCP delay for this address pair plus the delay of
    /// the interface hop they cross (none between socketpair ends), and are counted against the
    /// hop's interface statistics.
    fn write(&self, end: End, bytes: &[u8]) -> Option<usize> {
        #[cfg(target_os = "macos")]
        self.progress_tcp_shutdown();
        let pipe = self.write_pipe(end);
        if (pipe.reader_gone()
            || (cfg!(not(target_os = "macos"))
                && pipe.is_read_shut()
                && self.read_pipe(end).is_closed()))
            && !pipe.is_closed()
        {
            self.reset(if end == End::A { End::B } else { End::A });
            return Some(bytes.len());
        }
        let delay = self.delay();
        self.write_delays[end.index()].store(
            delay.as_nanos().min(u64::MAX as u128) as u64,
            Ordering::Relaxed,
        );
        #[cfg(target_os = "macos")]
        let mut shutdown_at = None;
        let written =
            self.write_pipe(end)
                .write_after(bytes, delay, |sent, arrival, _read_shutdown_at| {
                    self.record_write(end, sent, arrival, None, _read_shutdown_at.is_none());
                    #[cfg(target_os = "macos")]
                    if !sent.is_empty() {
                        shutdown_at = _read_shutdown_at;
                    }
                });
        #[cfg(target_os = "macos")]
        if let Some(at) = shutdown_at {
            self.schedule_read_shutdown_data(end, at);
        }
        written
    }

    fn record_write(
        &self,
        end: End,
        bytes: &[u8],
        arrival: Duration,
        mss: Option<usize>,
        _acknowledge: bool,
    ) {
        let shared = &self.regs.shared;
        if let Some(tap) = &self.tap {
            #[cfg(target_os = "macos")]
            if !_acknowledge {
                tap.data_mss_unacknowledged(end.index(), bytes, arrival, mss);
            } else {
                tap.data_mss(end.index(), bytes, arrival, mss);
            }
            #[cfg(not(target_os = "macos"))]
            tap.data_mss(end.index(), bytes, arrival, mss);
        }
        self.stamps[end.index()]
            .lock()
            .unwrap()
            .push_back((bytes.len(), shared.tstamp_now().later(arrival)));
        if !self.pair {
            let pipe = self.write_pipe(end);
            shared.account_tcp_mss(
                self.hop.as_ref(),
                end == End::A,
                bytes.len(),
                self.server.ip(),
                (pipe.has_writer(), pipe.has_reader()),
                mss,
            );
        }
    }

    /// The one-way delay of the connection's bytes: the TCP link policy between its two
    /// addresses plus the interface hop's own delay; none between socketpair ends.
    fn delay(&self) -> Duration {
        if self.pair {
            return Duration::ZERO;
        }
        let shared = &self.regs.shared;
        shared.policies.tcp_delay(self.server, self.client) + shared.hop_delay(self.hop.as_ref())
    }

    /// `end` read `n` bytes: drops their chunks' stamps and returns the arrival of the last byte
    /// read, the stamp Linux reports for a TCP read (net/ipv4/tcp.c `tcp_recvmsg_locked` keeps
    /// the stamp of each segment it copies from, so the last one's wins).
    fn took(&self, end: End, n: usize) -> Option<Stamp> {
        let writer = match end {
            End::A => End::B,
            End::B => End::A,
        };
        let mut chunks = self.stamps[writer.index()].lock().unwrap();
        let mut left = n;
        let mut last = None;
        while left > 0 {
            let Some((len, at)) = chunks.front_mut() else {
                break;
            };
            last = Some(*at);
            if *len <= left {
                left -= *len;
                chunks.pop_front();
            } else {
                *len -= left;
                left = 0;
            }
        }
        last
    }

    /// The pipe `end` reads from.
    fn read_pipe(&self, end: End) -> &Pipe {
        match end {
            End::A => &self.b_to_a,
            End::B => &self.a_to_b,
        }
    }

    /// The pipe `end` writes into.
    fn write_pipe(&self, end: End) -> &Arc<Pipe> {
        match end {
            End::A => &self.a_to_b,
            End::B => &self.b_to_a,
        }
    }

    /// Half-closes `end`'s sending direction (a FIN): the other side reads end of stream once the
    /// bytes already written have arrived.
    fn close(&self, end: End) {
        #[cfg(target_os = "macos")]
        self.progress_tcp_shutdown();
        self.write_pipe(end).close_writer();
        self.write_pipe(end).close(|arrival| {
            if let Some(tap) = &self.tap {
                tap.fin(end.index(), arrival);
            }
        });
    }

    /// `end`'s own address, as `getsockname` reports it.
    fn local(&self, end: End) -> SocketAddr {
        match end {
            End::A => self.client,
            End::B => self.server,
        }
    }

    /// The address of the side opposite `end`, as `getpeername` reports it.
    fn peer(&self, end: End) -> SocketAddr {
        match end {
            End::A => self.server,
            End::B => self.client,
        }
    }

    /// Aborts the connection with a reset sent from `from`: both directions fail at once, and
    /// either side's next read or write reports ECONNRESET (man 2 send; for an established
    /// connection net/ipv4/tcp_input.c tcp_reset sets `sk_err` to ECONNRESET).
    fn reset(&self, from: End) {
        if !self.a_to_b.is_reset() && !self.pair {
            self.regs.shared.count_reset(
                self.server.ip(),
                self.write_pipe(from).has_writer(),
                [
                    self.a_to_b.established_reader(),
                    self.b_to_a.established_reader(),
                ],
            );
        }
        if let Some(tap) = &self.tap {
            tap.rst(from.index());
        }
        if cfg!(target_os = "linux") {
            for (incoming, outgoing) in [(&self.a_to_b, &self.b_to_a), (&self.b_to_a, &self.a_to_b)]
            {
                if if incoming.is_read_shut() {
                    outgoing.is_write_shut()
                } else {
                    !incoming.is_closed()
                } {
                    incoming.reset_reader();
                }
            }
        } else {
            self.write_pipe(from).reset_reader();
        }
        self.a_to_b.reset();
        self.b_to_a.reset();
    }
}

impl End {
    /// The side's index in a [`TcpTap`]: 0 for the connecting side, 1 for the accepting side.
    fn index(self) -> usize {
        match self {
            End::A => 0,
            End::B => 1,
        }
    }
}

/// A listening address, a tester's or the code under test's: connections wait here to be
/// accepted.
///
pub struct Listener {
    rec: Option<std::sync::Weak<SockRec>>,
    /// The address it listens on, possibly a wildcard; a v4-mapped one as IPv4.
    addr: SocketAddr,
    /// A dual-stack socket at the IPv6 wildcard: it takes IPv4 connections too.
    dual: bool,
    /// Established connections not yet accepted, oldest first.
    pending: Mutex<VecDeque<Arc<Conn>>>,
    capacity: AtomicUsize,
    occupied: AtomicUsize,
    /// A tester's: a station at its address rather than a socket of the host.
    tester: bool,
    /// Connections queued so far. Each wakes the listening socket (Linux net/ipv4/tcp_ipv4.c
    /// `tcp_child_process` calls `sk_data_ready`; XNU bsd/kern/uipc_socket2.c `sonewconn` calls
    /// `sorwakeup`), a new edge for edge-triggered readiness.
    arrivals: AtomicU64,
    ready_order: AtomicU64,
    ready_at: AtomicU64,
}

impl Listener {
    fn wake_key(&self) -> Option<crate::readiness::WakeKey> {
        self.rec.as_ref()?.upgrade().map(|rec| rec.wake_key())
    }

    /// How it shares its address with other listeners there.
    fn share(&self) -> Share {
        self.rec
            .as_ref()
            .and_then(std::sync::Weak::upgrade)
            .map(|rec| Share::of(&rec))
            .unwrap_or_default()
    }

    /// Takes the next connection, or `None` if none is waiting.
    pub(crate) fn try_accept(&self) -> Option<Arc<Conn>> {
        snare_interpose::real(|| {
            let conn = self.pending.lock().unwrap().pop_front()?;
            self.occupied.fetch_sub(1, Ordering::AcqRel);
            Some(conn)
        })
    }

    /// Whether a connection is waiting to be accepted.
    pub(crate) fn has_pending(&self) -> bool {
        snare_interpose::real(|| !self.pending.lock().unwrap().is_empty())
    }

    fn reserve(self: &Arc<Self>) -> Option<ListenerAdmission> {
        let mut used = self.occupied.load(Ordering::Acquire);
        loop {
            if used >= self.capacity.load(Ordering::Acquire) {
                return None;
            }
            match self.occupied.compare_exchange_weak(
                used,
                used + 1,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => {
                    return Some(ListenerAdmission {
                        listener: self.clone(),
                        reserved: true,
                    });
                }
                Err(current) => used = current,
            }
        }
    }

    fn queue(&self, conn: Arc<Conn>) {
        self.ready_at.store(
            conn.regs
                .shared
                .tstamp_now()
                .mono
                .as_nanos()
                .min(u64::MAX as u128) as u64,
            Ordering::Relaxed,
        );
        self.pending.lock().unwrap().push_back(conn);
        self.arrivals.fetch_add(1, Ordering::Relaxed);
        self.ready_order
            .store(readiness_sequence(), Ordering::Relaxed);
    }
}

struct ListenerAdmission {
    listener: Arc<Listener>,
    reserved: bool,
}

impl ListenerAdmission {
    fn queue(mut self, conn: Arc<Conn>) {
        self.listener.queue(conn);
        self.reserved = false;
    }
}

impl Drop for ListenerAdmission {
    fn drop(&mut self) {
        if self.reserved {
            self.listener.occupied.fetch_sub(1, Ordering::AcqRel);
        }
    }
}

/// The per-`Sim` listener and datagram registries, shared by the `Fabric` and the tester free
/// functions (via the thread-local scope below) so tests never clobber each other's state.
pub(crate) struct Registries {
    /// Address → the listeners there, the code under test's or a tester's. Keyed on the exact
    /// address, so a wildcard listener is found only by [`Fabric::listener_for`]'s fallback.
    listeners: Mutex<Listeners>,
    /// Where datagrams to each address land.
    udp: Mutex<UdpRegistry>,
    /// Backends that model datagram sockets of their own (a `SimHost`), so a tester's datagram to
    /// one of their sockets is handed over rather than lost.
    foreign_udp: Mutex<Vec<std::sync::Weak<dyn ForeignUdp>>>,
    /// The sim state the fabric shares with the other backends: topology, routing, link
    /// policies, capture and the socket table.
    pub(crate) shared: Arc<SimShared>,
}

impl Registries {
    /// Empty registries over `shared`.
    fn new(shared: Arc<SimShared>) -> Self {
        Registries {
            listeners: Mutex::default(),
            udp: Mutex::default(),
            foreign_udp: Mutex::default(),
            shared,
        }
    }

    /// Delivers one datagram from `src` to every queue `dest` reaches, through the links it
    /// crosses and each receiving address's link policy (which may drop or duplicate it).
    /// Returns how many sockets and endpoints it reached, lost on the way or not.
    ///
    /// `sender` is the route the datagram left by and `tx` whether it is counted as sent on the
    /// egress interface. A copy the policy drops is counted as lost on the wire against the
    /// receiving socket; each surviving copy is queued after its own delay. Zero means nothing is
    /// bound there, for the caller's ICMP port-unreachable handling. Takes `udp` then releases it
    /// before queueing, which bumps readiness.
    ///
    /// `ip` is the header it carries. One with a GSO segment size (a Linux segmented send over
    /// loopback) reaches a socket with `UDP_GRO` on whole and every other recipient as its
    /// segments, as net/ipv4/udp.c `udp_queue_rcv_skb` hands a GSO packet to a socket that did not
    /// ask for one through `udp_rcv_segment`.
    #[allow(clippy::too_many_arguments)]
    fn deliver(
        &self,
        sender: &Sender,
        src: SocketAddr,
        dest: SocketAddr,
        data: &[u8],
        tx: bool,
        ip: crate::ancillary::Header,
    ) -> usize {
        let sent = self.shared.tstamp_now();
        let joined = dest.ip().is_multicast() && self.shared.host_joined(dest.ip());
        let cands = self.udp.lock().unwrap().delivery_candidates(dest, joined);
        let station = match &cands {
            UdpCandidates::One(None) => false,
            UdpCandidates::One(Some(cand)) if cand.addr == dest => false,
            _ => self.station_at(dest.ip()),
        };
        let wire = Wire {
            src,
            dest,
            len: data.len(),
        };
        let emit = |copy: crate::netif::Copy<Arc<DgramQueue>>| {
            if let Some(rec) = &copy.q.rec {
                if copy.delays.is_empty() {
                    rec.count_wire_lost();
                } else {
                    rec.note_rx_nic(copy.nic.as_deref());
                }
            }
            let ip = crate::ancillary::Header {
                ifindex: copy.ingress.unwrap_or(0),
                ..ip
            };
            let whole = ip.gso == 0 || copy.q.rec.as_deref().is_some_and(crate::ancillary::gro);
            for delay in copy.delays {
                if whole {
                    copy.q.push_after(
                        src,
                        data,
                        delay,
                        copy.via.clone(),
                        sent,
                        copy.mtu,
                        ip,
                        self.shared.domain_key(),
                    );
                    continue;
                }
                for segment in data.chunks(usize::from(ip.gso)) {
                    copy.q.push_after(
                        src,
                        segment,
                        delay,
                        copy.via.clone(),
                        sent,
                        copy.mtu,
                        crate::ancillary::Header { gso: 0, ..ip },
                        self.shared.domain_key(),
                    );
                }
            }
        };
        match cands {
            UdpCandidates::One(cand) => {
                if let Some(copy) = self.shared.fan_out_one(sender, wire, station, cand, tx) {
                    emit(copy);
                    1
                } else {
                    0
                }
            }
            UdpCandidates::Many(cands) => {
                let copies = self.shared.fan_out(sender, wire, station, cands, tx);
                let reached = copies.len();
                for copy in copies {
                    emit(copy);
                }
                reached
            }
        }
    }

    /// Whether a tester's endpoint or listener is bound at `ip`, making it a station: an external
    /// host on the simulated network, which routing reaches over an interface rather than
    /// treating as one of the host's own addresses.
    pub(crate) fn station_at(&self, ip: IpAddr) -> bool {
        let endpoint = self.udp.lock().unwrap().endpoints.contains_key(&ip);
        endpoint || self.listeners.lock().unwrap().testers.contains_key(&ip)
    }
}

/// [`Registries::listeners`]: the listeners by address, several sharing one in the order they
/// listened, with how many of them are testers' at each IP and the addresses listened on at each
/// port, so telling a station or a port conflict needs no scan.
#[derive(Default)]
struct Listeners {
    by_addr: HashMap<SocketAddr, Vec<Arc<Listener>>>,
    testers: HashMap<IpAddr, usize>,
    ports: HashMap<u16, Vec<SocketAddr>>,
}

impl Listeners {
    /// Adds `listener` at `addr`. A tester's replaces every listener there: it stands in for
    /// another host, which holds the address alone.
    fn insert(&mut self, addr: SocketAddr, listener: Arc<Listener>) {
        if !self.by_addr.contains_key(&addr) {
            self.ports.entry(addr.port()).or_default().push(addr);
        }
        if listener.tester {
            let replaced = self.by_addr.get_mut(&addr).map(std::mem::take);
            for replaced in replaced.unwrap_or_default() {
                self.forget_tester(&replaced);
            }
            *self.testers.entry(listener.addr.ip()).or_default() += 1;
        }
        let held = self.by_addr.entry(addr).or_default();
        if !held.iter().any(|l| Arc::ptr_eq(l, &listener)) {
            held.push(listener);
        }
    }

    /// Withdraws `listener`, if it is still registered.
    fn remove(&mut self, listener: &Arc<Listener>) {
        let addr = listener.addr;
        let Some(held) = self.by_addr.get_mut(&addr) else {
            return;
        };
        let Some(index) = held.iter().position(|l| Arc::ptr_eq(l, listener)) else {
            return;
        };
        let removed = held.remove(index);
        let emptied = held.is_empty();
        self.forget_tester(&removed);
        if !emptied {
            return;
        }
        self.by_addr.remove(&addr);
        if let Some(held) = self.ports.get_mut(&addr.port()) {
            held.retain(|a| *a != addr);
            if held.is_empty() {
                self.ports.remove(&addr.port());
            }
        }
    }

    /// The listeners at exactly `addr`, in the order they listened.
    fn at(&self, addr: &SocketAddr) -> &[Arc<Listener>] {
        self.by_addr.get(addr).map_or(&[], Vec::as_slice)
    }

    /// The listeners on `port`, at any address.
    fn on_port(&self, port: u16) -> impl Iterator<Item = &Arc<Listener>> + '_ {
        self.ports
            .get(&port)
            .map_or(&[][..], Vec::as_slice)
            .iter()
            .flat_map(|addr| self.at(addr))
    }

    #[cfg(test)]
    fn is_empty(&self) -> bool {
        self.by_addr.is_empty()
    }

    fn forget_tester(&mut self, listener: &Listener) {
        if !listener.tester {
            return;
        }
        let ip = listener.addr.ip();
        if let Some(count) = self.testers.get_mut(&ip) {
            *count -= 1;
            if *count == 0 {
                self.testers.remove(&ip);
            }
        }
    }
}

/// A backend with datagram sockets of its own, which a tester's UDP endpoint can reach.
pub(crate) trait ForeignUdp: Send + Sync {
    /// Delivers `data` from `src` to every one of its sockets a datagram to `dest` reaches,
    /// returning how many it reached.
    fn deliver_from_peer(&self, src: SocketAddr, dest: SocketAddr, data: &[u8]) -> usize;
}

/// Makes `backend`'s datagram sockets reachable from this sim's tester endpoints.
pub(crate) fn attach_foreign_udp(regs: &Registries, backend: std::sync::Weak<dyn ForeignUdp>) {
    snare_interpose::real(|| regs.foreign_udp.lock().unwrap().push(backend));
}

/// Delivers a datagram another backend's socket sent to this sim's tester endpoints (and any
/// fabric socket) that `dest` reaches. Returns how many it reached. Not counted as a send here:
/// the other backend accounts for its own socket's transmission.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) fn deliver_to_endpoints(
    regs: &Registries,
    sender: &Sender,
    src: SocketAddr,
    dest: SocketAddr,
    data: &[u8],
    ip: crate::ancillary::Header,
) -> usize {
    snare_interpose::real(|| regs.deliver(sender, src, dest, data, false, ip))
}

/// The datagram delivery map for one `Sim`: which receive queue a datagram sent to a given address
/// lands in. A bound datagram socket registers its queue here under its local address; `sendto`
/// resolves the destination against it. Multicast memberships live in the sockets' records.
#[derive(Default)]
struct UdpRegistry {
    /// Bound address → the queues of the sockets bound there, which a unicast datagram for that
    /// exact address picks among (`netif::pick_shared`). Keyed on the full `SocketAddr`, so
    /// several addresses on one port (snare 1.x's `add_ip_addr`) and a wildcard `0.0.0.0`/`::`
    /// bind coexist.
    bound: HashMap<SocketAddr, Vec<Arc<DgramQueue>>>,
    by_port: HashMap<u16, UdpBindings>,
    endpoints: HashMap<IpAddr, usize>,
    ports: HashMap<IpAddr, UdpPorts>,
    families: [UdpPorts; 2],
    /// The ports dual-stack sockets hold at the IPv6 wildcard, which IPv4 binds avoid too.
    dual: UdpPorts,
    references: HashMap<(bool, u16), usize>,
    addresses: HashMap<(IpAddr, u16), usize>,
    duals: HashMap<u16, usize>,
}

enum UdpCandidates {
    One(Option<Cand<Arc<DgramQueue>>>),
    Many(Vec<Cand<Arc<DgramQueue>>>),
}

struct UdpBindings {
    first: (SocketAddr, Arc<DgramQueue>),
    rest: Vec<(SocketAddr, Arc<DgramQueue>)>,
}

#[derive(Default)]
struct UdpPorts {
    words: Vec<u64>,
    first: usize,
    count: usize,
}

impl UdpPorts {
    const FIRST: u16 = 49152;
    const WORDS: usize = 256;

    fn insert(&mut self, port: u16) {
        let bit = usize::from(port - Self::FIRST);
        if self.words.len() <= bit / 64 {
            self.words.resize(bit / 64 + 1, 0);
        }
        self.words[bit / 64] |= 1 << (bit % 64);
        self.count += 1;
        while self.first < self.words.len() && self.words[self.first] == u64::MAX {
            self.first += 1;
        }
    }

    fn remove(&mut self, port: u16) {
        let bit = usize::from(port - Self::FIRST);
        self.words[bit / 64] &= !(1 << (bit % 64));
        self.first = self.first.min(bit / 64);
        self.count -= 1;
    }

    /// The lowest port from `start` (an offset into the range) short of `end` that none of
    /// `sets` holds.
    fn find(sets: &[&UdpPorts], start: usize, end: usize) -> Option<u16> {
        let full = sets.iter().map(|set| set.first).max().unwrap_or(0);
        let mut word = (start / 64).max(full);
        while word < Self::WORDS && word * 64 < end {
            let low = start.saturating_sub(word * 64);
            let high = (end - word * 64).min(64);
            let mask = (u64::MAX << low)
                & if high == 64 {
                    u64::MAX
                } else {
                    (1 << high) - 1
                };
            let taken = sets.iter().fold(0, |taken, set| {
                taken | set.words.get(word).copied().unwrap_or(0)
            });
            let free = !taken & mask;
            if free != 0 {
                return Some(Self::FIRST + (word * 64 + free.trailing_zeros() as usize) as u16);
            }
            word += 1;
        }
        None
    }

    /// The lowest port from `first` that none of `sets` holds, wrapping around the range once; 0
    /// when every port is taken.
    fn alloc(sets: &[&UdpPorts], first: u16) -> u16 {
        let start = usize::from(first.max(Self::FIRST) - Self::FIRST);
        Self::find(sets, start, Self::WORDS * 64)
            .or_else(|| Self::find(sets, 0, start))
            .unwrap_or(0)
    }

    #[cfg(test)]
    fn alloc_from(&self, first: u16) -> u16 {
        Self::alloc(&[self], first)
    }
}

impl UdpRegistry {
    fn add_endpoint(&mut self, ip: IpAddr) {
        *self.endpoints.entry(ip).or_default() += 1;
    }

    fn remove_endpoint(&mut self, ip: IpAddr) {
        let count = self.endpoints.get_mut(&ip).unwrap();
        *count -= 1;
        if *count == 0 {
            self.endpoints.remove(&ip);
        }
    }

    /// Whether `queue` is a dual-stack socket's at `addr`.
    fn dual_queue(addr: SocketAddr, queue: &DgramQueue) -> bool {
        queue
            .rec
            .as_ref()
            .is_some_and(|rec| rec.state().dual_at(addr))
    }

    /// Counts a dual-stack binding on `port` in or out of [`UdpRegistry::dual`].
    fn count_dual(&mut self, port: u16, add: bool) {
        if port < UdpPorts::FIRST {
            return;
        }
        let count = self.duals.entry(port).or_default();
        if add {
            *count += 1;
            if *count == 1 {
                self.dual.insert(port);
            }
        } else {
            *count -= 1;
            if *count == 0 {
                self.duals.remove(&port);
                self.dual.remove(port);
            }
        }
    }

    /// Registers `queue` at `addr`, beside any other socket's there.
    fn insert(&mut self, addr: SocketAddr, queue: Arc<DgramQueue>) {
        let endpoint = queue.rec.is_none();
        let dual = Self::dual_queue(addr, &queue);
        let indexed = queue.clone();
        let held = self.bound.entry(addr).or_default();
        if held.iter().any(|q| Arc::ptr_eq(q, &queue)) {
            return;
        }
        held.push(queue);
        if endpoint {
            self.add_endpoint(addr.ip());
        }
        if dual {
            self.count_dual(addr.port(), true);
        }
        match self.by_port.entry(addr.port()) {
            std::collections::hash_map::Entry::Occupied(mut bucket) => {
                bucket.get_mut().rest.push((addr, indexed));
            }
            std::collections::hash_map::Entry::Vacant(bucket) => {
                bucket.insert(UdpBindings {
                    first: (addr, indexed),
                    rest: Vec::new(),
                });
            }
        }
        if addr.port() < UdpPorts::FIRST {
            return;
        }
        let addresses = self.addresses.entry((addr.ip(), addr.port())).or_default();
        if *addresses == 0 {
            self.ports.entry(addr.ip()).or_default().insert(addr.port());
        }
        *addresses += 1;
        let references = self
            .references
            .entry((addr.is_ipv4(), addr.port()))
            .or_default();
        if *references == 0 {
            self.families[usize::from(addr.is_ipv4())].insert(addr.port());
        }
        *references += 1;
    }

    /// Withdraws `queue` from `addr`, if it is registered there.
    fn remove(&mut self, addr: &SocketAddr, queue: &Arc<DgramQueue>) {
        let Some(held) = self.bound.get_mut(addr) else {
            return;
        };
        let Some(index) = held.iter().position(|q| Arc::ptr_eq(q, queue)) else {
            return;
        };
        held.remove(index);
        if held.is_empty() {
            self.bound.remove(addr);
        }
        if queue.rec.is_none() {
            self.remove_endpoint(addr.ip());
        }
        if Self::dual_queue(*addr, queue) {
            self.count_dual(addr.port(), false);
        }
        let mine = |bound: &(SocketAddr, Arc<DgramQueue>)| {
            bound.0 == *addr && Arc::ptr_eq(&bound.1, queue)
        };
        let bucket = self.by_port.get_mut(&addr.port()).unwrap();
        if mine(&bucket.first) {
            if let Some(last) = bucket.rest.pop() {
                bucket.first = last;
            } else {
                self.by_port.remove(&addr.port());
            }
        } else {
            let index = bucket.rest.iter().position(mine).unwrap();
            bucket.rest.swap_remove(index);
        }
        if addr.port() >= UdpPorts::FIRST {
            let address = (addr.ip(), addr.port());
            let addresses = self.addresses.get_mut(&address).unwrap();
            *addresses -= 1;
            if *addresses == 0 {
                self.addresses.remove(&address);
                let ports = self.ports.get_mut(&addr.ip()).unwrap();
                ports.remove(addr.port());
                if ports.count == 0 {
                    self.ports.remove(&addr.ip());
                }
            }
            let key = (addr.is_ipv4(), addr.port());
            let references = self.references.get_mut(&key).unwrap();
            *references -= 1;
            if *references == 0 {
                self.references.remove(&key);
                self.families[usize::from(addr.is_ipv4())].remove(addr.port());
            }
        }
    }

    /// Picks a free ephemeral port for `ip` from the IANA dynamic range (RFC 6335), skipping any
    /// already bound on that IP or the wildcard of its family — any IP of its family for the
    /// wildcard — and the ports dual-stack sockets hold at the IPv6 wildcard if IPv4, and any IP
    /// at all for a `dual`-stack socket: a port no socket overlaps, as Linux and macOS pick for
    /// port 0 whatever `SO_REUSEADDR` and `SO_REUSEPORT` say. Called while the registry is
    /// locked, so the result stays free until the caller inserts it. Returns 0 once the range is
    /// full.
    ///
    /// 49152–65535 is the dynamic/private range of RFC 6335 §6 and macOS's default
    /// (`net.inet.ip.portrange.first`/`last`, XNU bsd/netinet/in.h `IPPORT_HIFIRSTAUTO`/
    /// `IPPORT_HILASTAUTO`). Linux defaults to 32768–60999 (Documentation/networking/
    /// ip-sysctl.rst, `ip_local_port_range`); using the IANA range everywhere is a snare choice,
    /// so addresses are the same on every host. The lowest free port is taken, not a random one.
    fn alloc_port(&self, ip: IpAddr, dual: bool) -> u16 {
        self.alloc_port_from(ip, 49152, dual)
    }

    fn alloc_port_from(&self, ip: IpAddr, first: u16, dual: bool) -> u16 {
        let v4 = ip.is_ipv4();
        let mut sets: Vec<&UdpPorts> = Vec::with_capacity(3);
        if dual {
            sets.extend(&self.families);
        } else if ip.is_unspecified() {
            sets.push(&self.families[usize::from(v4)]);
            if v4 {
                sets.push(&self.dual);
            }
        } else {
            sets.extend(self.ports.get(&ip));
            sets.extend(self.ports.get(&unspecified_like(ip)));
            if v4 {
                sets.push(&self.dual);
            }
        }
        UdpPorts::alloc(&sets, first)
    }

    /// The queues a datagram to `dest` could reach: for a multicast group the sockets on the port
    /// that take it ([`SockRec::takes_group`], given whether the host `joined` the group), else
    /// every queue bound on the port. Which of them actually receive it (exact address,
    /// wildcard, broadcast, the receiving interface) is decided by `SimShared::fan_out`; each
    /// candidate carries whether it is a tester endpoint and the interface the socket is bound
    /// to, if any.
    fn delivery_candidates(&self, dest: SocketAddr, joined: bool) -> UdpCandidates {
        let Some(bucket) = self.by_port.get(&dest.port()) else {
            return UdpCandidates::One(None);
        };
        if !bucket.rest.is_empty() {
            return UdpCandidates::Many(self.candidates(dest, joined));
        }
        let (addr, queue) = &bucket.first;
        let group = dest.ip();
        let accepted = !group.is_multicast()
            || queue
                .rec
                .as_ref()
                .is_some_and(|rec| rec.takes_group(*addr, group, joined));
        UdpCandidates::One(accepted.then(|| Self::candidate(*addr, queue)))
    }

    fn candidate(addr: SocketAddr, queue: &Arc<DgramQueue>) -> Cand<Arc<DgramQueue>> {
        let (device, dual, share) =
            queue
                .rec
                .as_ref()
                .map_or((None, false, Share::default()), |rec| {
                    let state = rec.state();
                    (
                        state.device.as_ref().map(|device| device.0),
                        state.dual_at(addr),
                        Share::of_state(&state),
                    )
                });
        Cand {
            addr,
            endpoint: queue.rec.is_none(),
            device,
            dual,
            share,
            q: queue.clone(),
        }
    }

    fn candidates(&self, dest: SocketAddr, joined: bool) -> Vec<Cand<Arc<DgramQueue>>> {
        let Some(bucket) = self.by_port.get(&dest.port()) else {
            return Vec::new();
        };
        let group = dest.ip();
        std::iter::once(&bucket.first)
            .chain(bucket.rest.iter())
            .filter(|(addr, q)| {
                !group.is_multicast()
                    || q.rec
                        .as_ref()
                        .is_some_and(|r| r.takes_group(*addr, group, joined))
            })
            .map(|(addr, q)| Self::candidate(*addr, q))
            .collect()
    }
}

/// The wildcard address (`0.0.0.0` or `::`) of `ip`'s family.
pub(crate) fn unspecified_like(ip: IpAddr) -> IpAddr {
    match ip {
        IpAddr::V4(_) => IpAddr::V4(Ipv4Addr::UNSPECIFIED),
        IpAddr::V6(_) => IpAddr::V6(Ipv6Addr::UNSPECIFIED),
    }
}

/// The address a bound datagram socket claims against a new bind: the address its `bind` named,
/// at the port it got, wherever a connect has since rehashed it for delivery. A socket a send or
/// connect bound implicitly claims where that put it.
fn dgram_claim(sock: &Sock) -> Option<SocketAddr> {
    match sock {
        Sock::Dgram {
            local: Some(local),
            requested,
            ..
        } => Some(requested.map_or(*local, |r| SocketAddr::new(r.ip(), local.port()))),
        _ => None,
    }
}

/// The address a TCP socket holds against a new bind, and whether it listens: a bound fresh or
/// connecting socket's, a listener's, or a connected stream's local address. Socketpair streams
/// hold none.
fn tcp_bound(sock: &Sock) -> Option<(SocketAddr, bool)> {
    match sock {
        Sock::Fresh {
            local: Some(local), ..
        }
        | Sock::Connecting {
            local: Some(local), ..
        } => Some((*local, false)),
        Sock::Listener { listener, .. } => Some((listener.addr, true)),
        Sock::Stream { conn, end, .. } if !conn.pair => Some((conn.local(*end), false)),
        _ => None,
    }
}

/// What a TCP socket holds against a new bind ([`tcp_bound`]).
fn tcp_claim(sock: &Sock) -> Option<Claim> {
    let (addr, listening) = tcp_bound(sock)?;
    Some(Claim {
        listening,
        ..Claim::of(sock.rec()?, addr)
    })
}

/// What a datagram socket holds against a new bind ([`dgram_claim`]).
fn udp_claim(sock: &Sock) -> Option<Claim> {
    Some(Claim::of(sock.rec()?, dgram_claim(sock)?))
}

/// The port `sock` holds against a new bind, TCP or datagram.
fn claimed_port(sock: &Sock) -> Option<u16> {
    tcp_bound(sock)
        .map(|(addr, _)| addr)
        .or_else(|| dgram_claim(sock))
        .map(|addr| addr.port())
}

/// What an unbound datagram socket still holds of the address its `bind` named: the address, at
/// no port. Only a Linux disconnect leaves a socket so (see [`Fabric::disconnect_dgram`]).
pub(crate) fn unhashed(requested: Option<SocketAddr>) -> Option<SocketAddr> {
    requested.map(|r| SocketAddr::new(r.ip(), 0))
}

thread_local! {
    /// The registries of the `Sim` this thread runs in, set by [`enter`].
    static CURRENT: std::cell::RefCell<Option<Arc<Registries>>> = const { std::cell::RefCell::new(None) };
}

/// Installs `regs` as the calling thread's current registries until the guard drops. `Sim::run`
/// wraps the test body in this so testers and topology calls reach this sim's registries.
pub(crate) fn enter(regs: Arc<Registries>) -> RegistryGuard {
    let previous = CURRENT.with(|c| c.replace(Some(regs)));
    RegistryGuard { previous }
}

/// Restores the thread's previous registries on drop, so nested `Sim::run`s unwind correctly.
pub(crate) struct RegistryGuard {
    /// What [`CURRENT`] held before [`enter`].
    previous: Option<Arc<Registries>>,
}

impl Drop for RegistryGuard {
    fn drop(&mut self) {
        CURRENT.with(|c| *c.borrow_mut() = self.previous.take());
    }
}

/// The calling thread's registries. Panics outside `Sim::run`, where a tester call has no sim.
fn current() -> Arc<Registries> {
    try_registries_here().expect("snare tester functions must be called inside Sim::run")
}

/// The registries of the `Sim` the calling thread runs in, if it runs in one.
pub(crate) fn try_registries_here() -> Option<Arc<Registries>> {
    CURRENT.with(|c| c.borrow().clone())
}

/// The registries of the `Sim` the calling thread runs in, for a tester to keep once it leaves
/// that thread.
pub(crate) fn registries_here() -> Arc<Registries> {
    current()
}

/// Gives every thread the sim starts this sim's registries, as `Sim::run` gives its own thread, so
/// testers, link policies and other tester-side calls work from any thread of the test.
pub(crate) struct ScopeLayer(pub(crate) Arc<Registries>);

impl snare_interpose::Layer for ScopeLayer {
    fn thread_started(&self) {
        // The scope lasts as long as the thread does.
        std::mem::forget(enter(self.0.clone()));
    }

    fn settling(&self, domain: usize) -> bool {
        crate::realfd::settling(domain)
    }

    fn real_ready(&self, domain: usize, ready: &mut dyn FnMut(snare_interpose::ReadinessKey)) {
        crate::realfd::real_ready(domain, ready);
    }

    /// With no virtual clock to hold to real time, a sim whose thread waits on what a child
    /// process may write waits for it, as it would on a held clock, rather than giving up.
    fn idle_wait(&self) -> Option<Duration> {
        (self.0.shared.clock.is_none() && crate::realfd::outside(self.0.shared.domain_key()))
            .then_some(crate::realfd::OUTSIDE_POLL)
    }
}

/// Withdraws `listener` from its address, so later connects there are refused (ECONNREFUSED) as
/// they would be once a real server exits. Leaves a listener that has since replaced it alone.
pub(crate) fn unlisten(regs: &Registries, listener: &Arc<Listener>) {
    snare_interpose::real(|| regs.listeners.lock().unwrap().remove(listener));
}

/// A datagram endpoint a tester owns at a fixed address: datagrams the code under test sends there
/// land in its queue, and what it sends carries that address as the source. Registered like a
/// bound socket, so broadcasts and wildcard binds behave the same; unregistered on drop.
pub(crate) struct UdpEndpoint {
    regs: Arc<Registries>,
    /// The fixed address it is bound at; its IP makes a station (see [`Registries::station_at`]).
    addr: SocketAddr,
    /// Its receive queue, with no socket record (`rec` is `None`), which marks it a tester's.
    queue: Arc<DgramQueue>,
}

impl UdpEndpoint {
    /// Binds `addr`. Panics if a socket or another tester already holds it, as a real bind would
    /// fail with EADDRINUSE.
    pub(crate) fn bind(regs: Arc<Registries>, addr: SocketAddr) -> Self {
        let queue = Arc::new(DgramQueue::default());
        snare_interpose::real(|| {
            let mut udp = regs.udp.lock().unwrap();
            assert!(
                !udp.bound.contains_key(&addr),
                "udp tester address {addr} is already bound"
            );
            udp.insert(addr, queue.clone());
        });
        UdpEndpoint { regs, addr, queue }
    }

    /// The next datagram received, with its source.
    pub(crate) fn try_recv(&self) -> Option<(SocketAddr, Vec<u8>)> {
        snare_interpose::real(|| {
            self.queue
                .pop(|_| true)
                .map(|(dg, _)| (dg.src, dg.data.into_vec()))
        })
    }

    /// Whether a datagram has arrived for it.
    pub(crate) fn has_pending(&self) -> bool {
        snare_interpose::real(|| self.queue.has(|_| true))
    }

    /// Sends one datagram to `dest` — a socket's address, a wildcard bind's port, the broadcast
    /// address or a multicast group — from this endpoint's address. It is captured as inbound
    /// traffic, delivered to the fabric's sockets and other endpoints, then offered to every
    /// attached [`ForeignUdp`] backend. One nothing takes counts in the host's UDP counters when
    /// it was the host's to take.
    pub(crate) fn send_to(&self, dest: SocketAddr, data: &[u8]) {
        snare_interpose::real(|| {
            let sender = Sender::Station(self.addr.ip());
            self.regs
                .shared
                .capture_udp(&sender, self.addr, dest, Dir::In, data, None);
            let ip = crate::ancillary::Header::plain(dest.ip());
            let mut reached = self.regs.deliver(&sender, self.addr, dest, data, true, ip);
            let foreign: Vec<_> = self.regs.foreign_udp.lock().unwrap().clone();
            for backend in foreign.iter().filter_map(std::sync::Weak::upgrade) {
                reached += backend.deliver_from_peer(self.addr, dest, data);
            }
            if reached == 0 {
                let station = self.regs.station_at(dest.ip());
                self.regs.shared.count_unreceived(dest, station);
            }
        });
    }
}

/// Unregisters the address.
impl Drop for UdpEndpoint {
    fn drop(&mut self) {
        snare_interpose::real(|| {
            self.regs
                .udp
                .lock()
                .unwrap()
                .remove(&self.addr, &self.queue);
        });
    }
}

/// Registers (and returns) the peer listener for `addr`, replacing any earlier one. Unlike a
/// socket's `listen`, it skips the bind-conflict rules: a tester stands in for another host.
pub(crate) fn listen_at(addr: SocketAddr) -> Arc<Listener> {
    let listener = Arc::new(Listener {
        rec: None,
        addr,
        dual: false,
        pending: Mutex::default(),
        capacity: AtomicUsize::new(usize::MAX),
        occupied: AtomicUsize::new(0),
        tester: true,
        arrivals: AtomicU64::new(0),
        ready_order: AtomicU64::new(0),
        ready_at: AtomicU64::new(0),
    });
    snare_interpose::real(|| {
        current()
            .listeners
            .lock()
            .unwrap()
            .insert(addr, listener.clone());
    });
    listener
}

pub(crate) use crate::readiness::readiness;
use crate::scope::SimShared;
use std::time::Duration;

use crate::faults::{ConnectAttempt, Outcome, Syn};
use crate::limits::{Arrival, RxQueue};
use crate::netif::{
    Cand, Hop, LinkState, Op, Sender, Share, Wire, pick_shared, reported, toward, unmapped,
};
#[cfg(target_os = "macos")]
use crate::notices::Ticket;
use crate::notices::{Keys, PollSet, Settled};
use crate::pcapng::{Dir, TcpTap};
use crate::readiness::Deadline;
use crate::sockets::{Membership, RxProbe, SockRec, SocketKind, Taker, UnmodelledOption};
use crate::stream::{Ends, Pipe, Read, Sent};
use crate::tstamp::{Rx, Stamp};

/// One open file description's state, shared by every descriptor that aliases it.
/// `nonblocking` is its `O_NONBLOCK`; `rec` holds socket options, pending errors and stats.
enum Sock {
    /// A TCP socket neither connected nor listening; `local` is where `bind` put it. Also what a
    /// socket whose connect failed returns to, with the error pending in `rec`.
    Fresh {
        /// `AF_INET` or `AF_INET6`, for the family of the wildcard address an unbound socket
        /// reports or listens on.
        domain: c_int,
        local: Option<SocketAddr>,
        nonblocking: bool,
        rec: Arc<SockRec>,
    },
    /// A TCP connect waiting on its SYN's answer; every descriptor of the socket shares the
    /// attempt.
    Connecting {
        domain: c_int,
        local: Option<SocketAddr>,
        nonblocking: bool,
        rec: Arc<SockRec>,
        /// The address being connected to.
        dest: SocketAddr,
        /// The SYN schedule (retransmits, the answer the fault plan gives), played forward by
        /// [`Fabric::advance_connect`].
        attempt: Arc<Mutex<ConnectAttempt>>,
    },
    /// One end of an established connection: a TCP socket, or a `SOCK_STREAM` socketpair end.
    Stream {
        conn: Arc<Conn>,
        end: End,
        nonblocking: bool,
        rec: Arc<SockRec>,
    },
    /// A listening TCP socket, its [`Listener`] registered under its address.
    Listener {
        listener: Arc<Listener>,
        nonblocking: bool,
        rec: Arc<SockRec>,
    },
    /// A UDP datagram socket. `local` is its bound address (registered in [`UdpRegistry`]); `peer`
    /// is the address a `connect` fixed, which filters receives and lets a plain `send` work.
    Dgram {
        queue: Arc<DgramQueue>,
        domain: c_int,
        local: Option<SocketAddr>,
        /// The address `bind` was given (port 0 for any): what a disconnect falls back to.
        requested: Option<SocketAddr>,
        peer: Option<SocketAddr>,
        nonblocking: bool,
        /// `SO_BROADCAST`: whether sends to a broadcast address are allowed (man 7 socket).
        broadcast: bool,
        rec: Arc<SockRec>,
    },
    /// One end of an `AF_UNIX` `SOCK_DGRAM` socketpair: datagrams land in `queue`, and a send goes
    /// to the other end's queue while that end is open.
    UnixDgram {
        queue: Arc<DgramQueue>,
        /// The other end's queue; weak, so it dies with the other end's last descriptor.
        peer: std::sync::Weak<DgramQueue>,
        nonblocking: bool,
        rec: Arc<SockRec>,
        /// The socketpair's process-wide identity (see [`ProcessPairs`]) and which end this is.
        pair: (u64, usize),
    },
    /// A counting eventfd (readiness wakeups), man 2 eventfd.
    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
    Event {
        ready_order: u64,
        ready_at: Duration,
        /// The 64-bit counter; readable while nonzero.
        counter: u64,
        nonblocking: bool,
        /// `EFD_SEMAPHORE`: a read takes 1 rather than the whole counter.
        semaphore: bool,
        /// Writes so far. Linux fs/eventfd.c `eventfd_write` wakes the fd's waiters with `EPOLLIN`
        /// on every write, even one to a counter already nonzero.
        writes: u64,
        /// Reads so far; `eventfd_read` there wakes with `EPOLLOUT`.
        reads: u64,
    },
    /// A timerfd (man 2 timerfd_create): readable once it has expired, a read returning the
    /// expirations since the last read as a native-endian u64. Expiry is played lazily against
    /// the sim's monotonic clock ([`Fabric::settle_timers`]).
    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
    Timer {
        /// `CLOCK_MONOTONIC`, `CLOCK_BOOTTIME` or `CLOCK_REALTIME`, for `TFD_TIMER_ABSTIME`.
        clock: c_int,
        /// When it next expires, on the sim's monotonic timeline; `None` while disarmed.
        expires: Option<Duration>,
        /// The reload interval; zero for a one-shot timer.
        interval: Duration,
        /// Expirations not yet read.
        ticks: u64,
        /// Expirations ever: a wake each, as Linux fs/timerfd.c `timerfd_triggered` wakes the
        /// waitqueue on every expiry.
        expired: u64,
        nonblocking: bool,
    },
    /// An epoll set: each watched fd's registration. Level-triggered unless registered with
    /// `EPOLLET` (see [`Edge`]); `EPOLLONESHOT` disables a registration once reported.
    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
    Epoll {
        /// Its registrations, and which of them a scan looks at (see [`crate::notices`]).
        interests: PollSet<(c_int, EpollIdentity), EpollInterest>,
        /// The watch on the real descriptors registered, while there are any.
        real: Option<Arc<crate::realfd::Watch>>,
    },
    /// A raw L2 endpoint on a virtual interface: whole Ethernet frames. On Linux this is an
    /// `AF_PACKET` socket (packet(7)); on macOS it is a `/dev/bpf*` device (bpf(4)); both share
    /// the frame fan-out.
    #[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(dead_code))]
    Raw {
        /// The interface it is bound to (`sockaddr_ll.sll_ifindex` or `BIOCSETIF`); `None` until
        /// bound, and an unbound endpoint can neither send nor receive.
        ifindex: Option<u32>,
        /// Frames other raw endpoints on the interface sent, unbounded, oldest first.
        rx: VecDeque<Vec<u8>>,
        /// Frames received so far, each a wake of the socket (net/packet/af_packet.c
        /// `packet_rcv` calls `sk_data_ready`; XNU bsd/net/bpf.c `bpf_wakeup` per buffer).
        arrived: u64,
        nonblocking: bool,
        rec: Arc<SockRec>,
    },
    /// A kqueue set (macOS): read/write interest per fd plus user-event (waker) triggers, each
    /// carrying the caller's `udata`. The kqueue analogue of [`Sock::Epoll`]. See kevent(2). The
    /// state is behind an `Arc` so a `dup`/`F_DUPFD` of the queue fd aliases the same set — which
    /// mio's macOS `Waker` relies on (it clones the kqueue fd and triggers through the clone).
    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
    Kqueue { state: Arc<Mutex<KqueueState>> },
    /// A signalfd (man 2 signalfd): readable while a signal of `mask`, the virtual signals as
    /// `snare_interpose::virtual_bits` gives them, is pending for the thread that looks, a read
    /// taking them.
    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
    Signal { mask: u64, nonblocking: bool },
}

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
enum EpollIdentity {
    Local(u64),
    Foreign(u64),
    Untracked,
}

/// One fd's registration in an epoll set (man 2 epoll_ctl).
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
struct EpollInterest {
    order: u64,
    pending_order: Option<(Duration, u64)>,
    /// The `events` mask given to `epoll_ctl`, `EPOLLET` and `EPOLLONESHOT` included.
    events: u32,
    /// The caller's `epoll_data`, echoed back by `epoll_wait`.
    data: u64,
    edge: Edge,
    /// Registered `EPOLLONESHOT` and reported: disabled until the next `EPOLL_CTL_MOD` (man 2
    /// epoll_ctl; fs/eventpoll.c `ep_send_events` strips the item's events to
    /// `EP_PRIVATE_BITS`).
    spent: bool,
}

/// The interest set of one kqueue: read/write interests keyed by fd, and user events keyed by
/// ident.
#[derive(Default)]
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) struct KqueueState {
    /// `EVFILT_READ` and `EVFILT_WRITE` registrations by filter and fd, and which of them a scan
    /// looks at (see [`crate::notices`]).
    notes: PollSet<(i16, c_int), Knote>,
    /// `EVFILT_USER` registrations by ident.
    users: HashMap<usize, UserNote>,
    /// The watch on the real descriptors registered, while there are any.
    real: Option<Arc<crate::realfd::Watch>>,
}

/// An `EVFILT_READ` or `EVFILT_WRITE` registration.
#[derive(Clone, Copy)]
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
struct Knote {
    udata: u64,
    /// `EV_CLEAR`, `EV_ONESHOT` and `EV_DISPATCH` as given when it was added: XNU
    /// bsd/kern/kern_event.c `kevent_register` keeps an existing knote's flags when it is added
    /// again, updating only its `udata` and filter state.
    flags: u16,
    /// `EV_DISABLE`d, or `EV_DISPATCH` and reported: not returned until `EV_ENABLE`.
    disabled: bool,
    /// Its `EV_CLEAR` state.
    edge: Edge,
    /// On a real descriptor the fabric does not serve, as [`EpollIdentity::Untracked`] is for
    /// epoll; its readiness is the OS's ([`real_kevent`]).
    untracked: bool,
    /// Which addition this is ([`next_knote_generation`]): a scan reads the notes, lets go of the
    /// kqueue's lock to look at the sockets and writes the edges back, and a note added again
    /// meanwhile (the same descriptor re-registered, or reused after a close) keeps its fresh
    /// edge.
    generation: u64,
}

/// A fresh [`Knote::generation`].
#[cfg(target_os = "macos")]
fn next_knote_generation() -> u64 {
    static GENERATIONS: AtomicU64 = AtomicU64::new(0);
    GENERATIONS.fetch_add(1, Ordering::Relaxed)
}

/// An `EVFILT_USER` registration (mio's macOS `Waker`).
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
struct UserNote {
    udata: u64,
    /// As for [`Knote::flags`].
    flags: u16,
    disabled: bool,
    /// Fired by `NOTE_TRIGGER`. kevent(2): it stays fired until retrieved with `EV_CLEAR` set
    /// (XNU bsd/kern/kern_event.c `filt_userprocess` resets it only under `EV_CLEAR`).
    triggered: bool,
}

/// One descriptor number naming a socketpair end, in the process-wide [`ProcessPairs`].
#[derive(Clone, Copy)]
struct PairEnd {
    /// The pair's identity, the same in every sim's instance of it.
    pair: u64,
    /// Which end: 0 for the first descriptor `socketpair` returned, 1 for the second.
    end: usize,
    dgram: bool,
    /// The end's `O_NONBLOCK` as the sim that minted the number last set it.
    nonblocking: bool,
}

/// Every descriptor number that names a socketpair end, whichever sim minted it. A socketpair
/// has no address and nothing of a network in it, so like an epoll set or an eventfd it is the
/// process's, not a world's; unlike them it carries bytes, and two worlds must not see each
/// other's, so instead of moving between sims each sim that reaches one gets an instance of its
/// own ([`Net::mirror`]). A number stays here until the sim that minted it closes it: a sim that
/// ends leaves its placeholders open, so a pair a library keeps in a static outlives its sim.
#[derive(Default)]
struct ProcessPairs {
    ends: std::collections::BTreeMap<c_int, PairEnd>,
}

impl ProcessPairs {
    fn get(&self, fd: c_int) -> Option<PairEnd> {
        self.ends.get(&fd).copied()
    }

    fn insert(&mut self, fd: c_int, end: PairEnd) {
        self.ends.insert(fd, end);
    }

    fn remove(&mut self, fd: c_int) {
        self.ends.remove(&fd);
    }

    /// A number naming the other end of `end`'s pair.
    fn peer_of(&self, end: PairEnd) -> Option<c_int> {
        self.ends
            .iter()
            .find(|(_, other)| other.pair == end.pair && other.end != end.end)
            .map(|(&fd, _)| fd)
    }
}

static PROCESS_PAIRS: Mutex<ProcessPairs> = Mutex::new(ProcessPairs {
    ends: std::collections::BTreeMap::new(),
});

/// The process's socketpair ends; a leaf lock, taken after a fabric's socket table.
fn process_pairs() -> std::sync::MutexGuard<'static, ProcessPairs> {
    PROCESS_PAIRS.lock().unwrap_or_else(|e| e.into_inner())
}

/// Identities for socketpairs, unique in the process.
static NEXT_PAIR: AtomicU64 = AtomicU64::new(1);

/// The descriptors registered in `sock` when it is an epoll set or a kqueue, real ones aside.
fn registered_sockets(sock: &Sock) -> Vec<c_int> {
    match sock {
        Sock::Epoll { interests, .. } => interests
            .iter()
            .filter(|((_, identity), _)| matches!(identity, EpollIdentity::Local(_)))
            .map(|(&(fd, _), _)| fd)
            .collect(),
        Sock::Kqueue { state } => {
            let state = state.lock().unwrap();
            state
                .notes
                .iter()
                .filter(|(_, note)| !note.untracked)
                .map(|(&(_, fd), _)| fd)
                .collect()
        }
        _ => Vec::new(),
    }
}

/// Sets or clears `O_NONBLOCK` on real descriptor `fd`.
fn set_real_nonblocking(fd: c_int, on: bool) {
    snare_interpose::real(|| unsafe {
        let flags = libc::fcntl(fd, libc::F_GETFL);
        if flags < 0 {
            return;
        }
        let wanted = if on {
            flags | libc::O_NONBLOCK
        } else {
            flags & !libc::O_NONBLOCK
        };
        if wanted != flags {
            libc::fcntl(fd, libc::F_SETFL, wanted);
        }
    });
}

/// What [`Sockets::mirrors`] records for a descriptor of another sim's network socket, served
/// here as a connection that is gone: no socketpair has this identity.
const DEAD: u64 = 0;

/// The real descriptor every virtual one but a socketpair end is a `dup` of, so each holds a
/// number the OS will not hand out meanwhile: the read end of a pipe whose write end is closed. A
/// call that reaches the OS with such a number instead of the fabric (one no hook covers, or one
/// from a thread outside every sim) finds a peer that has gone, as a dropped connection would
/// show it: end of file on a read, `EBADF` on a write, `ESPIPE` on a positioned call, `ENOTSOCK`
/// on a socket call and a hang-up in `poll`, never a write that succeeds and goes nowhere.
fn placeholder() -> c_int {
    static PLACEHOLDER: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(-1);
    let held = PLACEHOLDER.load(Ordering::Acquire);
    if held >= 0 {
        return held;
    }
    let made = snare_interpose::real(|| unsafe {
        let mut ends = [-1; 2];
        if libc::pipe(ends.as_mut_ptr()) != 0 {
            return -1;
        }
        libc::close(ends[1]);
        libc::fcntl(ends[0], libc::F_SETFD, libc::FD_CLOEXEC);
        ends[0]
    });
    if made < 0 {
        return made;
    }
    match PLACEHOLDER.compare_exchange(-1, made, Ordering::AcqRel, Ordering::Acquire) {
        Ok(_) => made,
        Err(held) => {
            snare_interpose::real(|| unsafe { libc::close(made) });
            held
        }
    }
}

struct SocketDescription {
    id: u64,
    sock: Sock,
    status_flags: c_int,
    /// A socket's signal-driven I/O settings.
    fcntl: SocketFcntl,
    descriptors: BTreeSet<c_int>,
    /// The port [`Sockets::ports`] lists it under.
    port: Option<u16>,
}

#[derive(Clone, Copy, PartialEq, Eq)]
struct DescriptionKey {
    slot: usize,
    id: u64,
}

/// How many descriptor numbers [`FdBits`] tells about.
const FD_BITS: usize = 1 << 16;

/// Which descriptor numbers a fabric's socket table holds, and which of them name another sim's
/// socketpair end ([`Sockets::mirrors`]), readable without the table's lock: a bit per number
/// below [`FD_BITS`], moved with the table under its lock. A number above that is looked up there.
struct FdBits {
    held: Box<[AtomicU64]>,
    mirrored: Box<[AtomicU64]>,
}

impl Default for FdBits {
    fn default() -> Self {
        let words = || (0..FD_BITS / 64).map(|_| AtomicU64::new(0)).collect();
        FdBits {
            held: words(),
            mirrored: words(),
        }
    }
}

impl FdBits {
    fn word(fd: c_int) -> Option<(usize, u64)> {
        let fd = usize::try_from(fd).ok().filter(|&fd| fd < FD_BITS)?;
        Some((fd / 64, 1 << (fd % 64)))
    }

    fn set(bits: &[AtomicU64], fd: c_int, on: bool) {
        if let Some((word, bit)) = Self::word(fd) {
            if on {
                bits[word].fetch_or(bit, Ordering::Release);
            } else {
                bits[word].fetch_and(!bit, Ordering::Release);
            }
        }
    }

    fn get(bits: &[AtomicU64], fd: c_int) -> Option<bool> {
        let (word, bit) = Self::word(fd)?;
        Some(bits[word].load(Ordering::Acquire) & bit != 0)
    }

    /// Whether the table holds `fd`, a number not mirrored: `None` when only the table can tell.
    fn held(&self, fd: c_int) -> Option<bool> {
        match Self::get(&self.held, fd)? {
            false => Some(false),
            true if Self::get(&self.mirrored, fd) == Some(false) => Some(true),
            true => None,
        }
    }
}

#[derive(Default)]
struct Sockets {
    /// The numbers `descriptors` and `mirrors` hold, for [`Fabric::owns`] to read without the
    /// lock.
    bits: Arc<FdBits>,
    descriptions: Vec<Option<SocketDescription>>,
    free_slots: Vec<usize>,
    descriptors: HashMap<c_int, DescriptionKey>,
    #[cfg(target_os = "linux")]
    identities: HashMap<u64, usize>,
    next_id: u64,
    /// How many descriptions are timerfds, so settling them costs nothing without one.
    timers: usize,
    /// How many descriptions are connecting sockets, so moving them on costs nothing without one.
    connecting: usize,
    /// The sim whose descriptors these are, recorded with each (`snare_interpose::claim_fd`) so a
    /// thread of another sim reaching one is not sent to the OS's placeholder. Learnt from the
    /// first thread to mint one, which is always one of the sim's.
    owner: Option<snare_interpose::SimId>,
    /// Descriptors another sim minted that name this sim's instance of a socketpair end (see
    /// [`Net::mirror`]), with the pair's identity: never claimed, and closed without the OS.
    mirrors: HashMap<c_int, u64>,
    /// This sim's instance of each socketpair it mirrored, by the pair's identity: the ends not
    /// yet reached under any descriptor.
    replicas: HashMap<u64, [Option<Sock>; 2]>,
    /// The slots of the descriptions that hold each port against a new bind ([`claimed_port`]),
    /// so a bind looks only at the sockets on its port. Kept by [`place`](Self::place),
    /// [`reindex`](Self::reindex) and removal.
    ports: HashMap<u16, HashSet<usize>>,
}

impl Sockets {
    fn identity(&self, fd: c_int) -> Option<u64> {
        self.descriptors.get(&fd).map(|key| key.id)
    }

    #[cfg(target_os = "linux")]
    fn get_identity(&self, id: u64) -> Option<&Sock> {
        let description = self
            .descriptions
            .get(*self.identities.get(&id)?)?
            .as_ref()?;
        (description.id == id).then_some(&description.sock)
    }

    fn get(&self, fd: &c_int) -> Option<&Sock> {
        let key = self.descriptors.get(fd)?;
        let description = self.descriptions.get(key.slot)?.as_ref()?;
        (description.id == key.id).then_some(&description.sock)
    }

    fn get_mut(&mut self, fd: &c_int) -> Option<&mut Sock> {
        Some(&mut self.description_mut(fd)?.sock)
    }

    fn description_mut(&mut self, fd: &c_int) -> Option<&mut SocketDescription> {
        let key = self.descriptors.get(fd)?;
        self.descriptions
            .get_mut(key.slot)?
            .as_mut()
            .filter(|description| description.id == key.id)
    }

    fn contains_key(&self, fd: &c_int) -> bool {
        self.descriptors.contains_key(fd)
    }

    /// Records `fd` as this sim's. A number that named a socketpair end of another sim, closed
    /// from elsewhere since, names that end no more.
    fn claim(&mut self, fd: c_int, local: bool) {
        if self.owner.is_none() {
            self.owner = snare_interpose::current_sim();
        }
        if let Some(owner) = self.owner {
            snare_interpose::claim_fd(fd, owner, local);
        }
        process_pairs().remove(fd);
    }

    fn insert(&mut self, fd: c_int, sock: Sock) {
        self.claim(fd, sock.process_local());
        self.place(fd, sock);
        self.publish_pair(fd);
    }

    /// Serves `fd`, another sim's number, as `sock`, an end of this sim's instance of the
    /// socketpair `pair`.
    fn insert_mirror(&mut self, fd: c_int, sock: Sock, pair: u64) {
        self.mirrors.insert(fd, pair);
        FdBits::set(&self.bits.mirrored, fd, true);
        self.place(fd, sock);
    }

    /// Serves `fd`, another sim's number, as one more descriptor of `held`'s description.
    fn alias_mirror(&mut self, held: c_int, fd: c_int, pair: u64) {
        self.mirrors.insert(fd, pair);
        FdBits::set(&self.bits.mirrored, fd, true);
        let key = self.descriptors[&held];
        self.descriptors.insert(fd, key);
        FdBits::set(&self.bits.held, fd, true);
        self.descriptions[key.slot]
            .as_mut()
            .unwrap()
            .descriptors
            .insert(fd);
    }

    /// A descriptor of this sim serving end `end` of its instance of `pair` under another sim's
    /// number.
    fn mirror_holding(&self, pair: u64, end: usize) -> Option<c_int> {
        self.mirrors
            .iter()
            .filter(|&(_, &of)| of == pair)
            .map(|(&fd, _)| fd)
            .find(|fd| {
                self.get(fd)
                    .and_then(Sock::pair_end)
                    .is_some_and(|(_, at, _)| at == end)
            })
    }

    /// Whether `fd` is a mirror whose pair the process no longer holds under that number: the
    /// sim that minted it closed it, and the OS may have reused it.
    fn stale_mirror(&self, fd: c_int) -> bool {
        self.mirrors.get(&fd).is_some_and(|&pair| {
            if pair == DEAD {
                return !snare_interpose::minted(fd);
            }
            process_pairs().get(fd).is_none_or(|end| end.pair != pair)
        })
    }

    /// Records every descriptor of `fd`'s description, when it is a socketpair end this sim
    /// minted, as naming that end, with its current `O_NONBLOCK`.
    fn publish_pair(&self, fd: c_int) {
        let Some(key) = self.descriptors.get(&fd) else {
            return;
        };
        let Some(description) = self.descriptions[key.slot].as_ref() else {
            return;
        };
        let Some((pair, end, nonblocking)) = description.sock.pair_end() else {
            return;
        };
        let dgram = matches!(description.sock, Sock::UnixDgram { .. });
        if let Some(&held) = description
            .descriptors
            .iter()
            .find(|fd| !self.mirrors.contains_key(fd))
        {
            set_real_nonblocking(held, nonblocking);
        }
        let mut pairs = process_pairs();
        for &fd in &description.descriptors {
            if !self.mirrors.contains_key(&fd) {
                pairs.insert(
                    fd,
                    PairEnd {
                        pair,
                        end,
                        dgram,
                        nonblocking,
                    },
                );
            }
        }
    }

    /// Counts `sock` in, or out of, [`timers`](Self::timers) and
    /// [`connecting`](Self::connecting).
    fn tally(&mut self, sock: &Sock, add: bool) {
        let timer = usize::from(matches!(sock, Sock::Timer { .. }));
        let connecting = usize::from(matches!(sock, Sock::Connecting { .. }));
        if add {
            self.timers += timer;
            self.connecting += connecting;
        } else {
            self.timers -= timer;
            self.connecting -= connecting;
        }
    }

    fn place(&mut self, fd: c_int, sock: Sock) {
        self.tally(&sock, true);
        if let Some(description) = self.description_mut(&fd) {
            let replaced = std::mem::replace(&mut description.sock, sock);
            let keys = description_keys(description.id, &description.sock);
            self.tally(&replaced, false);
            self.reindex(fd);
            for key in keys.iter() {
                crate::notices::notice(0, key);
            }
        } else {
            self.next_id += 1;
            let id = self.next_id;
            let slot = self.free_slots.pop().unwrap_or_else(|| {
                self.descriptions.push(None);
                self.descriptions.len() - 1
            });
            self.descriptions[slot] = Some(SocketDescription {
                id,
                sock,
                status_flags: libc::O_RDWR,
                fcntl: SocketFcntl::default(),
                descriptors: BTreeSet::from([fd]),
                port: None,
            });
            self.descriptors.insert(fd, DescriptionKey { slot, id });
            FdBits::set(&self.bits.held, fd, true);
            #[cfg(target_os = "linux")]
            self.identities.insert(id, slot);
            self.index_port(slot);
        }
    }

    /// Lists `fd`'s description under the port it now holds; called after a change to its socket
    /// in place that binds it or moves its address.
    fn reindex(&mut self, fd: c_int) {
        if let Some(key) = self.descriptors.get(&fd) {
            self.index_port(key.slot);
        }
    }

    fn index_port(&mut self, slot: usize) {
        let Some(description) = self.descriptions[slot].as_mut() else {
            return;
        };
        let port = claimed_port(&description.sock);
        let previous = std::mem::replace(&mut description.port, port);
        if previous == port {
            return;
        }
        if let Some(previous) = previous {
            self.unlist_port(previous, slot);
        }
        if let Some(port) = port {
            self.ports.entry(port).or_default().insert(slot);
        }
    }

    fn unlist_port(&mut self, port: u16, slot: usize) {
        if let Some(slots) = self.ports.get_mut(&port) {
            slots.remove(&slot);
            if slots.is_empty() {
                self.ports.remove(&port);
            }
        }
    }

    /// The sockets holding `port` against a new bind, in no particular order.
    fn on_port(&self, port: u16) -> impl Iterator<Item = &Sock> {
        self.ports
            .get(&port)
            .into_iter()
            .flatten()
            .map(move |&slot| {
                let description = self.descriptions[slot].as_ref().unwrap();
                debug_assert_eq!(claimed_port(&description.sock), Some(port));
                &description.sock
            })
    }

    fn alias(&mut self, fd: c_int, new_fd: c_int) {
        let local = self.get(&fd).is_some_and(Sock::process_local);
        self.claim(new_fd, local);
        let key = self.descriptors[&fd];
        self.descriptors.insert(new_fd, key);
        FdBits::set(&self.bits.held, new_fd, true);
        self.descriptions[key.slot]
            .as_mut()
            .unwrap()
            .descriptors
            .insert(new_fd);
        self.publish_pair(new_fd);
    }

    fn remove(&mut self, fd: &c_int) -> Option<Option<Sock>> {
        let key = self.descriptors.remove(fd)?;
        FdBits::set(&self.bits.held, *fd, false);
        if self.mirrors.remove(fd).is_some() {
            FdBits::set(&self.bits.mirrored, *fd, false);
        } else {
            if let Some(owner) = self.owner {
                snare_interpose::release_fd(*fd, owner);
            }
            let mut pairs = process_pairs();
            if let Some(description) = self.descriptions[key.slot].as_ref()
                && let Some((pair, ..)) = description.sock.pair_end()
                && pairs.get(*fd).is_some_and(|end| end.pair == pair)
            {
                pairs.remove(*fd);
            }
        }
        let description = self.descriptions[key.slot].as_mut().unwrap();
        description.descriptors.remove(fd);
        Some(if description.descriptors.is_empty() {
            let retired = self.descriptions[key.slot].take().unwrap();
            if let Some(port) = retired.port {
                self.unlist_port(port, key.slot);
            }
            self.free_slots.push(key.slot);
            #[cfg(target_os = "linux")]
            self.identities.remove(&key.id);
            self.tally(&retired.sock, false);
            Some(retired.sock)
        } else {
            None
        })
    }

    /// Plays every timerfd forward to `now`, turning the expirations due into ticks.
    fn settle_timers(&mut self, now: Duration) {
        if self.timers == 0 {
            return;
        }
        for description in self.descriptions.iter_mut().flatten() {
            if let Sock::Timer {
                expires,
                interval,
                ticks,
                expired,
                ..
            } = &mut description.sock
            {
                let (due, next) = timer_due(*expires, *interval, now);
                *ticks = ticks.saturating_add(due);
                *expired = expired.saturating_add(due);
                *expires = next;
            }
        }
    }

    /// The earliest expiry among the armed timerfds `keep` selects, on the sim's monotonic
    /// timeline.
    fn next_expiry(&self, mut keep: impl FnMut(&SocketDescription) -> bool) -> Option<Duration> {
        if self.timers == 0 {
            return None;
        }
        self.descriptions
            .iter()
            .flatten()
            .filter_map(|description| match description.sock {
                Sock::Timer {
                    expires: Some(at), ..
                } if keep(description) => Some(at),
                _ => None,
            })
            .min()
    }

    /// Takes out every process-local description (see [`Sock::process_local`]) for another sim's
    /// fabric to [`adopt`](Self::adopt), leaving each descriptor recorded as this sim's until the
    /// other claims it.
    fn take_local(&mut self) -> Vec<SocketDescription> {
        let mut taken = Vec::new();
        for slot in 0..self.descriptions.len() {
            if !self.descriptions[slot]
                .as_ref()
                .is_some_and(|description| description.sock.process_local())
            {
                continue;
            }
            let mut description = self.descriptions[slot].take().unwrap();
            if let Some(port) = description.port.take() {
                self.unlist_port(port, slot);
            }
            self.free_slots.push(slot);
            for fd in &description.descriptors {
                self.descriptors.remove(fd);
                FdBits::set(&self.bits.held, *fd, false);
            }
            #[cfg(target_os = "linux")]
            self.identities.remove(&description.id);
            self.tally(&description.sock, false);
            taken.push(description);
        }
        taken
    }

    /// Takes in descriptions another sim's fabric [took out](Self::take_local), each under a new
    /// identity.
    /// `rename` then sees each description with the identities every old one became.
    fn adopt(
        &mut self,
        mut descriptions: Vec<SocketDescription>,
        mut rename: impl FnMut(&mut Sock, &HashMap<u64, u64>),
    ) {
        let renamed: HashMap<u64, u64> = descriptions
            .iter()
            .enumerate()
            .map(|(i, description)| (description.id, self.next_id + 1 + i as u64))
            .collect();
        for description in &mut descriptions {
            rename(&mut description.sock, &renamed);
        }
        for mut description in descriptions {
            self.next_id += 1;
            let id = self.next_id;
            description.id = id;
            let slot = self.free_slots.pop().unwrap_or_else(|| {
                self.descriptions.push(None);
                self.descriptions.len() - 1
            });
            for &fd in &description.descriptors {
                self.claim(fd, true);
                self.descriptors.insert(fd, DescriptionKey { slot, id });
                FdBits::set(&self.bits.held, fd, true);
            }
            #[cfg(target_os = "linux")]
            self.identities.insert(id, slot);
            self.tally(&description.sock, true);
            self.descriptions[slot] = Some(description);
            self.index_port(slot);
        }
    }

    fn iter(&self) -> impl Iterator<Item = (&c_int, &Sock)> {
        self.descriptors
            .iter()
            .map(|(fd, key)| (fd, &self.descriptions[key.slot].as_ref().unwrap().sock))
    }

    fn iter_mut(&mut self) -> impl Iterator<Item = (&c_int, &mut Sock)> {
        self.descriptions.iter_mut().flatten().map(|description| {
            (
                description.descriptors.first().unwrap(),
                &mut description.sock,
            )
        })
    }
}

/// The [`Net`] the code under test's sockets route through.
///
/// Also the [`Fs`] that serves macOS `/dev/bpf*` devices.
pub struct Fabric {
    /// Every descriptor the fabric serves, by fd number. The first lock in the fabric's lock order;
    /// never held across a readiness bump or wait.
    socks: Mutex<Sockets>,
    /// The numbers `socks` holds, without its lock.
    fds: Arc<FdBits>,
    regs: Arc<Registries>,
}

/// Descriptions on their way to another sim's fabric (see [`Net::hand_over`]).
struct Handed(Vec<SocketDescription>);

impl Drop for Fabric {
    /// Keeps the process-local descriptors still served for the next sim to reach them (see
    /// `snare_interpose::orphan`), and leaves every other one recorded as gone: its placeholder
    /// stays open, so code still holding the number does not reach whatever the OS would hand out
    /// next under it.
    fn drop(&mut self) {
        let now = self.regs.shared.monotonic_now();
        let socks = self.socks.get_mut().unwrap_or_else(|e| e.into_inner());
        let Some(owner) = socks.owner else {
            return;
        };
        socks.settle_timers(now);
        let mut kept = socks.take_local();
        for description in &mut kept {
            if let Sock::Timer { expires, .. } = &mut description.sock {
                *expires = expires.map(|at| at.saturating_sub(now));
            }
        }
        if !kept.is_empty() {
            let fds = kept
                .iter()
                .flat_map(|description| description.descriptors.iter().copied())
                .collect();
            snare_interpose::orphan(fds, owner, Box::new(Handed(kept)));
        }
        for &fd in socks.descriptors.keys() {
            snare_interpose::bury_fd(fd, owner);
        }
    }
}

struct UdpSendEndpoint {
    local: Option<SocketAddr>,
    requested: Option<SocketAddr>,
    queue: Arc<DgramQueue>,
    domain: c_int,
    broadcast: bool,
    nonblocking: bool,
    rec: Arc<SockRec>,
}

impl UdpSendEndpoint {
    fn from_sock(sock: &Sock) -> Option<Self> {
        match sock {
            Sock::Dgram {
                local,
                requested,
                queue,
                domain,
                broadcast,
                nonblocking,
                rec,
                ..
            } => Some(Self {
                local: *local,
                requested: *requested,
                queue: queue.clone(),
                domain: *domain,
                broadcast: *broadcast,
                nonblocking: *nonblocking,
                rec: rec.clone(),
            }),
            _ => None,
        }
    }
}

struct DgramRecvEndpoint {
    queue: Arc<DgramQueue>,
    nonblocking: bool,
    rec: Arc<SockRec>,
    /// `AF_INET` or `AF_INET6`; `AF_UNIX` for a socketpair end.
    domain: c_int,
    /// Whether a sender's IPv4 address is reported v4-mapped: on an IPv6 socket, except on macOS
    /// once bound or connected to an IPv4 address (XNU bsd/netinet/udp_usrreq.c `udp_input`
    /// reports a `sockaddr_in` to a socket that takes IPv4 only, measured).
    mapped: bool,
}

impl DgramRecvEndpoint {
    fn from_sock(sock: &Sock) -> Option<Self> {
        match sock {
            Sock::Dgram {
                queue,
                nonblocking,
                rec,
                domain,
                local,
                ..
            } => Some(Self {
                queue: queue.clone(),
                nonblocking: *nonblocking,
                rec: rec.clone(),
                domain: *domain,
                mapped: *domain == libc::AF_INET6
                    && !(cfg!(target_os = "macos") && local.is_some_and(|l| l.is_ipv4())),
            }),
            Sock::UnixDgram {
                queue,
                nonblocking,
                rec,
                ..
            } => Some(Self {
                queue: queue.clone(),
                nonblocking: *nonblocking,
                rec: rec.clone(),
                domain: libc::AF_UNIX,
                mapped: false,
            }),
            _ => None,
        }
    }
}

impl Fabric {
    /// A fabric with empty registries over the sim state `shared`.
    pub(crate) fn new(shared: Arc<SimShared>) -> Self {
        placeholder();
        let socks = Sockets::default();
        Fabric {
            fds: socks.bits.clone(),
            socks: Mutex::new(socks),
            regs: Arc::new(Registries::new(shared)),
        }
    }

    /// The two ends of socketpair `pair`, numbered `fds` in this sim's socket table: a `Conn`
    /// with no addresses and no link policy for a stream pair, two queues pointing at each other
    /// for a datagram one.
    fn pair_ends(&self, dgram: bool, fds: [c_int; 2], nonblocking: bool, pair: u64) -> [Sock; 2] {
        let (ra, rb) = (
            self.shared().new_socket(SocketKind::Unix, fds[0]),
            self.shared().new_socket(SocketKind::Unix, fds[1]),
        );
        // unix_create (net/unix/af_unix.c) keeps no protocol: SO_PROTOCOL reads 0 even for
        // PF_UNIX.
        #[cfg(target_os = "linux")]
        for rec in [&ra, &rb] {
            rec.set_family(libc::AF_UNIX, 0);
        }
        let (sa, sb) = if !dgram {
            let conn = Arc::new(Conn {
                a_to_b: Pipe::new(None, None, self.shared().domain_key()),
                b_to_a: Pipe::new(None, None, self.shared().domain_key()),
                client: UNNAMED,
                server: UNNAMED,
                regs: self.regs.clone(),
                hop: None,
                pair: true,
                pair_id: pair,
                tap: None,
                stamps: Default::default(),
                write_delays: Default::default(),
                #[cfg(target_os = "macos")]
                mac_shutdown: Default::default(),
            });
            conn.b_to_a.read_by(&ra);
            conn.a_to_b.read_by(&rb);
            conn.a_to_b.write_by(&ra);
            conn.b_to_a.write_by(&rb);
            let end = |end, rec| Sock::Stream {
                conn: conn.clone(),
                end,
                nonblocking,
                rec,
            };
            (end(End::A, ra), end(End::B, rb))
        } else {
            let (qa, qb) = (DgramQueue::for_socket(&ra), DgramQueue::for_socket(&rb));
            (
                Sock::UnixDgram {
                    peer: Arc::downgrade(&qb),
                    queue: qa.clone(),
                    nonblocking,
                    rec: ra,
                    pair: (pair, 0),
                },
                Sock::UnixDgram {
                    peer: Arc::downgrade(&qa),
                    queue: qb,
                    nonblocking,
                    rec: rb,
                    pair: (pair, 1),
                },
            )
        };
        [sa, sb]
    }

    fn detach_fd(&self, fd: c_int) -> Option<()> {
        let (removed, rec, key) = {
            let mut socks = self.socks.lock().unwrap();
            let rec = socks.get(&fd)?.rec().cloned();
            let key = rec.as_ref().map(|rec| rec.wake_key()).or_else(|| {
                socks
                    .identity(fd)
                    .map(crate::readiness::WakeKey::Descriptor)
            });
            self.notice_detach(&socks, fd);
            (socks.remove(&fd)?, rec, key)
        };
        self.retire_descriptor(fd, removed, rec, key);
        Some(())
    }

    /// Marks `fd`'s description on the sets watching it (see [`crate::notices`]): something no
    /// readiness bump tells may have changed its readiness.
    fn notice_fd(&self, fd: c_int) {
        self.notice_detach(&self.socks.lock().unwrap(), fd);
    }

    /// Marks `fd`'s description on the sets watching it (see [`crate::notices`]), as `fd` is about
    /// to stop naming it: a kqueue registration on `fd` then looks at what `fd` names next.
    fn notice_detach(&self, socks: &Sockets, fd: c_int) {
        if let (Some(id), Some(sock)) = (socks.identity(fd), socks.get(&fd)) {
            let domain = self.shared().domain_key();
            for key in description_keys(id, sock).iter() {
                crate::notices::notice(domain, key);
            }
        }
    }

    fn retire_descriptor(
        &self,
        fd: c_int,
        sock: Option<Sock>,
        rec: Option<Arc<SockRec>>,
        key: Option<crate::readiness::WakeKey>,
    ) {
        let regs = self.regs.clone();
        let retired = rec.filter(|rec| {
            regs.shared
                .sockets
                .detach_replaced_fd(fd, rec, regs.shared.stamp())
        });
        snare_interpose::defer_descriptor_cleanup(Box::new(move || {
            Self::release_sock(&regs, sock);
            if let Some(rec) = retired {
                regs.shared.sockets.finish_replaced_fd(&rec);
            }
            if let Some(key) = key {
                regs.shared.bump_keys(&[key]);
            }
        }));
    }

    fn release_sock(regs: &Registries, sock: Option<Sock>) {
        match sock {
            Some(Sock::Stream { conn, end, rec, .. }) => {
                match rec.opts().linger {
                    Some(linger) if linger.is_zero() => conn.reset(end),
                    Some(linger) => {
                        conn.close(end);
                        let pipe = conn.write_pipe(end).clone();
                        let (_, interrupted) =
                            snare_interpose::interruptible(Restart::Never, || {
                                readiness().wait_until_on(
                                    "linger",
                                    Some(Deadline::timeout(linger)),
                                    &[rec.wake_key()],
                                    || rec.pending_time(),
                                    || pipe.acknowledged(),
                                )
                            });
                        if interrupted {
                            snare_interpose::close_interrupted();
                        }
                    }
                    None if conn.read_pipe(end).has_unread() && !conn.pair => conn.reset(end),
                    None => conn.close(end),
                }
                conn.read_pipe(end).abandon_reader();
                if conn.pair {
                    conn.read_pipe(end).close(|_| {});
                }
            }
            Some(Sock::Dgram {
                local: Some(local),
                queue,
                ..
            }) => {
                regs.udp.lock().unwrap().remove(&local, &queue);
            }
            Some(Sock::Listener { listener, .. }) => {
                unlisten(regs, &listener);
                let orphans: Vec<_> = listener.pending.lock().unwrap().drain(..).collect();
                for conn in orphans {
                    conn.reset(End::B);
                }
            }
            _ => {}
        }
    }

    /// The deadline a blocking receive on `fd` should honour: `now + SO_RCVTIMEO` if one is set,
    /// else `None` (wait indefinitely). Under the virtual clock the deadline is a pending timer the
    /// quiescence time-skip can jump to, so a receive timeout advances virtual time like a sleep.
    fn recv_deadline(&self, fd: c_int) -> Option<Deadline> {
        let rec = self.rec(fd)?;
        Some(Deadline::timeout(rec.opts().rcvtimeo?))
    }

    /// The socket record of `fd`; `None` for an fd the fabric does not serve or one with no
    /// record (eventfd, epoll, kqueue).
    fn rec(&self, fd: c_int) -> Option<Arc<SockRec>> {
        self.socks.lock().unwrap().get(&fd)?.rec().cloned()
    }

    fn fd_interests(
        &self,
        fds: impl IntoIterator<Item = c_int>,
        keys: &mut crate::readiness::WakeKeys,
    ) -> bool {
        let mut time_sensitive = false;
        let mut others = Vec::new();
        {
            let socks = self.socks.lock().unwrap();
            for fd in fds {
                match socks.get(&fd) {
                    Some(sock) => match sock.rec() {
                        Some(rec) => {
                            keys.push(rec.wake_key());
                            time_sensitive |=
                                matches!(sock, Sock::Connecting { .. }) || rec.pending_time();
                        }
                        None => others.push((fd, socks.identity(fd))),
                    },
                    None => others.push((fd, None)),
                }
            }
        }
        for (fd, identity) in others {
            if let Some(rec) = self.shared().sockets.lookup_fd(fd) {
                keys.push(rec.wake_key());
                time_sensitive |= rec.pending_time();
            } else if let Some(id) = identity {
                keys.push(crate::readiness::WakeKey::Descriptor(id));
            }
        }
        time_sensitive
    }

    /// Keeps `waiting` blocked on `watch`, the watch on the real descriptors of the set a wait
    /// blocks on, and returns the key it wakes the waiter on.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    fn wait_real(
        &self,
        waiting: &std::cell::RefCell<Option<crate::realfd::Waiting>>,
        watch: Option<Arc<crate::realfd::Watch>>,
    ) -> Option<crate::readiness::WakeKey> {
        let mut waiting = waiting.borrow_mut();
        let current = waiting.as_ref().map(crate::realfd::Waiting::watch);
        if current.map(Arc::as_ptr) != watch.as_ref().map(Arc::as_ptr) {
            *waiting = watch.map(|watch| watch.wait(&self.regs.shared));
        }
        waiting.as_ref().map(|waiting| waiting.watch().key())
    }

    /// Keeps `held`, a set's watch on its real descriptors, on `real`: made once there are any,
    /// dropped once there are none.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    fn watch_set(held: &mut Option<Arc<crate::realfd::Watch>>, real: &[(c_int, i16)]) {
        match held {
            Some(watch) if !real.is_empty() => watch.set(real),
            Some(_) => *held = None,
            None if !real.is_empty() => *held = crate::realfd::Watch::new(real),
            None => {}
        }
    }

    fn bump_fds(&self, fds: impl IntoIterator<Item = c_int>) {
        let mut keys = crate::readiness::WakeKeys::default();
        self.fd_interests(fds, &mut keys);
        self.shared().bump_keys(keys.as_slice());
    }

    /// The keys a wait on epoll set `epfd` listens on: the set's own, which every notice to one
    /// of its registrations reaches (see [`crate::notices`]); and whether its last scan found a
    /// registration whose readiness moves with the clock.
    #[cfg(target_os = "linux")]
    fn epoll_interests(&self, epfd: c_int, keys: &mut crate::readiness::WakeKeys) -> bool {
        let socks = self.socks.lock().unwrap();
        let Some(Sock::Epoll { interests, .. }) = socks.get(&epfd) else {
            return false;
        };
        keys.push(interests.list().key());
        interests.timed()
    }

    /// The watch on the real descriptors epoll set `epfd` holds, if it holds any.
    #[cfg(target_os = "linux")]
    fn epoll_watch(&self, epfd: c_int) -> Option<Arc<crate::realfd::Watch>> {
        match self.socks.lock().unwrap().get(&epfd) {
            Some(Sock::Epoll { real, .. }) => real.clone(),
            _ => None,
        }
    }

    /// Keeps epoll set `epfd`'s watch on the real descriptors it holds.
    #[cfg(target_os = "linux")]
    fn rewatch_epoll(&self, epfd: c_int) {
        let real = self.epoll_real_fds(epfd);
        if let Some(Sock::Epoll { real: held, .. }) = self.socks.lock().unwrap().get_mut(&epfd) {
            Self::watch_set(held, &real);
        }
    }

    /// The real descriptors epoll set `epfd` watches, with the `poll` events each is watched for.
    #[cfg(target_os = "linux")]
    fn epoll_real_fds(&self, epfd: c_int) -> Vec<(c_int, i16)> {
        let untracked: Vec<(c_int, u32)> = {
            let socks = self.socks.lock().unwrap();
            let Some(Sock::Epoll { interests, .. }) = socks.get(&epfd) else {
                return Vec::new();
            };
            interests
                .iter()
                .filter(|((_, identity), i)| *identity == EpollIdentity::Untracked && !i.spent)
                .map(|(&(fd, _), i)| (fd, i.events))
                .collect()
        };
        untracked
            .into_iter()
            .filter(|(fd, _)| self.shared().sockets.lookup_fd(*fd).is_none())
            .map(|(fd, events)| {
                let events = events & (EPOLLIN | EPOLLOUT | libc::EPOLLPRI as u32 | EPOLLRDHUP);
                (fd, events as u16 as i16)
            })
            .collect()
    }

    /// The watch on the real descriptors kqueue `kq` holds, if it holds any.
    #[cfg(target_os = "macos")]
    fn kqueue_watch(&self, kq: c_int) -> Option<Arc<crate::realfd::Watch>> {
        match self.socks.lock().unwrap().get(&kq) {
            Some(Sock::Kqueue { state }) => state.lock().unwrap().real.clone(),
            _ => None,
        }
    }

    /// As [`epoll_interests`](Self::epoll_interests), for kqueue `kq`.
    #[cfg(target_os = "macos")]
    fn kqueue_interests(&self, kq: c_int, keys: &mut crate::readiness::WakeKeys) -> bool {
        let state = match self.socks.lock().unwrap().get(&kq) {
            Some(Sock::Kqueue { state }) => state.clone(),
            _ => return false,
        };
        let state = state.lock().unwrap();
        keys.push(state.notes.list().key());
        state.notes.timed()
    }

    /// The sim state shared with the other backends.
    fn shared(&self) -> &SimShared {
        &self.regs.shared
    }

    /// Mints a socket fd served by the fabric, with its record. Fails with the errno `dup` gave
    /// (EMFILE once the process is out of descriptors, man 2 dup).
    fn open_socket(
        &self,
        kind: SocketKind,
        flags: c_int,
        sock: impl FnOnce(Arc<SockRec>) -> Sock,
    ) -> Option<NetResult> {
        match self.reserve_fd_flags(flags) {
            Ok(fd) => {
                let rec = self.shared().new_socket(kind, fd);
                self.socks.lock().unwrap().insert(fd, sock(rec));
                ok(fd as i64)
            }
            Err(e) => err(e.raw_os_error().unwrap_or(libc::EMFILE)),
        }
    }

    /// The per-`Sim` registries, shared with the tester free functions for the run's duration.
    pub(crate) fn registries(&self) -> Arc<Registries> {
        self.regs.clone()
    }

    /// A fresh real fd number for a virtual descriptor: a `dup` of [`placeholder`], which the OS
    /// will not hand out again until the virtual descriptor's `close` closes it.
    fn reserve_fd(&self) -> io::Result<c_int> {
        let fd = snare_interpose::real(|| unsafe { libc::dup(placeholder()) });
        if fd < 0 {
            return Err(io::Error::last_os_error());
        }
        self.forget_stale_mirror(fd);
        Ok(fd)
    }

    /// Fresh real fd numbers for the ends of a socketpair of type `ty`: the ends of a real
    /// socketpair, each held until its virtual end's `close`. A thread outside every sim that
    /// reaches one of them (a pair a library made in a sim and keeps in a static) uses that real
    /// pair, the outside world's instance of it, as each sim uses an instance of its own
    /// ([`ProcessPairs`]).
    fn reserve_pair(&self, ty: c_int) -> io::Result<[c_int; 2]> {
        #[cfg(target_os = "linux")]
        let ty = ty & (0xff | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK);
        #[cfg(not(target_os = "linux"))]
        let ty = ty & 0xff;
        let mut fds = [-1; 2];
        if snare_interpose::real(|| unsafe {
            libc::socketpair(libc::AF_UNIX, ty, 0, fds.as_mut_ptr())
        }) != 0
        {
            return Err(io::Error::last_os_error());
        }
        for fd in fds {
            self.forget_stale_mirror(fd);
        }
        Ok(fds)
    }

    /// Serves `fd`, another sim's network socket (or one gone with its sim), as a connection
    /// that is gone: one end of a TCP connection its peer reset, so the first read or write
    /// reports `ECONNRESET`, later reads end of stream and later writes `EPIPE`, and readiness
    /// shows the hang-up and the error. A world has no instance of another world's connection;
    /// this is how a connection pool kept across sims finds its connection dead, discards it and
    /// dials again.
    fn mirror_dead(&self, fd: c_int) -> bool {
        let stale = {
            let mut socks = self.socks.lock().unwrap();
            if !socks.contains_key(&fd) {
                None
            } else if socks.stale_mirror(fd) {
                self.notice_detach(&socks, fd);
                socks.remove(&fd)
            } else {
                return true;
            }
        };
        if let Some(stale) = stale {
            self.retire_descriptor(fd, stale, None, None);
        }
        let rec = self.shared().new_socket(SocketKind::TcpStream, fd);
        let conn = Arc::new(Conn {
            a_to_b: Pipe::new(None, None, self.shared().domain_key()),
            b_to_a: Pipe::new(None, None, self.shared().domain_key()),
            client: UNNAMED,
            server: UNNAMED,
            regs: self.regs.clone(),
            hop: None,
            pair: false,
            pair_id: 0,
            tap: None,
            stamps: Default::default(),
            write_delays: Default::default(),
            #[cfg(target_os = "macos")]
            mac_shutdown: Default::default(),
        });
        conn.b_to_a.read_by(&rec);
        conn.a_to_b.write_by(&rec);
        conn.b_to_a.reset_reader();
        conn.a_to_b.reset();
        conn.b_to_a.reset();
        let mut socks = self.socks.lock().unwrap();
        if !socks.contains_key(&fd) {
            let sock = Sock::Stream {
                conn,
                end: End::A,
                nonblocking: false,
                rec,
            };
            socks.insert_mirror(fd, sock, DEAD);
        }
        true
    }

    /// Stops serving `fd`, a number the OS has just handed out, as this sim's instance of another
    /// sim's descriptor: that sim has closed it since, so the number names something new.
    fn forget_stale_mirror(&self, fd: c_int) {
        let removed = {
            let mut socks = self.socks.lock().unwrap();
            if !socks.mirrors.contains_key(&fd) {
                return;
            }
            self.notice_detach(&socks, fd);
            socks.remove(&fd)
        };
        if let Some(removed) = removed {
            self.retire_descriptor(fd, removed, None, None);
        }
    }

    fn reserve_fd_flags(&self, flags: c_int) -> io::Result<c_int> {
        let fd = self.reserve_fd()?;
        #[cfg(target_os = "linux")]
        if flags & libc::SOCK_CLOEXEC != 0 {
            let result = snare_interpose::real(|| unsafe {
                libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC)
            });
            if result < 0 {
                let error = io::Error::last_os_error();
                unsafe { libc::close(fd) };
                return Err(error);
            }
        }
        #[cfg(not(target_os = "linux"))]
        let _ = flags;
        Ok(fd)
    }

    /// Delivers one datagram from `fd` to `dest` along the route the host picks, binding the
    /// socket to the wildcard address at an ephemeral port first if it is unbound, so a receiver
    /// can reply. Returns the bytes "sent" — UDP succeeds even when nothing listens at `dest`, or
    /// the link drops the frame.
    ///
    /// Order of checks: the macOS send-buffer size limit, a pending error (an earlier ICMP error
    /// reported on this send), the route (its errno decided by `SimShared::route_send`, which is
    /// told whether `SO_BROADCAST` is on), a don't-fragment datagram too large for the egress
    /// interface (`netif::frag`), the autobind, then a stalled link. A datagram nothing receives
    /// triggers the ICMP port-unreachable model.
    ///
    /// `ctl` holds what the send's control messages asked ([`crate::ancillary`]): an interface
    /// and, on Linux, a source address for the route, the source address the datagram carries,
    /// its header fields, and its transmit stamps. A Linux send with a segment size
    /// (`UDP_SEGMENT`) longer than one segment is checked per segment rather than as one datagram
    /// (`netif::frag::check_gso`) and leaves as its segments, except through loopback, where it
    /// stays whole until a receiver without `UDP_GRO` takes it (`Registries::deliver`).
    fn udp_send(
        &self,
        fd: c_int,
        endpoint: UdpSendEndpoint,
        data: &[u8],
        dest: SocketAddr,
        flags: c_int,
        ctl: &crate::ancillary::SendCtl,
    ) -> Option<NetResult> {
        if data.len() > if dest.is_ipv4() { 65507 } else { 65527 } {
            return if cfg!(target_os = "macos") && dest.is_ipv6() {
                ok(data.len() as i64)
            } else {
                err(libc::EMSGSIZE)
            };
        }
        let UdpSendEndpoint {
            local,
            requested,
            queue,
            domain,
            broadcast,
            nonblocking,
            rec,
        } = endpoint;
        let nonblocking = nonblocking || flags & libc::MSG_DONTWAIT != 0;
        // macOS refuses a datagram larger than the send buffer: XNU bsd/kern/uipc_socket.c
        // sosendcheck, `atomic && resid > so->so_snd.sb_hiwat` → EMSGSIZE. Linux has no such
        // check. Pinned by socket_limits' `macos_udp_send_over_sndbuf_is_emsgsize`.
        if cfg!(target_os = "macos") && data.len() > rec.state().buf.sndbuf.max(0) as usize {
            return err(libc::EMSGSIZE);
        }
        #[cfg(target_os = "linux")]
        rec.land();
        if let Some(errno) = rec.take_error_as(self.shared(), Taker::Send) {
            return err(errno);
        }
        if domain == libc::AF_INET6
            && let Err(errno) =
                dgram_crossing(&rec, local.or(unhashed(requested)), dest, false, false)
        {
            if cfg!(target_os = "linux") && local.is_none() && requested.is_none() {
                let _ = self.autobind(fd, &queue, &rec, Ipv6Addr::UNSPECIFIED.into());
            }
            return err(errno);
        }
        let station = self.regs.station_at(dest.ip());
        let mut view = rec.view(local.or(unhashed(requested)).map(|l| toward(l, dest)));
        if ctl.oif.is_some() {
            view.device = ctl.oif;
        }
        if cfg!(target_os = "linux")
            && let Some(src) = ctl.src.filter(|src| src.is_ipv4() == dest.is_ipv4())
        {
            view.local = Some(SocketAddr::new(src, view.local.map_or(0, |l| l.port())));
        }
        let sender = match self
            .shared()
            .route_send(&view, dest, Op::Send, station, broadcast)
        {
            Ok(sender) => sender,
            Err(errno) => return err(errno),
        };
        #[cfg(target_os = "linux")]
        let gso = crate::ancillary::gso_size(&rec, ctl);
        #[cfg(not(target_os = "linux"))]
        let gso = 0;
        let checked = if gso != 0 {
            crate::netif::frag::check_gso(self.shared(), &sender, dest, data.len(), gso)
        } else {
            crate::netif::frag::check_send(
                self.shared(),
                &rec,
                domain == libc::AF_INET6,
                &sender,
                dest,
                data.len(),
                ctl.dontfrag,
            )
        };
        if let Err(errno) = checked {
            return err(errno);
        }
        let local = match local {
            Some(local) => local,
            None => {
                let ip = requested.map_or(unspecified_like(loopback_for(domain)), |r| r.ip());
                match self.autobind(fd, &queue, &rec, ip) {
                    Ok(local) => local,
                    Err(errno) => return err(errno),
                }
            }
        };
        let src = match ctl.src {
            Some(ip) => SocketAddr::new(ip, local.port()),
            None => sender.source(toward(local, dest)),
        };
        // A stalled link (`UdpPolicy::send_queue_depth == Some(0)`) holds the send back. A blocking
        // send that never unstalls (a quiescent deadlock) gives EAGAIN, as SO_SNDTIMEO expiry does.
        let stalled = || {
            let policies = &self.regs.shared.policies;
            policies.send_stalled(local) || policies.send_stalled(src)
        };
        if stalled() {
            if nonblocking {
                return would_block();
            }
            if !readiness()
                .wait_until_on("udp send", None, &[rec.wake_key()], &stalled, || !stalled())
            {
                return err(libc::EAGAIN);
            }
        }
        #[cfg(target_os = "linux")]
        let now = self.shared().tstamp_now();
        #[cfg(target_os = "linux")]
        crate::tstamp::udp_sent(&rec, now, None, ctl.tx_flags, || {
            crate::tstamp::looped_frame(src, dest, false, data)
        });
        let ip = crate::ancillary::header(&rec, dest, ctl);
        let whole = gso == 0
            || data.len() <= usize::from(gso)
            || matches!(&sender, Sender::Host(path) if path.local);
        let (step, ip) = if whole {
            let gso = if data.len() > usize::from(gso) {
                gso
            } else {
                0
            };
            (data.len(), crate::ancillary::Header { gso, ..ip })
        } else {
            (usize::from(gso), ip)
        };
        let mut at = 0;
        loop {
            let end = (at + step).min(data.len());
            let packet = &data[at..end];
            self.shared()
                .capture_udp(&sender, src, dest, Dir::Out, packet, None);
            if self.regs.deliver(&sender, src, dest, packet, true, ip) == 0 {
                self.shared()
                    .unreachable_port(&rec, &sender, src, dest, packet, station);
            }
            at = end;
            if at >= data.len() {
                break;
            }
        }
        if rec.finish_udp_send(dest, &sender) {
            self.shared().bump_keys(&[rec.wake_key()]);
        }
        ok(data.len() as i64)
    }

    /// Binds unbound datagram socket `fd` to `ip` at an ephemeral port, as the kernel does on the
    /// first send or connect of an unbound socket (man 7 udp: the socket layer assigns a free
    /// local port and binds the socket to `INADDR_ANY`). Takes `udp`, releases it, then `socks`;
    /// called with neither held.
    fn autobind(
        &self,
        fd: c_int,
        queue: &Arc<DgramQueue>,
        rec: &Arc<SockRec>,
        ip: IpAddr,
    ) -> Result<SocketAddr, c_int> {
        let dual = rec.state().dual_at(SocketAddr::new(ip, 0));
        let mut regs = self.regs.udp.lock().unwrap();
        let first = queue.next_port.load(Ordering::Relaxed) as u16;
        let port = regs.alloc_port_from(ip, first, dual);
        if port == 0 {
            return Err(libc::EAGAIN);
        }
        let sa = SocketAddr::new(ip, port);
        rec.state().bound_order = self.shared().bind_order();
        regs.insert(sa, queue.clone());
        drop(regs);
        let mut socks = self.socks.lock().unwrap();
        if let Some(Sock::Dgram { local, .. }) = socks.get_mut(&fd) {
            *local = Some(sa);
        }
        socks.reindex(fd);
        drop(socks);
        rec.set_local(sa);
        Ok(sa)
    }

    /// Moves bound datagram socket `fd` from `from` to `to` in the delivery map, as the kernel
    /// rehashes a socket whose local address a connect or disconnect changed (Linux
    /// `udp_lib_rehash`, XNU `in_pcbrehash`), beside any other socket there.
    fn rehash(
        &self,
        fd: c_int,
        queue: &Arc<DgramQueue>,
        rec: &Arc<SockRec>,
        from: SocketAddr,
        to: SocketAddr,
    ) {
        if from == to {
            return;
        }
        let mut regs = self.regs.udp.lock().unwrap();
        regs.remove(&from, queue);
        regs.insert(to, queue.clone());
        drop(regs);
        let mut socks = self.socks.lock().unwrap();
        if let Some(Sock::Dgram { local, .. }) = socks.get_mut(&fd) {
            *local = Some(to);
        }
        socks.reindex(fd);
        drop(socks);
        rec.set_local(to);
    }

    /// Dissolves a datagram socket's association (`connect` with `AF_UNSPEC`, man 2 connect),
    /// returning the socket's family; `None` when `fd` is not a datagram socket. Linux
    /// `__udp_disconnect` (net/ipv4/udp.c) returns the local address to the wildcard unless
    /// `bind` named one (`SOCK_BINDADDR_LOCK`) and gives up the port unless `bind` named one
    /// (`SOCK_BINDPORT_LOCK`), so the next send or connect picks a new one. macOS
    /// `udp_disconnect` (bsd/netinet/udp_usrreq.c) always returns the address to the wildcard and
    /// keeps the port. Measured by tests/udp_connect_source.rs.
    fn disconnect_dgram(&self, fd: c_int) -> Option<(c_int, bool)> {
        let mut socks = self.socks.lock().unwrap();
        let Some(Sock::Dgram {
            peer,
            local,
            requested,
            queue,
            rec,
            domain,
            ..
        }) = socks.get_mut(&fd)
        else {
            return None;
        };
        let domain = *domain;
        *peer = None;
        rec.set_peer(None);
        let Some(bound) = *local else {
            return Some((domain, false));
        };
        let inet6 = domain == libc::AF_INET6;
        let mapped = inet6 && bound.is_ipv4();
        let (requested, queue, rec) = (*requested, queue.clone(), rec.clone());
        let wildcard = if inet6 && (cfg!(target_os = "linux") || bound.is_ipv6()) {
            IpAddr::V6(Ipv6Addr::UNSPECIFIED)
        } else {
            unspecified_like(bound.ip())
        };
        if cfg!(target_os = "linux") && requested.is_none_or(|r| r.port() == 0) {
            *local = None;
            socks.reindex(fd);
            drop(socks);
            queue.next_port.store(
                bound.port().checked_add(1).unwrap_or(49152) as u64,
                Ordering::Relaxed,
            );
            self.regs.udp.lock().unwrap().remove(&bound, &queue);
            rec.state().local = unhashed(requested).filter(|a| !a.ip().is_unspecified());
            return Some((domain, mapped));
        }
        drop(socks);
        let ip = requested
            .map(|r| r.ip())
            .filter(|&ip| cfg!(target_os = "linux") && ip != unspecified_like(loopback_for(domain)))
            .unwrap_or(wildcard);
        self.rehash(fd, &queue, &rec, bound, SocketAddr::new(ip, bound.port()));
        Some((domain, mapped))
    }
}

/// What `fcntl` keeps of a socket's open file description besides `O_NONBLOCK` and the
/// descriptor flags: the status flags `F_SETFL` keeps and the signal-driven I/O owner and signal.
/// Shared by the fabric's sockets and a `SimHost`'s. Measured by tests/fcntl_os_truth.rs.
///
/// Signal-driven I/O is not modelled: no `SIGIO` or `SIGURG` is ever sent, but the owner and
/// signal are kept and read back. Linux (fs/fcntl.c): `F_SETOWN` names a process, or a process
/// group when negative (`INT_MIN` is `EINVAL`), and `F_GETOWN` reads it back so;
/// `F_SETOWN_EX`/`F_GETOWN_EX` take an `f_owner_ex` (a type other than `F_OWNER_TID`,
/// `F_OWNER_PID`, `F_OWNER_PGRP` is `EINVAL`); `F_SETSIG` takes a signal up to 64
/// (`valid_signal`), else `EINVAL`. The owner is not looked up, so a process that does not exist
/// is not refused with `ESRCH`. Record locks (`F_SETLK`, `F_SETLKW`, `F_GETLK` and the OFD forms)
/// always succeed, as each socket is its own inode that no other process can reach here:
/// `F_GETLK` reports `F_UNLCK`. `F_GETLEASE` reads `F_UNLCK`; `F_SETLEASE` and the seals are
/// `EINVAL`, `F_NOTIFY` `ENOTDIR`, the pipe sizes `EBADF`.
///
/// macOS (bsd/kern/kern_descrip.c `fcntl_nocancel`): `F_SETOWN` stores `so_pgid` unchecked and
/// `F_GETOWN` reads it; every command it does not handle for a socket, other than a negative one,
/// is a vnode command and `EBADF`.
#[derive(Clone, Copy)]
pub(crate) struct SocketFcntl {
    /// The status flags `F_SETFL` kept, from [`SocketFcntl::KEPT_STATUS`].
    pub(crate) status: c_int,
    /// Linux's `F_OWNER_*` type and id (a process, 0, by default), or the macOS `so_pgid`.
    owner: (c_int, c_int),
    /// Linux `F_SETSIG`: the signal sent instead of `SIGIO`, 0 for `SIGIO`.
    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
    signal: c_int,
}

impl Default for SocketFcntl {
    fn default() -> Self {
        SocketFcntl {
            status: 0,
            owner: (Self::F_OWNER_PID, 0),
            signal: 0,
        }
    }
}

impl SocketFcntl {
    /// Linux `F_SETSIG`, `F_GETSIG` (include/uapi/asm-generic/fcntl.h).
    #[cfg(target_os = "linux")]
    const F_SETSIG: c_int = 10;
    #[cfg(target_os = "linux")]
    const F_GETSIG: c_int = 11;
    /// Linux `F_SETOWN_EX`, `F_GETOWN_EX` and the `f_owner_ex` types `F_OWNER_TID`,
    /// `F_OWNER_PID`, `F_OWNER_PGRP`.
    #[cfg(target_os = "linux")]
    const F_SETOWN_EX: c_int = 15;
    #[cfg(target_os = "linux")]
    const F_GETOWN_EX: c_int = 16;
    #[cfg(target_os = "linux")]
    const F_OWNER_TID: c_int = 0;
    const F_OWNER_PID: c_int = 1;
    #[cfg(target_os = "linux")]
    const F_OWNER_PGRP: c_int = 2;
    /// Linux open file description locks, `F_OFD_GETLK`, `F_OFD_SETLK`, `F_OFD_SETLKW`.
    #[cfg(target_os = "linux")]
    const F_OFD_GETLK: c_int = 36;
    #[cfg(target_os = "linux")]
    const F_OFD_SETLK: c_int = 37;
    #[cfg(target_os = "linux")]
    const F_OFD_SETLKW: c_int = 38;
    /// Linux `F_SETLEASE`, `F_SETPIPE_SZ`, `F_ADD_SEALS`.
    #[cfg(target_os = "linux")]
    const F_SETLEASE: c_int = 1024;
    #[cfg(target_os = "linux")]
    const F_SETPIPE_SZ: c_int = 1031;
    #[cfg(target_os = "linux")]
    const F_ADD_SEALS: c_int = 1033;
    /// The status flags `F_SETFL` keeps on a socket besides `O_NONBLOCK`: Linux `O_APPEND` and
    /// `O_ASYNC` (fs/fcntl.c `SETFL_MASK`, less `O_DIRECT` and `O_NOATIME`), macOS `O_APPEND`,
    /// `O_ASYNC` and `O_SYNC` (`FCNTLFLAGS`, bsd/sys/fcntl.h).
    #[cfg(target_os = "linux")]
    const KEPT_STATUS: c_int = libc::O_APPEND | libc::O_ASYNC;
    #[cfg(target_os = "macos")]
    const KEPT_STATUS: c_int = libc::O_APPEND | libc::O_ASYNC | libc::O_SYNC;

    /// The flags an `F_SETFL` of `arg` keeps; Linux refuses `O_DIRECT` on a socket (fs/fcntl.c
    /// `setfl`: no `direct_IO`).
    pub(crate) fn kept_status(arg: i64) -> Result<c_int, c_int> {
        #[cfg(target_os = "linux")]
        if arg as c_int & libc::O_DIRECT != 0 {
            return Err(libc::EINVAL);
        }
        Ok(arg as c_int & Self::KEPT_STATUS)
    }

    /// Carries out `cmd` (see the type); `None` for a command it does not answer: duplication,
    /// the descriptor and status flags, macOS `F_SETNOSIGPIPE`/`F_GETNOSIGPIPE`, and on Linux any
    /// command it does not know.
    ///
    /// # Safety
    /// For the commands taking a pointer, `arg` is the caller's `struct flock` or `f_owner_ex`.
    #[cfg(target_os = "linux")]
    pub(crate) unsafe fn command(&mut self, cmd: c_int, arg: i64) -> Option<NetResult> {
        match cmd {
            libc::F_GETOWN => {
                let (ty, id) = self.owner;
                ok(if ty == Self::F_OWNER_PGRP { -id } else { id } as i64)
            }
            libc::F_SETOWN => {
                let who = arg as c_int;
                if who == c_int::MIN {
                    return err(libc::EINVAL);
                }
                self.owner = if who < 0 {
                    (Self::F_OWNER_PGRP, -who)
                } else {
                    (Self::F_OWNER_PID, who)
                };
                ok(0)
            }
            Self::F_GETOWN_EX | Self::F_SETOWN_EX => {
                let owner = arg as *mut [c_int; 2];
                if owner.is_null() {
                    return err(libc::EFAULT);
                }
                if cmd == Self::F_GETOWN_EX {
                    let (ty, id) = self.owner;
                    unsafe { owner.write_unaligned([ty, id]) };
                } else {
                    let [ty, id] = unsafe { owner.read_unaligned() };
                    if ![Self::F_OWNER_TID, Self::F_OWNER_PID, Self::F_OWNER_PGRP].contains(&ty) {
                        return err(libc::EINVAL);
                    }
                    self.owner = (ty, id);
                }
                ok(0)
            }
            Self::F_GETSIG => ok(self.signal as i64),
            Self::F_SETSIG => {
                if !(0..=64).contains(&arg) {
                    return err(libc::EINVAL);
                }
                self.signal = arg as c_int;
                ok(0)
            }
            libc::F_GETLK
            | libc::F_SETLK
            | libc::F_SETLKW
            | Self::F_OFD_GETLK
            | Self::F_OFD_SETLK
            | Self::F_OFD_SETLKW => {
                let lock = arg as *mut libc::flock;
                if lock.is_null() {
                    return err(libc::EFAULT);
                }
                let mut fl = unsafe { lock.read_unaligned() };
                let getlk = cmd == libc::F_GETLK || cmd == Self::F_OFD_GETLK;
                let types: &[c_int] = if getlk {
                    &[libc::F_RDLCK, libc::F_WRLCK]
                } else {
                    &[libc::F_RDLCK, libc::F_WRLCK, libc::F_UNLCK]
                };
                if !types.contains(&c_int::from(fl.l_type))
                    || !(0..=2).contains(&c_int::from(fl.l_whence))
                    || (cmd >= Self::F_OFD_GETLK && fl.l_pid != 0)
                {
                    return err(libc::EINVAL);
                }
                if getlk {
                    fl.l_type = libc::F_UNLCK as _;
                    unsafe { lock.write_unaligned(fl) };
                }
                ok(0)
            }
            libc::F_GETLEASE => ok(libc::F_UNLCK as i64),
            Self::F_SETLEASE | libc::F_GET_SEALS | Self::F_ADD_SEALS => err(libc::EINVAL),
            libc::F_NOTIFY => err(libc::ENOTDIR),
            libc::F_GETPIPE_SZ | Self::F_SETPIPE_SZ => err(libc::EBADF),
            _ => None,
        }
    }

    #[cfg(target_os = "macos")]
    pub(crate) unsafe fn command(&mut self, cmd: c_int, arg: i64) -> Option<NetResult> {
        match cmd {
            libc::F_GETOWN => ok(self.owner.1 as i64),
            libc::F_SETOWN => {
                self.owner = (Self::F_OWNER_PID, arg as c_int);
                ok(0)
            }
            libc::F_DUPFD
            | libc::F_DUPFD_CLOEXEC
            | libc::F_GETFD
            | libc::F_SETFD
            | libc::F_GETFL
            | libc::F_SETFL
            | F_SETNOSIGPIPE
            | F_GETNOSIGPIPE => None,
            cmd if cmd < 0 => err(libc::EINVAL),
            _ => err(libc::EBADF),
        }
    }
}

/// macOS `F_SETNOSIGPIPE`, `F_GETNOSIGPIPE` (XNU bsd/sys/fcntl.h).
#[cfg(target_os = "macos")]
const F_SETNOSIGPIPE: c_int = 73;
#[cfg(target_os = "macos")]
const F_GETNOSIGPIPE: c_int = 74;

impl Fabric {
    /// The commands [`SocketFcntl::command`] answers on a socket, and macOS
    /// `F_SETNOSIGPIPE`/`F_GETNOSIGPIPE`, which XNU carries out as `SO_NOSIGPIPE` on a socket
    /// (`fcntl_nocancel` calls `sock_setsockopt`/`sock_getsockopt`); `None` for any other command
    /// or descriptor. A macOS `/dev/bpf` descriptor is a device, not a socket, and is left out.
    ///
    /// # Safety
    /// As [`SocketFcntl::command`].
    #[cfg_attr(target_os = "linux", allow(unused_variables))]
    unsafe fn socket_fcntl(&self, fd: c_int, cmd: c_int, arg: i64) -> Option<NetResult> {
        let mut socks = self.socks.lock().unwrap();
        let rec = match socks.get(&fd)? {
            sock @ (Sock::Fresh { .. }
            | Sock::Connecting { .. }
            | Sock::Stream { .. }
            | Sock::Listener { .. }
            | Sock::Dgram { .. }
            | Sock::UnixDgram { .. }) => sock.rec().cloned(),
            sock @ Sock::Raw { .. } if cfg!(target_os = "linux") => sock.rec().cloned(),
            _ => return None,
        };
        #[cfg(target_os = "macos")]
        if cmd == F_SETNOSIGPIPE || cmd == F_GETNOSIGPIPE {
            drop(socks);
            let rec = rec?;
            if cmd == F_SETNOSIGPIPE {
                let on = c_int::from(arg as c_int != 0);
                rec.keep_ignored(libc::SOL_SOCKET, SO_NOSIGPIPE, &on.to_ne_bytes());
                return ok(0);
            }
            let on = rec
                .ignored_value(libc::SOL_SOCKET, SO_NOSIGPIPE)
                .is_some_and(|v| v.iter().any(|&b| b != 0));
            return ok(i64::from(on));
        }
        unsafe { socks.description_mut(&fd)?.fcntl.command(cmd, arg) }
    }

    /// Whether `fd` is an IPv6 socket (`Some(false)` for IPv4); `None` for a descriptor that is
    /// not an IP socket, such as a socketpair end.
    fn ipv6(&self, fd: c_int) -> Option<bool> {
        match self.socks.lock().unwrap().get(&fd)? {
            Sock::Fresh { domain, .. }
            | Sock::Connecting { domain, .. }
            | Sock::Dgram { domain, .. } => Some(*domain == libc::AF_INET6),
            Sock::Stream { conn, .. } if conn.pair => None,
            Sock::Stream { rec, .. } | Sock::Listener { rec, .. } => Some(rec.state().inet6),
            _ => None,
        }
    }

    /// `fd`'s family and whether it is a stream socket, for an IP socket.
    fn family(&self, fd: c_int) -> Option<(c_int, bool)> {
        let socks = self.socks.lock().unwrap();
        let inet = |rec: &SockRec| {
            if rec.state().inet6 {
                libc::AF_INET6
            } else {
                libc::AF_INET
            }
        };
        match socks.get(&fd)? {
            Sock::Dgram { domain, .. } => Some((*domain, false)),
            Sock::Fresh { domain, .. } | Sock::Connecting { domain, .. } => Some((*domain, true)),
            Sock::Stream { conn, rec, .. } if !conn.pair => Some((inet(rec), true)),
            Sock::Listener { rec, .. } => Some((inet(rec), true)),
            _ => None,
        }
    }

    /// `fd`'s record, whether it is IPv6 and whether it is bound, for an IP socket: one bound,
    /// connecting, connected or listening holds a port (Linux `inet_num`; macOS a local port or
    /// address).
    fn v6only_target(&self, fd: c_int) -> Option<(Arc<SockRec>, bool, bool)> {
        let socks = self.socks.lock().unwrap();
        let (rec, bound) = match socks.get(&fd)? {
            Sock::Dgram { rec, local, .. } | Sock::Fresh { rec, local, .. } => {
                (rec, local.is_some())
            }
            Sock::Connecting { rec, .. } | Sock::Listener { rec, .. } => (rec, true),
            Sock::Stream { conn, rec, .. } if !conn.pair => (rec, true),
            _ => return None,
        };
        let inet6 = rec.state().inet6;
        Some((rec.clone(), inet6, bound))
    }

    /// [`v6only_set`] on `fd`; `None` for a descriptor that is not an IP socket.
    ///
    /// # Safety
    /// `val` is null or holds `len` bytes.
    unsafe fn set_v6only(&self, fd: c_int, val: *const u8, len: u32) -> Option<Option<NetResult>> {
        let (rec, _, bound) = self.v6only_target(fd)?;
        Some(unsafe { v6only_set(&rec, bound, val, len) })
    }

    /// [`v6only_get`] on `fd`; `None` for a descriptor that is not an IP socket.
    ///
    /// # Safety
    /// `val` and `len` are each null or valid, `val` writable for `*len` bytes.
    unsafe fn get_v6only(
        &self,
        fd: c_int,
        val: *mut u8,
        len: *mut u32,
    ) -> Option<Option<NetResult>> {
        let (rec, _, _) = self.v6only_target(fd)?;
        Some(unsafe { v6only_get(&rec, val, len) })
    }

    /// How `fd` stands for the timestamp options: a datagram socket, a connected stream, or a
    /// TCP socket that is not connected.
    fn ts_kind(&self, fd: c_int) -> crate::tstamp::Kind {
        match self.socks.lock().unwrap().get(&fd) {
            Some(Sock::Stream { .. }) => crate::tstamp::Kind::Established,
            Some(Sock::Fresh { .. } | Sock::Connecting { .. } | Sock::Listener { .. }) => {
                crate::tstamp::Kind::Unconnected
            }
            _ => crate::tstamp::Kind::Datagram,
        }
    }

    /// A `setsockopt` nothing modelled: a [`harmless`] option's value is kept for `getsockopt`
    /// and it succeeds; any other is recorded on the socket as unmodelled
    /// ([`SimShared::unmodelled_option`]) and succeeds with no effect, or fails with
    /// `ENOPROTOOPT` under `strict_sockopts` (man 2 setsockopt: "The option is unknown at the
    /// level indicated"). A descriptor with no socket record (an eventfd, epoll or kqueue) just
    /// succeeds.
    ///
    /// # Safety
    /// `val` is null or holds `len` bytes.
    unsafe fn unmodelled_set(
        &self,
        rec: Option<&Arc<SockRec>>,
        level: c_int,
        name: c_int,
        val: *const u8,
        len: u32,
    ) -> Option<NetResult> {
        let Some(rec) = rec else {
            return ok(0);
        };
        if harmless(level, name) {
            let bytes = if val.is_null() {
                Vec::new()
            } else {
                unsafe { std::slice::from_raw_parts(val, len as usize) }.to_vec()
            };
            rec.keep_ignored(level, name, &bytes);
            return ok(0);
        }
        if self
            .shared()
            .unmodelled_option(rec, UnmodelledOption::Set { level, name })
        {
            return err(libc::ENOPROTOOPT);
        }
        ok(0)
    }

    /// A `getsockopt` nothing modelled: a [`harmless`] option reads back what was set, or an
    /// `int` 0 (each one's default on Linux and macOS); any other is recorded as unmodelled and
    /// reads as an `int` 0, or fails with `ENOPROTOOPT` under `strict_sockopts`.
    ///
    /// # Safety
    /// `val`/`len` are null or the caller's buffer and its length.
    unsafe fn unmodelled_get(
        &self,
        rec: Option<&Arc<SockRec>>,
        level: c_int,
        name: c_int,
        val: *mut u8,
        len: *mut u32,
    ) -> Option<NetResult> {
        if let Some(rec) = rec {
            if harmless(level, name) {
                match rec.ignored_value(level, name) {
                    Some(bytes) if !val.is_null() && !len.is_null() => unsafe {
                        let n = bytes.len().min(*len as usize);
                        std::ptr::copy_nonoverlapping(bytes.as_ptr(), val, n);
                        *len = n as u32;
                    },
                    _ => unsafe { write_opt(0, val, len) },
                }
                return ok(0);
            }
            if self
                .shared()
                .unmodelled_option(rec, UnmodelledOption::Get { level, name })
            {
                return err(libc::ENOPROTOOPT);
            }
        }
        unsafe { write_opt(0, val, len) };
        ok(0)
    }

    /// Linux `SIOCGHWTSTAMP`/`SIOCSHWTSTAMP` on an interface of the topology, as
    /// net/core/dev_ioctl.c answers them for a device whose driver has no hardware timestamping
    /// (the plain fabric's interfaces have no clock): setting needs `CAP_NET_ADMIN` (`EPERM`,
    /// checked first), an unknown `ifr_name` is `ENODEV` (`dev_ifsioc`), and a known one
    /// `EOPNOTSUPP` (`dev_get_hwtstamp`/`dev_set_hwtstamp` with no `ndo_hwtstamp_*`). Measured
    /// on loopback by tests/timestamps.rs `hwtstamp_ioctl_os_truth`. `None` for other requests.
    ///
    /// # Safety
    /// `arg` is null or the caller's `struct ifreq`.
    #[cfg(target_os = "linux")]
    unsafe fn hwtstamp_ioctl(&self, request: u64, arg: i64) -> Option<NetResult> {
        /// include/uapi/linux/sockios.h.
        const SIOCSHWTSTAMP: u64 = 0x89b0;
        /// include/uapi/linux/sockios.h.
        const SIOCGHWTSTAMP: u64 = 0x89b1;
        if request != SIOCSHWTSTAMP && request != SIOCGHWTSTAMP {
            return None;
        }
        if request == SIOCSHWTSTAMP && !self.shared().sys.privileges().net_admin {
            return err(libc::EPERM);
        }
        let base = arg as *const u8;
        if base.is_null() {
            return err(libc::EFAULT);
        }
        let name: Vec<u8> = (0..libc::IFNAMSIZ)
            .map(|i| unsafe { *base.add(i) })
            .take_while(|&b| b != 0)
            .collect();
        let known = std::str::from_utf8(&name)
            .ok()
            .and_then(|name| self.shared().nic(name))
            .is_some();
        err(if known {
            libc::EOPNOTSUPP
        } else {
            libc::ENODEV
        })
    }
}

/// The options the fabric (and `SimHost`) accept and ignore on purpose, because nothing a test
/// can observe in the sim depends on them; their values are kept and read back:
///
/// - `SO_KEEPALIVE` and the TCP keepalive timers (`TCP_KEEPIDLE`/`TCP_KEEPINTVL`/`TCP_KEEPCNT`,
///   macOS `TCP_KEEPALIVE`): a connection in the sim never dies idle, so a probe would never
///   change an outcome.
/// - `TCP_NODELAY`, Linux `TCP_QUICKACK`: the sim has no Nagle delay and no delayed ACKs; every
///   write leaves at once.
/// - `SO_OOBINLINE`, `SO_DEBUG`: the sim sends no urgent data and keeps no debug trace.
/// - macOS `SO_NOSIGPIPE`: the sim never raises `SIGPIPE`; a write to a closed stream fails with
///   `EPIPE`, as with the option set. std sets it on every macOS socket.
/// - `IP_TOS`, `IP_TTL`, `IP_MULTICAST_TTL`, `IPV6_TCLASS`, `IPV6_UNICAST_HOPS`,
///   `IPV6_MULTICAST_HOPS`: the sim's links have no QoS and no hop count to run out.
///
/// Everything else not modelled — `IP_MULTICAST_LOOP`, `IP_DROP_MEMBERSHIP`,
/// `SO_RCVLOWAT` and the rest — changes behaviour the sim does not reproduce, so it is recorded
/// as unmodelled.
#[cfg(unix)]
pub(crate) fn harmless(level: c_int, name: c_int) -> bool {
    match level {
        libc::SOL_SOCKET => {
            matches!(
                name,
                libc::SO_KEEPALIVE | libc::SO_OOBINLINE | libc::SO_DEBUG
            ) || (cfg!(target_os = "macos") && name == SO_NOSIGPIPE)
        }
        libc::IPPROTO_TCP => {
            name == libc::TCP_NODELAY
                || TCP_KEEPALIVE_TIMERS.contains(&name)
                || (cfg!(target_os = "linux") && name == TCP_QUICKACK)
        }
        libc::IPPROTO_IP => matches!(name, libc::IP_TOS | libc::IP_TTL | libc::IP_MULTICAST_TTL),
        libc::IPPROTO_IPV6 => matches!(
            name,
            libc::IPV6_TCLASS | libc::IPV6_UNICAST_HOPS | libc::IPV6_MULTICAST_HOPS
        ),
        _ => false,
    }
}

/// What `getsockopt` reads for `SOL_SOCKET` boolean option `name`, `on` or off: 1 on Linux
/// (net/core/sock.c `sk_getsockopt`), the option's own bit on macOS, as XNU `sogetoptlock`
/// (bsd/kern/uipc_socket.c) answers `so_options & sopt_name`. Measured for `SO_REUSEADDR` and
/// `SO_REUSEPORT` by tests/reuseport_os_truth.rs.
pub(crate) fn socket_flag(on: bool, name: c_int) -> c_int {
    match (on, cfg!(target_os = "macos")) {
        (false, _) => 0,
        (true, true) => name,
        (true, false) => 1,
    }
}

/// macOS `SO_NOSIGPIPE` (0x1022, XNU bsd/sys/socket.h).
const SO_NOSIGPIPE: c_int = 0x1022;
/// Linux `TCP_QUICKACK` (12, include/uapi/linux/tcp.h).
const TCP_QUICKACK: c_int = 12;
/// The TCP keepalive timers: Linux `TCP_KEEPIDLE` (4), `TCP_KEEPINTVL` (5), `TCP_KEEPCNT` (6)
/// (include/uapi/linux/tcp.h); macOS `TCP_KEEPALIVE` (0x10), `TCP_KEEPINTVL` (0x101),
/// `TCP_KEEPCNT` (0x102) (XNU bsd/netinet/tcp.h).
#[cfg(target_os = "linux")]
const TCP_KEEPALIVE_TIMERS: [c_int; 3] = [4, 5, 6];
#[cfg(target_os = "macos")]
const TCP_KEEPALIVE_TIMERS: [c_int; 3] = [0x10, 0x101, 0x102];

/// What an `ioctl` request a socket does not know fails with: `ENOTTY` on Linux (net/socket.c
/// `sock_do_ioctl` turns `-ENOIOCTLCMD` into it), `ENXIO` on macOS (measured; XNU's
/// `soioctl` falls through to the protocol's `pru_control`). Measured by
/// tests/strict_sockopts.rs `unknown_option_os_truth`.
const UNKNOWN_IOCTL: c_int = if cfg!(target_os = "linux") {
    libc::ENOTTY
} else {
    libc::ENXIO
};

impl Fabric {
    /// Linux `recvmsg(MSG_ERRQUEUE)`: on a datagram socket the oldest ICMP error `IP_RECVERR`
    /// queued (see [`SimShared::icmp_to`]) or transmit timestamp that has arrived, in arrival
    /// order, written as the `SimHost` writes one (`simhost::read_error_report`). Never blocks: an
    /// empty queue is `EAGAIN`
    /// (net/ipv4/ip_sockglue.c `ip_recv_error` returns `-EAGAIN` when `sock_dequeue_err_skb`
    /// finds nothing), and the miss charges the per-call latency so a polling loop lets a
    /// discrete clock move. Reading the report clears the pending error it raised.
    ///
    /// # Safety
    /// `hdr` is a valid `msghdr` (see [`scatter`]).
    #[cfg(target_os = "linux")]
    unsafe fn recv_errqueue(&self, fd: c_int, hdr: *mut libc::msghdr) -> Option<NetResult> {
        let (rec, v6) = match self.socks.lock().unwrap().get(&fd)? {
            Sock::Dgram { rec, domain, .. } => (rec.clone(), *domain == libc::AF_INET6),
            Sock::Stream { rec, conn, end, .. } => (rec.clone(), conn.local(*end).is_ipv6()),
            _ => return err(libc::EAGAIN),
        };
        if let Some(read) = unsafe {
            crate::simhost::read_error_report(&rec, hdr, v6, self.shared().tstamp_now().real)
        } {
            return Some(read);
        }
        snare_interpose::charge_latency();
        err(libc::EAGAIN)
    }

    /// `recvmsg` on a connected stream: what [`Fabric::stream_read`] reads, gathered into the
    /// iovecs, with no source address (`msg_namelen` 0, as `recvmsg(2)` leaves it for a
    /// connected stream) and, when the read took bytes, the receive timestamps of the last byte
    /// (Linux `tcp_recv_timestamp`; none on macOS, see [`crate::tstamp`]).
    ///
    /// # Safety
    /// `hdr` is a valid `msghdr` (see [`scatter`]).
    #[allow(clippy::unnecessary_cast)]
    unsafe fn recvmsg_stream(
        &self,
        fd: c_int,
        hdr: *mut libc::msghdr,
        flags: c_int,
    ) -> Option<NetResult> {
        let (iov, iovlen) = unsafe { ((*hdr).msg_iov, (*hdr).msg_iovlen as usize) };
        let want = if iov.is_null() {
            0
        } else {
            (0..iovlen)
                .map(|i| unsafe { (*iov.add(i)).iov_len })
                .sum::<usize>()
        };
        let direct = iovlen == 1
            && !iov.is_null()
            && want > 0
            && want <= isize::MAX as usize
            && unsafe { !(*iov).iov_base.is_null() };
        let mut buf = if direct { Vec::new() } else { vec![0u8; want] };
        let out = if direct {
            unsafe { std::slice::from_raw_parts_mut((*iov).iov_base.cast::<u8>(), want) }
        } else {
            &mut buf
        };
        let (n, stamp) = match self.stream_read(fd, out, flags)? {
            Ok(got) => got,
            Err(errno) => return err(errno),
        };
        let copied = if direct {
            n
        } else {
            unsafe { scatter(hdr, &buf[..n]) }
        };
        let cmsgs = match (stamp, self.rec(fd)) {
            (Some(at), Some(rec)) => {
                crate::tstamp::rx_cmsgs(Some(self.shared()), &rec, at, Rx::Stream, None)
            }
            _ => Vec::new(),
        };
        if let Some(at) = stamp.filter(|_| !cmsgs.is_empty()) {
            self.shared().reach_stamp(at);
        }
        unsafe {
            if !(*hdr).msg_name.is_null() {
                (*hdr).msg_namelen = 0;
            }
            let truncated = write_cmsg_list(hdr, &cmsgs);
            (*hdr).msg_flags = if truncated { libc::MSG_CTRUNC } else { 0 };
        }
        ok(copied as i64)
    }

    /// Reads what has arrived on stream socket `fd` into `out`, blocking as the socket does, with
    /// the stamp of the last byte read; `None` for an fd that is not a connected stream. A read
    /// returns what has arrived (up to `out.len()`), 0 at end of stream or after `SHUT_RD`,
    /// ECONNRESET after a reset, and blocks for data otherwise.
    fn stream_read(
        &self,
        fd: c_int,
        out: &mut [u8],
        flags: c_int,
    ) -> Option<Result<(usize, Option<Stamp>), c_int>> {
        let (conn, end, nonblocking, rec) = match self.socks.lock().unwrap().get(&fd)? {
            Sock::Stream {
                conn,
                end,
                nonblocking,
                rec,
            } => (conn.clone(), *end, *nonblocking, rec.clone()),
            _ => return None,
        };
        #[cfg(target_os = "macos")]
        conn.progress_tcp_shutdown();
        let pipe = conn.read_pipe(end);
        if out.is_empty() && cfg!(target_os = "macos") {
            return Some(Ok((0, None)));
        }
        let peek = flags & libc::MSG_PEEK != 0;
        let waitall =
            flags & libc::MSG_WAITALL != 0 && !nonblocking && flags & libc::MSG_DONTWAIT == 0;
        let mut copied = 0;
        let mut stamp = None;
        // Fixed before the loop so the SO_RCVTIMEO budget covers the whole call, not each wakeup.
        let deadline = rec.opts().rcvtimeo.map(Deadline::timeout);
        let taker = if flags & libc::MSG_PEEK != 0 {
            Taker::Peek
        } else {
            Taker::Recv
        };
        // man 2 recv: MSG_DONTWAIT makes this one call nonblocking regardless of the fd's mode.
        // A blocking read parks on the sim's readiness channel (not a per-pipe condvar) so it is
        // counted in quiescence and woken by the virtual-clock time-skip, exactly like UDP/raw.
        // Both Linux and macOS return queued bytes before a pending error, and the error before
        // end of stream (net/ipv4/tcp.c tcp_recvmsg_locked checks sk_err only once nothing was
        // copied, then RCV_SHUTDOWN; XNU bsd/kern/uipc_socket.c soreceive reads queued data
        // before so_error and so_error before SS_CANTRCVMORE). Linux checks SOCK_DONE (a FIN
        // received) ahead of sk_err, so an error arriving after the peer's FIN reads as end of
        // stream there; that order is not modelled.
        loop {
            #[cfg(target_os = "macos")]
            conn.progress_tcp_shutdown();
            let read = if peek {
                pipe.peek(out)
            } else {
                pipe.read(&mut out[copied..])
            };
            if matches!(read, Read::Shut | Read::Eof | Read::WouldBlock)
                && let Some(errno) = rec.take_error_as(self.shared(), taker)
            {
                return Some(if copied > 0 {
                    Ok((copied, stamp))
                } else {
                    Err(errno)
                });
            }
            match read {
                Read::Data(n) => {
                    copied = if peek { n } else { copied + n };
                    if !peek {
                        stamp = conn.took(end, n).or(stamp);
                    }
                    if !waitall
                        || copied == out.len()
                        || n == 0
                        || (peek && (pipe.read_eof() || rec.peek_error().is_some()))
                    {
                        return Some(Ok((copied, stamp)));
                    }
                    if peek
                        && !snare_interpose::interruptible(
                            crate::signals::socket_restart(deadline.is_some()),
                            || {
                                readiness().wait_until_on(
                                    "tcp peek",
                                    deadline,
                                    &[rec.wake_key()],
                                    || rec.pending_time(),
                                    || {
                                        rec.fionread() as usize >= out.len()
                                            || pipe.read_eof()
                                            || rec.peek_error().is_some()
                                    },
                                )
                            },
                        )
                        .0
                    {
                        return Some(Ok((copied, stamp)));
                    }
                }
                Read::Reset => {
                    return Some(match rec.take_error_as(self.shared(), taker) {
                        Some(errno) if copied == 0 => Err(errno),
                        _ => Ok((copied, stamp)),
                    });
                }
                Read::Shut | Read::Eof => return Some(Ok((copied, stamp))),
                Read::WouldBlock if nonblocking || flags & libc::MSG_DONTWAIT != 0 => {
                    snare_interpose::charge_latency();
                    return Some(Err(libc::EAGAIN));
                }
                Read::WouldBlock => {
                    // `false` is a timeout (SO_RCVTIMEO) or a quiescent deadlock, both EAGAIN, or
                    // a signal handler's interruption, EINTR.
                    let (woke, interrupted) = snare_interpose::interruptible(
                        crate::signals::socket_restart(deadline.is_some()),
                        || {
                            readiness().wait_until_on(
                                "tcp recv",
                                deadline,
                                &[rec.wake_key()],
                                || rec.pending_time(),
                                || {
                                    #[cfg(target_os = "macos")]
                                    conn.progress_tcp_shutdown();
                                    pipe.readable_or_closed() || rec.peek_error().is_some()
                                },
                            )
                        },
                    );
                    if !woke {
                        return Some(if copied > 0 {
                            Ok((copied, stamp))
                        } else if interrupted {
                            Err(libc::EINTR)
                        } else {
                            Err(libc::EAGAIN)
                        });
                    }
                }
            }
        }
    }

    /// Takes the next datagram for `endpoint`, blocking as the socket does, or returns the errno
    /// a receive fails with. `MSG_PEEK` returns the
    /// next datagram and leaves it queued, and reads a pending error without clearing it; `MSG_DONTWAIT` makes this one call nonblocking
    /// (man 2 recv). A blocking receive gives EAGAIN when `SO_RCVTIMEO` expires (man 7 socket)
    /// or when the domain is quiescent with nothing left to deliver.
    fn recv_dgram(
        &self,
        endpoint: &DgramRecvEndpoint,
        flags: c_int,
    ) -> Result<(Datagram, u32), c_int> {
        let DgramRecvEndpoint {
            queue,
            nonblocking,
            rec,
            ..
        } = endpoint;
        let nonblocking = *nonblocking || flags & libc::MSG_DONTWAIT != 0;
        let taker = if flags & libc::MSG_PEEK != 0 {
            Taker::Peek
        } else {
            Taker::Recv
        };
        #[cfg(target_os = "linux")]
        rec.land();
        // Linux reports a pending error before the datagrams already queued (net/ipv4/udp.c
        // __skb_recv_udp checks sock_error() at the top of its loop); macOS after them (XNU
        // bsd/kern/uipc_socket.c soreceive: with so_error set and data queued it `goto dontblock`).
        let error_first = cfg!(target_os = "linux");
        // A connected datagram socket only receives from its peer; an unconnected one from anyone.
        let accept = |_: SocketAddr| true;
        let deadline = if nonblocking {
            None
        } else {
            rec.opts().rcvtimeo.map(Deadline::timeout)
        };
        loop {
            #[cfg(target_os = "linux")]
            rec.land();
            if error_first && let Some(errno) = rec.take_error_as(self.shared(), taker) {
                return Err(errno);
            }
            let got = if matches!(taker, Taker::Peek) {
                queue.peek(accept)
            } else {
                queue.pop(accept)
            };
            if let Some(got) = got {
                return Ok(got);
            }
            if let Some(errno) = rec.take_error_as(self.shared(), taker) {
                return Err(errno);
            }
            if nonblocking {
                snare_interpose::charge_latency();
                return Err(libc::EAGAIN);
            }
            let (woke, interrupted) = snare_interpose::interruptible(
                crate::signals::socket_restart(deadline.is_some()),
                || {
                    readiness().wait_until_on(
                        "udp recv",
                        deadline,
                        &[rec.wake_key()],
                        || rec.pending_time(),
                        || queue.has(accept) || rec.peek_error().is_some(),
                    )
                },
            );
            if interrupted {
                return Err(libc::EINTR);
            }
            if !woke {
                return Err(libc::EAGAIN); // quiescent deadlock or SO_RCVTIMEO timeout
            }
        }
    }

    unsafe fn recvfrom_dgram(
        &self,
        endpoint: DgramRecvEndpoint,
        buf: *mut u8,
        len: usize,
        flags: c_int,
        addr: *mut u8,
        addr_len: *mut u32,
    ) -> Option<NetResult> {
        let (dg, _) = match self.recv_dgram(&endpoint, flags) {
            Ok(got) => got,
            Err(errno) => return err(errno),
        };
        #[cfg(target_os = "linux")]
        crate::tstamp::note_datagram_read(self.shared(), &endpoint.rec, dg.stamp, &dg.rx_fallback);
        let n = len.min(dg.data.len());
        unsafe { std::ptr::copy_nonoverlapping(dg.data.as_ptr(), buf, n) };
        if !addr.is_null() && !addr_len.is_null() {
            if dg.src == UNNAMED {
                unsafe { write_unnamed(addr, addr_len) };
            } else {
                unsafe { write_addr(reported(endpoint.mapped, dg.src), addr, addr_len) };
            }
        }
        ok(
            if cfg!(target_os = "linux") && flags & libc::MSG_TRUNC != 0 {
                dg.data.len()
            } else {
                n
            } as i64,
        )
    }
}

/// Scatters `data` across the iovecs of `hdr`, returning how much fit. What did not fit is
/// discarded, as a datagram's tail is (the caller sets `MSG_TRUNC`, man 2 recvmsg).
///
/// # Safety
/// `hdr` must point to a valid `msghdr` whose `msg_iov` holds `msg_iovlen` iovecs, each either
/// null-based or writable for `iov_len` bytes.
#[allow(clippy::unnecessary_cast)]
pub(crate) unsafe fn scatter(hdr: *const libc::msghdr, data: &[u8]) -> usize {
    let (iov, iovlen) = unsafe { ((*hdr).msg_iov, (*hdr).msg_iovlen as usize) };
    let mut copied = 0;
    if iov.is_null() {
        return 0;
    }
    for i in 0..iovlen {
        let v = unsafe { &*iov.add(i) };
        let take = (data.len() - copied).min(v.iov_len);
        if take == 0 || v.iov_base.is_null() {
            continue;
        }
        unsafe {
            std::ptr::copy_nonoverlapping(data[copied..].as_ptr(), v.iov_base.cast::<u8>(), take)
        };
        copied += take;
    }
    copied
}

/// [`write_cmsg_list`] over borrowed payloads; `true` when every message fit.
///
/// # Safety
/// As [`write_cmsg_list`].
#[cfg(target_os = "linux")]
pub(crate) unsafe fn write_cmsgs_at(
    hdr: *mut libc::msghdr,
    msgs: &[(c_int, c_int, &[u8])],
) -> bool {
    let owned: Vec<crate::tstamp::Cmsg> = msgs
        .iter()
        .map(|&(level, ty, data)| (level, ty, data.to_vec()))
        .collect();
    !unsafe { write_cmsg_list(hdr, &owned) }
}

/// Writes control messages `(level, type, payload)` into `hdr`'s control buffer in order, setting
/// `msg_controllen` to the bytes written, as the host kernel copies them out; `true` when the
/// buffer cut some short, for the caller's `MSG_CTRUNC` (man 2 recvmsg).
///
/// Each message is laid out per man 3 cmsg: `CMSG_LEN(len)` in `cmsg_len`, the payload at
/// `CMSG_DATA`, the whole taking `CMSG_SPACE(len)`, padding zeroed. A message that does not fit:
///
/// - Linux (net/core/scm.c `put_cmsg`): with room for at least a `cmsghdr`, the part that fits is
///   written with `cmsg_len` cut to it; with less, or no control buffer at all, nothing is.
///   Either way it is truncated, and so is every message after it.
/// - macOS (XNU bsd/kern/uipc_syscalls.c `copyout_control`): the bytes that fit are copied as
///   they are, the header's `cmsg_len` uncut, and that is truncated; a message that finds the
///   buffer already full, or no control buffer, is dropped without `MSG_CTRUNC`.
///
/// Both measured by tests/timestamps.rs `short_control_buffer_os_truth`.
///
/// # Safety
/// `hdr` must point to a valid `msghdr` whose `msg_control`, when non-null, is writable for
/// `msg_controllen` bytes and aligned for `cmsghdr`.
pub(crate) unsafe fn write_cmsg_list(hdr: *mut libc::msghdr, msgs: &[crate::tstamp::Cmsg]) -> bool {
    let control = unsafe { (*hdr).msg_control }.cast::<u8>();
    let cap = if control.is_null() {
        0
    } else {
        #[allow(clippy::unnecessary_cast)]
        unsafe {
            (*hdr).msg_controllen as usize
        }
    };
    let mut used = 0;
    let mut truncated = false;
    for (level, ty, data) in msgs {
        let space = unsafe { libc::CMSG_SPACE(data.len() as u32) } as usize;
        let len = unsafe { libc::CMSG_LEN(data.len() as u32) } as usize;
        let room = cap - used;
        if space <= room {
            unsafe {
                let cmsg = control.add(used).cast::<libc::cmsghdr>();
                std::ptr::write_bytes(cmsg.cast::<u8>(), 0, space);
                (*cmsg).cmsg_level = *level;
                (*cmsg).cmsg_type = *ty;
                (*cmsg).cmsg_len = len as _;
                std::ptr::copy_nonoverlapping(data.as_ptr(), libc::CMSG_DATA(cmsg), data.len());
            }
            used += space;
            continue;
        }
        if cfg!(target_os = "linux") {
            truncated = true;
            if room >= size_of::<libc::cmsghdr>() {
                let mut whole = vec![0u8; space];
                unsafe {
                    let cmsg = whole.as_mut_ptr().cast::<libc::cmsghdr>();
                    (*cmsg).cmsg_level = *level;
                    (*cmsg).cmsg_type = *ty;
                    (*cmsg).cmsg_len = room as _;
                    std::ptr::copy_nonoverlapping(data.as_ptr(), libc::CMSG_DATA(cmsg), data.len());
                    std::ptr::copy_nonoverlapping(whole.as_ptr(), control.add(used), room);
                }
                used = cap;
            }
            break;
        }
        if room == 0 {
            continue;
        }
        let mut whole = vec![0u8; space];
        unsafe {
            let cmsg = whole.as_mut_ptr().cast::<libc::cmsghdr>();
            (*cmsg).cmsg_level = *level;
            (*cmsg).cmsg_type = *ty;
            (*cmsg).cmsg_len = len as _;
            std::ptr::copy_nonoverlapping(data.as_ptr(), libc::CMSG_DATA(cmsg), data.len());
            std::ptr::copy_nonoverlapping(whole.as_ptr(), control.add(used), room);
        }
        used = cap;
        truncated = true;
    }
    if !control.is_null() {
        unsafe { (*hdr).msg_controllen = used as _ };
    }
    truncated
}

pub(crate) fn duplicate_to(fd: c_int, newfd: c_int, flags: Option<c_int>) -> c_int {
    snare_interpose::real(|| unsafe {
        #[cfg(target_os = "linux")]
        if let Some(flags) = flags {
            return libc::dup3(fd, newfd, flags);
        }
        #[cfg(not(target_os = "linux"))]
        let _ = flags;
        libc::dup2(fd, newfd)
    })
}

/// The `SOCK_NONBLOCK` type flag on Linux; macOS has no such flag (it uses `fcntl`). man 2 socket:
/// `type` carries the base type in its low bits ORed with SOCK_NONBLOCK / SOCK_CLOEXEC. The fabric
/// takes the base type as `ty & 0xff`, wider than the kernel's `SOCK_TYPE_MASK` (0xf,
/// include/linux/net.h) but clear of both flags (`O_NONBLOCK` 0x800 and `O_CLOEXEC` 0x80000 on
/// x86_64 and aarch64, include/uapi/asm-generic/fcntl.h).
fn sock_nonblock() -> c_int {
    #[cfg(target_os = "linux")]
    {
        libc::SOCK_NONBLOCK
    }
    #[cfg(not(target_os = "linux"))]
    {
        0
    }
}

/// `FIONREAD` (`SIOCINQ` on Linux) and Linux's `SIOCOUTQ` (`TIOCOUTQ`, man 7 udp/tcp): bytes
/// waiting to be read, and bytes not yet sent, which is always none here.
const FIONREAD: libc::c_ulong = libc::FIONREAD as libc::c_ulong;

/// Whether `request` is Linux's `SIOCOUTQ`, which include/uapi/linux/sockios.h defines as
/// `TIOCOUTQ` (0x5411 on most architectures). Always 0 here: a write lands in the peer's pipe at
/// once, so nothing stays in a send queue.
fn is_siocoutq(request: libc::c_ulong) -> bool {
    cfg!(target_os = "linux") && request == libc::TIOCOUTQ as libc::c_ulong
}

/// A handled call that returns `n`.
fn ok(n: i64) -> Option<NetResult> {
    Some(NetResult::Ok(n))
}

/// A non-blocking call that found nothing to do: `EAGAIN`, charged the call latency so a caller
/// busy-polling it still lets a discrete virtual clock move (see `snare_interpose::charge_latency`).
/// Called with no fabric lock held, since charging can wake waiters.
fn would_block() -> Option<NetResult> {
    snare_interpose::charge_latency();
    err(libc::EAGAIN)
}

/// A handled call that fails with `errno` (the interposer sets `errno` and returns -1).
fn err(errno: c_int) -> Option<NetResult> {
    Some(NetResult::Err(errno))
}

/// The interface queries of man 7 netdevice that the fabric answers from the topology on any
/// socket: Linux `SIOCGIFINDEX`/`SIOCGIFMTU`/`SIOCGIFFLAGS`/`SIOCGIFHWADDR`, macOS
/// `SIOCGIFFLAGS`/`SIOCGIFMTU` (`<sys/sockio.h>`).
///
/// Each takes a `struct ifreq`: `ifr_name[IFNAMSIZ]` (16 bytes, `<net/if.h>`) then the union the
/// answer is written into, at offset 16 on both systems.
mod ifreq {
    #[cfg(target_os = "linux")]
    pub(super) const INDEX: libc::c_ulong = libc::SIOCGIFINDEX;
    #[cfg(target_os = "linux")]
    pub(super) const HWADDR: libc::c_ulong = libc::SIOCGIFHWADDR;
    #[cfg(target_os = "linux")]
    pub(super) const MTU: libc::c_ulong = libc::SIOCGIFMTU;
    #[cfg(target_os = "linux")]
    pub(super) const FLAGS: libc::c_ulong = libc::SIOCGIFFLAGS;
    /// `_IOWR('i', 51, struct ifreq)` (XNU bsd/sys/sockio.h): `IOC_INOUT` 0xc000_0000 | 32-byte
    /// `ifreq` << 16 | 'i' << 8 | 51. `libc` does not export it for Apple targets.
    #[cfg(target_os = "macos")]
    pub(super) const MTU: libc::c_ulong = 0xc020_6933;
    /// `_IOWR('i', 17, struct ifreq)` (XNU bsd/sys/sockio.h), encoded as for [`MTU`].
    #[cfg(target_os = "macos")]
    pub(super) const FLAGS: libc::c_ulong = 0xc020_6911;
    /// An unknown `ifr_name`: Linux fails with ENODEV (net/core/dev_ioctl.c dev_ifsioc_locked),
    /// macOS with ENXIO (XNU bsd/net/if.c ifioctl_ifreq). Measured by nic_enumeration's
    /// `siocgif_unknown_name_os_truth`.
    pub(super) const UNKNOWN: i32 = if cfg!(target_os = "linux") {
        libc::ENODEV
    } else {
        libc::ENXIO
    };
}

/// `if_nametoindex` of an unknown name: glibc passes on SIOCGIFINDEX's ENODEV (man 3
/// if_nametoindex), macOS's libc sets ENXIO (macOS man 3 if_nametoindex). Measured by
/// nic_enumeration's `unknown_names_os_truth`.
const NAMETOINDEX_UNKNOWN: i32 = if cfg!(target_os = "linux") {
    libc::ENODEV
} else {
    libc::ENXIO
};

impl Fabric {
    /// Answers a [`ifreq`] interface query from the topology. Keyed by the name in the `ifreq`,
    /// not by `fd`, so it answers on any socket, including a real one the fabric does not own.
    /// `None` for any other request.
    ///
    /// Linux `SIOCGIFHWADDR` writes a `sockaddr` whose `sa_family` is the ARP hardware type and
    /// whose `sa_data` starts with the MAC (man 7 netdevice); `SIOCGIFFLAGS` a `short` of
    /// `IFF_*` flags, `SIOCGIFMTU` and `SIOCGIFINDEX` an `int`.
    ///
    /// # Safety
    /// `arg` must be null or point to a writable `struct ifreq`.
    unsafe fn nic_ioctl(&self, request: u64, arg: i64) -> Option<NetResult> {
        let request = request as libc::c_ulong;
        #[cfg(target_os = "linux")]
        let modelled = [ifreq::INDEX, ifreq::MTU, ifreq::FLAGS, ifreq::HWADDR];
        #[cfg(target_os = "macos")]
        let modelled = [ifreq::MTU, ifreq::FLAGS];
        if !modelled.contains(&request) {
            return None;
        }
        let base = arg as *mut u8;
        if base.is_null() {
            return err(libc::EFAULT);
        }
        let mut name = Vec::new();
        for i in 0..libc::IFNAMSIZ {
            let b = unsafe { *base.add(i) };
            if b == 0 {
                break;
            }
            name.push(b);
        }
        let Some(nic) = std::str::from_utf8(&name)
            .ok()
            .and_then(|name| self.shared().nic(name))
        else {
            return err(ifreq::UNKNOWN);
        };
        let field = unsafe { base.add(16) };
        match request {
            ifreq::MTU => unsafe { field.cast::<c_int>().write_unaligned(nic.spec.mtu as c_int) },
            ifreq::FLAGS => unsafe {
                field
                    .cast::<libc::c_short>()
                    .write_unaligned(crate::ifaddrs::flags(&nic) as u16 as libc::c_short)
            },
            #[cfg(target_os = "linux")]
            ifreq::INDEX => unsafe { field.cast::<c_int>().write_unaligned(nic.index as c_int) },
            #[cfg(target_os = "linux")]
            ifreq::HWADDR => {
                // include/uapi/linux/if_arp.h.
                const ARPHRD_ETHER: u16 = 1;
                const ARPHRD_LOOPBACK: u16 = 772;
                let family = if nic.loopback {
                    ARPHRD_LOOPBACK
                } else {
                    ARPHRD_ETHER
                };
                let mut sa = [0u8; 16];
                sa[..2].copy_from_slice(&family.to_ne_bytes());
                sa[2..8].copy_from_slice(&nic.hw_addr());
                unsafe { std::ptr::copy_nonoverlapping(sa.as_ptr(), field, sa.len()) };
            }
            _ => return None,
        }
        ok(0)
    }
}

/// The socket calls of the code under test. Every method returns `None` for an fd, family or type
/// the fabric does not serve, so the call reaches the next backend or the OS, and otherwise the
/// result or errno the host OS would give.
impl Fabric {
    /// [`Net::setsockopt`] on `fd`, one of the fabric's own.
    unsafe fn set_option(
        &self,
        fd: c_int,
        level: c_int,
        name: c_int,
        val: *const u8,
        len: u32,
    ) -> Option<NetResult> {
        if let Some(rec) = self.rec(fd)
            && let Some(result) = unsafe {
                crate::netif::sockopt::set(self.shared(), &rec, level, name, val, len).or_else(
                    || crate::limits::sockopt::set(self.shared(), &rec, level, name, val, len),
                )
            }
        {
            return match result {
                Ok(()) => ok(0),
                Err(errno) => err(errno),
            };
        }
        if let Some(rec) = self.rec(fd)
            && let Some(v6) = self.ipv6(fd)
            && let Some(result) =
                unsafe { crate::netif::frag::set(&rec, v6, level, name, val, len) }
        {
            return match result {
                Ok(()) => ok(0),
                Err(errno) => err(errno),
            };
        }
        if self.kind(fd) == Some(Kind::Dgram)
            && let Some(rec) = self.rec(fd)
            && let Some(v6) = self.ipv6(fd)
            && let Some(result) = unsafe { crate::ancillary::set(&rec, v6, level, name, val, len) }
        {
            return match result {
                Ok(()) => ok(0),
                Err(errno) => err(errno),
            };
        }
        if level == libc::IPPROTO_TCP
            && let Some(rec) = self.rec(fd)
            && let Some(result) = unsafe { crate::faults::sockopt::set(&rec, name, val, len) }
        {
            return match result {
                Ok(()) => ok(0),
                Err(errno) => err(errno),
            };
        }
        if let Some(rec) = self.rec(fd)
            && let Some(result) = unsafe {
                crate::tstamp::set(
                    Some(self.shared()),
                    &rec,
                    self.ts_kind(fd),
                    level,
                    name,
                    val,
                    len,
                )
            }
        {
            return match result {
                Ok(()) => ok(0),
                Err(errno) => err(errno),
            };
        }
        #[cfg(target_os = "linux")]
        if let Some(rec) = self.rec(fd) {
            let net_admin = self.shared().sys.has_cap(crate::limits::CAP_NET_ADMIN);
            if let Some(result) =
                unsafe { crate::tstamp::set_txtime(&rec, net_admin, level, name, val, len) }
            {
                return match result {
                    Ok(()) => ok(0),
                    Err(errno) => err(errno),
                };
            }
        }
        // man 7 socket: SO_BROADCAST permits sending to a broadcast address.
        if level == libc::SOL_SOCKET && name == libc::SO_BROADCAST {
            let on = unsafe { read_int(val, len) } != 0;
            if let Some(Sock::Dgram { broadcast, .. }) = self.socks.lock().unwrap().get_mut(&fd) {
                *broadcast = on;
            }
            return ok(0);
        }
        if level == libc::SOL_SOCKET
            && let Some(rec) = self.rec(fd)
        {
            // man 7 socket: SO_RCVTIMEO/SO_SNDTIMEO bound how long a blocking receive/send waits;
            // a zero timeval clears them (block indefinitely again).
            let timeout = || unsafe { parse_timeval(val, len) }.filter(|d| !d.is_zero());
            let mut state = rec.state();
            match name {
                libc::SO_RCVTIMEO => state.opts.rcvtimeo = timeout(),
                libc::SO_SNDTIMEO => state.opts.sndtimeo = timeout(),
                libc::SO_REUSEADDR => state.opts.reuseaddr = unsafe { read_int(val, len) } != 0,
                libc::SO_REUSEPORT => state.opts.reuseport = unsafe { read_int(val, len) } != 0,
                libc::SO_LINGER => {
                    state.opts.linger = unsafe { parse_linger(val, len, LINGER_UNIT) }
                }
                #[cfg(target_os = "macos")]
                SO_LINGER_SEC => {
                    state.opts.linger = unsafe { parse_linger(val, len, Duration::from_secs(1)) }
                }
                _ => {
                    drop(state);
                    return unsafe { self.unmodelled_set(Some(&rec), level, name, val, len) };
                }
            }
            return ok(0);
        }
        // IP_RECVERR(2const): queues errors on a datagram socket. Without it Linux reports an
        // ICMP error only on a connected socket (net/ipv4/udp.c udp_err), so it is what makes
        // errors fail calls on an unconnected one too.
        #[cfg(target_os = "linux")]
        if (level, name) == (libc::IPPROTO_IP, libc::IP_RECVERR)
            || (level, name) == (libc::IPPROTO_IPV6, libc::IPV6_RECVERR)
        {
            if let Some(rec) = self.rec(fd) {
                rec.state().dgram.recverr = unsafe { read_int(val, len) } != 0;
            }
            return ok(0);
        }
        // IP_ADD_MEMBERSHIP(2const) / IPV6_ADD_MEMBERSHIP(2const): joining a multicast group so
        // datagrams to it are delivered here.
        let drop_group = (level == libc::IPPROTO_IP && name == libc::IP_DROP_MEMBERSHIP)
            || (level == libc::IPPROTO_IPV6 && name == IPV6_LEAVE);
        let membership_name = if drop_group {
            if level == libc::IPPROTO_IP {
                libc::IP_ADD_MEMBERSHIP
            } else {
                IPV6_JOIN
            }
        } else {
            name
        };
        if let Some(membership) = unsafe { parse_add_membership(level, membership_name, val, len) }
        {
            if let Some(rec) = self.rec(fd) {
                return match rec.change_membership(membership, !drop_group) {
                    Ok(()) => ok(0),
                    Err(errno) => err(errno),
                };
            }
            return err(libc::ENOTSOCK);
        }
        unsafe { self.unmodelled_set(self.rec(fd).as_ref(), level, name, val, len) }
    }
}

impl Net for Fabric {
    /// Whether `fd` is one of the fabric's virtual descriptors.
    fn owns(&self, fd: c_int) -> bool {
        if let Some(held) = self.fds.held(fd) {
            return held;
        }
        let socks = self.socks.lock().unwrap();
        socks.contains_key(&fd) && !socks.stale_mirror(fd)
    }

    /// Serves `fd`, a number another sim minted for a socketpair end, as that end of this sim's
    /// own instance of the pair (see [`ProcessPairs`]), made at the first such number reached:
    /// bytes written in one world are never read in another, and each instance wakes only its
    /// own sim's waiters, so neither sim's run touches the other's. Both ends of the instance
    /// start open, as the process's pair is; a number of an end this sim has already reached
    /// joins that end's description. `O_NONBLOCK` is the end's as its sim last set it. Any
    /// other descriptor is a network socket, served as a connection that is gone
    /// ([`Fabric::mirror_dead`]).
    unsafe fn mirror(&self, fd: c_int) -> bool {
        let Some(end) = process_pairs().get(fd) else {
            return self.mirror_dead(fd);
        };
        snare_interpose::share_statics(fd);
        let fresh = {
            let mut socks = self.socks.lock().unwrap();
            if socks.stale_mirror(fd) {
                self.notice_detach(&socks, fd);
                let removed = socks.remove(&fd);
                drop(socks);
                if let Some(removed) = removed {
                    self.retire_descriptor(fd, removed, None, None);
                }
                socks = self.socks.lock().unwrap();
            }
            if socks.contains_key(&fd) {
                return true;
            }
            if let Some(held) = socks.mirror_holding(end.pair, end.end) {
                socks.alias_mirror(held, fd, end.pair);
                return true;
            }
            match socks.replicas.get_mut(&end.pair) {
                Some(pending) => match pending[end.end].take() {
                    Some(mut sock) => {
                        sock.set_nonblocking(end.nonblocking);
                        socks.insert_mirror(fd, sock, end.pair);
                        return true;
                    }
                    None => return false,
                },
                None => {
                    drop(socks);
                    let peer = process_pairs().peer_of(end).unwrap_or(fd);
                    let mut fds = [peer; 2];
                    fds[end.end] = fd;
                    self.pair_ends(end.dgram, fds, end.nonblocking, end.pair)
                }
            }
        };
        let [a, b] = fresh;
        let mut ends = [Some(a), Some(b)];
        let mut socks = self.socks.lock().unwrap();
        if socks.contains_key(&fd) || socks.replicas.contains_key(&end.pair) {
            drop(socks);
            // SAFETY: as for this call.
            return unsafe { self.mirror(fd) };
        }
        let sock = ends[end.end].take().unwrap();
        socks.insert_mirror(fd, sock, end.pair);
        socks.replicas.insert(end.pair, ends);
        true
    }

    /// Gives up the fabric's epoll sets, kqueues, eventfds and timerfds. A timer keeps the time
    /// it had left; registrations of the fabric's network sockets stay behind, as those sockets
    /// do.
    unsafe fn hand_over(&self) -> Option<snare_interpose::HandOver> {
        let now = self.shared().monotonic_now();
        let mut taken = {
            let mut socks = self.socks.lock().unwrap();
            socks.settle_timers(now);
            socks.take_local()
        };
        if taken.is_empty() {
            return None;
        }
        for description in &mut taken {
            if let Sock::Timer { expires, .. } = &mut description.sock {
                *expires = expires.map(|at| at.saturating_sub(now));
            }
        }
        let fds = taken
            .iter()
            .flat_map(|description| description.descriptors.iter().copied())
            .collect();
        let keys: Vec<_> = taken
            .iter()
            .map(|description| crate::readiness::WakeKey::Descriptor(description.id))
            .collect();
        let regs = self.regs.clone();
        Some(snare_interpose::HandOver {
            fds,
            state: Box::new(Handed(taken)),
            wake: Box::new(move || regs.shared.bump_keys(&keys)),
        })
    }

    unsafe fn take_over(
        &self,
        state: Box<dyn std::any::Any + Send>,
        fds: &[c_int],
    ) -> Result<(), Box<dyn std::any::Any + Send>> {
        let Handed(mut descriptions) = *state.downcast::<Handed>()?;
        let now = self.shared().monotonic_now();
        let moved: BTreeSet<c_int> = fds.iter().copied().collect();
        descriptions.retain_mut(|description| {
            description.descriptors.retain(|fd| moved.contains(fd));
            !description.descriptors.is_empty()
        });
        let staying: BTreeSet<c_int> = descriptions
            .iter()
            .flat_map(|description| registered_sockets(&description.sock))
            .filter(|fd| !moved.contains(fd) && snare_interpose::minted_socket(*fd))
            .collect();
        for &fd in &staying {
            // SAFETY: no pointers are involved.
            unsafe { Net::mirror(self, fd) };
        }
        let mut socks = self.socks.lock().unwrap();
        let mirrored: HashMap<c_int, u64> = staying
            .iter()
            .filter_map(|&fd| Some((fd, socks.identity(fd)?)))
            .collect();
        socks.adopt(descriptions, |sock, renamed| match sock {
            Sock::Timer { expires, .. } => *expires = expires.map(|left| now + left),
            Sock::Event { ready_at, .. } => *ready_at = now,
            Sock::Epoll { interests, .. } => {
                let held: Vec<_> = interests.iter().map(|(key, _)| *key).collect();
                let held: Vec<_> = held
                    .into_iter()
                    .filter_map(|key| Some((key, interests.remove(&key)?)))
                    .collect();
                for ((fd, identity), mut interest) in held {
                    let identity = match identity {
                        EpollIdentity::Local(id) => {
                            match renamed.get(&id).or_else(|| mirrored.get(&fd)) {
                                Some(&id) => EpollIdentity::Local(id),
                                None => continue,
                            }
                        }
                        EpollIdentity::Foreign(_) => continue,
                        EpollIdentity::Untracked => EpollIdentity::Untracked,
                    };
                    interest.pending_order = None;
                    interests.insert((fd, identity), interest, Keys::default());
                }
            }
            Sock::Kqueue { state } => {
                let mut state = state.lock().unwrap();
                let keep = |fd: &c_int, note: &mut Knote| {
                    note.untracked || moved.contains(fd) || mirrored.contains_key(fd)
                };
                state.notes.retain(|(_, fd), note| keep(fd, note));
                state.notes.everything();
            }
            _ => {}
        });
        Ok(())
    }

    /// Opens an `AF_INET`/`AF_INET6` stream or datagram socket, or on Linux an `AF_PACKET` one;
    /// declines any other family or type (`AF_UNIX` sockets other than socketpairs, raw IP).
    /// `protocol` is not checked.
    unsafe fn socket(&self, domain: c_int, ty: c_int, protocol: c_int) -> Option<NetResult> {
        let base = ty & 0xff;
        let nonblocking = ty & sock_nonblock() != 0;
        // AF_PACKET gives raw L2 access: SOCK_RAW passes whole frames incl. the Ethernet header,
        // SOCK_DGRAM has the link header cooked off. See packet(7).
        #[cfg(target_os = "linux")]
        if domain == libc::AF_PACKET {
            if base != libc::SOCK_RAW && base != libc::SOCK_DGRAM {
                return None;
            }
            // packet(7): only processes with CAP_NET_RAW may open packet sockets (EPERM,
            // net/packet/af_packet.c packet_create).
            if !self.shared().sys.has_cap(crate::limits::CAP_NET_RAW) {
                return err(libc::EPERM);
            }
            return self.open_socket(SocketKind::Packet, ty, |rec| {
                // SO_PROTOCOL reads 0 on a packet socket whatever protocol it was opened with
                // (measured on Linux 7.0 by tests/socket_family.rs).
                rec.set_family(domain, 0);
                rec.set_type(base);
                Sock::Raw {
                    ifindex: None,
                    rx: VecDeque::new(),
                    arrived: 0,
                    nonblocking,
                    rec,
                }
            });
        }
        if domain != libc::AF_INET && domain != libc::AF_INET6 {
            return None;
        }
        // inet_create (net/ipv4/af_inet.c) resolves protocol 0 to the type's own, which is
        // what SO_PROTOCOL reports.
        #[cfg(target_os = "linux")]
        let resolved = match (protocol, base) {
            (0, libc::SOCK_DGRAM) => libc::IPPROTO_UDP,
            (0, _) => libc::IPPROTO_TCP,
            (given, _) => given,
        };
        #[cfg(not(target_os = "linux"))]
        let _ = protocol;
        let inet6 = domain == libc::AF_INET6;
        let v6only = inet6 && self.shared().sys.limits().bindv6only;
        let family = |rec: &SockRec| {
            let mut state = rec.state();
            state.inet6 = inet6;
            state.v6only = v6only;
        };
        if base == libc::SOCK_DGRAM {
            return self.open_socket(SocketKind::Udp, ty, |rec| {
                #[cfg(target_os = "linux")]
                rec.set_family(domain, resolved);
                family(&rec);
                Sock::Dgram {
                    queue: DgramQueue::for_socket(&rec),
                    domain,
                    local: None,
                    requested: None,
                    peer: None,
                    nonblocking,
                    broadcast: false,
                    rec,
                }
            });
        }
        if base != libc::SOCK_STREAM {
            return None;
        }
        self.open_socket(SocketKind::TcpStream, ty, |rec| {
            #[cfg(target_os = "linux")]
            rec.set_family(domain, resolved);
            family(&rec);
            Sock::Fresh {
                domain,
                local: None,
                nonblocking,
                rec,
            }
        })
    }

    /// Makes a real pipe (man 2 pipe, and `pipe2` with `flags` on Linux) and records it as the
    /// sim's ([`Pipes`](crate::realfd::Pipes)), so that a wait on it beside the sim's own
    /// descriptors blocks on it as well.
    unsafe fn pipe(&self, fds: *mut c_int, flags: c_int) -> Option<NetResult> {
        if fds.is_null() {
            return err(libc::EFAULT);
        }
        #[cfg(not(target_os = "linux"))]
        if flags != 0 {
            return err(libc::EINVAL);
        }
        let mut ends = [-1; 2];
        let made = snare_interpose::real(|| {
            #[cfg(target_os = "linux")]
            let made = unsafe { libc::pipe2(ends.as_mut_ptr(), flags) };
            #[cfg(not(target_os = "linux"))]
            let made = unsafe { libc::pipe(ends.as_mut_ptr()) };
            (made == 0).then_some(()).ok_or_else(|| {
                io::Error::last_os_error()
                    .raw_os_error()
                    .unwrap_or(libc::EMFILE)
            })
        });
        if let Err(errno) = made {
            return err(errno);
        }
        self.shared().pipes.add(ends);
        unsafe {
            fds.write(ends[0]);
            fds.add(1).write(ends[1]);
        }
        ok(0)
    }

    /// Marks the pipe `fd` is an end of (every pipe of the sim's, for a `fork`) as one a child
    /// process may hold, and has the sim's waits on real descriptors look again.
    fn spawning(&self, fd: Option<c_int>) {
        self.shared().pipes.lend(fd);
        crate::realfd::recheck(self.shared().domain_key());
    }

    /// Holds the sim's clock to real time while child process `pid` runs (see
    /// [`Clock::hold_child`](crate::clock::Clock::hold_child)), and has its end be the sim's
    /// `SIGCHLD` ([`watch_child`](crate::realfd::watch_child)). The sim's waits on real
    /// descriptors look again: one waiting for any child ([`await_children`](Net::await_children))
    /// waits for this one too.
    fn spawned(&self, pid: c_int) {
        if let Some(clock) = &self.shared().clock {
            clock.hold_child(pid);
        }
        crate::realfd::watch_child(&self.regs.shared, pid);
        crate::realfd::recheck(self.shared().domain_key());
    }

    /// Opens a connected pair of `AF_UNIX` stream or datagram sockets (man 2 socketpair): a
    /// `Conn` with no addresses and no link policy for `SOCK_STREAM`, two queues pointing at
    /// each other for `SOCK_DGRAM`. Both fds are reserved before either is registered, so a
    /// failure leaks neither.
    unsafe fn socketpair(
        &self,
        domain: c_int,
        ty: c_int,
        protocol: c_int,
        fds: *mut c_int,
    ) -> Option<NetResult> {
        if domain != libc::AF_UNIX {
            return None;
        }
        let base = ty & 0xff;
        if base != libc::SOCK_STREAM && base != libc::SOCK_DGRAM {
            return None;
        }
        // Linux's unix_create also takes PF_UNIX as the protocol (net/unix/af_unix.c,
        // `protocol && protocol != PF_UNIX` → EPROTONOSUPPORT); Darwin only 0 (XNU
        // bsd/kern/uipc_socket.c socreate_internal: pffindproto finds no AF_UNIX protocol).
        if protocol != 0 && (cfg!(not(target_os = "linux")) || protocol != libc::PF_UNIX) {
            return err(libc::EPROTONOSUPPORT);
        }
        let nonblocking = ty & sock_nonblock() != 0;
        let [a, b] = match self.reserve_pair(ty) {
            Ok(fds) => fds,
            Err(e) => return err(e.raw_os_error().unwrap_or(libc::EMFILE)),
        };
        let pair = NEXT_PAIR.fetch_add(1, Ordering::Relaxed);
        let [sa, sb] = self.pair_ends(base == libc::SOCK_DGRAM, [a, b], nonblocking, pair);
        let mut socks = self.socks.lock().unwrap();
        socks.insert(a, sa);
        socks.insert(b, sb);
        drop(socks);
        unsafe {
            fds.write(a);
            fds.add(1).write(b);
        }
        ok(0)
    }

    /// Binds a fresh TCP socket, a UDP socket, or (Linux) a packet socket to its interface.
    ///
    /// For TCP and UDP the address must be of the socket's family ([`sock_addr`]), one the host
    /// holds or the wildcard (`SimShared::claim_address`, EADDRNOTAVAIL otherwise, man 7 ip) and a
    /// port the process may take (`bind_denied`: EACCES for a privileged port without the
    /// capability, man 7 ip); an IPv6 socket's v4-mapped address binds it to that IPv4 address,
    /// unless `IPV6_V6ONLY` is on ([`bind_addr`]). It then must not collide ([`bind_conflict`])
    /// with a socket of its protocol: every TCP socket of the sim, or every datagram socket, each
    /// holding the address `bind` named, not where a connect since rehashed it, and a tester's
    /// endpoint at the address. Port 0 takes an ephemeral port. A second bind of a bound socket is
    /// EINVAL (man 2 bind).
    unsafe fn bind(&self, fd: c_int, addr: *const u8, len: u32) -> Option<NetResult> {
        #[cfg(target_os = "linux")]
        {
            let mut socks = self.socks.lock().unwrap();
            if let Some(Sock::Raw { ifindex, .. }) = socks.get_mut(&fd) {
                if (len as usize) < size_of::<libc::sockaddr_ll>() {
                    return err(libc::EINVAL);
                }
                // packet(7): binding an AF_PACKET socket takes a struct sockaddr_ll; sll_ifindex
                // selects the interface (0 = any). We only model that field.
                let sll = unsafe { std::ptr::read_unaligned(addr.cast::<libc::sockaddr_ll>()) };
                *ifindex = Some(sll.sll_ifindex as u32);
                return ok(0);
            }
        }
        let mut socks = self.socks.lock().unwrap();
        match socks.get(&fd) {
            Some(Sock::Fresh {
                local: None,
                rec,
                domain,
                ..
            }) => {
                let rec = rec.clone();
                let want = match unsafe { bind_addr(&rec, *domain, addr, len, true) } {
                    Ok(want) => want,
                    Err(errno) => return err(errno),
                };
                if let Err(errno) = self.shared().claim_address(want.ip()) {
                    return err(errno);
                }
                if let Some(errno) = self.shared().sys.bind_denied(want) {
                    return err(errno);
                }
                let Some(want) = self.tcp_bind_addr(&socks, self.want(&rec, want)) else {
                    return err(libc::EADDRINUSE);
                };
                if let Some(Sock::Fresh { local, .. }) = socks.get_mut(&fd) {
                    *local = Some(want);
                }
                socks.reindex(fd);
                rec.state().bound_order = self.shared().bind_order();
                rec.set_local(want);
                bound_at(&rec, want);
                return ok(0);
            }
            Some(Sock::Fresh { .. } | Sock::Stream { .. } | Sock::Listener { .. }) => {
                return err(libc::EINVAL); // man 2 bind: already bound
            }
            _ => {}
        }
        let Some(Sock::Dgram {
            queue,
            local,
            rec,
            domain,
            ..
        }) = socks.get_mut(&fd)
        else {
            return None;
        };
        if local.is_some() {
            return err(libc::EINVAL); // man 2 bind: already bound
        }
        let mut want = match unsafe { bind_addr(rec, *domain, addr, len, false) } {
            Ok(want) => want,
            Err(errno) => return err(errno),
        };
        if let Err(errno) = self.shared().claim_address(want.ip()) {
            return err(errno);
        }
        if let Some(errno) = self.shared().sys.bind_denied(want) {
            return err(errno);
        }
        let asked = want;
        let (queue, rec) = (queue.clone(), rec.clone());
        let claim = self.want(&rec, want);
        let mut regs = self.regs.udp.lock().unwrap();
        if want.port() == 0 {
            let port = regs.alloc_port(want.ip(), claim.dual);
            if port == 0 {
                return err(if cfg!(target_os = "linux") {
                    libc::EADDRINUSE
                } else {
                    libc::EADDRNOTAVAIL
                });
            }
            want.set_port(port);
        } else if regs
            .bound
            .get(&want)
            .is_some_and(|held| held.iter().any(|q| q.rec.is_none()))
            || socks
                .on_port(want.port())
                .filter_map(udp_claim)
                .any(|held| bind_conflict(held, claim))
        {
            return err(libc::EADDRINUSE);
        }
        rec.state().bound_order = self.shared().bind_order();
        regs.insert(want, queue);
        drop(regs);
        if let Some(Sock::Dgram {
            local, requested, ..
        }) = socks.get_mut(&fd)
        {
            *local = Some(want);
            *requested = Some(asked);
        }
        socks.reindex(fd);
        rec.set_local(want);
        bound_at(&rec, want);
        ok(0)
    }

    /// Turns a fresh TCP socket into a listener registered at its address. Listening on a connected socket is EINVAL
    /// (net/ipv4/af_inet.c inet_listen; XNU bsd/kern/uipc_socket.c solisten; macOS listen(2))
    /// and on a datagram socket EOPNOTSUPP (man 2 listen). A connecting socket also gets
    /// EOPNOTSUPP here, where both kernels give EINVAL. Linux checks the address again as the
    /// socket starts listening (net/ipv4/inet_connection_sock.c `inet_csk_listen_start` calls
    /// `get_port` with the socket already listening), so of two sockets that shared an address
    /// through `SO_REUSEADDR`, the second to listen gets EADDRINUSE unless both set `SO_REUSEPORT`
    /// ([`bind_conflict`]); macOS does not (measured by tests/reuseport_os_truth.rs).
    unsafe fn listen(&self, fd: c_int, backlog: c_int) -> Option<NetResult> {
        let maximum = self.shared().sys.limits().listen_backlog_max;
        let capacity = if cfg!(target_os = "linux") {
            (if backlog < 0 {
                maximum
            } else {
                (backlog as usize).min(maximum)
            })
            .saturating_add(1)
        } else if backlog <= 0 {
            maximum
        } else {
            (backlog as usize).min(maximum)
        };
        let mut socks = self.socks.lock().unwrap();
        let (domain, local, nonblocking, rec) = match socks.get(&fd)? {
            Sock::Fresh {
                domain,
                local,
                nonblocking,
                rec,
            } => (*domain, *local, *nonblocking, rec.clone()),
            // Listening again only changes the backlog (net/ipv4/af_inet.c __inet_listen_sk).
            Sock::Listener { listener, .. } => {
                listener.capacity.store(capacity, Ordering::Release);
                return ok(0);
            }
            Sock::Stream { .. } => return err(libc::EINVAL),
            _ => return err(libc::EOPNOTSUPP),
        };
        // An unbound socket listens on the wildcard address at an ephemeral port (man 7 ip).
        let addr = match local {
            Some(addr) => {
                if cfg!(target_os = "linux")
                    && !self.tcp_free(&socks, Claim::of(&rec, addr), Some(&rec))
                {
                    return err(libc::EADDRINUSE);
                }
                addr
            }
            None => {
                let wildcard = SocketAddr::new(unspecified_like(loopback_for(domain)), 0);
                match self.tcp_bind_addr(&socks, self.want(&rec, wildcard)) {
                    Some(addr) => {
                        rec.state().bound_order = self.shared().bind_order();
                        addr
                    }
                    None => return err(libc::EADDRINUSE),
                }
            }
        };
        let dual = rec.state().dual_at(addr);
        let listener = Arc::new(Listener {
            rec: Some(Arc::downgrade(&rec)),
            addr,
            dual,
            pending: Mutex::default(),
            capacity: AtomicUsize::new(capacity),
            occupied: AtomicUsize::new(0),
            tester: false,
            arrivals: AtomicU64::new(0),
            ready_order: AtomicU64::new(0),
            ready_at: AtomicU64::new(0),
        });
        self.regs
            .listeners
            .lock()
            .unwrap()
            .insert(addr, listener.clone());
        rec.set_kind(SocketKind::TcpListener);
        rec.set_local(addr);
        socks.insert(
            fd,
            Sock::Listener {
                listener,
                nonblocking,
                rec,
            },
        );
        ok(0)
    }

    /// Takes the oldest pending connection as a new stream fd, writing the peer's address to
    /// `addr`. `flags` is `accept4`'s: `SOCK_NONBLOCK` makes the new fd nonblocking (man 2
    /// accept4); otherwise on Linux it starts blocking whatever the listener's mode (man 2 accept:
    /// the new socket does not inherit `O_NONBLOCK`), while macOS's accept(2) gives it "the same
    /// properties" as the listener, `O_NONBLOCK` included, which mio relies on there. If no fd
    /// can be reserved the connection goes back to the head of the queue.
    unsafe fn accept(
        &self,
        fd: c_int,
        addr: *mut u8,
        addr_len: *mut u32,
        flags: c_int,
    ) -> Option<NetResult> {
        let (listener, nonblocking, lrec) = match self.socks.lock().unwrap().get(&fd)? {
            Sock::Listener {
                listener,
                nonblocking,
                rec,
            } => (listener.clone(), *nonblocking, rec.clone()),
            // man 2 accept: EINVAL when the socket is not listening.
            Sock::Fresh { .. } | Sock::Stream { .. } => return err(libc::EINVAL),
            _ => return err(libc::EOPNOTSUPP),
        };
        let pop = || listener.pending.lock().unwrap().pop_front();
        let conn = if let Some(conn) = pop() {
            conn
        } else if nonblocking {
            return would_block();
        } else {
            // Linux bounds a blocking accept by SO_RCVTIMEO (EAGAIN): net/ipv4/
            // inet_connection_sock.c inet_csk_accept waits `sock_rcvtimeo()`. macOS ignores it:
            // XNU bsd/kern/uipc_syscalls.c accept_nocancel sleeps with no timeout. Pinned by
            // tcp_server's `accept_honours_rcvtimeo`.
            let deadline = if cfg!(target_os = "linux") {
                lrec.opts().rcvtimeo.map(Deadline::timeout)
            } else {
                None
            };
            let (woke, interrupted) = snare_interpose::interruptible(
                crate::signals::socket_restart(deadline.is_some()),
                || {
                    readiness().wait_until_on(
                        "accept",
                        deadline,
                        &[lrec.wake_key()],
                        || lrec.pending_time(),
                        || listener.has_pending(),
                    )
                },
            );
            if interrupted {
                return err(libc::EINTR);
            }
            if !woke {
                return err(libc::EAGAIN);
            }
            match pop() {
                Some(conn) => conn,
                None => return err(libc::EAGAIN),
            }
        };
        snare_interpose::descriptor_transaction(|| {
            let new_fd = match self.reserve_fd_flags(flags) {
                Ok(new_fd) => new_fd,
                Err(e) => {
                    listener.pending.lock().unwrap().push_front(conn);
                    return err(e.raw_os_error().unwrap_or(libc::EMFILE));
                }
            };
            listener.occupied.fetch_sub(1, Ordering::AcqRel);
            let rec = self.shared().new_socket(SocketKind::TcpStream, new_fd);
            rec.set_ends(conn.server, conn.client);
            rec.set_listener(lrec.id);
            rec.inherit_buffers(&lrec);
            // An accepted socket takes the listener's `IPV6_V6ONLY` on Linux and reads it off on
            // macOS (measured by tests/dual_stack_os_truth.rs).
            let inet6 = {
                let listener = lrec.state();
                let mut state = rec.state();
                state.inet6 = listener.inet6;
                state.v6only = cfg!(target_os = "linux") && listener.v6only;
                listener.inet6
            };
            // sk_clone_lock (net/core/sock.c) copies the listener whole: its family, protocol
            // and busy-poll settings carry over.
            #[cfg(target_os = "linux")]
            {
                let (family, busy_poll) = {
                    let listener = lrec.state();
                    (listener.family, listener.opts.busy_poll)
                };
                rec.set_family(family.0, family.1);
                rec.state().opts.busy_poll = busy_poll;
            }
            rec.note_conn_nic(self.shared().hop_name(conn.hop.as_ref()).as_deref());
            conn.a_to_b.read_by(&rec);
            conn.b_to_a.write_by(&rec);
            #[cfg(target_os = "macos")]
            conn.attach_tcp_probe(End::B, &rec);
            let peer = conn.client;
            self.socks.lock().unwrap().insert(
                new_fd,
                Sock::Stream {
                    conn,
                    end: End::B,
                    nonblocking: flags & sock_nonblock() != 0
                        || (cfg!(target_os = "macos") && nonblocking),
                    rec,
                },
            );
            if !addr.is_null() && !addr_len.is_null() {
                unsafe { write_addr(reported(inet6, peer), addr, addr_len) };
            }
            ok(new_fd as i64)
        })
    }

    /// Connects a socket. A datagram socket only fixes its peer. A TCP socket probes the
    /// destination's SYN answer (`SimShared::syn_probe`, which applies the fault plan): a SYN a
    /// listener accepts at once establishes the connection and queues it on the listener;
    /// anything else becomes a `ConnectAttempt` played forward on the clock, returning
    /// EINPROGRESS for a nonblocking socket (man 2 connect) or waiting it out otherwise.
    ///
    /// On a socket already connecting: a nonblocking call reports EALREADY while it is pending,
    /// the failure (consuming it) or EISCONN once settled (man 2 connect). A blocking call on
    /// Linux waits for the same attempt, as `__inet_stream_connect` (net/ipv4/af_inet.c) does for
    /// a socket in SYN_SENT.
    unsafe fn connect(&self, fd: c_int, addr: *const u8, len: u32) -> Option<NetResult> {
        if !Net::owns(self, fd) {
            return None;
        }
        if !addr.is_null() && len as usize >= size_of::<libc::sa_family_t>() {
            let family = unsafe { (*addr.cast::<libc::sockaddr>()).sa_family } as c_int;
            if family == libc::AF_UNSPEC
                && let Some((domain, mapped)) = self.disconnect_dgram(fd)
            {
                if cfg!(not(target_os = "macos")) {
                    return ok(0);
                }
                if mapped {
                    return err(libc::EADDRNOTAVAIL);
                }
                // XNU in_pcbladdr and in6_pcbladdr (bsd/netinet/in_pcb.c, in6_pcb.c) check
                // the address length before its family.
                let fits = len as usize
                    == if domain == libc::AF_INET6 {
                        size_of::<libc::sockaddr_in6>()
                    } else {
                        size_of::<libc::sockaddr_in>()
                    };
                return err(if fits {
                    libc::EAFNOSUPPORT
                } else {
                    libc::EINVAL
                });
            }
        }
        let (server, native) = match self.family(fd) {
            Some((domain, stream)) => {
                let usage = if stream {
                    AddrUse::Stream
                } else {
                    AddrUse::Datagram
                };
                match unsafe { sock_addr(domain, addr, len, usage) } {
                    Ok(server) => server,
                    Err(errno) => return err(errno),
                }
            }
            None => match unsafe { parse_addr(addr, len) } {
                Some(server) => (server, false),
                None => return err(libc::EINVAL),
            },
        };
        // man 2 connect on a datagram socket: it sends nothing, it just fixes the default peer so a
        // later plain `send`/`recv` works and receives from other addresses are filtered out. An
        // unbound socket takes the route's source address at an ephemeral port.
        let station = self.regs.station_at(server.ip());
        let (domain, nonblocking, bound, rec) = {
            let socks = self.socks.lock().unwrap();
            match socks.get(&fd)? {
                // XNU soconnectlock (bsd/kern/uipc_socket.c) dissolves a datagram socket's
                // association before connecting it again, so the source is picked anew. An IPv6
                // socket connected to one family then refuses the other (`EINVAL`, measured).
                Sock::Dgram {
                    peer: Some(peer),
                    domain,
                    ..
                } if cfg!(target_os = "macos") => {
                    let crossed = *domain == libc::AF_INET6 && peer.is_ipv4() != server.is_ipv4();
                    drop(socks);
                    self.disconnect_dgram(fd);
                    if crossed {
                        return err(libc::EINVAL);
                    }
                    return unsafe { self.connect(fd, addr, len) };
                }
                Sock::Dgram {
                    local,
                    requested,
                    queue,
                    rec,
                    broadcast,
                    domain,
                    ..
                } => {
                    let (local, requested, queue, rec, broadcast) =
                        (*local, *requested, queue.clone(), rec.clone(), *broadcast);
                    if *domain == libc::AF_INET6
                        && let Err(errno) = dgram_crossing(
                            &rec,
                            local.or(unhashed(requested)),
                            server,
                            native,
                            true,
                        )
                    {
                        return err(errno);
                    }
                    drop(socks);
                    return self.connect_dgram(
                        fd, server, station, local, requested, &queue, &rec, broadcast,
                    );
                }
                Sock::Fresh {
                    domain,
                    nonblocking,
                    local,
                    rec,
                } => (*domain, *nonblocking, *local, rec.clone()),
                #[cfg(target_os = "linux")]
                Sock::Connecting {
                    nonblocking: false, ..
                } => {
                    drop(socks);
                    return self.await_connect(fd);
                }
                Sock::Connecting { nonblocking, .. } => {
                    let nonblocking = *nonblocking;
                    drop(socks);
                    return match self.advance_connect(fd) {
                        // XNU's `connectit` (bsd/kern/uipc_syscalls.c) reports EALREADY only for
                        // a nonblocking socket; a blocking one reaches `soconnectlock`, which
                        // refuses a socket still connecting with EISCONN (measured after a
                        // connect a signal interrupted).
                        Progress::Pending(_) if !nonblocking => err(libc::EISCONN),
                        Progress::Pending(_) => {
                            snare_interpose::charge_latency();
                            err(libc::EALREADY)
                        }
                        Progress::Settled(Outcome::Failed(errno), rec) => {
                            rec.take_error();
                            err(errno)
                        }
                        Progress::Settled(Outcome::Connected, _) => err(libc::EISCONN),
                        Progress::Idle => unsafe { self.connect(fd, addr, len) },
                    };
                }
                Sock::Stream { rec, .. }
                    if cfg!(target_os = "linux") && rec.state().connect_ack =>
                {
                    rec.state().connect_ack = false;
                    return ok(0);
                }
                Sock::Stream { .. } | Sock::Listener { .. } => return err(libc::EISCONN),
                _ => return err(libc::EOPNOTSUPP),
            }
        };
        if domain == libc::AF_INET6
            && let Err(errno) = stream_crossing(&rec, bound, server)
        {
            return err(errno);
        }
        rec.state().tcp_failed = false;
        let from = bound.map(|bound| toward(bound, server));
        let sender =
            match self
                .shared()
                .route_send(&rec.view(from), server, Op::Connect, station, true)
            {
                Ok(sender) => sender,
                Err(errno) => return err(errno),
            };
        if from == Some(server) {
            return self.connect_to_self(fd, server, nonblocking, rec);
        }
        crate::netstats::bump(&self.shared().stats.tcp(server.ip()).active_opens);
        let host_local = matches!(&sender, Sender::Host(path) if path.local);
        let client = self.client_addr(server, from, &sender);
        if client.port() == 0 {
            return err(libc::EADDRNOTAVAIL);
        }
        let listener = self.listener_for(server, host_local, client);
        let mut syn = self.shared().syn_probe(server, listener.is_some(), station);
        let admission = if matches!(syn, Syn::Accept) {
            listener.as_ref().and_then(Listener::reserve)
        } else {
            None
        };
        if matches!(syn, Syn::Accept) && admission.is_none() {
            syn = Syn::Silent;
        }
        let connect = StreamConnect {
            domain,
            bound,
            nonblocking,
            server,
            client,
            host_local,
        };
        if let (Syn::Accept, Some(listener)) = (syn, &listener) {
            let admission = admission.expect("accepted SYN reserves a queue entry");
            return self.connect_accepted(fd, rec, &sender, listener, admission, &connect);
        }
        let server_in = listener.as_ref().is_none_or(|l| l.tester);
        if let ControlFlow::Break(result) =
            self.start_connect(fd, rec, &sender, syn, server_in, &connect)
        {
            return result;
        }
        self.await_connect(fd)
    }

    /// Sends on a connected socket. A stream write takes what the window has room for, blocking
    /// (up to `SO_SNDTIMEO`) for room unless nonblocking or `MSG_DONTWAIT`; a pending error is
    /// reported first. A datagram socket sends one datagram to its connected peer. Any other
    /// socket is ENOTCONN (man 2 send).
    unsafe fn send(
        &self,
        fd: c_int,
        buf: *const u8,
        len: usize,
        flags: c_int,
    ) -> Option<NetResult> {
        let socks = self.socks.lock().unwrap();
        match socks.get(&fd) {
            Some(Sock::Stream {
                conn,
                end,
                rec,
                nonblocking,
            }) => {
                let bytes = unsafe { std::slice::from_raw_parts(buf, len) };
                let (conn, end, rec) = (conn.clone(), *end, rec.clone());
                let nonblocking = *nonblocking || flags & libc::MSG_DONTWAIT != 0;
                drop(socks);
                #[cfg(target_os = "macos")]
                conn.progress_tcp_shutdown();
                if (cfg!(target_os = "macos") && conn.write_pipe(end).is_write_shut())
                    || (conn.is_reset() && conn.write_pipe(end).reader_gone())
                {
                    return err(libc::EPIPE);
                }
                if let Some(errno) = rec.take_error_as(self.shared(), Taker::Send) {
                    return err(errno);
                }
                let sent = conn.write_pipe(end).send(
                    bytes,
                    nonblocking,
                    rec.opts().sndtimeo,
                    |rest| conn.write(end, rest),
                    || {
                        #[cfg(target_os = "macos")]
                        conn.progress_tcp_shutdown();
                        rec.peek_error().is_some()
                    },
                );
                // man 2 send: writing after our side shut down (or the stream closed) fails with
                // EPIPE, or ECONNRESET once the connection was reset (man 2 send); a send that
                // could not start in time fails with EAGAIN.
                match sent {
                    Sent::Bytes(n) => {
                        rec.count_sent();
                        #[cfg(target_os = "linux")]
                        if !conn.pair {
                            conn.write_pipe(end).timestamp_write(
                                self.shared().tstamp_now(),
                                &bytes[..n],
                                Duration::from_nanos(
                                    conn.write_delays[end.index()].load(Ordering::Relaxed),
                                ) * 2,
                            );
                        }
                        ok(n as i64)
                    }
                    Sent::Closed if conn.is_reset() => err(rec
                        .take_error_as(self.shared(), Taker::Send)
                        .unwrap_or(libc::EPIPE)),
                    Sent::Closed => err(libc::EPIPE),
                    Sent::WouldBlock | Sent::TimedOut | Sent::Stuck => err(libc::EAGAIN),
                    Sent::Interrupted => err(libc::EINTR),
                    Sent::Error => err(rec
                        .take_error_as(self.shared(), Taker::Send)
                        .unwrap_or(libc::EAGAIN)),
                }
            }
            Some(Sock::UnixDgram { peer, rec, .. }) => {
                let (peer, rec) = (peer.upgrade(), rec.clone());
                drop(socks);
                let Some(peer) = peer else {
                    return err(PAIR_PEER_GONE);
                };
                let data = unsafe { std::slice::from_raw_parts(buf, len) };
                peer.push_after(
                    UNNAMED,
                    data,
                    Duration::ZERO,
                    None,
                    self.shared().tstamp_now(),
                    None,
                    crate::ancillary::Header::plain(UNNAMED.ip()),
                    self.shared().domain_key(),
                );
                rec.count_sent();
                ok(len as i64)
            }
            Some(sock @ Sock::Dgram { peer, .. }) => {
                // man 2 send: a datagram socket with no connected peer has nowhere to send.
                let Some(dest) = *peer else {
                    return err(libc::EDESTADDRREQ);
                };
                let endpoint = UdpSendEndpoint::from_sock(sock).unwrap();
                drop(socks);
                let data = unsafe { std::slice::from_raw_parts(buf, len) };
                self.udp_send(fd, endpoint, data, dest, flags, &Default::default())
            }
            Some(_) => err(libc::ENOTCONN),
            None => None,
        }
    }

    /// Sends one datagram to `addr`; declines a non-datagram socket with an address, so a
    /// `sendto` on a TCP socket reaches its `send` only through a null address.
    unsafe fn sendto(
        &self,
        fd: c_int,
        buf: *const u8,
        len: usize,
        flags: c_int,
        addr: *const u8,
        addr_len: u32,
    ) -> Option<NetResult> {
        // man 2 sendto: a null destination means "use the connected peer", i.e. a plain send.
        if addr.is_null() {
            return unsafe { self.send(fd, buf, len, flags) };
        }
        let endpoint = {
            let socks = self.socks.lock().unwrap();
            UdpSendEndpoint::from_sock(socks.get(&fd)?)?
        };
        let dest = match unsafe { sock_addr(endpoint.domain, addr, addr_len, AddrUse::Datagram) } {
            Ok((dest, _)) => dest,
            Err(errno) => return err(errno),
        };
        let data = unsafe { std::slice::from_raw_parts(buf, len) };
        self.udp_send(fd, endpoint, data, dest, flags, &Default::default())
    }

    /// Sends the payload `msg`'s iovecs gather (man 2 sendmsg) as [`sendto`](Self::sendto) to
    /// `msg_name`, or as [`send`](Self::send) to the connected peer when it is null. Control
    /// messages are checked and applied as the host does ([`crate::ancillary`]) on an IP datagram
    /// socket and a TCP stream; on a `socketpair` end, which would carry `SCM_RIGHTS` or
    /// credentials, they are not modelled and fail with `EOPNOTSUPP`.
    unsafe fn sendmsg(&self, fd: c_int, msg: *const u8, flags: c_int) -> Option<NetResult> {
        if !Net::owns(self, fd) {
            return None;
        }
        if msg.is_null() {
            return err(libc::EFAULT);
        }
        let hdr = msg as *const libc::msghdr;
        // SAFETY: `hdr` is the caller's msghdr.
        let (name, name_len, iov, iov_len) = unsafe {
            (
                (*hdr).msg_name,
                (*hdr).msg_namelen,
                (*hdr).msg_iov,
                (*hdr).msg_iovlen,
            )
        };
        let control = match unsafe { crate::ancillary::control(hdr) } {
            Ok(control) => control,
            Err(errno) => return err(errno),
        };
        let mut data = Vec::new();
        if !iov.is_null() {
            for i in 0..iov_len as _ {
                // SAFETY: `iov` holds `iov_len` iovecs, each describing the caller's bytes.
                let v = unsafe { &*iov.add(i) };
                if !v.iov_base.is_null() && v.iov_len != 0 {
                    data.extend_from_slice(unsafe {
                        std::slice::from_raw_parts(v.iov_base as *const u8, v.iov_len)
                    });
                }
            }
        }
        if let Some(control) = control {
            let (endpoint, peer, stream) = {
                let socks = self.socks.lock().unwrap();
                match socks.get(&fd)? {
                    sock @ Sock::Dgram { peer, .. } => {
                        (UdpSendEndpoint::from_sock(sock), *peer, None)
                    }
                    Sock::Stream { conn, rec, .. } if !conn.pair => (None, None, Some(rec.clone())),
                    _ => return err(libc::EOPNOTSUPP),
                }
            };
            if let Some(rec) = stream {
                if let Err(errno) = crate::ancillary::stream_send(self.shared(), &rec, &control) {
                    return err(errno);
                }
            } else if let Some(endpoint) = endpoint {
                let dest = if name.is_null() {
                    match peer {
                        Some(peer) => peer,
                        None => return err(libc::EDESTADDRREQ),
                    }
                } else {
                    let name = name as *const u8;
                    match unsafe { sock_addr(endpoint.domain, name, name_len, AddrUse::Datagram) } {
                        Ok((dest, _)) => dest,
                        Err(errno) => return err(errno),
                    }
                };
                let ctl = match crate::ancillary::datagram_send(
                    self.shared(),
                    &endpoint.rec,
                    &control,
                    endpoint.domain == libc::AF_INET6,
                    dest,
                ) {
                    Ok(ctl) => ctl,
                    Err(errno) => return err(errno),
                };
                return self.udp_send(fd, endpoint, &data, dest, flags, &ctl);
            }
        }
        unsafe {
            self.sendto(
                fd,
                data.as_ptr(),
                data.len(),
                flags,
                name as *const u8,
                name_len,
            )
        }
    }

    /// Receives one datagram, truncated to `len` (the rest is discarded, man 7 udp), and writes
    /// its source to `addr`: the unnamed `AF_UNIX` address for a socketpair end. Returns the
    /// bytes copied. Declines (`None`) any socket that is not a datagram socket.
    unsafe fn recvfrom(
        &self,
        fd: c_int,
        buf: *mut u8,
        len: usize,
        flags: c_int,
        addr: *mut u8,
        addr_len: *mut u32,
    ) -> Option<NetResult> {
        let endpoint = {
            let socks = self.socks.lock().unwrap();
            DgramRecvEndpoint::from_sock(socks.get(&fd)?)?
        };
        unsafe { self.recvfrom_dgram(endpoint, buf, len, flags, addr, addr_len) }
    }

    fn keep_error(&self, fd: c_int, errno: c_int) {
        if let Some(rec) = self.rec(fd) {
            rec.raise_error(errno, crate::sockets::ErrorOrigin::Raised, None);
        }
    }

    /// Receives one datagram into `msg`'s iovecs (man 2 recvmsg), setting `MSG_TRUNC` in
    /// `msg_flags` when it did not fit and `MSG_CTRUNC` when its control messages did not. On
    /// Linux a datagram read whole from a segmented send leads with its `UDP_GRO` message; the
    /// receive timestamps the socket asked for come next (see [`crate::tstamp`]); then, with
    /// Linux's `SO_RXQ_OVFL` on, a `SOL_SOCKET`/`SO_RXQ_OVFL` message carries the `u32` count of
    /// datagrams the socket has dropped since its creation, as recorded on this datagram (man 7
    /// socket); none is attached while the count is 0 (net/socket.c `__sock_recv_cmsgs` writes
    /// the timestamps, then the drops); last the IP-level messages the socket asked for
    /// ([`crate::ancillary::rx_cmsgs`]). On Linux `MSG_ERRQUEUE` reads the error queue instead
    /// (`Fabric::recv_errqueue`). A stream socket reads what has arrived
    /// ([`Fabric::recvmsg_stream`]).
    unsafe fn recvmsg(&self, fd: c_int, msg: *mut u8, flags: c_int) -> Option<NetResult> {
        if msg.is_null() {
            return Net::owns(self, fd).then_some(NetResult::Err(libc::EFAULT));
        }
        #[cfg(target_os = "linux")]
        if flags & libc::MSG_ERRQUEUE != 0 {
            return unsafe { self.recv_errqueue(fd, msg.cast()) };
        }
        let endpoint = {
            let socks = self.socks.lock().unwrap();
            let sock = socks.get(&fd)?;
            if matches!(sock, Sock::Stream { .. }) {
                None
            } else {
                Some(DgramRecvEndpoint::from_sock(sock)?)
            }
        };
        let Some(endpoint) = endpoint else {
            return unsafe { self.recvmsg_stream(fd, msg.cast(), flags) };
        };
        #[cfg(target_os = "linux")]
        let rxq_ovfl = endpoint.rec.state().buf.rxq_ovfl;
        let (dg, drops) = match self.recv_dgram(&endpoint, flags) {
            Ok(got) => got,
            Err(errno) => return err(errno),
        };
        let hdr = msg.cast::<libc::msghdr>();
        let copied = unsafe { scatter(hdr, &dg.data) };
        let mut msg_flags = 0;
        if copied < dg.data.len() {
            msg_flags |= libc::MSG_TRUNC;
        }
        unsafe {
            let name = (*hdr).msg_name.cast::<u8>();
            if !name.is_null() {
                let mut name_len = (*hdr).msg_namelen;
                if dg.src == UNNAMED {
                    write_unnamed(name, &mut name_len);
                } else {
                    write_addr(reported(endpoint.mapped, dg.src), name, &mut name_len);
                }
                (*hdr).msg_namelen = name_len;
            }
        }
        #[cfg(target_os = "linux")]
        let fallback = Some(dg.rx_fallback.as_ref());
        #[cfg(not(target_os = "linux"))]
        let fallback = None;
        let mut cmsgs = Vec::new();
        #[cfg(target_os = "linux")]
        cmsgs.extend(crate::ancillary::gro_cmsg(&endpoint.rec, &dg.ip));
        let stamps = crate::tstamp::rx_cmsgs(
            Some(self.shared()),
            &endpoint.rec,
            dg.stamp,
            Rx::Datagram,
            fallback,
        );
        if !stamps.is_empty() {
            self.shared().reach_stamp(dg.stamp);
        }
        cmsgs.extend(stamps);
        #[cfg(target_os = "linux")]
        if rxq_ovfl && drops > 0 {
            cmsgs.push((
                libc::SOL_SOCKET,
                crate::limits::SO_RXQ_OVFL,
                drops.to_ne_bytes().to_vec(),
            ));
        }
        #[cfg(not(target_os = "linux"))]
        let _ = drops;
        if endpoint.domain != libc::AF_UNIX {
            cmsgs.extend(crate::ancillary::rx_cmsgs(
                self.shared(),
                &endpoint.rec,
                endpoint.domain == libc::AF_INET6,
                dg.src.ip(),
                &dg.ip,
            ));
        }
        if unsafe { write_cmsg_list(hdr, &cmsgs) } {
            msg_flags |= libc::MSG_CTRUNC;
        }
        unsafe { (*hdr).msg_flags = msg_flags };
        // man 2 recv, MSG_TRUNC: in the call's flags it returns the datagram's real length even
        // when longer than the buffer (Linux only; macOS has no such input flag).
        let real_len = cfg!(target_os = "linux") && flags & libc::MSG_TRUNC != 0;
        ok(if real_len { dg.data.len() } else { copied } as i64)
    }

    /// Reads from a connected stream, or one datagram from a datagram socket. A stream read
    /// returns what has arrived (up to `len`), 0 at end of stream or after `SHUT_RD`, ECONNRESET
    /// after a reset, and blocks for data otherwise. Fresh and listening sockets are ENOTCONN.
    unsafe fn recv(&self, fd: c_int, buf: *mut u8, len: usize, flags: c_int) -> Option<NetResult> {
        let endpoint = {
            let socks = self.socks.lock().unwrap();
            match socks.get(&fd)? {
                Sock::Stream { .. } => None,
                sock => match DgramRecvEndpoint::from_sock(sock) {
                    Some(endpoint) => Some(endpoint),
                    None => return err(libc::ENOTCONN),
                },
            }
        };
        if let Some(endpoint) = endpoint {
            return unsafe {
                self.recvfrom_dgram(
                    endpoint,
                    buf,
                    len,
                    flags,
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                )
            };
        }
        let out = unsafe { std::slice::from_raw_parts_mut(buf, len) };
        match self.stream_read(fd, out, flags)? {
            Ok((n, _)) => ok(n as i64),
            Err(errno) => err(errno),
        }
    }

    /// Shuts down a stream's sending side (a FIN to the peer), its receiving side (later reads
    /// return 0), or both. A no-op on a connected datagram socket, a datagram socketpair end, a
    /// connecting socket, and the fabric's eventfd, epoll, raw and kqueue descriptors (where a
    /// real kernel would refuse with ENOTSOCK or EOPNOTSUPP).
    unsafe fn shutdown(&self, fd: c_int, how: c_int) -> Option<NetResult> {
        let socks = self.socks.lock().unwrap();
        let sock = socks.get(&fd)?;
        // man 2 shutdown: `how` is SHUT_RD, SHUT_WR or SHUT_RDWR, else EINVAL; a socket that is
        // not connected gives ENOTCONN.
        if ![libc::SHUT_RD, libc::SHUT_WR, libc::SHUT_RDWR].contains(&how) {
            return err(libc::EINVAL);
        }
        match sock {
            Sock::Stream { conn, end, .. } => {
                let (conn, end) = (conn.clone(), *end);
                drop(socks);
                #[cfg(target_os = "macos")]
                conn.progress_tcp_shutdown();
                if how != libc::SHUT_WR {
                    if cfg!(target_os = "macos")
                        && (conn.read_pipe(end).is_read_shut() || conn.read_pipe(end).is_closed())
                    {
                        return err(libc::ENOTCONN);
                    }
                    #[cfg(target_os = "macos")]
                    conn.shut_read_tcp(end);
                    #[cfg(not(target_os = "macos"))]
                    conn.read_pipe(end).shut_read();
                }
                if how != libc::SHUT_RD {
                    #[cfg(target_os = "macos")]
                    if conn.write_pipe(end).is_write_closed() {
                        return err(libc::ENOTCONN);
                    }
                    conn.close(end);
                }
                ok(0)
            }
            Sock::Fresh { .. } | Sock::Listener { .. } | Sock::Dgram { peer: None, .. } => {
                err(libc::ENOTCONN)
            }
            _ => ok(0),
        }
    }

    /// Closes a descriptor. Only the last descriptor of a socket (see `F_DUPFD`) tears it down:
    /// a stream end sends its FIN (or RST, per `SO_LINGER`), a datagram socket leaves the address
    /// and group registries, and a listener unregisters and resets its unaccepted connections.
    /// The real fd behind it is closed in every case.
    unsafe fn close(&self, fd: c_int) -> Option<NetResult> {
        let mirror = self.socks.lock().unwrap().mirrors.contains_key(&fd);
        self.detach_fd(fd)?;
        if mirror {
            return ok(0);
        }
        let ret = unsafe { libc::close(fd) };
        ok(ret as i64)
    }

    unsafe fn fd_replaced(&self, fd: c_int) -> Option<NetResult> {
        self.detach_fd(fd)?;
        ok(0)
    }

    unsafe fn dup_to(&self, fd: c_int, newfd: c_int, flags: Option<c_int>) -> Option<NetResult> {
        let mut socks = self.socks.lock().unwrap();
        let rec = socks.get(&fd)?.rec().cloned();
        let result = duplicate_to(fd, newfd, flags);
        if result < 0 {
            return err(io::Error::last_os_error()
                .raw_os_error()
                .unwrap_or(libc::EBADF));
        }
        if fd == newfd || socks.descriptors.get(&fd) == socks.descriptors.get(&newfd) {
            return ok(result as i64);
        }
        let previous = socks.get(&newfd).and_then(Sock::rec).cloned();
        let previous_key = previous.as_ref().map(|rec| rec.wake_key()).or_else(|| {
            socks
                .identity(newfd)
                .map(crate::readiness::WakeKey::Descriptor)
        });
        self.notice_detach(&socks, newfd);
        let removed = socks.remove(&newfd).flatten();
        socks.alias(fd, newfd);
        if let Some(rec) = rec {
            self.shared().sockets.alias(newfd, &rec);
        }
        drop(socks);
        self.retire_descriptor(newfd, removed, previous, previous_key);
        ok(result as i64)
    }

    /// The connected peer's address; the unnamed `AF_UNIX` address for a socketpair end, ENOTCONN
    /// for an unconnected socket (man 2 getpeername) and for another sim's socket, a connection
    /// that is gone here. A truncated buffer gets the address's prefix and the full length, as
    /// man 2 getpeername describes.
    unsafe fn getpeername(
        &self,
        fd: c_int,
        addr: *mut u8,
        addr_len: *mut u32,
    ) -> Option<NetResult> {
        let socks = self.socks.lock().unwrap();
        if socks.mirrors.get(&fd) == Some(&DEAD) && socks.contains_key(&fd) {
            return err(libc::ENOTCONN);
        }
        let peer = match socks.get(&fd)? {
            Sock::Stream { conn, .. } if conn.pair => None,
            Sock::UnixDgram { .. } => None,
            Sock::Stream { conn, end, rec, .. } => {
                Some(reported(rec.state().inet6, conn.peer(*end)))
            }
            Sock::Dgram {
                peer: Some(peer),
                domain,
                ..
            } => Some(reported(*domain == libc::AF_INET6, *peer)),
            _ => return err(libc::ENOTCONN),
        };
        drop(socks);
        match peer {
            Some(peer) => unsafe { write_addr(peer, addr, addr_len) },
            None => unsafe { write_unnamed(addr, addr_len) },
        }
        ok(0)
    }

    /// The socket's own address; the unnamed `AF_UNIX` address for a socketpair end. An unbound
    /// socket reports its family's wildcard at port 0. Truncation is as for `getpeername`.
    unsafe fn getsockname(
        &self,
        fd: c_int,
        addr: *mut u8,
        addr_len: *mut u32,
    ) -> Option<NetResult> {
        let socks = self.socks.lock().unwrap();
        let local = match socks.get(&fd)? {
            Sock::Stream { conn, .. } if conn.pair => None,
            Sock::UnixDgram { .. } => None,
            Sock::Stream { conn, end, rec, .. } => {
                Some(reported(rec.state().inet6, conn.local(*end)))
            }
            Sock::Listener { listener, rec, .. } => {
                Some(reported(rec.state().inet6, listener.addr))
            }
            Sock::Dgram {
                local: None,
                requested: Some(requested),
                domain,
                ..
            } => Some(reported(
                *domain == libc::AF_INET6,
                SocketAddr::new(requested.ip(), 0),
            )),
            Sock::Dgram { local, domain, .. }
            | Sock::Fresh { local, domain, .. }
            | Sock::Connecting { local, domain, .. } => Some(reported(
                *domain == libc::AF_INET6,
                local
                    .unwrap_or_else(|| SocketAddr::new(unspecified_like(loopback_for(*domain)), 0)),
            )),
            _ => return None,
        };
        drop(socks);
        match local {
            Some(local) => unsafe { write_addr(local, addr, addr_len) },
            None => unsafe { write_unnamed(addr, addr_len) },
        }
        ok(0)
    }

    /// Sets a socket option. The interface/routing options (`netif::sockopt`) and buffer/limit
    /// options (`limits::sockopt`) are tried first, then the don't-fragment options of an IP
    /// socket (`netif::frag`), the TCP fault options
    /// (`faults::sockopt`), the timestamp options and Linux `SO_TXTIME` (`tstamp`), then the ones
    /// kept here:
    /// `SO_BROADCAST`, the timeouts, `SO_REUSEADDR`, `SO_LINGER` (and macOS `SO_LINGER_SEC`),
    /// Linux `IP_RECVERR`/`IPV6_RECVERR`, and multicast joins. The rest go to
    /// [`Fabric::unmodelled_set`]: the [`harmless`] ones are kept and ignored, any other is
    /// recorded as unmodelled and accepted, or refused under `strict_sockopts`.
    unsafe fn setsockopt(
        &self,
        fd: c_int,
        level: c_int,
        name: c_int,
        val: *const u8,
        len: u32,
    ) -> Option<NetResult> {
        if !Net::owns(self, fd) {
            return None;
        }
        if (level, name) == (libc::IPPROTO_IPV6, libc::IPV6_V6ONLY)
            && let Some(result) = unsafe { self.set_v6only(fd, val, len) }
        {
            return result;
        }
        if cfg!(target_os = "macos") && level == libc::IPPROTO_IP && self.ipv6(fd) == Some(true) {
            return err(libc::EINVAL);
        }
        let result = unsafe { self.set_option(fd, level, name, val, len) };
        self.notice_fd(fd);
        result
    }

    /// Reads a socket option, consulting the same owners as [`setsockopt`](Net::setsockopt).
    /// `SO_ERROR` first moves a pending connect on, so a caller polling it after EINPROGRESS sees
    /// the attempt settle. Any other option goes to [`Fabric::unmodelled_get`].
    unsafe fn getsockopt(
        &self,
        fd: c_int,
        level: c_int,
        name: c_int,
        val: *mut u8,
        len: *mut u32,
    ) -> Option<NetResult> {
        if !Net::owns(self, fd) {
            return None;
        }
        if (level, name) == (libc::IPPROTO_IPV6, libc::IPV6_V6ONLY)
            && let Some(result) = unsafe { self.get_v6only(fd, val, len) }
        {
            return result;
        }
        if cfg!(target_os = "macos") && level == libc::IPPROTO_IP && self.ipv6(fd) == Some(true) {
            return err(libc::EINVAL);
        }
        if level == libc::SOL_SOCKET && name == libc::SO_ERROR {
            self.advance_connect(fd);
        }
        let rec = self.rec(fd);
        #[cfg(any(target_os = "linux", target_os = "macos"))]
        if let Some(rec) = &rec {
            rec.land();
        }
        if let Some(rec) = &rec
            && unsafe { crate::tstamp::get(rec, level, name, val, len) }.is_some()
        {
            return ok(0);
        }
        if let Some(rec) = &rec
            && level == libc::SOL_SOCKET
            && let Some(unit) = linger_unit(name)
        {
            unsafe { write_linger(rec.opts().linger, unit, val, len) };
            return ok(0);
        }
        if let Some(rec) = &rec
            && unsafe { crate::netif::sockopt::get(rec, level, name, val, len) }.is_some()
        {
            return ok(0);
        }
        if let Some(rec) = &rec
            && let Some(v6) = self.ipv6(fd)
            && let Some(result) = unsafe { crate::netif::frag::get(rec, v6, level, name, val, len) }
        {
            return match result {
                Ok(()) => ok(0),
                Err(errno) => err(errno),
            };
        }
        if let Some(rec) = &rec
            && self.kind(fd) == Some(Kind::Dgram)
            && let Some(v6) = self.ipv6(fd)
            && let Some(result) = unsafe { crate::ancillary::get(rec, v6, level, name, val, len) }
        {
            return match result {
                Ok(()) => ok(0),
                Err(errno) => err(errno),
            };
        }
        if level == libc::IPPROTO_TCP
            && let Some(rec) = &rec
            && let Some(value) = crate::faults::sockopt::get(self.shared(), rec, name)
        {
            unsafe { write_opt(value, val, len) };
            return ok(0);
        }
        if let Some(rec) = &rec
            && let Some(result) = unsafe { crate::limits::sockopt::get(rec, level, name, val, len) }
        {
            return match result {
                Ok(()) => ok(0),
                Err(errno) => err(errno),
            };
        }
        // man 7 socket: report the stored SO_RCVTIMEO/SO_SNDTIMEO as a timeval (zero = unset), so
        // code that reads back what it set (e.g. std's `read_timeout`) sees it.
        if level == libc::SOL_SOCKET && (name == libc::SO_RCVTIMEO || name == libc::SO_SNDTIMEO) {
            let opts = rec.map(|rec| rec.opts()).unwrap_or_default();
            let d = if name == libc::SO_RCVTIMEO {
                opts.rcvtimeo
            } else {
                opts.sndtimeo
            };
            unsafe { write_timeval(d.unwrap_or_default(), val, len) };
            return ok(0);
        }
        // socket(7): SO_TYPE reports the socket's type, SO_ERROR reads and clears the pending
        // error, SO_ACCEPTCONN whether it listens.
        let value: i32 = if level != libc::SOL_SOCKET {
            return unsafe { self.unmodelled_get(rec.as_ref(), level, name, val, len) };
        } else {
            match name {
                libc::SO_TYPE => match self.kind(fd) {
                    Some(Kind::Dgram) => libc::SOCK_DGRAM,
                    _ => libc::SOCK_STREAM,
                },
                libc::SO_BROADCAST => matches!(
                    self.socks.lock().unwrap().get(&fd),
                    Some(Sock::Dgram {
                        broadcast: true,
                        ..
                    })
                ) as i32,
                libc::SO_ERROR => rec
                    .and_then(|rec| rec.take_error_as(self.shared(), Taker::SoError))
                    .unwrap_or(0),
                libc::SO_REUSEADDR => {
                    socket_flag(rec.is_some_and(|rec| rec.opts().reuseaddr), name)
                }
                libc::SO_REUSEPORT => {
                    socket_flag(rec.is_some_and(|rec| rec.opts().reuseport), name)
                }
                libc::SO_ACCEPTCONN => (self.kind(fd) == Some(Kind::Listener)) as i32,
                _ => return unsafe { self.unmodelled_get(rec.as_ref(), level, name, val, len) },
            }
        };
        unsafe { write_opt(value, val, len) };
        ok(0)
    }

    /// Duplicates a descriptor, sharing its open file description.
    unsafe fn dup(&self, fd: c_int) -> Option<NetResult> {
        unsafe { Net::fcntl(self, fd, libc::F_DUPFD, 0) }
    }

    unsafe fn fcntl(&self, fd: c_int, cmd: c_int, arg: i64) -> Option<NetResult> {
        if cmd == libc::F_DUPFD || cmd == libc::F_DUPFD_CLOEXEC {
            let mut socks = self.socks.lock().unwrap();
            let sock = socks.get(&fd)?;
            let rec = sock.rec().cloned();
            let new_fd = snare_interpose::real(|| unsafe { libc::fcntl(fd, cmd, arg as c_int) });
            if new_fd < 0 {
                return err(io::Error::last_os_error()
                    .raw_os_error()
                    .unwrap_or(libc::EMFILE));
            }
            let stale = if socks.mirrors.contains_key(&new_fd) {
                self.notice_detach(&socks, new_fd);
                socks.remove(&new_fd)
            } else {
                None
            };
            socks.alias(fd, new_fd);
            if let Some(rec) = rec {
                self.shared().sockets.alias(new_fd, &rec);
            }
            drop(socks);
            if let Some(stale) = stale {
                self.retire_descriptor(new_fd, stale, None, None);
            }
            return ok(new_fd as i64);
        }
        if cmd == libc::F_GETFD || cmd == libc::F_SETFD {
            if !self.socks.lock().unwrap().contains_key(&fd) {
                return None;
            }
            let result = snare_interpose::real(|| unsafe { libc::fcntl(fd, cmd, arg as c_int) });
            return if result < 0 {
                err(io::Error::last_os_error()
                    .raw_os_error()
                    .unwrap_or(libc::EBADF))
            } else {
                ok(result as i64)
            };
        }
        if let Some(result) = unsafe { self.socket_fcntl(fd, cmd, arg) } {
            return Some(result);
        }
        let mut socks = self.socks.lock().unwrap();
        if matches!(socks.get(&fd)?, Sock::Epoll { .. } | Sock::Kqueue { .. }) {
            let status = &mut socks.description_mut(&fd).unwrap().status_flags;
            return match cmd {
                libc::F_GETFL => ok(*status as i64),
                libc::F_SETFL => {
                    *status = libc::O_RDWR | (arg as c_int & libc::O_NONBLOCK);
                    ok(0)
                }
                _ => err(libc::EINVAL),
            };
        }
        let nb = match socks.get_mut(&fd) {
            Some(Sock::Fresh { nonblocking, .. })
            | Some(Sock::Connecting { nonblocking, .. })
            | Some(Sock::Stream { nonblocking, .. })
            | Some(Sock::Listener { nonblocking, .. })
            | Some(Sock::Dgram { nonblocking, .. })
            | Some(Sock::UnixDgram { nonblocking, .. })
            | Some(Sock::Event { nonblocking, .. })
            | Some(Sock::Timer { nonblocking, .. })
            | Some(Sock::Signal { nonblocking, .. })
            | Some(Sock::Raw { nonblocking, .. }) => nonblocking,
            _ => return None,
        };
        // man 2 fcntl: F_GETFL/F_SETFL read/set the fd's status flags, F_GETFD/F_SETFD the
        // FD_CLOEXEC flag. A socket's file is opened O_RDWR (net/socket.c sock_alloc_file), so
        // F_GETFL reports that access mode. Besides O_NONBLOCK, F_SETFL keeps the flags
        // [`fcntl_cmd::KEPT_STATUS`] lists; Linux refuses O_DIRECT on a socket (fs/fcntl.c
        // setfl: no `direct_IO`).
        match cmd {
            libc::F_GETFL => {
                let nonblock = if *nb { libc::O_NONBLOCK } else { 0 };
                let kept = socks.description_mut(&fd).map_or(0, |d| d.fcntl.status);
                ok((libc::O_RDWR | nonblock | kept) as i64)
            }
            libc::F_SETFL => {
                let kept = match SocketFcntl::kept_status(arg) {
                    Ok(kept) => kept,
                    Err(errno) => return err(errno),
                };
                *nb = arg as c_int & libc::O_NONBLOCK != 0;
                if let Some(description) = socks.description_mut(&fd) {
                    description.fcntl.status = kept;
                }
                socks.publish_pair(fd);
                ok(0)
            }
            _ => err(libc::EINVAL),
        }
    }

    /// The interface queries of `ifreq` on any fd, then on the fabric's own sockets `FIONREAD`
    /// (bytes readable: a stream's unread bytes, man 7 tcp; a datagram socket's next datagram
    /// length on Linux, man 7 udp), Linux `SIOCOUTQ` (always 0), `FIONBIO` (set nonblocking
    /// mode from the pointed-to `int`: Linux fs/ioctl.c ioctl_fionbio; macOS `<sys/filio.h>`,
    /// `_IOW('f', 126, int)`), `FIOCLEX`/`FIONCLEX`, and Linux `SIOCGHWTSTAMP`/`SIOCSHWTSTAMP`
    /// ([`Fabric::hwtstamp_ioctl`]). Any other request on a fabric socket is recorded as
    /// unmodelled and succeeds with no effect, or fails with the host's code for an unknown
    /// request under `strict_sockopts`.
    unsafe fn ioctl(&self, fd: c_int, request: u64, arg: i64) -> Option<NetResult> {
        if let Some(r) = unsafe { self.nic_ioctl(request, arg) } {
            return Some(r);
        }
        if request as libc::c_ulong == FIONREAD || is_siocoutq(request as libc::c_ulong) {
            let rec = match self.socks.lock().unwrap().get(&fd) {
                Some(
                    sock @ (Sock::Stream { .. } | Sock::Dgram { .. } | Sock::UnixDgram { .. }),
                ) => sock.rec().cloned(),
                Some(_) => None,
                None => return None,
            };
            if arg == 0 {
                return err(libc::EFAULT);
            }
            let value = match rec {
                Some(rec) if request as libc::c_ulong == FIONREAD => rec.fionread(),
                _ => 0,
            };
            unsafe { (arg as *mut c_int).write_unaligned(value) };
            return ok(0);
        }
        let mut socks = self.socks.lock().unwrap();
        let nb = match socks.get_mut(&fd) {
            Some(Sock::Fresh { nonblocking, .. })
            | Some(Sock::Connecting { nonblocking, .. })
            | Some(Sock::Stream { nonblocking, .. })
            | Some(Sock::Listener { nonblocking, .. })
            | Some(Sock::Dgram { nonblocking, .. })
            | Some(Sock::UnixDgram { nonblocking, .. })
            | Some(Sock::Raw { nonblocking, .. }) => nonblocking,
            _ => return None,
        };
        // FIONBIO toggles nonblocking mode from a pointed-to int (fs/ioctl.c ioctl_fionbio).
        if request as libc::c_ulong == libc::FIONBIO {
            let on = unsafe { *(arg as *const c_int) };
            *nb = on != 0;
            socks.publish_pair(fd);
            return ok(0);
        }
        let rec = socks.get(&fd).and_then(Sock::rec).cloned();
        drop(socks);
        if [libc::FIOCLEX, libc::FIONCLEX].contains(&(request as libc::c_ulong)) {
            let result = snare_interpose::real(|| unsafe {
                libc::fcntl(
                    fd,
                    libc::F_SETFD,
                    if request as libc::c_ulong == libc::FIOCLEX {
                        libc::FD_CLOEXEC
                    } else {
                        0
                    },
                )
            });
            return if result < 0 {
                err(io::Error::last_os_error()
                    .raw_os_error()
                    .unwrap_or(libc::EBADF))
            } else {
                ok(result as i64)
            };
        }
        #[cfg(target_os = "linux")]
        if let Some(r) = unsafe { self.hwtstamp_ioctl(request, arg) } {
            return Some(r);
        }
        match rec {
            Some(rec)
                if self
                    .shared()
                    .unmodelled_option(&rec, UnmodelledOption::Ioctl { request }) =>
            {
                err(UNKNOWN_IOCTL)
            }
            _ => ok(0),
        }
    }

    /// The index of a simulated interface by name (man 3 if_nametoindex); an unknown name fails
    /// with `NAMETOINDEX_UNKNOWN`.
    unsafe fn if_nametoindex(&self, name: *const std::ffi::c_char) -> Option<NetResult> {
        if name.is_null() {
            return err(libc::EFAULT);
        }
        let name = unsafe { std::ffi::CStr::from_ptr(name) };
        match name.to_str().ok().and_then(|n| self.shared().nic(n)) {
            Some(nic) => ok(nic.index as i64),
            None => err(NAMETOINDEX_UNKNOWN),
        }
    }

    /// Writes the name of interface `index` into `name`, a caller buffer of at least
    /// `IF_NAMESIZE` (16) bytes, and returns that pointer; an unknown index is ENXIO (man 3
    /// if_indextoname). A longer name is cut to 15 bytes plus the NUL.
    unsafe fn if_indextoname(&self, index: u32, name: *mut std::ffi::c_char) -> Option<NetResult> {
        let found = self.shared().nics().into_iter().find(|n| n.index == index);
        let Some(nic) = found else {
            return err(libc::ENXIO);
        };
        let bytes = nic.spec.name.as_bytes();
        let n = bytes.len().min(libc::IF_NAMESIZE - 1);
        unsafe {
            std::ptr::copy_nonoverlapping(bytes.as_ptr(), name.cast::<u8>(), n);
            *name.add(n) = 0;
        }
        ok(name as i64)
    }

    /// The simulated interfaces as an `if_nameindex` array (man 3 if_nameindex), allocated by
    /// `ifaddrs` and freed by [`if_freenameindex`](Net::if_freenameindex).
    unsafe fn if_nameindex(&self) -> Option<NetResult> {
        match crate::ifaddrs::nameindex(self.shared().nics()) {
            Ok(ptr) => ok(ptr as i64),
            Err(errno) => err(errno),
        }
    }

    /// Frees an array from [`if_nameindex`](Net::if_nameindex); declines a pointer it did not
    /// allocate, so a real one reaches the OS.
    unsafe fn if_freenameindex(&self, ptr: *mut u8) -> Option<NetResult> {
        crate::ifaddrs::release(ptr).then_some(NetResult::Ok(0))
    }

    /// The simulated interfaces and their addresses as a `struct ifaddrs` list (man 3
    /// getifaddrs), built by `ifaddrs`.
    unsafe fn getifaddrs(&self, ifap: *mut *mut u8) -> Option<NetResult> {
        if ifap.is_null() {
            return err(libc::EFAULT);
        }
        match crate::ifaddrs::getifaddrs(self.shared().nics()) {
            Ok(head) => {
                unsafe { *ifap = head.cast() };
                ok(0)
            }
            Err(errno) => err(errno),
        }
    }

    /// Frees a list from [`getifaddrs`](Net::getifaddrs); declines one it did not allocate.
    unsafe fn freeifaddrs(&self, ifa: *mut u8) -> Option<NetResult> {
        crate::ifaddrs::release(ifa).then_some(NetResult::Ok(0))
    }

    /// `poll(2)` over a set holding the fabric's fds, the sim's other datagram sockets (a
    /// `SimHost`'s, [`foreign_ready`]) or a pipe the sim made; a set of real descriptors only,
    /// none of them the sim's pipes, is declined whole. The real descriptors in a set the fabric
    /// takes report what a zero-timeout `poll` of them reads, and a wait keeps a
    /// [`Watch`](crate::realfd::Watch) on them while it blocks. Connecting sockets are moved on
    /// before each check, so a nonblocking connect's POLLOUT appears when its attempt settles. An
    /// fd closed during the wait reports `POLLNVAL` (man 2 poll).
    unsafe fn poll(&self, fds: *mut u8, nfds: u64, timeout: c_int) -> Option<NetResult> {
        // man 2 poll: each pollfd has requested `events` and returned `revents`; a connected
        // stream is always writable (POLLOUT) and readable (POLLIN) once data or EOF is pending,
        // and POLLERR/POLLHUP are reported whether asked for or not. `timeout` is in ms, -1
        // blocking indefinitely. Only handle a poll set made entirely of our fds; otherwise decline
        // so the OS sees it.
        let pfds =
            unsafe { std::slice::from_raw_parts_mut(fds.cast::<libc::pollfd>(), nfds as usize) };
        let watched: Vec<(c_int, i16)> = pfds.iter().map(|p| (p.fd, p.events)).collect();
        let foreign = self.foreign_masks(watched.iter().map(|w| w.0));
        let real: Vec<(c_int, i16)> = watched
            .iter()
            .filter(|(fd, _)| {
                *fd >= 0
                    && foreign.iter().any(|(f, ready)| f == fd && ready.is_none())
                    && unsafe { libc::fcntl(*fd, libc::F_GETFD) } >= 0
            })
            .copied()
            .collect();
        let sim_fds = foreign.len() < watched.len() || foreign.iter().any(|(_, r)| r.is_some());
        if !real.is_empty()
            && !sim_fds
            && !real
                .iter()
                .any(|(fd, _)| self.shared().pipes.lent(*fd).is_some())
        {
            return None;
        }
        let fds: Vec<c_int> = watched.iter().map(|(fd, _)| *fd).collect();
        let mut waiting: Option<crate::realfd::Waiting> = None;
        let deadline = (timeout >= 0)
            .then(|| Deadline::timeout(std::time::Duration::from_millis(timeout as u64)));
        // A return that never blocked — fds already ready, or a zero timeout — is a busy-poll step
        // when repeated, so it is charged the call latency.
        let mut waited = false;
        let mut last = timeout == 0;
        loop {
            self.advance_connecting(Some(&fds));
            let revents = self.poll_revents(&watched, &foreign);
            let ready = revents.iter().filter(|r| **r != 0).count();
            if ready > 0 || last {
                for (p, r) in pfds.iter_mut().zip(revents) {
                    p.revents = r;
                }
                if !waited {
                    snare_interpose::charge_latency();
                }
                return ok(ready as i64);
            }
            if waiting.is_none() && !real.is_empty() {
                waiting =
                    crate::realfd::Watch::new(&real).map(|watch| watch.wait(&self.regs.shared));
            }
            let expiry = self.fds_timer_expiry(&fds);
            let timer = expiry.map(|at| self.timer_deadline(at));
            let (woke, interrupted) = snare_interpose::interruptible(Restart::Never, || {
                readiness().wait_until_dynamic(
                    "poll",
                    earlier(deadline, timer),
                    |keys| {
                        if let Some(waiting) = &waiting {
                            keys.push(waiting.watch().key());
                        }
                        self.fd_interests(fds.iter().copied(), keys)
                    },
                    || {
                        if let Some(waiting) = &waiting {
                            waiting.look();
                        }
                        self.poll_revents(&watched, &foreign)
                            .iter()
                            .any(|r| *r != 0)
                            || self.connecting_due(Some(&fds))
                            || self.fds_timer_expiry(&fds) != expiry
                    },
                )
            });
            if interrupted {
                return err(libc::EINTR);
            }
            last = !woke;
            if let (false, Some(at), Some(timer)) = (woke, expiry, timer)
                && timer.passed()
                && deadline.is_none_or(|d| !d.passed())
            {
                snare_interpose::expire_timer(at);
                last = false;
            }
            waited = true;
        }
    }

    unsafe fn select(
        &self,
        nfds: c_int,
        read: *mut u8,
        write: *mut u8,
        except: *mut u8,
        timeout: *const u8,
    ) -> Option<NetResult> {
        if nfds < 0 || nfds as usize > libc::FD_SETSIZE {
            return err(libc::EINVAL);
        }
        let sets = [read.cast::<libc::fd_set>(), write.cast(), except.cast()];
        let mut pfds = Vec::new();
        for fd in 0..nfds {
            let mut events = 0;
            for (set, event) in sets
                .iter()
                .zip([libc::POLLIN, libc::POLLOUT, libc::POLLPRI])
            {
                if !set.is_null() && unsafe { libc::FD_ISSET(fd, *set) } {
                    events |= event;
                }
            }
            if events != 0 {
                pfds.push(libc::pollfd {
                    fd,
                    events,
                    revents: 0,
                });
            }
        }
        if pfds
            .iter()
            .any(|p| unsafe { libc::fcntl(p.fd, libc::F_GETFD) } < 0)
        {
            return err(libc::EBADF);
        }
        let millis = if timeout.is_null() {
            -1
        } else {
            let tv = unsafe { timeout.cast::<libc::timeval>().read() };
            if tv.tv_sec < 0 || tv.tv_usec < 0 || tv.tv_usec >= 1_000_000 {
                return err(libc::EINVAL);
            }
            ((tv.tv_sec as u128 * 1000 + (tv.tv_usec as u128).div_ceil(1000))
                .min(c_int::MAX as u128)) as c_int
        };
        let result =
            unsafe { Net::poll(self, pfds.as_mut_ptr().cast(), pfds.len() as u64, millis) }?;
        if let NetResult::Err(_) = result {
            return Some(result);
        }
        for set in sets.into_iter().filter(|s| !s.is_null()) {
            unsafe { libc::FD_ZERO(set) };
        }
        let mut count = 0;
        for p in pfds {
            for (set, event) in sets
                .iter()
                .zip([libc::POLLIN, libc::POLLOUT, libc::POLLPRI])
            {
                if !set.is_null() && p.revents & event != 0 {
                    unsafe { libc::FD_SET(p.fd, *set) };
                    count += 1;
                }
            }
        }
        ok(count)
    }

    /// `read(2)` on a fabric fd: an eventfd's counter, a socket's `recv` with no flags, or a raw
    /// endpoint's next frame. EINVAL on an epoll or kqueue fd, as Linux's epoll file has no read
    /// operation (fs/eventpoll.c eventpoll_fops). A real kqueue fd gives ENXIO instead (XNU
    /// bsd/kern/kern_event.c kqueueops → fo_no_read), which is not modelled.
    unsafe fn read(&self, fd: c_int, buf: *mut u8, len: usize) -> Option<NetResult> {
        match self.kind(fd)? {
            Kind::Event => self.eventfd_read(fd, buf, len),
            #[cfg(target_os = "linux")]
            Kind::Timer => self.timerfd_read(fd, buf, len),
            #[cfg(target_os = "linux")]
            Kind::Signal => self.signalfd_read(fd, buf, len),
            Kind::Stream | Kind::Dgram | Kind::Fresh | Kind::Listener => unsafe {
                self.recv(fd, buf, len, 0)
            },
            Kind::Raw => self.raw_read(fd, buf, len),
            _ => err(libc::EINVAL),
        }
    }

    /// `write(2)` on a fabric fd: adds to an eventfd's counter, a socket's `send` with no flags,
    /// or a raw endpoint's frame. EINVAL on an epoll or kqueue fd (a real kqueue gives ENXIO,
    /// XNU fo_no_write; not modelled).
    unsafe fn write(&self, fd: c_int, buf: *const u8, len: usize) -> Option<NetResult> {
        match self.kind(fd)? {
            Kind::Event => self.eventfd_write(fd, buf, len),
            Kind::Stream | Kind::Dgram | Kind::Fresh | Kind::Listener => unsafe {
                self.send(fd, buf, len, 0)
            },
            Kind::Raw => self.raw_write(fd, buf, len),
            _ => err(libc::EINVAL),
        }
    }

    /// man 2 eventfd: a counting fd seeded with `initval`; EFD_NONBLOCK sets nonblocking mode and
    /// EFD_SEMAPHORE makes each read decrement by one (vs. draining the whole counter).
    #[cfg(target_os = "linux")]
    unsafe fn eventfd(&self, initval: u32, flags: c_int) -> Option<NetResult> {
        if flags & !(libc::EFD_NONBLOCK | libc::EFD_CLOEXEC | libc::EFD_SEMAPHORE) != 0 {
            return err(libc::EINVAL);
        }
        let nonblocking = flags & libc::EFD_NONBLOCK != 0;
        let semaphore = flags & libc::EFD_SEMAPHORE != 0;
        match self.reserve_fd_flags(flags) {
            Ok(fd) => {
                self.socks.lock().unwrap().insert(
                    fd,
                    Sock::Event {
                        ready_at: self.shared().tstamp_now().mono,
                        ready_order: readiness_sequence(),
                        counter: u64::from(initval),
                        nonblocking,
                        semaphore,
                        writes: 0,
                        reads: 0,
                    },
                );
                ok(fd as i64)
            }
            Err(e) => err(e.raw_os_error().unwrap_or(libc::EMFILE)),
        }
    }

    /// Waits for a blocking `read` of a pipe the sim made, read alone, as a `poll` of it would (see
    /// [`await_real`](Self::await_real)); any other descriptor, or one in nonblocking mode, is
    /// left to the OS.
    fn await_readable(&self, fd: c_int) -> Option<NetResult> {
        self.await_pipe(fd, libc::O_RDONLY, libc::POLLIN, "pipe read")
    }

    /// Waits for child process `pid` to end through a descriptor that turns readable then
    /// ([`child_probe`](crate::realfd::child_probe)), as [`await_real`](Self::await_real).
    fn await_child(&self, pid: c_int) -> Option<NetResult> {
        let probe = snare_interpose::real(|| crate::realfd::child_probe(pid));
        if probe < 0 {
            return None;
        }
        let r = self.await_real(probe, libc::POLLIN, "waitpid");
        // SAFETY: the probe made above.
        snare_interpose::real(|| unsafe { libc::close(probe) });
        r
    }

    /// Waits for a blocking `write` or `writev` of a pipe the sim made to find room, as a `poll`
    /// of it would (see [`await_real`](Self::await_real)); any other descriptor, or one in
    /// nonblocking mode, is left to the OS.
    fn await_writable(&self, fd: c_int) -> Option<NetResult> {
        self.await_pipe(fd, libc::O_WRONLY, libc::POLLOUT, "pipe write")
    }

    /// Waits for one of the children `children` lists to end, through a probe of each
    /// ([`child_probe`](crate::realfd::child_probe)) held in one
    /// [`Watch`](crate::realfd::Watch), as [`await_real`](Self::await_real) waits. The list is
    /// asked again each time the wait looks, which a child the sim spawns meanwhile makes it do
    /// ([`spawned`](Net::spawned)).
    fn await_children(
        &self,
        children: &mut dyn FnMut() -> Vec<c_int>,
        ready: &mut dyn FnMut() -> bool,
    ) -> Option<NetResult> {
        if ready() {
            return ok(0);
        }
        let watch = crate::realfd::Watch::new(&[])?;
        let mut probes: Vec<(c_int, c_int)> = Vec::new();
        let mut refresh = |probes: &mut Vec<(c_int, c_int)>| {
            let pids = children();
            let mut gone = Vec::new();
            probes.retain(|&(pid, probe)| {
                let keep = pids.contains(&pid);
                if !keep {
                    gone.push(probe);
                }
                keep
            });
            for pid in pids {
                if !probes.iter().any(|&(held, _)| held == pid) {
                    let probe = snare_interpose::real(|| crate::realfd::child_probe(pid));
                    if probe >= 0 {
                        probes.push((pid, probe));
                    }
                }
            }
            let watched: Vec<(c_int, i16)> = probes
                .iter()
                .map(|&(_, probe)| (probe, libc::POLLIN))
                .collect();
            watch.set(&watched);
            for probe in gone {
                // SAFETY: a probe made here, no longer watched.
                snare_interpose::real(|| unsafe { libc::close(probe) });
            }
        };
        refresh(&mut probes);
        let waiting = watch.wait(&self.regs.shared);
        let (woke, interrupted) = snare_interpose::interruptible(Restart::WithSaRestart, || {
            readiness().wait_until_dynamic(
                "wait",
                None,
                |keys| {
                    keys.push(waiting.watch().key());
                    false
                },
                || {
                    waiting.look();
                    if ready() {
                        return true;
                    }
                    refresh(&mut probes);
                    ready()
                },
            )
        });
        drop(waiting);
        drop(watch);
        for (_, probe) in probes {
            // SAFETY: a probe made here.
            snare_interpose::real(|| unsafe { libc::close(probe) });
        }
        if interrupted {
            return err(libc::EINTR);
        }
        woke.then(|| ok(0)).flatten()
    }

    /// man 2 signalfd: with `fd` -1 a new descriptor reading the signals of `mask` (the caller's
    /// set's virtual signals), with `SFD_NONBLOCK`/`SFD_CLOEXEC`; with a signalfd of the sim's, its
    /// set replaced by `mask`. EINVAL for other flags (checked first, fs/signalfd.c
    /// `do_signalfd4`) and for an `fd` of the sim's that is no signalfd. A new set of none of the
    /// sim's signals, or an `fd` not the sim's, is the OS's.
    #[cfg(target_os = "linux")]
    unsafe fn signalfd(&self, fd: c_int, mask: u64, flags: c_int) -> Option<NetResult> {
        let invalid = flags & !(libc::SFD_NONBLOCK | libc::SFD_CLOEXEC) != 0;
        if fd != -1 {
            let mut socks = self.socks.lock().unwrap();
            let sock = socks.get_mut(&fd)?;
            if invalid {
                return err(libc::EINVAL);
            }
            let Sock::Signal { mask: set, .. } = sock else {
                return err(libc::EINVAL);
            };
            *set = mask;
            drop(socks);
            self.bump_fds([fd]);
            return ok(fd as i64);
        }
        if mask == 0 {
            return None;
        }
        if invalid {
            return err(libc::EINVAL);
        }
        match self.reserve_fd_flags(flags) {
            Ok(fd) => {
                self.socks.lock().unwrap().insert(
                    fd,
                    Sock::Signal {
                        mask,
                        nonblocking: flags & libc::SFD_NONBLOCK != 0,
                    },
                );
                ok(fd as i64)
            }
            Err(e) => err(e.raw_os_error().unwrap_or(libc::EMFILE)),
        }
    }

    /// man 2 epoll_create1: creates an epoll instance and returns an fd referring to it.
    #[cfg(target_os = "linux")]
    unsafe fn epoll_create1(&self, flags: c_int) -> Option<NetResult> {
        if flags & !libc::EPOLL_CLOEXEC != 0 {
            return err(libc::EINVAL);
        }
        match self.reserve_fd_flags(flags) {
            Ok(fd) => {
                let interests = PollSet::new();
                let list = interests.list().clone();
                let mut socks = self.socks.lock().unwrap();
                socks.insert(
                    fd,
                    Sock::Epoll {
                        interests,
                        real: None,
                    },
                );
                if let Some(id) = socks.identity(fd) {
                    list.place(id, self.shared().domain_key());
                }
                ok(fd as i64)
            }
            Err(e) => err(e.raw_os_error().unwrap_or(libc::EMFILE)),
        }
    }

    /// Adds, changes or removes an open file description's interest in epoll set `epfd`.
    #[cfg(target_os = "linux")]
    unsafe fn epoll_ctl(
        &self,
        epfd: c_int,
        op: c_int,
        fd: c_int,
        event: *const u8,
    ) -> Option<NetResult> {
        let mut socks = self.socks.lock().unwrap();
        if !socks.contains_key(&epfd) {
            return None;
        }
        if !socks.contains_key(&fd) && snare_interpose::minted_socket(fd) {
            drop(socks);
            // SAFETY: no pointers are involved.
            unsafe { Net::mirror(self, fd) };
            socks = self.socks.lock().unwrap();
        }
        if unsafe { libc::fcntl(fd, libc::F_GETFD) } < 0 {
            return err(libc::EBADF);
        }
        if fd == epfd {
            return err(libc::EINVAL);
        }
        let identity = socks
            .identity(fd)
            .map(EpollIdentity::Local)
            .unwrap_or_else(|| {
                self.shared()
                    .sockets
                    .lookup_fd(fd)
                    .map_or(EpollIdentity::Untracked, |rec| {
                        EpollIdentity::Foreign(rec.id.get())
                    })
            });
        if identity == EpollIdentity::Untracked && !real_pollable(fd) {
            return err(libc::EPERM);
        }
        if matches!(identity, EpollIdentity::Local(id) if Some(id) == socks.identity(epfd)) {
            return err(libc::EINVAL);
        }
        let keys = match identity {
            EpollIdentity::Local(id) => socks
                .get(&fd)
                .map_or_else(Keys::default, |sock| description_keys(id, sock)),
            EpollIdentity::Foreign(id) => {
                Keys::of(Some(crate::readiness::WakeKey::Socket(id)), None)
            }
            EpollIdentity::Untracked => Keys::default(),
        };
        let Some(Sock::Epoll { interests, .. }) = socks.get_mut(&epfd) else {
            return err(libc::EINVAL);
        };
        let key = (fd, identity);
        match op {
            libc::EPOLL_CTL_ADD | libc::EPOLL_CTL_MOD => {
                if op == libc::EPOLL_CTL_ADD && interests.contains_key(&key) {
                    return err(libc::EEXIST);
                }
                if op == libc::EPOLL_CTL_MOD && !interests.contains_key(&key) {
                    return err(libc::ENOENT);
                }
                if event.is_null() {
                    return err(libc::EFAULT);
                }
                let ev = unsafe { std::ptr::read_unaligned(event.cast::<libc::epoll_event>()) };
                interests.insert(
                    key,
                    EpollInterest {
                        events: ev.events,
                        data: ev.u64,
                        edge: Edge::default(),
                        spent: false,
                        order: readiness_sequence(),
                        pending_order: None,
                    },
                    keys,
                );
            }
            libc::EPOLL_CTL_DEL => {
                if interests.remove(&key).is_none() {
                    return err(libc::ENOENT);
                }
            }
            _ => return err(libc::EINVAL),
        }
        drop(socks);
        if identity == EpollIdentity::Untracked {
            self.rewatch_epoll(epfd);
        }
        self.bump_fds([epfd]);
        ok(0)
    }

    /// man 2 epoll_wait: fills up to `maxevents` ready epoll_event structs; `timeout` in ms, -1
    /// blocks indefinitely, 0 returns at once. Returns the number of ready fds (0 on timeout).
    #[cfg(target_os = "linux")]
    unsafe fn epoll_wait(
        &self,
        epfd: c_int,
        events: *mut u8,
        maxevents: c_int,
        timeout: c_int,
    ) -> Option<NetResult> {
        let timeout = (timeout >= 0).then(|| Duration::from_millis(timeout as u64));
        unsafe { self.epoll_wait_for(epfd, events, maxevents, timeout) }
    }

    /// man 2 epoll_pwait2: `epoll_wait` with a timespec timeout; EINVAL for a negative or
    /// out-of-range one (fs/eventpoll.c `poll_select_set_timeout`).
    #[cfg(target_os = "linux")]
    unsafe fn epoll_pwait2(
        &self,
        epfd: c_int,
        events: *mut u8,
        maxevents: c_int,
        timeout: *const u8,
    ) -> Option<NetResult> {
        if !Net::owns(self, epfd) {
            return None;
        }
        let timeout = if timeout.is_null() {
            None
        } else {
            let ts = unsafe { std::ptr::read_unaligned(timeout.cast::<libc::timespec>()) };
            match timespec_span(&ts) {
                Some(span) => Some(span),
                None => return err(libc::EINVAL),
            }
        };
        unsafe { self.epoll_wait_for(epfd, events, maxevents, timeout) }
    }

    /// man 2 timerfd_create: CLOCK_REALTIME, CLOCK_MONOTONIC or CLOCK_BOOTTIME, with
    /// TFD_NONBLOCK/TFD_CLOEXEC; EINVAL for other flags or clocks. The alarm clocks need
    /// CAP_WAKE_ALARM (fs/timerfd.c `timerfd_create`), which a sim's process lacks: EPERM.
    #[cfg(target_os = "linux")]
    unsafe fn timerfd_create(&self, clockid: c_int, flags: c_int) -> Option<NetResult> {
        if flags & !(libc::TFD_NONBLOCK | libc::TFD_CLOEXEC) != 0 {
            return err(libc::EINVAL);
        }
        match clockid {
            libc::CLOCK_REALTIME | libc::CLOCK_MONOTONIC | libc::CLOCK_BOOTTIME => {}
            libc::CLOCK_REALTIME_ALARM | libc::CLOCK_BOOTTIME_ALARM => return err(libc::EPERM),
            _ => return err(libc::EINVAL),
        }
        match self.reserve_fd_flags(flags) {
            Ok(fd) => {
                self.socks.lock().unwrap().insert(
                    fd,
                    Sock::Timer {
                        clock: clockid,
                        expires: None,
                        interval: Duration::ZERO,
                        ticks: 0,
                        expired: 0,
                        nonblocking: flags & libc::TFD_NONBLOCK != 0,
                    },
                );
                ok(fd as i64)
            }
            Err(e) => err(e.raw_os_error().unwrap_or(libc::EMFILE)),
        }
    }

    /// man 2 timerfd_settime: a zero `it_value` disarms, anything else arms the timer to expire
    /// that long from now (or at that time on its clock with TFD_TIMER_ABSTIME), then every
    /// `it_interval`. Arming or disarming discards unread expirations (fs/timerfd.c
    /// `timerfd_setup` zeroes `ticks`). `old_value` receives the setting replaced, as
    /// `timerfd_gettime` would have read it.
    #[cfg(target_os = "linux")]
    unsafe fn timerfd_settime(
        &self,
        fd: c_int,
        flags: c_int,
        new_value: *const u8,
        old_value: *mut u8,
    ) -> Option<NetResult> {
        let now = self.shared().monotonic_now();
        let mut socks = self.socks.lock().unwrap();
        socks.settle_timers(now);
        let Sock::Timer {
            clock,
            expires,
            interval,
            ticks,
            ..
        } = socks.get_mut(&fd)?
        else {
            return err(libc::EINVAL);
        };
        if flags & !(libc::TFD_TIMER_ABSTIME | libc::TFD_TIMER_CANCEL_ON_SET) != 0 {
            return err(libc::EINVAL);
        }
        if new_value.is_null() {
            return err(libc::EFAULT);
        }
        let new = unsafe { std::ptr::read_unaligned(new_value.cast::<libc::itimerspec>()) };
        let (Some(value), Some(reload)) = (
            timespec_span(&new.it_value),
            timespec_span(&new.it_interval),
        ) else {
            return err(libc::EINVAL);
        };
        if !old_value.is_null() {
            let old = itimerspec(expires.map(|at| at.saturating_sub(now)), *interval);
            unsafe { std::ptr::write_unaligned(old_value.cast::<libc::itimerspec>(), old) };
        }
        *ticks = 0;
        *interval = reload;
        *expires = (!value.is_zero()).then(|| {
            if flags & libc::TFD_TIMER_ABSTIME == 0 {
                now.saturating_add(value)
            } else if *clock == libc::CLOCK_REALTIME {
                let real = self.shared().tstamp_now().real;
                match value.checked_sub(real) {
                    Some(ahead) => now.saturating_add(ahead),
                    None => now.saturating_sub(real - value),
                }
            } else {
                value
            }
        });
        drop(socks);
        self.bump_fds([fd]);
        ok(0)
    }

    /// man 2 timerfd_gettime: the time left to the next expiry (zero while disarmed) and the
    /// interval.
    #[cfg(target_os = "linux")]
    unsafe fn timerfd_gettime(&self, fd: c_int, curr_value: *mut u8) -> Option<NetResult> {
        let now = self.shared().monotonic_now();
        let mut socks = self.socks.lock().unwrap();
        socks.settle_timers(now);
        let Sock::Timer {
            expires, interval, ..
        } = socks.get(&fd)?
        else {
            return err(libc::EINVAL);
        };
        if curr_value.is_null() {
            return err(libc::EFAULT);
        }
        let current = itimerspec(expires.map(|at| at.saturating_sub(now)), *interval);
        unsafe { std::ptr::write_unaligned(curr_value.cast::<libc::itimerspec>(), current) };
        ok(0)
    }

    /// man 2 kqueue: a new kernel event queue.
    #[cfg(target_os = "macos")]
    unsafe fn kqueue(&self) -> Option<NetResult> {
        match self.reserve_fd() {
            Ok(fd) => {
                let state = KqueueState::default();
                let list = state.notes.list().clone();
                let mut socks = self.socks.lock().unwrap();
                socks.insert(
                    fd,
                    Sock::Kqueue {
                        state: Arc::new(Mutex::new(state)),
                    },
                );
                if let Some(id) = socks.identity(fd) {
                    list.place(id, self.shared().domain_key());
                }
                ok(fd as i64)
            }
            Err(e) => err(e.raw_os_error().unwrap_or(libc::EMFILE)),
        }
    }

    /// Applies `changelist` to kqueue `kq`, then waits for up to `nevents` ready events (man 2
    /// kevent). Only `EVFILT_READ`, `EVFILT_WRITE` and `EVFILT_USER` are modelled; other filters
    /// are accepted and never fire. A registration is level-triggered unless added with
    /// `EV_CLEAR` (see [`Edge`]); `EV_ONESHOT` deletes it once reported, `EV_DISPATCH` disables
    /// it once reported, and `EV_DISABLE`/`EV_ENABLE` turn it off and on. Adding a registration
    /// that exists updates its `udata` and reports it again if it is ready, as XNU
    /// bsd/kern/kern_event.c `kevent_register` re-runs the filter's `f_touch` and activates the
    /// knote when that fires. With any `EV_RECEIPT` change the call
    /// returns only the receipts, without waiting: XNU bsd/kern/kern_event.c kevent_internal
    /// scans for events only when `noutputs == 0`. A real descriptor the fabric does not serve
    /// registers with the errno the OS's kqueue would give it (`real_pollable`) and reports the
    /// OS's readiness (`real_kevent`) until it is closed; another sim's socket is served as a
    /// connection that is gone ([`Fabric::mirror_dead`]), and any other descriptor of another
    /// sim is EBADF.
    #[cfg(target_os = "macos")]
    unsafe fn kevent(
        &self,
        kq: c_int,
        changelist: *const u8,
        nchanges: c_int,
        eventlist: *mut u8,
        nevents: c_int,
        timeout: *const u8,
    ) -> Option<NetResult> {
        let state = {
            let socks = self.socks.lock().unwrap();
            match socks.get(&kq) {
                Some(Sock::Kqueue { state }) => state.clone(),
                _ => return None,
            }
        };
        for i in 0..nchanges.max(0) as usize {
            let ch = unsafe { changelist.cast::<libc::kevent>().add(i).read_unaligned() };
            let fd = ch.ident as c_int;
            if matches!(ch.filter, libc::EVFILT_READ | libc::EVFILT_WRITE)
                && !Net::owns(self, fd)
                && snare_interpose::minted_socket(fd)
            {
                // SAFETY: no pointers are involved.
                unsafe { Net::mirror(self, fd) };
            }
        }
        // Apply the changelist, collecting any EV_RECEIPT acknowledgements to return at once.
        let targets: Vec<(Result<bool, c_int>, Keys)> = {
            let socks = self.socks.lock().unwrap();
            (0..nchanges.max(0) as usize)
                .map(|i| {
                    let ch = unsafe { changelist.cast::<libc::kevent>().add(i).read_unaligned() };
                    let fd = ch.ident as c_int;
                    let keys = match (socks.identity(fd), socks.get(&fd)) {
                        (Some(id), Some(sock)) => description_keys(id, sock),
                        _ => Keys::default(),
                    };
                    let target = if !matches!(ch.filter, libc::EVFILT_READ | libc::EVFILT_WRITE)
                        || socks.contains_key(&fd)
                    {
                        Ok(false)
                    } else if snare_interpose::minted(fd) {
                        Err(libc::EBADF)
                    } else if ch.flags & libc::EV_ADD != 0 {
                        real_pollable(fd, ch.filter).map(|()| true)
                    } else if unsafe { libc::fcntl(fd, libc::F_GETFD) } < 0 {
                        Err(libc::ENOENT)
                    } else {
                        Ok(true)
                    };
                    (target, keys)
                })
                .collect()
        };
        let mut receipts: Vec<libc::kevent> = Vec::new();
        let mut plain_error = None;
        let mut changed = false;
        {
            let mut guard = state.lock().unwrap();
            let KqueueState { notes, users, .. } = &mut *guard;
            for (i, &(target, keys)) in targets.iter().enumerate() {
                // `kevent` is a packed struct (`#pragma pack(4)` in <sys/event.h>,
                // `repr(packed(4))` in libc); read each entry by value to avoid unaligned refs.
                let ch = unsafe { changelist.cast::<libc::kevent>().add(i).read_unaligned() };
                let ident = ch.ident;
                let filter = ch.filter;
                let flags = ch.flags;
                let fflags = ch.fflags;
                let udata = ch.udata as u64;
                let adding = flags & libc::EV_ADD != 0;
                let deleting = flags & libc::EV_DELETE != 0;
                let kept =
                    flags & (libc::EV_ADD | libc::EV_CLEAR | libc::EV_ONESHOT | libc::EV_DISPATCH);
                let toggle = |disabled: &mut bool| {
                    if flags & libc::EV_DISABLE != 0 {
                        *disabled = true;
                    }
                    if flags & libc::EV_ENABLE != 0 {
                        *disabled = false;
                    }
                };
                let exists = match filter {
                    libc::EVFILT_READ | libc::EVFILT_WRITE => {
                        notes.contains_key(&(filter, ident as c_int))
                    }
                    libc::EVFILT_USER => users.contains_key(&ident),
                    _ => false,
                };
                let change_error = if let Err(errno) = target {
                    errno
                } else if !adding && !exists {
                    libc::ENOENT
                } else {
                    0
                };
                if change_error != 0 && flags & libc::EV_RECEIPT == 0 {
                    if nevents > receipts.len() as c_int {
                        let mut ev = ch;
                        ev.flags |= libc::EV_ERROR;
                        ev.data = change_error as _;
                        receipts.push(ev);
                    } else {
                        plain_error.get_or_insert(change_error);
                    }
                }
                if change_error == 0 {
                    changed |= matches!(
                        filter,
                        libc::EVFILT_READ | libc::EVFILT_WRITE | libc::EVFILT_USER
                    );
                    match filter {
                        libc::EVFILT_READ | libc::EVFILT_WRITE => {
                            let at = (filter, ident as c_int);
                            if deleting {
                                notes.remove(&at);
                            } else {
                                let mut note = notes.get(&at).copied();
                                if adding {
                                    let untracked = target == Ok(true);
                                    let note = note.get_or_insert(Knote {
                                        udata,
                                        flags: kept,
                                        disabled: false,
                                        edge: Edge::default(),
                                        untracked,
                                        generation: 0,
                                    });
                                    if note.untracked != untracked {
                                        note.flags = kept;
                                        note.disabled = false;
                                        note.untracked = untracked;
                                    }
                                    note.udata = udata;
                                    note.edge = Edge::default();
                                    note.generation = next_knote_generation();
                                }
                                if let Some(mut note) = note {
                                    toggle(&mut note.disabled);
                                    notes.insert(at, note, keys);
                                }
                            }
                        }
                        libc::EVFILT_USER => {
                            if deleting {
                                users.remove(&ident);
                            } else {
                                let note = users.entry(ident).or_insert(UserNote {
                                    udata,
                                    flags: kept,
                                    disabled: false,
                                    triggered: false,
                                });
                                if adding {
                                    note.udata = udata;
                                }
                                toggle(&mut note.disabled);
                                // NOTE_TRIGGER fires the user event (mio's Waker).
                                if fflags & libc::NOTE_TRIGGER != 0 {
                                    note.triggered = true;
                                }
                            }
                        }
                        _ => {}
                    }
                }
                // kevent(2) EV_RECEIPT: the change is echoed back with EV_ERROR set and `data` 0
                // for success.
                if flags & libc::EV_RECEIPT != 0 {
                    let mut ev = ch;
                    ev.flags = flags | libc::EV_ERROR;
                    ev.data = change_error as _;
                    receipts.push(ev);
                }
            }
        }
        if changed {
            let mut guard = state.lock().unwrap();
            let real: Vec<(c_int, i16)> = guard
                .notes
                .iter()
                .filter(|(_, n)| n.untracked)
                .map(|(&(filter, fd), _)| {
                    let events = if filter == libc::EVFILT_READ {
                        libc::POLLIN
                    } else {
                        libc::POLLOUT
                    };
                    (fd, events)
                })
                .collect();
            Self::watch_set(&mut guard.real, &real);
            drop(guard);
            self.bump_fds([kq]);
        }
        if let Some(errno) = plain_error {
            return err(errno);
        }
        let cap = nevents.max(0) as usize;
        // EV_RECEIPT acknowledgements return immediately, before any wait.
        if !receipts.is_empty() {
            let n = receipts.len().min(cap);
            for (i, ev) in receipts.iter().take(n).enumerate() {
                unsafe { std::ptr::write_unaligned(eventlist.cast::<libc::kevent>().add(i), *ev) };
            }
            return ok(n as i64);
        }
        if cap == 0 {
            return ok(0);
        }
        let deadline = unsafe { kevent_deadline(timeout) };
        let zero_timeout = !timeout.is_null()
            && unsafe {
                let span = timeout.cast::<libc::timespec>().read_unaligned();
                span.tv_sec == 0 && span.tv_nsec == 0
            };
        // As for epoll_wait: a return that never blocked is charged the call latency.
        let immediate = deadline.is_some_and(|d| d.passed());
        let mut waited = false;
        let waiting = std::cell::RefCell::new(None);
        let _waiting = snare_interpose::fd_wait(kq);
        loop {
            if !Net::owns(self, kq) {
                return None;
            }
            self.advance_connecting(None);
            let ready = self.collect_kevents(kq, cap, true);
            if !ready.is_empty() {
                if !waited {
                    snare_interpose::charge_latency();
                }
                for (i, ev) in ready.iter().enumerate() {
                    unsafe {
                        std::ptr::write_unaligned(eventlist.cast::<libc::kevent>().add(i), *ev)
                    };
                }
                return ok(ready.len() as i64);
            }
            if zero_timeout {
                snare_interpose::end_spin();
                if self.connecting_due(None) {
                    waited = true;
                    continue;
                }
                snare_interpose::charge_latency();
                return ok(0);
            }
            let (woke, interrupted) = snare_interpose::interruptible(Restart::Never, || {
                readiness().wait_until_dynamic(
                    "kevent",
                    deadline,
                    |keys| {
                        if let Some(key) = self.wait_real(&waiting, self.kqueue_watch(kq)) {
                            keys.push(key);
                        }
                        self.kqueue_interests(kq, keys)
                    },
                    || {
                        if let Some(waiting) = &*waiting.borrow() {
                            waiting.look();
                        }
                        !Net::owns(self, kq)
                            || !self.collect_kevents(kq, 1, false).is_empty()
                            || self.connecting_due(None)
                    },
                )
            });
            if !Net::owns(self, kq) {
                return None;
            }
            if interrupted {
                return err(libc::EINTR);
            }
            if !woke {
                if immediate {
                    snare_interpose::charge_latency();
                }
                return ok(0);
            }
            waited = true;
        }
    }
}

/// The peer side of a connection, driven by a tester on a managed thread. Each runs under
/// passthrough like the rest of the fabric: a wait on one of the fabric's own locks is the sim's
/// business, not a blocked thread, and counting it toward quiescence could make a socket wait
/// holding that lock mistake the domain for deadlocked.
impl Conn {
    /// Writes what the window has room for; 0 once the stream is closed.
    pub(crate) fn write_from_peer(&self, bytes: &[u8]) -> usize {
        snare_interpose::real(|| self.write(End::B, bytes).unwrap_or(0))
    }

    /// Whether a peer's write of `len` bytes would take some of them, or fail at once.
    pub(crate) fn peer_can_write(&self, len: usize) -> bool {
        snare_interpose::real(|| {
            #[cfg(target_os = "macos")]
            self.progress_tcp_shutdown();
            self.write_pipe(End::B).can_write(len)
        })
    }

    /// Reads what the code under test has sent: `Ok(0)` at end of stream, `WouldBlock` when
    /// nothing has arrived yet (or the tester shut its reading side), `ConnectionReset` after a
    /// reset.
    pub(crate) fn read_from_peer(&self, out: &mut [u8]) -> io::Result<usize> {
        snare_interpose::real(|| {
            #[cfg(target_os = "macos")]
            self.progress_tcp_shutdown();
            match self.read_pipe(End::B).read(out) {
                Read::Data(n) => {
                    self.took(End::B, n);
                    Ok(n)
                }
                Read::Eof => Ok(0),
                Read::Reset => Err(io::ErrorKind::ConnectionReset.into()),
                Read::WouldBlock | Read::Shut => Err(io::ErrorKind::WouldBlock.into()),
            }
        })
    }

    /// Closes the peer's sending side (a FIN): the code under test reads end of stream once the
    /// bytes already written have arrived.
    pub(crate) fn close_peer(&self) {
        snare_interpose::real(|| self.close(End::B));
    }

    /// Aborts the connection with a reset (RST): the code under test's next read or write fails
    /// with ECONNRESET.
    pub(crate) fn reset_peer(&self) {
        snare_interpose::real(|| self.reset(End::B));
    }

    /// Whether the connection was reset. A reset hits both pipes at once, so one tells.
    fn is_reset(&self) -> bool {
        self.a_to_b.is_reset()
    }

    /// Whether the peer has bytes to read or has seen the code under test close its end.
    pub(crate) fn peer_readable(&self) -> bool {
        snare_interpose::real(|| {
            #[cfg(target_os = "macos")]
            self.progress_tcp_shutdown();
            self.read_pipe(End::B).readable_or_closed()
        })
    }
}

/// The loopback address of `domain`'s family; callers use it only for the family, via
/// [`unspecified_like`].
fn loopback_for(domain: c_int) -> IpAddr {
    if domain == libc::AF_INET6 {
        IpAddr::V6(Ipv6Addr::LOCALHOST)
    } else {
        IpAddr::V4(Ipv4Addr::LOCALHOST)
    }
}

/// A ready event for `ident` on `filter`, carrying the caller's `udata`, with no flags or data.
#[cfg(target_os = "macos")]
fn make_kevent(ident: usize, filter: i16, udata: u64) -> libc::kevent {
    libc::kevent {
        ident,
        filter,
        flags: 0,
        fflags: 0,
        data: 0,
        udata: udata as *mut libc::c_void,
    }
}

/// A `kevent` timeout (`*const timespec`) as a deadline: null blocks indefinitely, `{0,0}` is an
/// already-passed deadline (a non-blocking poll), per man 2 kevent. Negative fields count as 0.
#[cfg(target_os = "macos")]
unsafe fn kevent_deadline(timeout: *const u8) -> Option<Deadline> {
    if timeout.is_null() {
        return None;
    }
    let ts = unsafe { timeout.cast::<libc::timespec>().read() };
    let d = std::time::Duration::new(ts.tv_sec.max(0) as u64, ts.tv_nsec.max(0) as u32);
    Some(Deadline::timeout(d))
}

/// Reads a C `int` option value (SO_BROADCAST et al.), zero if the buffer is null or too short.
pub(crate) unsafe fn read_int(val: *const u8, len: u32) -> c_int {
    if val.is_null() || (len as usize) < size_of::<c_int>() {
        return 0;
    }
    unsafe { val.cast::<c_int>().read_unaligned() }
}

/// Reads a `struct timeval` option value (SO_RCVTIMEO), `None` if the buffer is null or too short.
/// A negative `tv_sec` counts as 0 and a negative `tv_usec` as 0; `tv_usec` is otherwise taken
/// modulo one second. Linux's net/core/sock.c sock_set_timeout rejects an out-of-range `tv_usec`
/// with EDOM and turns a negative `tv_sec` into a zero (immediate) timeout; neither is modelled.
pub(crate) unsafe fn parse_timeval(val: *const u8, len: u32) -> Option<std::time::Duration> {
    if val.is_null() || (len as usize) < size_of::<libc::timeval>() {
        return None;
    }
    let tv = unsafe { val.cast::<libc::timeval>().read_unaligned() };
    let usecs = u64::try_from(tv.tv_usec).unwrap_or(0);
    Some(std::time::Duration::new(
        tv.tv_sec.max(0) as u64,
        (usecs % 1_000_000) as u32 * 1_000,
    ))
}

/// Writes a `struct timeval` option value back out (getsockopt SO_RCVTIMEO), clamped to the
/// caller's buffer; a null buffer or length is a no-op.
pub(crate) unsafe fn write_timeval(d: std::time::Duration, val: *mut u8, len: *mut u32) {
    if val.is_null() || len.is_null() || (unsafe { *len } as usize) < size_of::<libc::timeval>() {
        return;
    }
    let tv = libc::timeval {
        tv_sec: d.as_secs() as libc::time_t,
        tv_usec: d.subsec_micros() as libc::suseconds_t,
    };
    unsafe {
        val.cast::<libc::timeval>().write_unaligned(tv);
        *len = size_of::<libc::timeval>() as u32;
    }
}

/// The IPv6 "join a multicast group" setsockopt name. `libc` spells it `IPV6_JOIN_GROUP` (the
/// POSIX name, `<netinet/in.h>`) on the BSDs/macOS and `IPV6_ADD_MEMBERSHIP`
/// (IPV6_ADD_MEMBERSHIP(2const)) on Linux, where glibc defines both
/// (sysdeps/unix/sysv/linux/bits/in.h). The values differ per
/// OS — 20 on Linux (include/uapi/linux/in6.h), 12 on macOS (XNU bsd/netinet6/in6.h) — but the
/// `ipv6_mreq` payload is the same.
#[cfg(target_os = "linux")]
const IPV6_JOIN: c_int = libc::IPV6_ADD_MEMBERSHIP;
#[cfg(not(target_os = "linux"))]
const IPV6_JOIN: c_int = libc::IPV6_JOIN_GROUP;
#[cfg(target_os = "linux")]
const IPV6_LEAVE: c_int = libc::IPV6_DROP_MEMBERSHIP;
#[cfg(not(target_os = "linux"))]
const IPV6_LEAVE: c_int = libc::IPV6_LEAVE_GROUP;

/// If `(level, name)` is an `IP_ADD_MEMBERSHIP`/`IPV6_ADD_MEMBERSHIP`, reads the membership out of
/// the request the caller passed. IP_ADD_MEMBERSHIP(2const): `struct ip_mreq { imr_multiaddr;
/// imr_interface; }`, or on Linux `struct ip_mreqn`, which appends `int imr_ifindex`
/// (ip_mreqn(2type)); IPV6_ADD_MEMBERSHIP(2const):
/// `struct ipv6_mreq { ipv6mr_multiaddr; unsigned ipv6mr_interface; }`.
///
/// Offsets: `ip_mreq` is two 4-byte `in_addr`s (group at 0, interface at 4), and Linux tells an
/// `ip_mreqn` by its 12-byte length (`imr_ifindex` at 8; net/ipv4/ip_sockglue.c
/// do_ip_setsockopt checks `optlen >= sizeof(struct ip_mreqn)`). `ipv6_mreq` is a 16-byte
/// `in6_addr` then the interface index at 16. A wildcard interface address means "any". A
/// 4-to-7-byte `ip_mreq` is read as the group alone, where Linux refuses anything shorter than
/// `struct ip_mreq` with EINVAL (the same do_ip_setsockopt check).
unsafe fn parse_add_membership(
    level: c_int,
    name: c_int,
    val: *const u8,
    len: u32,
) -> Option<Membership> {
    if val.is_null() {
        return None;
    }
    let len = len as usize;
    if level == libc::IPPROTO_IP && name == libc::IP_ADD_MEMBERSHIP {
        if len < size_of::<libc::in_addr>() {
            return None;
        }
        let group = unsafe { val.cast::<libc::in_addr>().read_unaligned() };
        let interface = (len >= 2 * size_of::<libc::in_addr>())
            .then(|| unsafe { val.add(4).cast::<libc::in_addr>().read_unaligned() })
            .map(|a| Ipv4Addr::from(u32::from_be(a.s_addr)))
            .filter(|a| !a.is_unspecified());
        let ifindex = if cfg!(target_os = "linux") && len >= 12 {
            unsafe { val.add(8).cast::<c_int>().read_unaligned() }.max(0) as u32
        } else {
            0
        };
        return Some(Membership {
            group: IpAddr::V4(Ipv4Addr::from(u32::from_be(group.s_addr))),
            interface_addr: interface.map(IpAddr::V4),
            ifindex,
        });
    }
    if level == libc::IPPROTO_IPV6 && name == IPV6_JOIN {
        if len < size_of::<libc::in6_addr>() {
            return None;
        }
        let group = unsafe { val.cast::<libc::in6_addr>().read_unaligned() };
        let ifindex = if len >= size_of::<libc::ipv6_mreq>() {
            unsafe { val.add(16).cast::<u32>().read_unaligned() }
        } else {
            0
        };
        return Some(Membership {
            group: IpAddr::V6(Ipv6Addr::from(group.s6_addr)),
            interface_addr: None,
            ifindex,
        });
    }
    None
}

/// macOS `SO_LINGER_SEC` (`<sys/socket.h>`, 0x1080): `SO_LINGER` with the time in seconds, which
/// std and socket2 use, since macOS's own `SO_LINGER` counts clock ticks.
#[cfg(target_os = "macos")]
const SO_LINGER_SEC: c_int = 0x1080;

/// What `SO_LINGER`'s `l_linger` counts: seconds on Linux (man 7 socket), clock ticks of 1/100 s
/// on macOS. XNU bsd/kern/uipc_socket.c sosetoptlock stores `SO_LINGER`'s value as is in
/// `so_linger` (ticks) and scales `SO_LINGER_SEC`'s by `hz`, which bsd/kern/kern_clock.c fixes at
/// 100; `<sys/socket.h>` labels `SO_LINGER` "(in ticks)".
#[cfg(target_os = "linux")]
const LINGER_UNIT: Duration = Duration::from_secs(1);
#[cfg(not(target_os = "linux"))]
const LINGER_UNIT: Duration = Duration::from_millis(10);

/// The unit of `l_linger` for option `name`, or `None` if it is not a linger option.
fn linger_unit(name: c_int) -> Option<Duration> {
    match name {
        libc::SO_LINGER => Some(LINGER_UNIT),
        #[cfg(target_os = "macos")]
        SO_LINGER_SEC => Some(Duration::from_secs(1)),
        _ => None,
    }
}

/// Reads a `struct linger` (man 7 socket: `l_onoff`, `l_linger` in `unit`s): `Some` while on.
unsafe fn parse_linger(val: *const u8, len: u32, unit: Duration) -> Option<Duration> {
    if val.is_null() || (len as usize) < size_of::<libc::linger>() {
        return None;
    }
    let l = unsafe { val.cast::<libc::linger>().read_unaligned() };
    (l.l_onoff != 0).then(|| unit * l.l_linger.max(0) as u32)
}

/// Writes a `struct linger` for getsockopt, `l_linger` in `unit`s (rounded down); a buffer
/// shorter than the struct is left untouched.
unsafe fn write_linger(linger: Option<Duration>, unit: Duration, val: *mut u8, len: *mut u32) {
    if val.is_null() || len.is_null() || (unsafe { *len } as usize) < size_of::<libc::linger>() {
        return;
    }
    let l = libc::linger {
        l_onoff: linger.is_some() as c_int,
        l_linger: linger.map_or(0, |d| (d.as_nanos() / unit.as_nanos()) as c_int),
    };
    unsafe {
        val.cast::<libc::linger>().write_unaligned(l);
        *len = size_of::<libc::linger>() as u32;
    }
}

/// Reads a caller's `sockaddr_in`/`sockaddr_in6`; `None` for a null pointer, a length short of
/// the family's struct, or any other family.
unsafe fn parse_addr(ptr: *const u8, len: u32) -> Option<SocketAddr> {
    if ptr.is_null() || (len as usize) < size_of::<libc::sockaddr>() {
        return None;
    }
    // man 7 ip / man 7 ipv6: sin_family/sin6_family tags the union; sin_port/sin6_port and the
    // address fields are network (big-endian) byte order, hence the from_be/to_be conversions.
    let family = unsafe { (*ptr.cast::<libc::sockaddr>()).sa_family } as c_int;
    match family {
        libc::AF_INET => {
            if (len as usize) < size_of::<libc::sockaddr_in>() {
                return None;
            }
            let sa = unsafe { std::ptr::read_unaligned(ptr.cast::<libc::sockaddr_in>()) };
            let ip = Ipv4Addr::from(u32::from_be(sa.sin_addr.s_addr));
            Some(SocketAddr::V4(SocketAddrV4::new(
                ip,
                u16::from_be(sa.sin_port),
            )))
        }
        libc::AF_INET6 => {
            // The base guard only covers `sockaddr`; a v6 address reads more.
            if (len as usize) < size_of::<libc::sockaddr_in6>() {
                return None;
            }
            let sa = unsafe { std::ptr::read_unaligned(ptr.cast::<libc::sockaddr_in6>()) };
            let ip = Ipv6Addr::from(sa.sin6_addr.s6_addr);
            Some(SocketAddr::V6(SocketAddrV6::new(
                ip,
                u16::from_be(sa.sin6_port),
                sa.sin6_flowinfo,
                sa.sin6_scope_id,
            )))
        }
        _ => None,
    }
}

/// What a call does with the address it names, for [`sock_addr`]'s family checks.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum AddrUse {
    /// A `bind`, of a stream socket if `stream`.
    Bind { stream: bool },
    /// A datagram socket's `connect` or send.
    Datagram,
    /// A stream socket's `connect`.
    Stream,
}

/// Reads the address a call on a socket of family `domain` names, a v4-mapped one as the IPv4
/// address it carries ([`unmapped`]), with whether it came as a `sockaddr_in`. The other family's
/// address is refused as each host refuses it (measured by tests/dual_stack_os_truth.rs):
/// Linux refuses an IPv6 one on an IPv4 socket with `EAFNOSUPPORT` and lets an IPv6 datagram
/// socket send to and connect to an IPv4 one (net/ipv6/udp.c `udpv6_sendmsg`, net/ipv6/
/// datagram.c `__ip6_datagram_connect`), while binding one or connecting a stream to one is
/// `EINVAL`, the address being shorter than an IPv6 one; macOS refuses either way, `EINVAL` on a
/// datagram socket and `EAFNOSUPPORT` on a stream.
///
/// # Safety
/// `ptr` is null or holds `len` readable bytes.
pub(crate) unsafe fn sock_addr(
    domain: c_int,
    ptr: *const u8,
    len: u32,
    usage: AddrUse,
) -> Result<(SocketAddr, bool), c_int> {
    let addr = unsafe { parse_addr(ptr, len) }.ok_or(libc::EINVAL)?;
    let inet6 = domain == libc::AF_INET6;
    if addr.is_ipv6() == inet6 {
        return Ok((unmapped(addr), false));
    }
    let refused = if cfg!(target_os = "linux") {
        if !inet6 {
            libc::EAFNOSUPPORT
        } else if usage == AddrUse::Datagram {
            return Ok((addr, true));
        } else {
            libc::EINVAL
        }
    } else if matches!(usage, AddrUse::Stream | AddrUse::Bind { stream: true }) {
        libc::EAFNOSUPPORT
    } else {
        libc::EINVAL
    };
    Err(refused)
}

/// `setsockopt(IPV6_V6ONLY)` (RFC 3493 §5.3, man 7 ipv6) on IP socket `rec`, `bound` or not: an
/// `int`, any nonzero value on, taken only before the socket is bound (`EINVAL` after). Linux
/// refuses a value shorter than an `int` with `EINVAL` and the option on an IPv4 socket with
/// `ENOPROTOOPT` (net/ipv6/ipv6_sockglue.c `do_ipv6_setsockopt`); macOS refuses a value of any
/// other size and an IPv4 socket with `EINVAL` (XNU bsd/netinet6/ip6_output.c `ip6_ctloutput`).
/// Measured by tests/dual_stack_os_truth.rs.
///
/// # Safety
/// `val` is null or holds `len` bytes.
pub(crate) unsafe fn v6only_set(
    rec: &SockRec,
    bound: bool,
    val: *const u8,
    len: u32,
) -> Option<NetResult> {
    if !rec.state().inet6 {
        return err(if cfg!(target_os = "linux") {
            libc::ENOPROTOOPT
        } else {
            libc::EINVAL
        });
    }
    let sized = if cfg!(target_os = "linux") {
        len as usize >= size_of::<c_int>()
    } else {
        len as usize == size_of::<c_int>()
    };
    if !sized || bound {
        return err(libc::EINVAL);
    }
    if val.is_null() {
        return err(libc::EFAULT);
    }
    rec.state().v6only = unsafe { val.cast::<c_int>().read_unaligned() } != 0;
    ok(0)
}

/// `getsockopt(IPV6_V6ONLY)` on IP socket `rec`: the flag as an `int`, truncated to a shorter
/// buffer. On an IPv4 socket Linux fails with `EOPNOTSUPP` and macOS with `EINVAL` (measured).
///
/// # Safety
/// `val` and `len` are each null or valid, `val` writable for `*len` bytes.
pub(crate) unsafe fn v6only_get(rec: &SockRec, val: *mut u8, len: *mut u32) -> Option<NetResult> {
    let state = rec.state();
    if !state.inet6 {
        return err(if cfg!(target_os = "linux") {
            libc::EOPNOTSUPP
        } else {
            libc::EINVAL
        });
    }
    let value = c_int::from(state.v6only);
    drop(state);
    if !val.is_null() && !len.is_null() {
        let n = (unsafe { *len } as usize).min(size_of::<c_int>());
        unsafe {
            std::ptr::copy_nonoverlapping(value.to_ne_bytes().as_ptr(), val, n);
            *len = n as u32;
        }
    }
    ok(0)
}

/// The address a `bind` of `rec`'s socket (of family `domain`, a stream if `stream`) names
/// ([`sock_addr`]). A v4-mapped one on an IPv6 socket with `IPV6_V6ONLY` on is refused: Linux
/// `EINVAL` (net/ipv6/af_inet6.c `__inet6_bind`), macOS `EADDRNOTAVAIL`, as measured.
///
/// # Safety
/// `ptr` is null or holds `len` readable bytes.
pub(crate) unsafe fn bind_addr(
    rec: &SockRec,
    domain: c_int,
    ptr: *const u8,
    len: u32,
    stream: bool,
) -> Result<SocketAddr, c_int> {
    let (want, _) = unsafe { sock_addr(domain, ptr, len, AddrUse::Bind { stream }) }?;
    if domain == libc::AF_INET6 && want.is_ipv4() && rec.state().v6only {
        return Err(if cfg!(target_os = "linux") {
            libc::EINVAL
        } else {
            libc::EADDRNOTAVAIL
        });
    }
    Ok(want)
}

/// Records that `rec`'s socket was bound to `addr`: Linux turns `IPV6_V6ONLY` on for an IPv6
/// address other than the wildcard (net/ipv6/af_inet6.c `__inet6_bind`), which `getsockopt` and
/// an accepted socket then read.
pub(crate) fn bound_at(rec: &SockRec, addr: SocketAddr) {
    if cfg!(target_os = "linux") && addr.is_ipv6() && !addr.ip().is_unspecified() {
        rec.state().v6only = true;
    }
}

/// Whether IPv6 datagram socket `rec`, bound at `local`, may send to (or, for `connect`, connect
/// to) `dest`, which a `sockaddr_in` named when `native`; `Err` with the errno the host gives.
/// IPv4 traffic needs a dual-stack socket not bound to an IPv6 address, and IPv6 traffic one not
/// bound to a v4-mapped address. Linux (net/ipv6/udp.c `udpv6_sendmsg`, net/ipv6/datagram.c
/// `__ip6_datagram_connect`): `ENETUNREACH` for IPv4 from an `IPV6_V6ONLY` socket or one bound to
/// an IPv6 address (a `connect` to a `sockaddr_in` from an `IPV6_V6ONLY` socket `EAFNOSUPPORT`),
/// `EAFNOSUPPORT` for IPv6 from a v4-mapped one. macOS lets an `IPV6_V6ONLY` socket send to and
/// connect to IPv4; from an IPv6 address it refuses IPv4 (`EADDRNOTAVAIL` to send, `EINVAL` to
/// connect), and from a v4-mapped address IPv6 (`EHOSTUNREACH` to send from a specific one,
/// `EINVAL` to connect). Measured by tests/dual_stack_os_truth.rs.
pub(crate) fn dgram_crossing(
    rec: &SockRec,
    local: Option<SocketAddr>,
    dest: SocketAddr,
    native: bool,
    connect: bool,
) -> Result<(), c_int> {
    let linux = cfg!(target_os = "linux");
    if dest.is_ipv4() {
        if linux && rec.state().v6only {
            return Err(if native && connect {
                libc::EAFNOSUPPORT
            } else {
                libc::ENETUNREACH
            });
        }
        if local.is_some_and(|l| l.is_ipv6() && !l.ip().is_unspecified()) {
            return Err(if linux {
                libc::ENETUNREACH
            } else if connect {
                libc::EINVAL
            } else {
                libc::EADDRNOTAVAIL
            });
        }
    } else if let Some(local) = local.filter(SocketAddr::is_ipv4) {
        if linux {
            return Err(libc::EAFNOSUPPORT);
        }
        if connect {
            return Err(libc::EINVAL);
        }
        if !local.ip().is_unspecified() {
            return Err(libc::EHOSTUNREACH);
        }
    }
    Ok(())
}

/// Whether IPv6 stream socket `rec`, bound at `bound`, may connect to `server`; `Err` with the
/// errno the host gives (measured by tests/dual_stack_os_truth.rs): an IPv4 server from an
/// `IPV6_V6ONLY` socket or one bound to an IPv6 address is `ENETUNREACH` on Linux
/// (net/ipv6/tcp_ipv6.c `tcp_v6_connect`) and `EAFNOSUPPORT` on macOS, and an IPv6 one from a
/// socket bound to a v4-mapped address `EAFNOSUPPORT` on both.
fn stream_crossing(
    rec: &SockRec,
    bound: Option<SocketAddr>,
    server: SocketAddr,
) -> Result<(), c_int> {
    let refused = if server.is_ipv4() {
        rec.state().v6only || bound.is_some_and(|b| b.is_ipv6() && !b.ip().is_unspecified())
    } else {
        return match bound {
            Some(b) if b.is_ipv4() => Err(libc::EAFNOSUPPORT),
            _ => Ok(()),
        };
    };
    if !refused {
        return Ok(());
    }
    Err(if cfg!(target_os = "linux") {
        libc::ENETUNREACH
    } else {
        libc::EAFNOSUPPORT
    })
}

/// The placeholder address of a socketpair end, which has none. Never a real peer: no socket can
/// connect from `0.0.0.0:0`, so comparing against it is safe.
const UNNAMED: SocketAddr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0));

/// What a send on a datagram socketpair end whose other end is closed fails with. Measured on the
/// dev box and in docker (`socketpair_os_truth`): Linux refuses it, Darwin reports a reset.
#[cfg(target_os = "linux")]
const PAIR_PEER_GONE: c_int = libc::ECONNREFUSED;
#[cfg(not(target_os = "linux"))]
const PAIR_PEER_GONE: c_int = libc::ECONNRESET;

/// Writes the unnamed `AF_UNIX` address a socketpair end reports: just the family on Linux (length
/// `sizeof(sa_family_t)`, 2, per man 7 unix), a zeroed 16-byte `sockaddr` with `sa_len` 16 on
/// Darwin. Measured by `socketpair_os_truth`.
unsafe fn write_unnamed(out: *mut u8, out_len: *mut u32) {
    if out.is_null() || out_len.is_null() {
        return;
    }
    #[cfg(target_os = "linux")]
    let bytes: &[u8] = &(libc::AF_UNIX as u16).to_ne_bytes();
    #[cfg(not(target_os = "linux"))]
    let bytes: &[u8] = &{
        let mut b = [0u8; 16];
        b[0] = 16;
        b[1] = libc::AF_UNIX as u8;
        b
    };
    unsafe {
        let n = (*out_len as usize).min(bytes.len());
        std::ptr::copy_nonoverlapping(bytes.as_ptr(), out, n);
        *out_len = bytes.len() as u32;
    }
}

/// Writes `addr` as a `sockaddr_in`/`sockaddr_in6` (port and IPv4 address in network byte order,
/// man 7 ip / man 7 ipv6) into a caller buffer of `*out_len` bytes, truncating, and sets
/// `*out_len` to the full size. The IPv6 flow info and scope id are written as 0, and the BSD
/// `sin_len` byte is left 0.
unsafe fn write_addr(addr: SocketAddr, out: *mut u8, out_len: *mut u32) {
    if out.is_null() || out_len.is_null() {
        return;
    }
    let cap = unsafe { *out_len } as usize;
    match addr {
        SocketAddr::V4(v4) => {
            let mut sa: libc::sockaddr_in = unsafe { std::mem::zeroed() };
            sa.sin_family = libc::AF_INET as libc::sa_family_t;
            sa.sin_port = v4.port().to_be();
            sa.sin_addr.s_addr = u32::from(*v4.ip()).to_be();
            unsafe { copy_out(&sa, out, out_len, cap) };
        }
        SocketAddr::V6(v6) => {
            let mut sa: libc::sockaddr_in6 = unsafe { std::mem::zeroed() };
            sa.sin6_family = libc::AF_INET6 as libc::sa_family_t;
            sa.sin6_port = v6.port().to_be();
            sa.sin6_addr.s6_addr = v6.ip().octets();
            unsafe { copy_out(&sa, out, out_len, cap) };
        }
    }
}

/// Copies at most `cap` bytes of `src` to `out` and reports its full size in `*out_len`, the
/// truncation rule of man 2 getsockname.
unsafe fn copy_out<T>(src: &T, out: *mut u8, out_len: *mut u32, cap: usize) {
    let size = size_of::<T>();
    let n = size.min(cap);
    unsafe {
        std::ptr::copy_nonoverlapping(src as *const T as *const u8, out, n);
        *out_len = size as u32;
    }
}

/// Writes an `int` getsockopt value, truncated to the caller's `*len`, and sets `*len` to 4.
///
/// # Safety
/// `val` and `len` must each be null or valid, `val` writable for `*len` bytes.
pub(crate) unsafe fn write_opt(value: i32, val: *mut u8, len: *mut u32) {
    if val.is_null() || len.is_null() {
        return;
    }
    let cap = unsafe { *len } as usize;
    let n = size_of::<i32>().min(cap);
    unsafe {
        std::ptr::copy_nonoverlapping(&value as *const i32 as *const u8, val, n);
        *len = n as u32;
    }
}

/// Where a connect waiting on its SYN stands after it was moved on.
enum Progress {
    /// Still waiting; the next point of the attempt (a retransmit or the answer) is due then.
    Pending(Deadline),
    /// This call settled it; the socket's record comes with it.
    Settled(Outcome, Arc<SockRec>),
    /// The socket is not connecting.
    Idle,
}

/// A stream socket's connect, as [`Net::connect`] has worked it out so far. The branches it hands
/// this to are kept out of line, so the frame `connect` keeps beneath the calls it makes, a
/// blocking connect's wait among them, holds none of their locals: a thread on the smallest stack
/// the OS allows connects too.
struct StreamConnect {
    domain: c_int,
    bound: Option<SocketAddr>,
    nonblocking: bool,
    server: SocketAddr,
    client: SocketAddr,
    host_local: bool,
}

impl Fabric {
    /// Connects datagram socket `fd`, bound at `local` (asked for `requested`), to `server`: fixes
    /// its default peer and source address, binding it first if it is not bound (man 2 connect).
    #[allow(clippy::too_many_arguments)]
    #[inline(never)]
    fn connect_dgram(
        &self,
        fd: c_int,
        server: SocketAddr,
        station: bool,
        local: Option<SocketAddr>,
        requested: Option<SocketAddr>,
        queue: &Arc<DgramQueue>,
        rec: &Arc<SockRec>,
        broadcast: bool,
    ) -> Option<NetResult> {
        let from = local.or(unhashed(requested)).map(|l| toward(l, server));
        let sender =
            match self
                .shared()
                .route_send(&rec.view(from), server, Op::Connect, station, broadcast)
            {
                Ok(sender) => sender,
                Err(errno) => return err(errno),
            };
        match local {
            None => {
                let unbound = from.unwrap_or(SocketAddr::new(unspecified_like(server.ip()), 0));
                let ip = sender.connected_local(unbound).ip();
                if let Err(errno) = self.autobind(fd, queue, rec, ip) {
                    return err(errno);
                }
            }
            Some(bound) => {
                let to = sender.connected_local(toward(bound, server));
                self.rehash(fd, queue, rec, bound, to);
            }
        }
        if let Some(Sock::Dgram { peer, .. }) = self.socks.lock().unwrap().get_mut(&fd) {
            *peer = Some(server);
        }
        rec.set_peer(Some(server));
        rec.note_tx_nic(sender.egress_name());
        ok(0)
    }

    /// Connects stream socket `fd` to the address it is bound at: Linux makes it a connection to
    /// itself; macOS refuses it with EINVAL.
    #[inline(never)]
    fn connect_to_self(
        &self,
        fd: c_int,
        server: SocketAddr,
        nonblocking: bool,
        rec: Arc<SockRec>,
    ) -> Option<NetResult> {
        if cfg!(target_os = "macos") {
            return err(libc::EINVAL);
        }
        let pipe = Pipe::new(None, None, self.shared().domain_key());
        pipe.read_by(&rec);
        pipe.write_by(&rec);
        rec.set_ends(server, server);
        let conn = Arc::new(Conn {
            a_to_b: pipe.clone(),
            b_to_a: pipe,
            client: server,
            server,
            regs: self.regs.clone(),
            hop: None,
            pair: false,
            pair_id: 0,
            tap: None,
            stamps: Default::default(),
            write_delays: Default::default(),
            #[cfg(target_os = "macos")]
            mac_shutdown: Default::default(),
        });
        self.socks.lock().unwrap().insert(
            fd,
            Sock::Stream {
                conn,
                end: End::A,
                nonblocking,
                rec,
            },
        );
        if nonblocking {
            err(libc::EINPROGRESS)
        } else {
            ok(0)
        }
    }

    /// Completes `fd`'s connect at once, on a SYN `listener` accepts into the queue entry
    /// `admission` reserved.
    #[inline(never)]
    fn connect_accepted(
        &self,
        fd: c_int,
        rec: Arc<SockRec>,
        sender: &Sender,
        listener: &Arc<Listener>,
        admission: ListenerAdmission,
        connect: &StreamConnect,
    ) -> Option<NetResult> {
        let conn = self.establish(
            &rec,
            connect.server,
            connect.client,
            sender,
            listener.tester,
        );
        if let Some(lrec) = listener.rec.as_ref().and_then(std::sync::Weak::upgrade) {
            conn.a_to_b.pending_reader(lrec.state().buf);
        }
        if let Some(tap) = &conn.tap {
            tap.open(false, Duration::ZERO);
        }
        self.socks.lock().unwrap().insert(
            fd,
            Sock::Stream {
                conn: conn.clone(),
                end: End::A,
                nonblocking: connect.nonblocking,
                rec,
            },
        );
        admission.queue(conn);
        let mut keys = crate::readiness::WakeKeys::default();
        self.fd_interests([fd], &mut keys);
        if let Some(key) = listener.wake_key() {
            keys.push(key);
        }
        self.shared().bump_keys(keys.as_slice());
        if connect.nonblocking {
            if let Some(rec) = self.rec(fd) {
                rec.state().connect_ack = cfg!(target_os = "linux");
            }
            return err(libc::EINPROGRESS);
        }
        ok(0)
    }

    /// Starts `fd`'s connect on a SYN no listener accepts at once, leaving the socket connecting;
    /// `server_in` when a tester answers it. Continues when a blocking connect has to wait for the
    /// attempt to settle.
    #[inline(never)]
    fn start_connect(
        &self,
        fd: c_int,
        rec: Arc<SockRec>,
        sender: &Sender,
        syn: Syn,
        server_in: bool,
        connect: &StreamConnect,
    ) -> ControlFlow<Option<NetResult>> {
        let &StreamConnect {
            domain,
            bound,
            nonblocking,
            server,
            client,
            host_local,
        } = connect;
        let plan = self.shared().syn_plan(&rec.opts(), syn);
        let tap = self.shared().tcp_tap(sender, client, server, server_in);
        let attempt = match ConnectAttempt::start(&plan, syn, client, tap) {
            Ok(attempt) => attempt,
            Err(Outcome::Failed(errno)) => {
                self.shared()
                    .connect_settled(server, Outcome::Failed(errno), false);
                if errno == libc::ECONNREFUSED && host_local {
                    crate::netstats::bump(&self.shared().stats.tcp(server.ip()).out_rsts);
                }
                if nonblocking {
                    rec.state().tcp_failed = true;
                    rec.set_pending_error(errno, None);
                    return ControlFlow::Break(err(libc::EINPROGRESS));
                }
                return ControlFlow::Break(err(errno));
            }
            Err(Outcome::Connected) => unreachable!("a SYN a listener accepts connects at once"),
        };
        self.socks.lock().unwrap().insert(
            fd,
            Sock::Connecting {
                domain,
                local: bound,
                nonblocking,
                rec,
                dest: server,
                attempt: Arc::new(Mutex::new(attempt)),
            },
        );
        // man 2 connect: a nonblocking socket's connect that cannot complete at once fails with
        // EINPROGRESS; poll for POLLOUT, then read SO_ERROR.
        if nonblocking {
            return ControlFlow::Break(err(libc::EINPROGRESS));
        }
        ControlFlow::Continue(())
    }

    /// The listener a connect to `server` reaches: one on the exact address, else — for one of
    /// the host's own addresses — one on the wildcard address of that port, an IPv4 socket's
    /// before a dual-stack one's (as for datagrams, [`Cand::dual`]). Of several listening on one
    /// address, the one [`pick_shared`] picks for a connection from `client`.
    fn listener_for(
        &self,
        server: SocketAddr,
        host_local: bool,
        client: SocketAddr,
    ) -> Option<Arc<Listener>> {
        let listeners = self.regs.listeners.lock().unwrap();
        let seed = self.shared().seed;
        let pick = |held: Vec<&Arc<Listener>>| {
            let i = match held.len() {
                0 => return None,
                1 => 0,
                _ => {
                    let shares: Vec<Share> = held.iter().map(|l| l.share()).collect();
                    let wildcard = held[0].addr.ip().is_unspecified();
                    pick_shared(&shares, wildcard, client, server, seed)
                }
            };
            Some(held[i].clone())
        };
        let at = |ip| listeners.at(&SocketAddr::new(ip, server.port())).iter();
        if let Some(listener) = pick(at(server.ip()).collect()) {
            return Some(listener);
        }
        if !host_local {
            return None;
        }
        pick(at(unspecified_like(server.ip())).collect()).or_else(|| {
            pick(
                at(Ipv6Addr::UNSPECIFIED.into())
                    .filter(|listener| server.is_ipv4() && listener.dual)
                    .collect(),
            )
        })
    }

    /// The address a connect to `server` along `sender` leaves from, from a socket bound at
    /// `bound`: an unbound socket takes the next ephemeral port, and a wildcard bind keeps its
    /// port but takes the route's source address (man 7 ip: an unbound socket is bound on
    /// `connect`).
    fn client_addr(
        &self,
        server: SocketAddr,
        bound: Option<SocketAddr>,
        sender: &Sender,
    ) -> SocketAddr {
        let src = sender
            .source(SocketAddr::new(unspecified_like(server.ip()), 0))
            .ip();
        match bound {
            Some(local) if !local.ip().is_unspecified() => local,
            Some(local) => SocketAddr::new(src, local.port()),
            None => {
                let socks = self.socks.lock().unwrap();
                let want = Claim {
                    addr: SocketAddr::new(src, 0),
                    dual: false,
                    inet: src.is_ipv4(),
                    reuse: false,
                    reuseport: false,
                    listening: false,
                    station: self.shared().topo().is_station_ip(src),
                };
                let local = self.tcp_bind_addr(&socks, want);
                local.unwrap_or(SocketAddr::new(src, 0))
            }
        }
    }

    /// A new connection from the socket `rec` at `client` to `server` along `sender`;
    /// `server_in` when a tester accepts it (the capture then records the server side as
    /// inbound). Both pipes cross the interface hop the route takes, so a link going down hits
    /// the bytes in flight. Records the ends and egress interface on `rec`, which becomes the
    /// reader of `b_to_a` and writer of `a_to_b`. A listener of the code under test taking it
    /// counts in the host's TCP `PassiveOpens`.
    fn establish(
        &self,
        rec: &Arc<SockRec>,
        server: SocketAddr,
        client: SocketAddr,
        sender: &Sender,
        server_in: bool,
    ) -> Arc<Conn> {
        let hop = self.shared().tcp_hop(sender, server.ip());
        let via = hop.as_ref().map(|hop| hop.link.clone());
        let ends = |from, to| {
            Some(Ends {
                shared: self.regs.shared.clone(),
                from,
                to,
            })
        };
        let conn = Arc::new(Conn {
            a_to_b: Pipe::new(
                via.clone(),
                ends(client, server),
                self.shared().domain_key(),
            ),
            b_to_a: Pipe::new(via, ends(server, client), self.shared().domain_key()),
            client,
            server,
            regs: self.regs.clone(),
            hop,
            pair: false,
            pair_id: 0,
            tap: self.shared().tcp_tap(sender, client, server, server_in),
            stamps: Default::default(),
            write_delays: Default::default(),
            #[cfg(target_os = "macos")]
            mac_shutdown: Default::default(),
        });
        #[cfg(target_os = "linux")]
        {
            let topo = self.shared().topo();
            let mtu = topo
                .mtu_of(conn.hop.as_ref().map_or(topo.loopback_index(), |h| h.index))
                .unwrap_or(1500);
            conn.a_to_b.set_mtu(mtu);
            conn.b_to_a.set_mtu(mtu);
            for end in [End::A, End::B] {
                let weak = Arc::downgrade(&conn);
                conn.write_pipe(end)
                    .on_transmit(Box::new(move |bytes, arrival, mss| {
                        if let Some(conn) = weak.upgrade() {
                            conn.record_write(end, bytes, arrival, Some(mss), true);
                        }
                    }));
            }
        }
        rec.set_ends(client, server);
        rec.note_conn_nic(sender.egress_name());
        if !server_in {
            crate::netstats::bump(&self.shared().stats.tcp(server.ip()).passive_opens);
        }
        conn.b_to_a.read_by(rec);
        conn.a_to_b.write_by(rec);
        #[cfg(target_os = "macos")]
        conn.attach_tcp_probe(End::A, rec);
        conn
    }

    /// Plays the points of `fd`'s connect that have come. Settling it makes the socket a stream
    /// handed to the listener, or leaves it unconnected with the error pending in `SO_ERROR`.
    /// Called with no fabric lock held. This is a blocking connect, so the error is consumed as it
    /// is returned. `Idle` means another descriptor of the socket settled it meanwhile: the
    /// socket's state then says how; ECONNABORTED stands in if its error was already taken.
    ///
    /// A signal handler interrupts the wait as the host's does
    /// ([`connect_restart`](crate::signals::connect_restart)); the attempt goes on, for a later
    /// `connect` or a poll to settle.
    fn await_connect(&self, fd: c_int) -> Option<NetResult> {
        let timeout = self
            .rec(fd)
            .is_some_and(|rec| rec.opts().sndtimeo.is_some());
        let restart = crate::signals::connect_restart(timeout);
        loop {
            match self.advance_connect(fd) {
                Progress::Pending(next) => {
                    let (_, interrupted) = snare_interpose::interruptible(restart, || {
                        readiness().wait_until_dynamic(
                            "connect",
                            Some(next),
                            |keys| self.fd_interests([fd], keys),
                            || self.connect_due(fd),
                        )
                    });
                    if interrupted {
                        return err(libc::EINTR);
                    }
                }
                Progress::Settled(Outcome::Connected, _) => return ok(0),
                Progress::Settled(Outcome::Failed(errno), rec) => {
                    rec.take_error();
                    return err(errno);
                }
                Progress::Idle => {
                    return match self.socks.lock().unwrap().get(&fd) {
                        Some(Sock::Stream { .. }) => ok(0),
                        Some(Sock::Fresh { rec, .. }) => {
                            err(rec.take_error().unwrap_or(libc::ECONNABORTED))
                        }
                        _ => err(libc::EBADF),
                    };
                }
            }
        }
    }

    /// Plays `fd`'s connect attempt up to now. While it is pending, returns when the next point
    /// is due. Once it settles, every descriptor sharing the attempt (dups) becomes a stream on
    /// the new connection, which joins the listener's queue, or a fresh socket with the errno
    /// pending; a SYN the plan accepts but that finds no listener any more is ECONNREFUSED.
    ///
    /// Holds `socks` throughout so no other descriptor settles the same attempt concurrently;
    /// the attempt's lock and the registries are taken under it (see the module's lock order),
    /// and readiness is bumped only after `socks` is released.
    fn advance_connect(&self, fd: c_int) -> Progress {
        let mut socks = self.socks.lock().unwrap();
        let Some(Sock::Connecting {
            local,
            rec,
            dest,
            attempt,
            ..
        }) = socks.get(&fd)
        else {
            return Progress::Idle;
        };
        let (local, rec, dest, attempt) = (*local, rec.clone(), *dest, attempt.clone());
        let client = attempt.lock().unwrap().client;
        let mut listener = None;
        let mut admission = None;
        let step = attempt.lock().unwrap().poll(|| {
            let station = self.regs.station_at(dest.ip());
            let host_local = self.shared().dest_is_host(dest.ip(), station);
            listener = self.listener_for(dest, host_local, client);
            let syn = self.shared().syn_probe(dest, listener.is_some(), station);
            if matches!(syn, Syn::Accept) {
                admission = listener.as_ref().and_then(Listener::reserve);
                if admission.is_none() {
                    return Syn::Silent;
                }
            }
            syn
        });
        let outcome = match step {
            Ok(next) => return Progress::Pending(next),
            Err(outcome) => outcome,
        };
        let conn = match (outcome, listener) {
            (Outcome::Connected, Some(listener)) => {
                let station = self.regs.station_at(dest.ip());
                self.shared()
                    .route_send(&rec.view(local), dest, Op::Connect, station, true)
                    .map(|sender| {
                        let conn = self.establish(&rec, dest, client, &sender, listener.tester);
                        if let Some(lrec) = listener.rec.as_ref().and_then(std::sync::Weak::upgrade)
                        {
                            conn.a_to_b.pending_reader(lrec.state().buf);
                        }
                        (conn, listener)
                    })
            }
            (Outcome::Connected, None) => Err(crate::faults::code::ECONNREFUSED),
            (Outcome::Failed(errno), _) => Err(errno),
        };
        let Some(Sock::Connecting {
            domain,
            local,
            nonblocking,
            rec: settled_rec,
            ..
        }) = socks.get(&fd)
        else {
            return Progress::Idle;
        };
        let settled = match &conn {
            Ok((conn, _)) => Sock::Stream {
                conn: conn.clone(),
                end: End::A,
                nonblocking: *nonblocking,
                rec: settled_rec.clone(),
            },
            Err(_) => Sock::Fresh {
                domain: *domain,
                local: *local,
                nonblocking: *nonblocking,
                rec: settled_rec.clone(),
            },
        };
        socks.insert(fd, settled);
        let mut keys = crate::readiness::WakeKeys::default();
        keys.push(rec.wake_key());
        let outcome = match conn {
            Ok((conn, listener)) => {
                attempt.lock().unwrap().established(conn.tap.as_ref());
                if let Some(key) = listener.wake_key() {
                    keys.push(key);
                }
                admission
                    .expect("accepted SYN reserves a queue entry")
                    .queue(conn);
                Outcome::Connected
            }
            Err(errno) => {
                rec.state().tcp_failed = true;
                rec.set_pending_error(errno, None);
                Outcome::Failed(errno)
            }
        };
        drop(socks);
        self.shared().connect_settled(dest, outcome, true);
        self.shared().bump_keys(keys.as_slice());
        Progress::Settled(outcome, rec)
    }

    /// Moves on every connecting socket among `fds` (all of them for `None`).
    fn advance_connecting(&self, fds: Option<&[c_int]>) {
        let socks = self.socks.lock().unwrap();
        if socks.connecting == 0 {
            return;
        }
        let connecting: Vec<c_int> = socks
            .iter()
            .filter(|(fd, sock)| {
                matches!(sock, Sock::Connecting { .. }) && fds.is_none_or(|fds| fds.contains(fd))
            })
            .map(|(fd, _)| *fd)
            .collect();
        drop(socks);
        for fd in connecting {
            self.advance_connect(fd);
        }
    }

    /// Whether `fd`'s connect has a point to play, or is no longer waiting.
    fn connect_due(&self, fd: c_int) -> bool {
        match self.socks.lock().unwrap().get(&fd) {
            Some(Sock::Connecting { attempt, .. }) => attempt.lock().unwrap().due(),
            _ => true,
        }
    }

    /// Whether any connecting socket among `fds` (all of them for `None`) has a point to play.
    fn connecting_due(&self, fds: Option<&[c_int]>) -> bool {
        let socks = self.socks.lock().unwrap();
        socks.connecting > 0
            && socks.iter().any(|(fd, sock)| match sock {
                Sock::Connecting { attempt, .. } => {
                    fds.is_none_or(|fds| fds.contains(fd)) && attempt.lock().unwrap().due()
                }
                _ => false,
            })
    }
}

/// A descriptor's kind without its state, for dispatching `read`/`write` and answering `SO_TYPE`.
/// `Fresh` covers connecting sockets; `Dgram` covers `AF_UNIX` datagram ends.
#[derive(Clone, Copy, PartialEq)]
enum Kind {
    Fresh,
    Stream,
    Listener,
    Dgram,
    Event,
    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
    Timer,
    Epoll,
    Raw,
    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
    Kqueue,
    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
    Signal,
}

/// The expirations of a timer armed for `expires` (reloading every `interval`, or once for
/// zero) that have fallen due by `now`, and when it expires next. Overruns are counted whole, as
/// Linux kernel/time/hrtimer.c `hrtimer_forward` does for fs/timerfd.c.
fn timer_due(
    expires: Option<Duration>,
    interval: Duration,
    now: Duration,
) -> (u64, Option<Duration>) {
    match expires {
        Some(at) if at <= now => {
            if interval.is_zero() {
                return (1, None);
            }
            let due = (now - at).as_nanos() / interval.as_nanos() + 1;
            let next = at.as_nanos() + due * interval.as_nanos();
            (
                u64::try_from(due).unwrap_or(u64::MAX),
                Some(Duration::from_nanos(
                    u64::try_from(next).unwrap_or(u64::MAX),
                )),
            )
        }
        _ => (0, expires),
    }
}

/// Whichever of two deadlines falls first; either may be absent.
fn earlier(a: Option<Deadline>, b: Option<Deadline>) -> Option<Deadline> {
    match (a, b) {
        (Some(a), Some(b)) => Some(if b.remaining() < a.remaining() { b } else { a }),
        (a, b) => a.or(b),
    }
}

/// A `timespec` as a span; `None` when negative or with `tv_nsec` out of range, which the kernel
/// rejects with EINVAL (include/linux/time64.h `timespec64_valid`).
#[cfg(target_os = "linux")]
fn timespec_span(ts: &libc::timespec) -> Option<Duration> {
    if ts.tv_sec < 0 || !(0..1_000_000_000).contains(&ts.tv_nsec) {
        return None;
    }
    Some(Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32))
}

/// An `itimerspec` reading `value` left (zero for `None`, a disarmed timer) and `interval`.
#[cfg(target_os = "linux")]
fn itimerspec(value: Option<Duration>, interval: Duration) -> libc::itimerspec {
    let ts = |span: Duration| libc::timespec {
        tv_sec: span.as_secs() as libc::time_t,
        tv_nsec: span.subsec_nanos() as libc::c_long,
    };
    libc::itimerspec {
        it_interval: ts(interval),
        it_value: ts(value.unwrap_or_default()),
    }
}

pub(crate) fn readiness_sequence() -> u64 {
    static SEQUENCE: AtomicU64 = AtomicU64::new(1);
    SEQUENCE.fetch_add(1, Ordering::Relaxed)
}

#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(dead_code))]
fn readiness_order(sock: &Sock, fallback: u64) -> (Duration, u64) {
    match sock {
        Sock::Dgram { queue, .. } | Sock::UnixDgram { queue, .. } => queue
            .readiness_metadata()
            .map_or((Duration::MAX, fallback), |(at, sequence, _)| {
                (at, sequence)
            }),
        Sock::Stream { conn, end, .. } => {
            let writer = if *end == End::A { End::B } else { End::A };
            let at = conn.stamps[writer.index()]
                .lock()
                .unwrap()
                .front()
                .map_or(Duration::ZERO, |(_, stamp)| stamp.mono);
            (at, conn.read_pipe(*end).read_order().max(fallback))
        }
        Sock::Listener { listener, .. } => (
            Duration::from_nanos(listener.ready_at.load(Ordering::Relaxed)),
            listener.ready_order.load(Ordering::Relaxed),
        ),
        Sock::Event {
            ready_order,
            ready_at,
            ..
        } => (*ready_at, *ready_order),
        _ => (Duration::ZERO, fallback),
    }
}

/// The keys a registration on description `id`, holding `sock`, is subscribed under: the
/// description's own and its socket record's.
#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(dead_code))]
fn description_keys(id: u64, sock: &Sock) -> Keys {
    Keys::of(
        Some(crate::readiness::WakeKey::Descriptor(id)),
        sock.rec().map(|rec| rec.wake_key()),
    )
}

/// Whether `sock`'s readiness can change with the clock alone: a connect under way, an armed
/// timerfd, or a delayed arrival, error or report its record is waiting on. A blocking wait on it
/// wakes on clock moves for the same reasons.
#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(dead_code))]
fn moves_with_time(sock: &Sock) -> bool {
    match sock {
        Sock::Connecting { .. } => true,
        Sock::Timer { expires, .. } => expires.is_some(),
        _ => sock.rec().is_some_and(|rec| rec.pending_time()),
    }
}

/// The Linux epoll readiness bits, as constants so this compiles on every platform (only Linux
/// creates the fds these describe). Values from include/uapi/linux/eventpoll.h (`<sys/epoll.h>`,
/// man 2 epoll_ctl). They double as the fabric's internal readiness mask on every platform, from
/// which `poll` revents and kqueue filters are derived.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
const EPOLLIN: u32 = 0x001;
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
const EPOLLOUT: u32 = 0x004;
const EPOLLERR: u32 = 0x008;
const EPOLLHUP: u32 = 0x010;
const EPOLLRDHUP: u32 = 0x2000;

/// The readiness of `sock` as epoll bits: [`base_mask`] plus what a pending error adds, and on
/// Linux the `EPOLLERR` a readable transmit timestamp on the error queue adds.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn ready_mask(sock: &Sock) -> u32 {
    #[cfg(target_os = "macos")]
    if let Sock::Stream { conn, .. } = sock {
        conn.progress_tcp_shutdown();
    }
    let mask = base_mask(sock);
    // A pending error: Linux reports EPOLLERR (sk_err in net/ipv4/tcp.c tcp_poll and
    // net/core/datagram.c datagram_poll); macOS makes the socket readable (soreadable,
    // XNU bsd/kern/uipc_socket2.c, true while so_error is set), which kqueue's EVFILT_READ
    // reports.
    match sock {
        Sock::Fresh { rec, .. } if rec.state().tcp_failed && cfg!(target_os = "macos") => mask,
        Sock::Stream { rec, .. } | Sock::Dgram { rec, .. } | Sock::Fresh { rec, .. }
            if rec.peek_error().is_some() =>
        {
            mask | if cfg!(target_os = "linux") {
                EPOLLERR
            } else {
                EPOLLIN
            }
        }
        #[cfg(target_os = "linux")]
        Sock::Stream { rec, .. } | Sock::Dgram { rec, .. }
            if crate::tstamp::tx_report_ready(rec) || rec.icmp_report_ready() =>
        {
            mask | EPOLLERR
        }
        _ => mask,
    }
}

/// The readiness of a datagram socket another backend of the sim serves (a Linux `SimHost`'s),
/// read from its record, and its wakes: always writable, readable with a datagram waiting, and
/// `EPOLLERR` for a pending error or a readable transmit stamp, as Linux net/core/datagram.c
/// `datagram_poll` reports `sk_err` and a non-empty `sk_error_queue` (Linux 7.0); a pending
/// error makes it readable instead on macOS, as for the fabric's own ([`ready_mask`]). `None`
/// for any other socket.
fn foreign_ready(rec: &SockRec) -> Option<(u32, Wakes)> {
    let (readable, landed) = rec.dgram_readiness()?;
    let mut mask = EPOLLOUT;
    if readable {
        mask |= EPOLLIN;
    }
    if rec.peek_error().is_some() {
        mask |= if cfg!(target_os = "linux") {
            EPOLLERR
        } else {
            EPOLLIN
        };
    }
    #[cfg(target_os = "linux")]
    if crate::tstamp::tx_report_ready(rec) || rec.icmp_report_ready() {
        mask |= EPOLLERR;
    }
    Some((
        mask,
        Wakes {
            read: landed,
            write: 0,
            error: rec.error_wakes(),
        },
    ))
}

/// Whether the OS's epoll accepts real descriptor `fd`: Linux refuses, with `EPERM`, a file
/// whose driver has no poll (a regular file, a directory, `/dev/null`; fs/eventpoll.c
/// `do_epoll_ctl` checks `file_can_poll`), which only the OS can tell, so it is asked with a
/// probe set of its own.
#[cfg(target_os = "linux")]
fn real_pollable(fd: c_int) -> bool {
    snare_interpose::real(|| unsafe {
        let probe = libc::epoll_create1(libc::EPOLL_CLOEXEC);
        if probe < 0 {
            return true;
        }
        let mut event = libc::epoll_event { events: 0, u64: 0 };
        let added = libc::epoll_ctl(probe, libc::EPOLL_CTL_ADD, fd, &mut event);
        let refused =
            added < 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM);
        libc::close(probe);
        !refused
    })
}

/// The readiness of a real descriptor registered in a simulated epoll set, as a zero-timeout
/// `poll(2)` of it reads now; `None` once it is closed. Linux keeps an epoll registration until
/// the file's last descriptor closes (fs/eventpoll.c `eventpoll_release`), so a live one stays
/// registered. Its readiness cannot wake a simulated wait; it is seen when the wait next looks.
#[cfg(target_os = "linux")]
fn real_ready(fd: c_int) -> Option<u32> {
    let mut pfd = libc::pollfd {
        fd,
        events: libc::POLLIN | libc::POLLOUT | libc::POLLPRI | libc::POLLRDHUP,
        revents: 0,
    };
    let polled = snare_interpose::real(|| unsafe { libc::poll(&mut pfd, 1, 0) });
    if polled < 0 || pfd.revents & libc::POLLNVAL != 0 {
        return None;
    }
    // The poll bits share their values with the epoll bits on Linux (include/uapi/linux/
    // eventpoll.h defines EPOLLIN as POLLIN and so on).
    Some(u32::from(pfd.revents as u16))
}

/// Whether the OS's kqueue accepts `filter` on real descriptor `fd`, or the errno it refuses it
/// with: EBADF once it is closed, or the filter's attach error (XNU bsd/kern/kern_event.c
/// `kevent_register`), which only the OS can tell.
#[cfg(target_os = "macos")]
fn real_pollable(fd: c_int, filter: i16) -> Result<(), c_int> {
    real_kevent(fd, filter).map(drop)
}

/// The readiness of a real descriptor registered in a simulated kqueue: what `filter` reports on
/// a probe queue of its own with a zero-timeout `kevent`, its `data`, `EV_EOF` and `fflags`
/// included; `Ok(None)` while not ready, and the errno the registration is refused with
/// otherwise. XNU drops a descriptor's knotes when it closes (bsd/kern/kern_event.c
/// `knote_fdclose`), so a closed one is EBADF here and its registration goes. Its readiness
/// cannot wake a simulated wait; it is seen when the wait next looks.
#[cfg(target_os = "macos")]
fn real_kevent(fd: c_int, filter: i16) -> Result<Option<libc::kevent>, c_int> {
    snare_interpose::real(|| unsafe {
        if libc::fcntl(fd, libc::F_GETFD) < 0 {
            return Err(libc::EBADF);
        }
        let probe = libc::kqueue();
        if probe < 0 {
            return Ok(None);
        }
        let change = libc::kevent {
            ident: fd as usize,
            filter,
            flags: libc::EV_ADD | libc::EV_RECEIPT,
            fflags: 0,
            data: 0,
            udata: std::ptr::null_mut(),
        };
        let mut receipt = make_kevent(0, 0, 0);
        let zero = libc::timespec {
            tv_sec: 0,
            tv_nsec: 0,
        };
        let n = libc::kevent(probe, &change, 1, &mut receipt, 1, &zero);
        let result = if n < 0 {
            Err(std::io::Error::last_os_error()
                .raw_os_error()
                .unwrap_or(libc::EBADF))
        } else if n == 1 && receipt.data != 0 {
            Err(receipt.data as c_int)
        } else {
            let mut ready = make_kevent(0, 0, 0);
            let n = libc::kevent(probe, std::ptr::null(), 0, &mut ready, 1, &zero);
            Ok((n == 1).then_some(ready))
        };
        libc::close(probe);
        result
    })
}

/// The readiness of `sock` apart from a pending error. A stream is writable while its window has
/// room and readable once data, end of stream or a reset is there; datagram, eventfd and raw
/// endpoints are always writable (sends never block on them here, bar a stalled link); a
/// listener is readable with a connection pending. Epoll and kqueue fds are never ready.
fn base_mask(sock: &Sock) -> u32 {
    let (epollin, epollout) = (EPOLLIN, EPOLLOUT);
    match sock {
        Sock::Stream { conn, end, .. } => {
            let mut m = 0;
            if conn.write_pipe(*end).writable() {
                m |= epollout;
            }
            let read = conn.read_pipe(*end);
            let write = conn.write_pipe(*end);
            if read.readable_or_closed() {
                m |= epollin;
            }
            if read.read_eof() {
                m |= EPOLLRDHUP;
            }
            #[cfg(target_os = "macos")]
            let hung_up = write.reader_gone() || (read.read_eof() && write.is_write_closed());
            #[cfg(not(target_os = "macos"))]
            let hung_up = read.read_eof() && write.is_closed();
            if hung_up {
                m |= EPOLLHUP;
                if cfg!(target_os = "macos") {
                    m &= !epollout;
                }
            }
            m
        }
        Sock::Dgram { queue, .. } | Sock::UnixDgram { queue, .. } => {
            let mut m = epollout;
            if queue.has(|_| true) {
                m |= epollin;
            }
            m
        }
        Sock::Event { counter, .. } => {
            let mut m = if *counter < u64::MAX - 1 { epollout } else { 0 };
            if *counter > 0 {
                m |= epollin;
            }
            m
        }
        Sock::Raw { rx, .. } => {
            let mut m = epollout;
            if !rx.is_empty() {
                m |= epollin;
            }
            m
        }
        Sock::Timer { ticks, .. } if *ticks > 0 => epollin,
        #[cfg(target_os = "linux")]
        Sock::Signal { mask, .. } if snare_interpose::signals_pending(*mask) => epollin,
        Sock::Listener { listener, .. } if listener.has_pending() => epollin,
        // A connect that failed: writable, with its error and the hang-up of a closed socket
        // (net/ipv4/tcp.c tcp_poll: TCP_CLOSE gives EPOLLHUP, SEND_SHUTDOWN gives EPOLLOUT, sk_err
        // gives EPOLLERR).
        Sock::Fresh { rec, .. } if rec.state().tcp_failed => {
            epollin
                | EPOLLHUP
                | if cfg!(target_os = "linux") {
                    epollout
                } else {
                    0
                }
        }
        Sock::Fresh { rec, .. } if rec.peek_error().is_some() => epollout | EPOLLERR | EPOLLHUP,
        _ => 0,
    }
}

/// `poll(2)` revents for readiness `mask` (epoll bits), for the `events` asked. `POLLERR` and
/// `POLLHUP` are reported whether asked for or not (man 2 poll: they are ignored in `events`).
fn poll_bits(mask: u32, events: i16) -> i16 {
    let mut r = 0;
    if mask & EPOLLIN != 0 && events & libc::POLLIN != 0 {
        r |= libc::POLLIN;
    }
    if mask & EPOLLOUT != 0 && events & libc::POLLOUT != 0 {
        r |= libc::POLLOUT;
    }
    #[cfg(target_os = "linux")]
    if mask & EPOLLRDHUP != 0 && events & libc::POLLRDHUP != 0 {
        r |= libc::POLLRDHUP;
    }
    if mask & EPOLLERR != 0 {
        r |= libc::POLLERR;
    }
    if mask & EPOLLHUP != 0 {
        r |= libc::POLLHUP;
    }
    r
}

/// How many times a descriptor has been woken for reading and for writing. A kernel marks an
/// edge-triggered registration ready from the wake itself, not from a change in readiness: Linux
/// fs/eventpoll.c `ep_poll_callback` queues the item on every wake whose key meets its events,
/// and XNU bsd/kern/kern_event.c `knote` runs the filter on every wake and activates the knote
/// when it fires. So data arriving at a socket already readable, or a write to an eventfd whose
/// counter is already nonzero, is a new edge.
#[derive(Clone, Copy, Default, PartialEq)]
struct Wakes {
    read: u64,
    write: u64,
    error: u64,
}

/// `sock`'s [`Wakes`]. Call after [`ready_mask`], which lands what has arrived by now. Sockets
/// that have not connected count none: their one edge, becoming writable or failing, is a
/// readiness bit rising.
#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(dead_code))]
fn wakes(sock: &Sock) -> Wakes {
    let mut wakes = data_wakes(sock);
    wakes.error = sock.rec().map_or(0, |rec| rec.error_wakes());
    wakes
}

/// [`ready_mask`] and then [`wakes`], reading a stream's or datagram socket's record once.
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn mask_and_wakes(sock: &Sock) -> (u32, Wakes) {
    let (Sock::Stream { rec, .. } | Sock::Dgram { rec, .. }) = sock else {
        let mask = ready_mask(sock);
        return (mask, wakes(sock));
    };
    #[cfg(target_os = "macos")]
    if let Sock::Stream { conn, .. } = sock {
        conn.progress_tcp_shutdown();
    }
    let (mut mask, mut wakes) = match sock {
        Sock::Dgram { queue, .. } => {
            let (readable, landed) = queue.readable_landed();
            let wakes = Wakes {
                read: landed,
                ..Wakes::default()
            };
            (EPOLLOUT | if readable { EPOLLIN } else { 0 }, wakes)
        }
        _ => (base_mask(sock), data_wakes(sock)),
    };
    let (error, report, error_wakes) = rec.error_readiness();
    if error.is_some() {
        mask |= if cfg!(target_os = "linux") {
            EPOLLERR
        } else {
            EPOLLIN
        };
    } else if report {
        mask |= EPOLLERR;
    }
    wakes.error = error_wakes;
    (mask, wakes)
}

/// `sock`'s [`Wakes`] for reading and writing, without its error wakes.
fn data_wakes(sock: &Sock) -> Wakes {
    match sock {
        Sock::Stream { conn, end, .. } => Wakes {
            read: conn.read_pipe(*end).read_wakes(),
            write: conn.write_pipe(*end).write_wakes(),
            ..Wakes::default()
        },
        Sock::Dgram { queue, .. } | Sock::UnixDgram { queue, .. } => Wakes {
            read: queue.landed(),
            write: 0,
            ..Wakes::default()
        },
        Sock::Event { writes, reads, .. } => Wakes {
            read: *writes,
            write: *reads,
            ..Wakes::default()
        },
        Sock::Timer { expired, .. } => Wakes {
            read: *expired,
            write: 0,
            ..Wakes::default()
        },
        #[cfg(target_os = "linux")]
        Sock::Signal { .. } => Wakes {
            read: snare_interpose::signal_generation(),
            write: 0,
            ..Wakes::default()
        },
        Sock::Raw { arrived, .. } => Wakes {
            read: *arrived,
            write: 0,
            ..Wakes::default()
        },
        Sock::Listener { listener, .. } => Wakes {
            read: listener.arrivals.load(Ordering::Relaxed),
            write: 0,
            ..Wakes::default()
        },
        _ => Wakes::default(),
    }
}

/// The edge-trigger state of one registration: `EPOLLET` (man 7 epoll: delivered "only when
/// changes occur on the monitored file descriptor", so a wait does not report an fd again merely
/// because it is still ready) or `EV_CLEAR` (kevent(2): "After the event is retrieved by the
/// user, its state is reset"). An edge is a readiness bit rising since it was last reported, or a
/// direction that is ready having been woken ([`Wakes`]) since. The report carries the full
/// current readiness, as Linux `ep_send_events` re-polls the item (`ep_item_poll`) before
/// copying it out.
#[derive(Clone, Copy, Default, PartialEq)]
#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(dead_code))]
struct Edge {
    /// The bits last reported, less any since seen clear.
    seen: u32,
    /// The descriptor's wakes when last reported.
    wakes: Wakes,
}

#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(dead_code))]
impl Edge {
    /// Whether readiness `ready` (the registration's bits) with wakes `now` holds an edge not
    /// yet reported. Forgets any reported bit `ready` lacks, so its rising again is a new edge;
    /// consumes nothing else, so a wait's predicate may ask.
    fn pending(&mut self, ready: u32, now: Wakes) -> bool {
        self.seen &= ready;
        ready & !self.seen != 0
            || (ready & EPOLLIN != 0 && now.read != self.wakes.read)
            || (ready & EPOLLOUT != 0 && now.write != self.wakes.write)
            || (ready
                & if cfg!(target_os = "linux") {
                    EPOLLERR
                } else {
                    EPOLLIN | EPOLLOUT
                }
                != 0
                && now.error != self.wakes.error)
    }

    /// Consumes the edge: readiness `ready` with wakes `now` was reported.
    fn report(&mut self, ready: u32, now: Wakes) {
        self.seen = ready;
        self.wakes = now;
    }
}

impl Sock {
    /// The socket record, for every variant that is a socket.
    /// Whether this is a kernel object of the process rather than of a network: an epoll set, a
    /// kqueue, an eventfd or a timerfd. These may move to another sim of the process (see
    /// [`Net::hand_over`]).
    fn set_nonblocking(&mut self, on: bool) {
        if let Sock::Stream { nonblocking, .. } | Sock::UnixDgram { nonblocking, .. } = self {
            *nonblocking = on;
        }
    }

    /// For a socketpair end: its pair's identity, which end it is, and its `O_NONBLOCK`.
    fn pair_end(&self) -> Option<(u64, usize, bool)> {
        match self {
            Sock::Stream {
                conn,
                end,
                nonblocking,
                ..
            } if conn.pair => Some((conn.pair_id, end.index(), *nonblocking)),
            Sock::UnixDgram {
                pair: (pair, end),
                nonblocking,
                ..
            } => Some((*pair, *end, *nonblocking)),
            _ => None,
        }
    }

    fn process_local(&self) -> bool {
        matches!(
            self,
            Sock::Epoll { .. }
                | Sock::Kqueue { .. }
                | Sock::Event { .. }
                | Sock::Timer { .. }
                | Sock::Signal { .. }
        )
    }

    fn rec(&self) -> Option<&Arc<SockRec>> {
        match self {
            Sock::Fresh { rec, .. }
            | Sock::Connecting { rec, .. }
            | Sock::Stream { rec, .. }
            | Sock::Listener { rec, .. }
            | Sock::Dgram { rec, .. }
            | Sock::UnixDgram { rec, .. }
            | Sock::Raw { rec, .. } => Some(rec),
            _ => None,
        }
    }
}

/// One socket's hold on an address, or a bind's want of one.
#[derive(Clone, Copy)]
pub(crate) struct Claim {
    /// The address, a v4-mapped one as IPv4.
    addr: SocketAddr,
    /// An IPv6 socket at the wildcard without `IPV6_V6ONLY`, which holds the IPv4 wildcard too.
    dual: bool,
    /// Created `AF_INET`.
    inet: bool,
    /// `SO_REUSEADDR`.
    reuse: bool,
    /// `SO_REUSEPORT`.
    reuseport: bool,
    listening: bool,
    /// At a station address: a socket standing in for another host, whose addresses the host's
    /// wildcard does not cover.
    station: bool,
}

impl Claim {
    /// A bind of `rec`'s socket to `addr`.
    pub(crate) fn of(rec: &SockRec, addr: SocketAddr) -> Self {
        let state = rec.state();
        Claim {
            addr,
            dual: state.dual_at(addr),
            inet: !state.inet6,
            reuse: state.opts.reuseaddr,
            reuseport: state.opts.reuseport,
            listening: false,
            station: state.station,
        }
    }

    /// A bind of `rec`'s socket to `addr`, a station address if `station`.
    pub(crate) fn want(rec: &SockRec, addr: SocketAddr, station: bool) -> Self {
        Claim {
            station,
            ..Claim::of(rec, addr)
        }
    }

    /// What a tester's listener at `addr` holds: the address alone, listening.
    fn tester(addr: SocketAddr, dual: bool) -> Self {
        Claim {
            addr,
            dual,
            inet: addr.is_ipv4(),
            reuse: false,
            reuseport: false,
            listening: true,
            station: false,
        }
    }

    /// What `listener` holds against a new bind.
    fn of_listener(listener: &Listener) -> Self {
        match listener.rec.as_ref().and_then(std::sync::Weak::upgrade) {
            Some(rec) => Claim {
                listening: true,
                ..Claim::of(&rec, listener.addr)
            },
            None => Claim::tester(listener.addr, listener.dual),
        }
    }

    /// The addresses it holds: its own, and the IPv4 wildcard for a dual-stack one.
    fn held(self) -> impl Iterator<Item = SocketAddr> {
        let v4 = self
            .dual
            .then(|| SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), self.addr.port()));
        std::iter::once(self.addr).chain(v4)
    }
}

/// Whether the bind `want` collides with the socket of its protocol that holds `held`, TCP and UDP
/// alike. Two addresses overlap on the same port and family when they are equal or one is the
/// wildcard; a dual-stack socket holds the IPv4 wildcard as well as the IPv6 one. Measured against
/// the host OS for IPv4, IPv6, v4-mapped and dual-stack binds under every combination of
/// `SO_REUSEADDR` and `SO_REUSEPORT` (bind_os_truth.rs, dual_stack_os_truth.rs,
/// reuseport_os_truth.rs):
///
/// - Linux refuses any overlap unless both sockets set `SO_REUSEADDR` and the held one is not
///   listening, or both set `SO_REUSEPORT` (net/ipv4/inet_connection_sock.c
///   `inet_bind_conflict`, net/ipv4/udp.c `udp_lib_lport_inuse`). Both sockets have one owner
///   in a sim, so the effective-UID match `SO_REUSEPORT` also asks for always holds.
/// - macOS refuses an equal address and, unless the new socket sets `SO_REUSEADDR` or
///   `SO_REUSEPORT`, a wildcard overlap, unless both set `SO_REUSEPORT` (XNU bsd/netinet/in_pcb.c
///   `in_pcbbind`: the lookup is exact-only once either option is set, and a socket found passes
///   only when its options share the new socket's `SO_REUSEPORT`); and a dual-stack bind passes
///   over an `AF_INET` socket at the IPv4 wildcard (bsd/netinet6/in6_pcb.c `in6_pcbbind`). A bind
///   of a multicast group with `SO_REUSEADDR` counts it as both options, so it passes a socket
///   that set either.
///
/// A socket at a station address stands in for another host, so it and a socket of the host
/// never collide.
pub(crate) fn bind_conflict(held: Claim, want: Claim) -> bool {
    let group_reuse = cfg!(target_os = "macos")
        && want.addr.ip().is_multicast()
        && want.reuse
        && (held.reuse || held.reuseport);
    if (want.reuseport && held.reuseport) || group_reuse || held.station != want.station {
        return false;
    }
    held.held().any(|h| {
        want.held().any(|w| {
            if h.port() != w.port() || h.is_ipv4() != w.is_ipv4() {
                return false;
            }
            let exact = h.ip() == w.ip();
            if !exact && !h.ip().is_unspecified() && !w.ip().is_unspecified() {
                return false;
            }
            if cfg!(target_os = "linux") {
                return !(want.reuse && held.reuse && !held.listening);
            }
            if want.dual && w.is_ipv4() && held.inet && h.ip().is_unspecified() {
                return false;
            }
            exact || !(want.reuse || want.reuseport)
        })
    })
}

impl Fabric {
    /// A bind of `rec`'s socket to `addr`, as a station's when `addr` is a station address.
    fn want(&self, rec: &SockRec, addr: SocketAddr) -> Claim {
        Claim::want(rec, addr, self.shared().topo().is_station_ip(addr.ip()))
    }

    /// `want` with its port resolved (an ephemeral one for port 0), or `None` when it collides
    /// ([`bind_conflict`]) with a TCP socket already bound or listening there.
    ///
    /// The held addresses are every bound fresh or connecting socket, listener and connected
    /// stream in `socks` (the caller holds it), plus every registered listener, a tester's
    /// counted as listening without SO_REUSEADDR or SO_REUSEPORT. Socketpair ends hold none. Only
    /// the sockets and listeners on the port asked about are looked at. Port 0 takes a port no
    /// socket overlaps, whatever the options say (Linux `inet_csk_find_open_port` checks without
    /// relaxing for them; XNU `in_pcbbind` looks for an unused port): it draws from the sim's
    /// ephemeral counter at most once per port in the range, so a full range gives `None`
    /// (EADDRINUSE) rather than looping.
    fn tcp_bind_addr(&self, socks: &Sockets, mut want: Claim) -> Option<SocketAddr> {
        if want.addr.port() != 0 {
            return self.tcp_free(socks, want, None).then_some(want.addr);
        }
        let port = (0..=u16::MAX - crate::scope::EPHEMERAL_FIRST)
            .map(|_| self.shared().ephemeral_port())
            .find(|&port| {
                let want = Claim {
                    addr: SocketAddr::new(want.addr.ip(), port),
                    reuse: false,
                    reuseport: false,
                    ..want
                };
                self.tcp_free(socks, want, None)
            })?;
        want.addr.set_port(port);
        Some(want.addr)
    }

    /// Whether `want` collides ([`bind_conflict`]) with none of the TCP sockets and listeners
    /// [`tcp_bind_addr`](Self::tcp_bind_addr) looks at, but for `except`'s.
    fn tcp_free(&self, socks: &Sockets, want: Claim, except: Option<&Arc<SockRec>>) -> bool {
        let port = want.addr.port();
        let other = |rec: Option<&Arc<SockRec>>| match (rec, except) {
            (Some(rec), Some(except)) => !Arc::ptr_eq(rec, except),
            _ => true,
        };
        let listened = self
            .regs
            .listeners
            .lock()
            .unwrap()
            .on_port(port)
            .filter(|listener| {
                let rec = listener.rec.as_ref().and_then(std::sync::Weak::upgrade);
                other(rec.as_ref())
            })
            .any(|listener| bind_conflict(Claim::of_listener(listener), want));
        !listened
            && !socks
                .on_port(port)
                .filter(|sock| other(sock.rec()))
                .filter_map(tcp_claim)
                .any(|held| bind_conflict(held, want))
    }

    /// `fd`'s [`Kind`], or `None` if the fabric does not serve it.
    fn kind(&self, fd: c_int) -> Option<Kind> {
        let socks = self.socks.lock().unwrap();
        Some(match socks.get(&fd)? {
            Sock::Fresh { .. } | Sock::Connecting { .. } => Kind::Fresh,
            Sock::Stream { .. } => Kind::Stream,
            Sock::Listener { .. } => Kind::Listener,
            Sock::Dgram { .. } | Sock::UnixDgram { .. } => Kind::Dgram,
            Sock::Event { .. } => Kind::Event,
            Sock::Timer { .. } => Kind::Timer,
            Sock::Epoll { .. } => Kind::Epoll,
            Sock::Raw { .. } => Kind::Raw,
            Sock::Kqueue { .. } => Kind::Kqueue,
            Sock::Signal { .. } => Kind::Signal,
        })
    }

    /// Whether `fd` is in nonblocking mode; only asked of eventfds and raw endpoints, so fresh
    /// and listening sockets are not listed.
    fn is_nonblocking(&self, fd: c_int) -> bool {
        let socks = self.socks.lock().unwrap();
        matches!(
            socks.get(&fd),
            Some(Sock::Event {
                nonblocking: true,
                ..
            }) | Some(Sock::Timer {
                nonblocking: true,
                ..
            }) | Some(Sock::Signal {
                nonblocking: true,
                ..
            }) | Some(Sock::Stream {
                nonblocking: true,
                ..
            }) | Some(Sock::Dgram {
                nonblocking: true,
                ..
            }) | Some(Sock::UnixDgram {
                nonblocking: true,
                ..
            }) | Some(Sock::Raw {
                nonblocking: true,
                ..
            })
        )
    }

    /// The revents of each `(fd, events)`; for a real descriptor what a zero-timeout `poll` of it
    /// reads. `began` is [`foreign_masks`](Self::foreign_masks) of the set when the wait began: an
    /// fd the sim served then and no longer does was closed meanwhile and reports `POLLNVAL`,
    /// without a look at the real descriptor its number may still name (the reserved one its
    /// close has yet to release, or a reuse after that).
    fn poll_revents(
        &self,
        watched: &[(c_int, i16)],
        began: &[(c_int, Option<(u32, Wakes)>)],
    ) -> Vec<i16> {
        let foreign: HashMap<c_int, Option<(u32, Wakes)>> = self
            .foreign_masks(watched.iter().map(|w| w.0))
            .into_iter()
            .filter(|(fd, ready)| {
                ready.is_some() || began.iter().any(|(f, then)| f == fd && then.is_none())
            })
            .collect();
        let mut real: Vec<libc::pollfd> = watched
            .iter()
            .map(|&(fd, events)| libc::pollfd {
                fd: if matches!(foreign.get(&fd), Some(None)) {
                    fd
                } else {
                    -1
                },
                events,
                revents: 0,
            })
            .collect();
        if real.iter().any(|p| p.fd >= 0) {
            snare_interpose::real(|| unsafe {
                libc::poll(real.as_mut_ptr(), real.len() as libc::nfds_t, 0)
            });
        }
        let mut socks = self.socks.lock().unwrap();
        socks.settle_timers(self.shared().monotonic_now());
        watched
            .iter()
            .zip(&real)
            .map(|((fd, events), real)| match socks.get(fd) {
                Some(s) => poll_bits(ready_mask(s), *events),
                None if *fd < 0 => 0,
                None => match foreign.get(fd).copied() {
                    Some(Some((mask, _))) => poll_bits(mask, *events),
                    Some(None) => real.revents,
                    None => libc::POLLNVAL,
                },
            })
            .collect()
    }

    /// The readiness of each of `fds` that is not one of the fabric's own: `Some` with
    /// [`foreign_ready`]'s answer for a datagram socket another backend of the sim serves,
    /// `None` for any other fd. The fabric's fds are left out. Takes `socks` only to tell the two
    /// apart, and reads the others' records without it.
    fn foreign_masks(
        &self,
        fds: impl Iterator<Item = c_int>,
    ) -> Vec<(c_int, Option<(u32, Wakes)>)> {
        let others: Vec<c_int> = {
            let socks = self.socks.lock().unwrap();
            fds.filter(|fd| !socks.contains_key(fd)).collect()
        };
        others
            .into_iter()
            .map(|fd| {
                let rec = self.shared().sockets.lookup_fd(fd);
                (fd, rec.as_deref().and_then(foreign_ready))
            })
            .collect()
    }

    /// `epoll_wait` with its timeout as a span (`None` blocks). A watched timerfd's next expiry
    /// bounds the wait as well, so the timer fires on the sim's clock like any other deadline: a
    /// time skip lands on it, and an as-fast-as-possible clock jumps to it.
    #[cfg(target_os = "linux")]
    unsafe fn epoll_wait_for(
        &self,
        epfd: c_int,
        events: *mut u8,
        maxevents: c_int,
        timeout: Option<Duration>,
    ) -> Option<NetResult> {
        if !Net::owns(self, epfd) {
            return None;
        }
        if maxevents <= 0 {
            return err(libc::EINVAL);
        }
        if events.is_null() {
            return err(libc::EFAULT);
        }
        if !matches!(
            self.socks.lock().unwrap().get(&epfd),
            Some(Sock::Epoll { .. })
        ) {
            return err(libc::EINVAL);
        }
        let deadline = timeout.map(Deadline::timeout);
        // A wait that returns without blocking — events already pending, or a zero timeout — is a
        // busy-poll step when repeated, so it is charged the call latency.
        let mut waited = false;
        let waiting = std::cell::RefCell::new(None);
        let _waiting = snare_interpose::fd_wait(epfd);
        loop {
            if !Net::owns(self, epfd) {
                return None;
            }
            self.advance_connecting(None);
            let ready = self.collect_ready(epfd, maxevents as usize, true);
            if !ready.is_empty() {
                if !waited {
                    snare_interpose::charge_latency();
                }
                for (i, (ev, data)) in ready.iter().enumerate() {
                    let slot = unsafe { events.cast::<libc::epoll_event>().add(i) };
                    unsafe {
                        std::ptr::write_unaligned(
                            slot,
                            libc::epoll_event {
                                events: *ev,
                                u64: *data,
                            },
                        )
                    };
                }
                return ok(ready.len() as i64);
            }
            // A zero timeout never blocks, so it needs no subscription or interests. The wait
            // would only look again, and of what it looks at only a due connect is not already
            // covered by the scan just made.
            if timeout.is_some_and(|t| t.is_zero()) {
                snare_interpose::end_spin();
                if self.connecting_due(None) {
                    waited = true;
                    continue;
                }
                snare_interpose::charge_latency();
                return ok(0);
            }
            let expiry = self.epoll_timer_expiry(epfd);
            let timer = expiry.map(|at| self.timer_deadline(at));
            let (woke, interrupted) = snare_interpose::interruptible(Restart::Never, || {
                readiness().wait_until_dynamic(
                    "epoll_wait",
                    earlier(deadline, timer),
                    |keys| {
                        if let Some(key) = self.wait_real(&waiting, self.epoll_watch(epfd)) {
                            keys.push(key);
                        }
                        self.epoll_interests(epfd, keys)
                    },
                    || {
                        if let Some(waiting) = &*waiting.borrow() {
                            waiting.look();
                        }
                        !Net::owns(self, epfd)
                            || !self.collect_ready(epfd, 1, false).is_empty()
                            || self.connecting_due(None)
                            || self.epoll_timer_expiry(epfd) != expiry
                    },
                )
            });
            if !Net::owns(self, epfd) {
                return None;
            }
            if interrupted {
                return err(libc::EINTR);
            }
            if !woke {
                if let (Some(at), Some(timer)) = (expiry, timer)
                    && timer.passed()
                    && deadline.is_none_or(|d| !d.passed())
                {
                    snare_interpose::expire_timer(at);
                    waited = true;
                    continue;
                }
                if timeout.is_some_and(|t| t.is_zero()) {
                    snare_interpose::charge_latency();
                }
                return ok(0);
            }
            waited = true;
        }
    }

    /// The earliest expiry among the timerfds epoll set `epfd` watches.
    #[cfg(target_os = "linux")]
    fn epoll_timer_expiry(&self, epfd: c_int) -> Option<Duration> {
        let socks = self.socks.lock().unwrap();
        if socks.timers == 0 {
            return None;
        }
        let Some(Sock::Epoll { interests, .. }) = socks.get(&epfd) else {
            return None;
        };
        let watched: crate::HashSet<u64> = interests
            .iter()
            .filter(|(_, interest)| !interest.spent)
            .filter_map(|((_, identity), _)| match identity {
                EpollIdentity::Local(id) => Some(*id),
                _ => None,
            })
            .collect();
        if watched.is_empty() {
            return None;
        }
        socks.next_expiry(|description| watched.contains(&description.id))
    }

    /// The earliest expiry among the timerfds in `fds`.
    fn fds_timer_expiry(&self, fds: &[c_int]) -> Option<Duration> {
        let socks = self.socks.lock().unwrap();
        socks.next_expiry(|description| description.descriptors.iter().any(|fd| fds.contains(fd)))
    }

    /// Blocks until real descriptor `fd` is ready for `events`, as a `poll` of it alone blocks (a
    /// [`Watch`](crate::realfd::Watch) on it), in a wait a signal handler interrupts, restarted
    /// under `SA_RESTART`: a pipe `read`, `readv`, `write` and `writev`, and `wait`, `waitpid` and
    /// `waitid`, restart on both hosts, and fail with EINTR without it (man 7 signal,
    /// "Interruption of system calls and library functions by signal handlers"; pinned by
    /// tests/signal_interrupts.rs). `Some(Ok(0))` once it is ready, for the call to go to the OS;
    /// `None` when the sim gives up the wait as deadlocked, or has no probe set to watch it with,
    /// leaving it to the OS as before.
    fn await_real(&self, fd: c_int, events: i16, label: &'static str) -> Option<NetResult> {
        let ready = || {
            let mut pfd = libc::pollfd {
                fd,
                events,
                revents: 0,
            };
            // SAFETY: one pollfd; a zero timeout.
            snare_interpose::real(|| unsafe { libc::poll(&mut pfd, 1, 0) }) > 0
        };
        if ready() {
            return ok(0);
        }
        let watch = crate::realfd::Watch::new(&[(fd, events)])?;
        let waiting = watch.wait(&self.regs.shared);
        let (woke, interrupted) = snare_interpose::interruptible(Restart::WithSaRestart, || {
            readiness().wait_until_dynamic(
                label,
                None,
                |keys| {
                    keys.push(waiting.watch().key());
                    false
                },
                || {
                    waiting.look();
                    ready()
                },
            )
        });
        if interrupted {
            return err(libc::EINTR);
        }
        woke.then(|| ok(0)).flatten()
    }

    /// Waits for `fd`, an end of a pipe the sim made that is open for `access` (`O_RDONLY`,
    /// `O_WRONLY`) in blocking mode, to be ready for `events`, as
    /// [`await_real`](Self::await_real) waits. Any other descriptor is left to the OS, which fails
    /// a call on the wrong end at once (EBADF).
    fn await_pipe(
        &self,
        fd: c_int,
        access: c_int,
        events: i16,
        label: &'static str,
    ) -> Option<NetResult> {
        self.shared().pipes.lent(fd)?;
        // SAFETY: no pointers.
        let flags = snare_interpose::real(|| unsafe { libc::fcntl(fd, libc::F_GETFL) });
        if flags < 0 || flags & libc::O_NONBLOCK != 0 || flags & libc::O_ACCMODE != access {
            return None;
        }
        self.await_real(fd, events, label)
    }

    /// A wait's deadline for a timer expiring at `at` on the sim's monotonic timeline.
    fn timer_deadline(&self, at: Duration) -> Deadline {
        Deadline::timeout(at.saturating_sub(self.shared().monotonic_now()))
    }

    /// man 2 timerfd_create, "Operating on a timer file descriptor": a read of at least 8 bytes
    /// returns the expirations since the last read and resets them, blocking (or EAGAIN when
    /// nonblocking) until there is one; a shorter buffer is EINVAL.
    #[cfg(target_os = "linux")]
    fn timerfd_read(&self, fd: c_int, buf: *mut u8, len: usize) -> Option<NetResult> {
        if len < 8 {
            return err(libc::EINVAL);
        }
        let take = || -> Option<u64> {
            let mut socks = self.socks.lock().unwrap();
            socks.settle_timers(self.shared().monotonic_now());
            match socks.get_mut(&fd) {
                Some(Sock::Timer { ticks, .. }) if *ticks > 0 => Some(std::mem::take(ticks)),
                _ => None,
            }
        };
        let _waiting = snare_interpose::fd_wait(fd);
        let value = loop {
            if !Net::owns(self, fd) {
                return None;
            }
            if let Some(value) = take() {
                break value;
            }
            if self.is_nonblocking(fd) {
                return would_block();
            }
            let expiry = self.fds_timer_expiry(&[fd]);
            let timer = expiry.map(|at| self.timer_deadline(at));
            let (woke, interrupted) =
                snare_interpose::interruptible(Restart::WithSaRestart, || {
                    readiness().wait_until_dynamic(
                        "timerfd",
                        timer,
                        |keys| self.fd_interests([fd], keys),
                        || {
                            !Net::owns(self, fd)
                                || self.fds_timer_expiry(&[fd]) != expiry
                                || matches!(
                                    self.socks.lock().unwrap().get(&fd),
                                    Some(Sock::Timer { ticks, .. }) if *ticks > 0
                                )
                        },
                    )
                });
            if interrupted && Net::owns(self, fd) {
                return err(libc::EINTR);
            }
            if !woke && Net::owns(self, fd) {
                match (expiry, timer) {
                    (Some(at), Some(timer)) if timer.passed() => {
                        snare_interpose::expire_timer(at);
                    }
                    _ => return err(libc::EAGAIN),
                }
            }
        };
        unsafe { std::ptr::copy_nonoverlapping(value.to_ne_bytes().as_ptr(), buf, 8) };
        ok(8)
    }

    /// man 2 signalfd, "read(2)": each `signalfd_siginfo` (128 bytes) the buffer has room for takes
    /// one pending signal of the descriptor's set, blocking (or EAGAIN when nonblocking) until there
    /// is one; a buffer too small for one is EINVAL (fs/signalfd.c `signalfd_read`). A handler
    /// that interrupts the wait restarts it under `SA_RESTART` and fails it with EINTR otherwise,
    /// as the kernel's `-ERESTARTSYS` does (`signalfd_dequeue`).
    #[cfg(target_os = "linux")]
    fn signalfd_read(&self, fd: c_int, buf: *mut u8, len: usize) -> Option<NetResult> {
        const SIZE: usize = size_of::<libc::signalfd_siginfo>();
        if len < SIZE {
            return err(libc::EINVAL);
        }
        let mask = || match self.socks.lock().unwrap().get(&fd) {
            Some(Sock::Signal { mask, .. }) => Some(*mask),
            _ => None,
        };
        let _waiting = snare_interpose::fd_wait(fd);
        let taken = loop {
            let set = mask()?;
            let taken = snare_interpose::take_signals(set, len / SIZE);
            if !taken.is_empty() {
                break taken;
            }
            if self.is_nonblocking(fd) {
                return would_block();
            }
            let (_, interrupted) = snare_interpose::interruptible(Restart::WithSaRestart, || {
                readiness().wait_until_dynamic(
                    "signalfd",
                    None,
                    |keys| self.fd_interests([fd], keys),
                    || mask().is_none_or(snare_interpose::signals_pending),
                )
            });
            if interrupted && Net::owns(self, fd) {
                return err(libc::EINTR);
            }
        };
        for (at, info) in taken.iter().enumerate() {
            // SAFETY: all-zero is a valid signalfd_siginfo.
            let mut out: libc::signalfd_siginfo = unsafe { std::mem::zeroed() };
            out.ssi_signo = info.signo as u32;
            out.ssi_code = info.code;
            out.ssi_pid = info.pid as u32;
            out.ssi_uid = info.uid;
            out.ssi_status = info.status;
            unsafe { std::ptr::write_unaligned(buf.add(at * SIZE).cast(), out) };
        }
        ok((taken.len() * SIZE) as i64)
    }

    /// Ready registrations in activation order; reported level-triggered registrations move
    /// behind the remaining ready registrations. `take` consumes edges and one-shot events.
    #[cfg(target_os = "linux")]
    fn collect_ready(&self, epfd: c_int, max: usize, take: bool) -> Vec<(u32, u64)> {
        let domain = self.shared().domain_key();
        let (due, others, watch) = {
            let mut socks = self.socks.lock().unwrap();
            let id = socks.identity(epfd);
            let Some(Sock::Epoll { interests, real }) = socks.get_mut(&epfd) else {
                return Vec::new();
            };
            if let Some(id) = id {
                interests.list().place(id, domain);
            }
            let due = interests.due();
            let others: Vec<_> = due
                .iter()
                .filter_map(|&ticket| interests.at(ticket))
                .map(|(key, _)| key)
                .filter(|key| !matches!(key.1, EpollIdentity::Local(_)))
                .collect();
            (due, others, real.clone())
        };
        if let Some(watch) = &watch {
            watch.drain();
        }
        if due.is_empty() {
            return Vec::new();
        }
        let foreign: HashMap<_, (u32, Wakes, bool)> = others
            .into_iter()
            .filter_map(|key| {
                let rec = match key.1 {
                    EpollIdentity::Foreign(id) => self.shared().sockets.lookup_raw_id(id),
                    EpollIdentity::Untracked => self.shared().sockets.lookup_fd(key.0),
                    EpollIdentity::Local(_) => None,
                };
                match rec {
                    Some(rec) => {
                        let (mask, wakes) = foreign_ready(&rec)?;
                        Some((key, (mask, wakes, rec.pending_time())))
                    }
                    None if key.1 == EpollIdentity::Untracked => {
                        let (read, write) =
                            watch.as_ref().map_or((0, 0), |watch| watch.edges(key.0));
                        let wakes = Wakes {
                            read,
                            write,
                            error: 0,
                        };
                        Some((key, (real_ready(key.0)?, wakes, false)))
                    }
                    None => None,
                }
            })
            .collect();
        let mut socks = self.socks.lock().unwrap();
        socks.settle_timers(self.shared().monotonic_now());
        let Some(Sock::Epoll { interests, .. }) = socks.get(&epfd) else {
            return Vec::new();
        };
        let mut pending = Vec::new();
        let mut seen = Vec::new();
        let mut settled = Vec::with_capacity(due.len());
        let mut gone = Vec::new();
        for ticket in due {
            let ticket = interests.current(ticket);
            let Some((key, interest)) = interests.at(ticket) else {
                continue;
            };
            if interest.spent {
                settled.push((ticket, Settled::Idle, None));
                continue;
            }
            let (events, data, was, order, pending_order) = (
                interest.events,
                interest.data,
                interest.edge,
                interest.order,
                interest.pending_order,
            );
            let sock = match key.1 {
                EpollIdentity::Local(id) => socks.get_identity(id),
                EpollIdentity::Untracked => socks.get(&key.0),
                EpollIdentity::Foreign(_) => None,
            };
            let (mask, now, timed) = match sock {
                Some(sock) => {
                    let (mask, now) = mask_and_wakes(sock);
                    (mask, now, None)
                }
                None => match foreign.get(&key) {
                    Some(&(mask, now, timed)) => (mask, now, Some(timed)),
                    None => {
                        gone.push(key);
                        continue;
                    }
                },
            };
            let got = mask & (events | EPOLLERR | EPOLLHUP);
            let mut edge = was;
            let edged = edge.pending(got, now);
            let fire = got != 0 && (events & libc::EPOLLET as u32 == 0 || edged);
            let fired_order = fire.then(|| {
                pending_order.unwrap_or_else(|| {
                    sock.map_or((Duration::ZERO, order), |sock| readiness_order(sock, order))
                })
            });
            if let Some(at) = fired_order {
                pending.push((at, key, got, data, now, ticket));
            }
            if edge != was || fired_order != pending_order {
                seen.push((ticket, edge, fired_order));
            }
            let keys = match (key.1, sock) {
                (EpollIdentity::Local(id), Some(sock)) => Some(description_keys(id, sock)),
                _ => None,
            };
            let state = if fire || key.1 == EpollIdentity::Untracked {
                Settled::Due
            } else if timed.unwrap_or_else(|| sock.is_some_and(moves_with_time)) {
                Settled::Timed
            } else {
                Settled::Idle
            };
            settled.push((ticket, state, keys));
        }
        pending.sort_by_key(|p| (p.0, p.1.0));
        let mut out = Vec::new();
        if let Some(Sock::Epoll { interests, .. }) = socks.get_mut(&epfd) {
            for (ticket, state, keys) in settled {
                interests.settle(ticket, state, keys);
            }
            for key in gone {
                interests.remove(&key);
            }
            for (ticket, edge, pending_order) in seen {
                if let Some((_, i)) = interests.at_mut(ticket) {
                    i.edge = edge;
                    i.pending_order = pending_order;
                }
            }
            for (_, _, got, data, now, ticket) in pending.into_iter().take(max) {
                out.push((got, data));
                if take && let Some((_, i)) = interests.at_mut(ticket) {
                    i.edge.report(got, now);
                    i.spent |= i.events & libc::EPOLLONESHOT as u32 != 0;
                    i.pending_order = if i.events & libc::EPOLLET as u32 == 0 {
                        Some((Duration::MAX, readiness_sequence()))
                    } else {
                        None
                    };
                    if i.spent {
                        interests.settle(ticket, Settled::Idle, None);
                    }
                }
            }
        }
        out
    }

    /// The kqueue analogue of `collect_ready`: the ready `kevent`s for a kqueue's read/write
    /// interests and fired user events, up to `max`, level-triggered or once per edge as each was
    /// added; `take` as there, and a taken report also deletes `EV_ONESHOT` registrations,
    /// disables `EV_DISPATCH` ones and resets `EV_CLEAR` user events. The kqueue state's lock is
    /// released before `socks` is taken, so the two are never nested.
    #[cfg(target_os = "macos")]
    fn collect_kevents(&self, kq: c_int, max: usize, take: bool) -> Vec<libc::kevent> {
        let (state, id) = {
            let socks = self.socks.lock().unwrap();
            match socks.get(&kq) {
                Some(Sock::Kqueue { state }) => (state.clone(), socks.identity(kq)),
                _ => return Vec::new(),
            }
        };
        type Watch = (Ticket, c_int, Knote);
        let mut g = state.lock().unwrap();
        if let Some(id) = id {
            g.notes.list().place(id, self.shared().domain_key());
        }
        let (mut reads, mut writes): (Vec<Watch>, Vec<Watch>) = (Vec::new(), Vec::new());
        for ticket in g.notes.due() {
            let Some(((filter, fd), &note)) = g.notes.at(ticket) else {
                continue;
            };
            if note.disabled {
                g.notes.settle(ticket, Settled::Idle, None);
            } else if filter == libc::EVFILT_READ {
                reads.push((ticket, fd, note));
            } else {
                writes.push((ticket, fd, note));
            }
        }
        let users_ready: Vec<(usize, u64)> = g
            .users
            .iter()
            .filter(|(_, n)| n.triggered && !n.disabled)
            .map(|(id, n)| (*id, n.udata))
            .collect();
        let watch = g.real.clone();
        drop(g);
        if let Some(watch) = &watch {
            watch.drain();
        }
        let real: HashMap<(i16, c_int), Option<libc::kevent>> =
            [(libc::EVFILT_READ, &reads), (libc::EVFILT_WRITE, &writes)]
                .into_iter()
                .flat_map(|(filter, watched)| {
                    watched
                        .iter()
                        .filter(|watch| watch.2.untracked)
                        .filter_map(move |watch| {
                            Some(((filter, watch.1), real_kevent(watch.1, filter).ok()?))
                        })
                })
                .collect();
        let socks = self.socks.lock().unwrap();
        let mut out = Vec::new();
        let mut seen: Vec<(Ticket, i16, c_int, u64, Edge, bool)> = Vec::new();
        let mut settled: Vec<(Ticket, Settled, Option<Keys>)> = Vec::new();
        let mut gone = Vec::new();
        for (filter, watched) in [(libc::EVFILT_READ, reads), (libc::EVFILT_WRITE, writes)] {
            if out.len() >= max {
                break;
            }
            let bit = if filter == libc::EVFILT_READ {
                EPOLLIN
            } else {
                EPOLLOUT
            };
            let mut pending = Vec::new();
            for (ticket, fd, note) in watched {
                let Knote {
                    udata,
                    flags,
                    mut edge,
                    untracked,
                    generation,
                    ..
                } = note;
                if untracked {
                    let Some(&polled) = real.get(&(filter, fd)) else {
                        gone.push((filter, fd, generation));
                        continue;
                    };
                    let got = if polled.is_some() { bit } else { 0 };
                    let (read, write) = watch.as_ref().map_or((0, 0), |watch| watch.edges(fd));
                    let now = Wakes {
                        read,
                        write,
                        error: 0,
                    };
                    let edged = edge.pending(got, now);
                    let fire = got != 0 && (flags & libc::EV_CLEAR == 0 || edged);
                    let seen_index = seen.len();
                    seen.push((ticket, filter, fd, generation, edge, false));
                    settled.push((ticket, Settled::Due, None));
                    if fire {
                        pending.push((
                            (Duration::ZERO, fd as u64),
                            fd,
                            udata,
                            flags,
                            got,
                            now,
                            seen_index,
                            polled,
                        ));
                    }
                    continue;
                }
                let Some(sock) = socks.get(&fd) else {
                    settled.push((ticket, Settled::Due, Some(Keys::default())));
                    continue;
                };
                let keys = socks.identity(fd).map(|id| description_keys(id, sock));
                let (mask, now) = mask_and_wakes(sock);
                let got = if matches!(sock, Sock::Fresh { rec, .. } if rec.state().tcp_failed)
                    || (filter == libc::EVFILT_WRITE
                        && matches!(sock, Sock::Stream { conn, end, .. }
                            if conn.write_pipe(*end).is_write_closed()
                                || conn.write_pipe(*end).reader_gone()))
                {
                    bit
                } else {
                    mask & bit
                };
                let was = edge;
                let edged = edge.pending(got, now);
                let fire = got != 0 && (flags & libc::EV_CLEAR == 0 || edged);
                let state = if fire {
                    Settled::Due
                } else if moves_with_time(sock) {
                    Settled::Timed
                } else {
                    Settled::Idle
                };
                settled.push((ticket, state, keys));
                if !fire && edge == was {
                    continue;
                }
                let seen_index = seen.len();
                seen.push((ticket, filter, fd, generation, edge, false));
                if fire {
                    pending.push((
                        readiness_order(sock, fd as u64),
                        fd,
                        udata,
                        flags,
                        got,
                        now,
                        seen_index,
                        None,
                    ));
                }
            }
            pending.sort_by_key(|p| (p.0, p.1));
            for (_, fd, udata, flags, got, now, seen_index, polled) in
                pending.into_iter().take(max - out.len())
            {
                if let Some(polled) = polled {
                    let mut ev = make_kevent(fd as usize, filter, udata);
                    ev.flags = flags | (polled.flags & libc::EV_EOF);
                    ev.fflags = polled.fflags;
                    ev.data = polled.data;
                    out.push(ev);
                    if take {
                        seen[seen_index].4.report(got, now);
                        seen[seen_index].5 = true;
                    }
                } else if let Some(sock) = socks.get(&fd) {
                    let mut ev = make_kevent(fd as usize, filter, udata);
                    ev.flags = flags;
                    if let Sock::Fresh { rec, .. } = sock
                        && rec.state().tcp_failed
                    {
                        ev.flags |= libc::EV_EOF;
                        ev.fflags = rec.peek_error().unwrap_or(0) as u32;
                    }
                    if filter == libc::EVFILT_READ {
                        // kevent(2): EVFILT_READ on a listening socket reports the backlog in
                        // `data`.
                        if let Sock::Stream { conn, end, rec, .. } = sock {
                            ev.data = conn.read_pipe(*end).queued_bytes() as _;
                            if conn.read_pipe(*end).read_eof() {
                                ev.flags |= libc::EV_EOF;
                                ev.fflags = rec.peek_error().unwrap_or(0) as u32;
                            }
                        }
                        if let Sock::Dgram { queue, .. } | Sock::UnixDgram { queue, .. } = sock {
                            ev.data = queue.readiness_metadata().map_or(0, |(_, _, len)| len) as _;
                        }
                        if let Sock::Listener { listener, .. } = sock {
                            ev.data =
                                snare_interpose::real(|| listener.pending.lock().unwrap().len())
                                    as _;
                        }
                    } else {
                        // kevent(2): EVFILT_WRITE reports the free space in the send buffer in
                        // `data`.
                        if let Sock::Stream { conn, end, rec, .. } = sock {
                            ev.data = conn.write_pipe(*end).room().unwrap_or(8192) as _;
                            if conn.write_pipe(*end).is_write_closed()
                                || conn.write_pipe(*end).reader_gone()
                            {
                                ev.flags |= libc::EV_EOF;
                                ev.fflags = rec.peek_error().unwrap_or(0) as u32;
                            }
                        }
                        if let Sock::Fresh { rec, .. } = sock {
                            // XNU tcp_attach keeps sb_preconn_hiwat at 2048 until soisconnected.
                            ev.data = rec.state().buf.tcp_send_space().min(2048) as _;
                        }
                        // A socket whose connect failed reports EV_EOF with the error in fflags
                        // (XNU bsd/kern/uipc_socket.c filt_sowrite_common: SS_CANTSENDMORE →
                        // EV_EOF, kn_fflags = so_error).
                        if let Sock::Fresh { rec, .. } = sock
                            && let Some(errno) = rec.peek_error()
                        {
                            ev.flags |= libc::EV_EOF;
                            ev.fflags = errno as u32;
                        }
                    }
                    out.push(ev);
                    if take {
                        seen[seen_index].4.report(got, now);
                        seen[seen_index].5 = true;
                    }
                }
            }
        }
        drop(socks);
        let mut users_taken = Vec::new();
        for (id, udata) in users_ready {
            if out.len() >= max {
                break;
            }
            let mut ev = make_kevent(id, libc::EVFILT_USER, udata);
            ev.flags = state.lock().unwrap().users.get(&id).map_or(0, |n| n.flags);
            out.push(ev);
            users_taken.push(id);
        }
        let mut g = state.lock().unwrap();
        let notes = &mut g.notes;
        for (ticket, state, keys) in settled {
            notes.settle(ticket, state, keys);
        }
        for (filter, fd, generation) in gone {
            if notes
                .get(&(filter, fd))
                .is_some_and(|note| note.generation == generation)
            {
                notes.remove(&(filter, fd));
            }
        }
        for (ticket, filter, fd, generation, edge, reported) in seen {
            let at = (filter, fd);
            let unmoved = notes
                .at(ticket)
                .is_some_and(|(_, note)| note.generation == generation);
            let note = if unmoved {
                notes.at_mut(ticket).map(|(_, note)| note)
            } else {
                notes
                    .get_mut(&at)
                    .filter(|note| note.generation == generation)
            };
            let Some(note) = note else {
                continue;
            };
            note.edge = edge;
            if reported {
                if note.flags & libc::EV_ONESHOT != 0 {
                    notes.remove(&at);
                } else if note.flags & libc::EV_DISPATCH != 0 {
                    note.disabled = true;
                    notes.unlist(&at);
                }
            }
        }
        if take {
            for id in users_taken {
                let Some(note) = g.users.get_mut(&id) else {
                    continue;
                };
                if note.flags & libc::EV_ONESHOT != 0 {
                    g.users.remove(&id);
                    continue;
                }
                if note.flags & libc::EV_DISPATCH != 0 {
                    note.disabled = true;
                }
                if note.flags & libc::EV_CLEAR != 0 {
                    note.triggered = false;
                }
            }
        }
        out
    }

    /// An eventfd's counter without taking it; 0 for any other fd.
    fn eventfd_peek(&self, fd: c_int) -> u64 {
        let socks = self.socks.lock().unwrap();
        match socks.get(&fd) {
            Some(Sock::Event { counter, .. }) => *counter,
            _ => 0,
        }
    }

    /// Takes what one read of an eventfd returns: the whole counter, or 1 in semaphore mode
    /// (man 2 eventfd). `None` while the counter is 0.
    fn eventfd_take(&self, fd: c_int) -> Option<u64> {
        let mut socks = self.socks.lock().unwrap();
        let Some(Sock::Event {
            counter,
            semaphore,
            reads,
            ..
        }) = socks.get_mut(&fd)
        else {
            return None;
        };
        if *counter == 0 {
            return None;
        }
        *reads += 1;
        let value = if *semaphore {
            *counter -= 1;
            1
        } else {
            std::mem::take(counter)
        };
        Some(value)
    }

    /// Takes a raw endpoint's oldest received frame.
    fn raw_pop(&self, fd: c_int) -> Option<Vec<u8>> {
        let mut socks = self.socks.lock().unwrap();
        match socks.get_mut(&fd) {
            Some(Sock::Raw { rx, .. }) => rx.pop_front(),
            _ => None,
        }
    }

    /// Whether a raw endpoint has a frame waiting.
    fn raw_has(&self, fd: c_int) -> bool {
        let socks = self.socks.lock().unwrap();
        matches!(socks.get(&fd), Some(Sock::Raw { rx, .. }) if !rx.is_empty())
    }

    /// Reads one whole frame from a Linux packet socket, truncated to `len` (the rest is
    /// discarded, as for any message-based socket, man 2 recv), blocking unless nonblocking. A
    /// frame is delivered with its Ethernet header whatever the socket type: the `SOCK_DGRAM`
    /// cooked mode is not modelled.
    fn raw_read(&self, fd: c_int, buf: *mut u8, len: usize) -> Option<NetResult> {
        let frame = if let Some(f) = self.raw_pop(fd) {
            f
        } else if self.is_nonblocking(fd) {
            return would_block();
        } else {
            let deadline = self.recv_deadline(fd);
            let (woke, interrupted) = snare_interpose::interruptible(
                crate::signals::socket_restart(deadline.is_some()),
                || {
                    readiness().wait_until_dynamic(
                        "raw recv",
                        deadline,
                        |keys| self.fd_interests([fd], keys),
                        || self.raw_has(fd),
                    )
                },
            );
            if interrupted {
                return err(libc::EINTR);
            }
            if !woke {
                return err(libc::EAGAIN); // quiescent deadlock or SO_RCVTIMEO timeout
            }
            self.raw_pop(fd)?
        };
        let n = len.min(frame.len());
        unsafe { std::ptr::copy_nonoverlapping(frame.as_ptr(), buf, n) };
        ok(n as i64)
    }

    /// Sends one whole frame from a bound raw endpoint (EINVAL unbound). `SimShared::raw_send`
    /// decides by the interface's state whether it fails, is lost on the wire (`Ok(false)`, still
    /// a successful send), or goes out (`Ok(true)`), in which case every other raw endpoint bound
    /// to the same interface receives a copy: the interface is one shared L2 segment. The sender
    /// does not receive its own frame.
    fn raw_write(&self, fd: c_int, buf: *const u8, len: usize) -> Option<NetResult> {
        let frame = unsafe { std::slice::from_raw_parts(buf, len) }.to_vec();
        let (ifindex, rec) = match self.socks.lock().unwrap().get(&fd) {
            Some(Sock::Raw {
                ifindex: Some(i),
                rec,
                ..
            }) => (*i, rec.clone()),
            _ => return err(libc::EINVAL),
        };
        let sent = self.shared().raw_send(ifindex, len);
        if sent.is_ok() {
            self.shared().capture_l2(ifindex, &frame);
        }
        match sent {
            Err(errno) => return err(errno),
            Ok(false) => {
                rec.count_sent();
                return ok(len as i64);
            }
            Ok(true) => rec.count_sent(),
        }
        let mut keys = crate::readiness::WakeKeys::default();
        keys.push(rec.wake_key());
        {
            let mut socks = self.socks.lock().unwrap();
            // Fan out to every other raw socket on the same interface: the shared L2 medium.
            for (other, sock) in socks.iter_mut() {
                if *other == fd
                    || sock
                        .rec()
                        .is_some_and(|other_rec| Arc::ptr_eq(other_rec, &rec))
                {
                    continue;
                }
                if let Sock::Raw {
                    ifindex: Some(oi),
                    rx,
                    arrived,
                    rec,
                    ..
                } = sock
                    && *oi == ifindex
                {
                    rx.push_back(frame.clone());
                    *arrived += 1;
                    rec.count_delivered(frame.len());
                    keys.push(rec.wake_key());
                }
            }
        }
        self.shared().bump_keys(keys.as_slice());
        ok(len as i64)
    }

    /// man 2 eventfd: read/write transfer a single 8-byte native-endian u64; a buffer under 8 bytes
    /// is EINVAL. A read drains the counter (or subtracts 1 in semaphore mode).
    fn eventfd_read(&self, fd: c_int, buf: *mut u8, len: usize) -> Option<NetResult> {
        if len < 8 {
            return err(libc::EINVAL);
        }
        let value = if let Some(v) = self.eventfd_take(fd) {
            v
        } else if self.is_nonblocking(fd) {
            return would_block();
        } else {
            let _waiting = snare_interpose::fd_wait(fd);
            let (woke, interrupted) =
                snare_interpose::interruptible(Restart::WithSaRestart, || {
                    readiness().wait_until_dynamic(
                        "eventfd",
                        None,
                        |keys| self.fd_interests([fd], keys),
                        || !Net::owns(self, fd) || self.eventfd_peek(fd) > 0,
                    )
                });
            if !Net::owns(self, fd) {
                return None;
            }
            if interrupted {
                return err(libc::EINTR);
            }
            if !woke {
                return err(libc::EAGAIN); // quiescent: nothing will post to this eventfd
            }
            self.eventfd_take(fd).unwrap_or(0)
        };
        unsafe { std::ptr::copy_nonoverlapping(value.to_ne_bytes().as_ptr(), buf, 8) };
        self.bump_fds([fd]);
        ok(8)
    }

    /// Adds an 8-byte value to the counter, waiting for room unless the descriptor is nonblocking.
    fn eventfd_write(&self, fd: c_int, buf: *const u8, len: usize) -> Option<NetResult> {
        if len < 8 {
            return err(libc::EINVAL);
        }
        let mut bytes = [0u8; 8];
        unsafe { std::ptr::copy_nonoverlapping(buf, bytes.as_mut_ptr(), 8) };
        let add = u64::from_ne_bytes(bytes);
        // man 2 eventfd: writing 0xffffffffffffffff (u64::MAX) is rejected with EINVAL.
        if add == u64::MAX {
            return err(libc::EINVAL);
        }
        loop {
            let mut socks = self.socks.lock().unwrap();
            let Some(Sock::Event {
                counter,
                writes,
                nonblocking,
                ready_order,
                ready_at,
                ..
            }) = socks.get_mut(&fd)
            else {
                return err(libc::EINVAL);
            };
            if add <= (u64::MAX - 1).saturating_sub(*counter) {
                *counter += add;
                *writes += 1;
                *ready_order = readiness_sequence();
                *ready_at = self.shared().tstamp_now().mono;
                break;
            }
            if *nonblocking {
                return err(libc::EAGAIN);
            }
            drop(socks);
            let (woke, interrupted) =
                snare_interpose::interruptible(Restart::WithSaRestart, || {
                    readiness().wait_until_dynamic(
                        "eventfd write",
                        None,
                        |keys| self.fd_interests([fd], keys),
                        || add <= (u64::MAX - 1).saturating_sub(self.eventfd_peek(fd)),
                    )
                });
            if interrupted {
                return err(libc::EINTR);
            }
            if !woke {
                return err(libc::EAGAIN);
            }
        }
        self.bump_fds([fd]);
        ok(8)
    }
}

/// The macOS BPF device constants (bpf(4), `<net/bpf.h>`).
#[cfg(target_os = "macos")]
mod bpf {
    // bpf(4): request codes encoded with _IOW/_IOR from <net/bpf.h>. BIOCSETIF binds the device to
    // an interface (struct ifreq), BIOCIMMEDIATE toggles immediate (unbuffered) read mode, and
    // BIOCGBLEN reads the required read-buffer length.
    /// `_IOW('B', 108, struct ifreq)`: `IOC_IN` 0x8000_0000 | 32-byte `ifreq` << 16 |
    /// 'B' << 8 | 108.
    pub(super) const BIOCSETIF: u64 = 0x8020_426c;
    /// `_IOW('B', 112, u_int)`. Accepted and ignored: reads already return each frame at once.
    pub(super) const BIOCIMMEDIATE: u64 = 0x8004_4270;
    /// `_IOR('B', 102, u_int)`: `IOC_OUT` 0x4000_0000 | 4 << 16 | 'B' << 8 | 102.
    pub(super) const BIOCGBLEN: u64 = 0x4004_4266;
    /// The header length ethercrab expects before the frame: `BPF_WORDALIGN(18+14) - 14 == 18`.
    /// bpf(4): each packet a read returns is prefixed by a struct bpf_hdr, word-aligned. XNU
    /// bsd/net/bpf.h defines `SIZEOF_BPF_HDR` as 18 whenever `sizeof(struct bpf_hdr)` is at most
    /// 20, which it is on LP64 (an 8-byte `timeval32` stamp, `bh_caplen`, `bh_datalen`, the
    /// 2-byte `bh_hdrlen`); XNU bsd/net/bpf.c bpf_attach sets
    /// `bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen` with a 14-byte Ethernet
    /// header and `BPF_ALIGNMENT` `sizeof(int32_t)`, which is 18.
    pub(super) const BPF_HDRLEN: usize = 18;
    /// The buffer length `BIOCGBLEN` reports: XNU's default `BPF_BUFSIZE`, 4096 (bsd/net/bpf.c).
    /// Reads here return one frame each, so it only sizes the caller's buffer.
    pub(super) const BUF_LEN: u32 = 4096;
}

/// On macOS the fabric serves `/dev/bpf*` raw L2 (ethercrab's BSD transport); on Linux it declines
/// every path (the trait defaults), so registering it as the file plane is a no-op there. A BPF
/// device is a `Sock::Raw` minted by `open` and bound with `BIOCSETIF`, framed with a `bpf_hdr`
/// on read, sharing the sim's interfaces and frame fan-out with the socket path.
impl Fs for Fabric {
    /// Whether `fd` is a raw endpoint (on macOS, always a BPF device).
    #[cfg(target_os = "macos")]
    fn owns(&self, fd: c_int) -> bool {
        if self.fds.held(fd) == Some(false) {
            return false;
        }
        matches!(self.socks.lock().unwrap().get(&fd), Some(Sock::Raw { .. }))
    }

    /// Opens any `/dev/bpf*` path as an unbound raw endpoint (every unit number is free); declines
    /// every other path.
    #[cfg(target_os = "macos")]
    unsafe fn open(
        &self,
        path: *const std::ffi::c_char,
        flags: c_int,
        _mode: u32,
    ) -> Option<NetResult> {
        if path.is_null() {
            return None;
        }
        let name = unsafe { std::ffi::CStr::from_ptr(path) }.to_str().ok()?;
        if !name.starts_with("/dev/bpf") {
            return None; // not a BPF device: let a VirtualFs or the real OS take it
        }
        // The /dev/bpf* nodes are root-only (crw------- root:wheel: XNU bsd/net/bpf.c
        // bpf_make_dev_t creates them with mode 0600). Wireshark's ChmodBPF can loosen this on a
        // real host; the sim keeps the default.
        if !self.shared().sys.privileges().root {
            return err(libc::EACCES);
        }
        let nonblocking = flags & libc::O_NONBLOCK != 0;
        self.open_socket(SocketKind::Packet, 0, |rec| Sock::Raw {
            ifindex: None,
            rx: VecDeque::new(),
            arrived: 0,
            nonblocking,
            rec,
        })
    }

    /// The BPF ioctls ethercrab uses: `BIOCSETIF` binds the device to the interface named in the
    /// `ifreq` (ENXIO for an unknown one, as XNU bsd/net/bpf.c bpfioctl's `BIOCSETIF` case gives
    /// when `ifunit` finds no interface), `BIOCGBLEN` reports
    /// `bpf::BUF_LEN`, `BIOCIMMEDIATE` is accepted. Others are declined.
    #[cfg(target_os = "macos")]
    unsafe fn ioctl(&self, fd: c_int, request: u64, arg: i64) -> Option<NetResult> {
        if !matches!(self.socks.lock().unwrap().get(&fd), Some(Sock::Raw { .. })) {
            return None;
        }
        match request {
            bpf::BIOCIMMEDIATE => ok(0),
            bpf::BIOCGBLEN => {
                if arg == 0 {
                    return err(libc::EFAULT);
                }
                unsafe { (arg as *mut u32).write_unaligned(bpf::BUF_LEN) };
                ok(0)
            }
            bpf::BIOCSETIF => {
                let base = arg as *const u8;
                if base.is_null() {
                    return err(libc::EFAULT);
                }
                let mut name = Vec::new();
                for i in 0..libc::IFNAMSIZ {
                    let b = unsafe { *base.add(i) };
                    if b == 0 {
                        break;
                    }
                    name.push(b);
                }
                let Ok(name) = String::from_utf8(name) else {
                    return err(libc::EINVAL);
                };
                let Some(index) = self.shared().topo().index_of(&name) else {
                    return err(libc::ENXIO);
                };
                if let Some(Sock::Raw { ifindex, .. }) = self.socks.lock().unwrap().get_mut(&fd) {
                    *ifindex = Some(index);
                }
                ok(0)
            }
            _ => None,
        }
    }

    /// Reads one frame behind a `bpf_hdr`, truncated to `len`. A real BPF read returns a whole
    /// buffer of packets and fails with EINVAL unless `len` equals the buffer length (bpf(4));
    /// here each read carries exactly one frame and any length is accepted.
    #[cfg(target_os = "macos")]
    unsafe fn read(&self, fd: c_int, buf: *mut u8, len: usize) -> Option<NetResult> {
        let frame = if let Some(f) = self.raw_pop(fd) {
            f
        } else if self.is_nonblocking(fd) {
            return would_block();
        } else if readiness().wait_until_dynamic(
            "bpf read",
            self.recv_deadline(fd),
            |keys| self.fd_interests([fd], keys),
            || self.raw_has(fd),
        ) {
            self.raw_pop(fd)?
        } else {
            return err(libc::EAGAIN); // quiescent deadlock or SO_RCVTIMEO timeout
        };
        // bpf(4) struct bpf_hdr with XNU's 8-byte `timeval32` stamp (bsd/net/bpf.h BPF_TIMEVAL):
        // bh_tstamp(8, zero), bh_caplen@8, bh_datalen@12, bh_hdrlen@16, frame@18. bh_caplen ==
        // bh_datalen since nothing is truncated.
        let fl = frame.len() as u32;
        let mut out = vec![0u8; bpf::BPF_HDRLEN + frame.len()];
        out[8..12].copy_from_slice(&fl.to_ne_bytes());
        out[12..16].copy_from_slice(&fl.to_ne_bytes());
        out[16..18].copy_from_slice(&(bpf::BPF_HDRLEN as u16).to_ne_bytes());
        out[bpf::BPF_HDRLEN..].copy_from_slice(&frame);
        let n = len.min(out.len());
        unsafe { std::ptr::copy_nonoverlapping(out.as_ptr(), buf, n) };
        ok(n as i64)
    }

    /// Sends one whole Ethernet frame, as `Fabric::raw_write`.
    #[cfg(target_os = "macos")]
    unsafe fn write(&self, fd: c_int, buf: *const u8, len: usize) -> Option<NetResult> {
        self.raw_write(fd, buf, len)
    }

    /// Closes a BPF device: forgets it and closes the real fd behind it.
    #[cfg(target_os = "macos")]
    unsafe fn close(&self, fd: c_int) -> Option<NetResult> {
        unsafe { Net::close(self, fd) }
    }

    #[cfg(target_os = "macos")]
    unsafe fn fd_replaced(&self, fd: c_int) -> Option<NetResult> {
        unsafe { Net::fd_replaced(self, fd) }
    }
}

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

    fn event(counter: u64) -> Sock {
        Sock::Event {
            ready_order: 0,
            ready_at: Duration::ZERO,
            counter,
            nonblocking: false,
            semaphore: false,
            writes: 0,
            reads: 0,
        }
    }

    fn counter(sockets: &Sockets, fd: c_int) -> u64 {
        let Sock::Event { counter, .. } = sockets.get(&fd).unwrap() else {
            panic!("expected event")
        };
        *counter
    }

    #[test]
    fn aliases_share_status_flags_and_socket_state() {
        crate::Sim::new().run(|| {
            let mut sockets = Sockets::default();
            sockets.insert(30, event(1));
            sockets.alias(30, 10);
            let id = sockets.identity(30).unwrap();
            sockets.description_mut(&10).unwrap().status_flags |= libc::O_NONBLOCK;
            let Sock::Event {
                counter: value,
                nonblocking,
                ..
            } = sockets.get_mut(&10).unwrap()
            else {
                unreachable!()
            };
            *value = 7;
            *nonblocking = true;
            assert_eq!(counter(&sockets, 30), 7);
            assert_eq!(sockets.identity(10), Some(id));
            assert_eq!(
                sockets.description_mut(&30).unwrap().status_flags,
                libc::O_RDWR | libc::O_NONBLOCK
            );
            assert!(matches!(
                sockets.get(&30),
                Some(Sock::Event {
                    nonblocking: true,
                    ..
                })
            ));
            assert!(sockets.remove(&10).unwrap().is_none());
            assert_eq!(counter(&sockets, 30), 7);
            assert_eq!(sockets.identity(30), Some(id));
            assert!(sockets.remove(&30).unwrap().is_some());
        });
    }

    #[test]
    fn replacement_through_an_alias_keeps_identity_and_description_flags() {
        crate::Sim::new().run(|| {
            let mut sockets = Sockets::default();
            sockets.insert(10, event(1));
            sockets.alias(10, 20);
            let id = sockets.identity(10).unwrap();
            sockets.description_mut(&20).unwrap().status_flags |= libc::O_NONBLOCK;
            sockets.insert(20, event(9));
            assert_eq!(counter(&sockets, 10), 9);
            assert_eq!(counter(&sockets, 20), 9);
            assert_eq!(sockets.identity(10), Some(id));
            assert_eq!(sockets.identity(20), Some(id));
            assert_eq!(sockets.descriptions.len(), 1);
            assert!(sockets.free_slots.is_empty());
            assert_eq!(
                sockets.description_mut(&10).unwrap().status_flags,
                libc::O_RDWR | libc::O_NONBLOCK
            );
        });
    }

    #[test]
    fn retired_slots_are_recycled_without_reusing_open_description_identity() {
        crate::Sim::new().run(|| {
            let mut sockets = Sockets::default();
            sockets.insert(10, event(1));
            sockets.alias(10, 20);
            let previous = sockets.descriptors[&10];
            assert!(sockets.remove(&10).unwrap().is_none());
            assert!(sockets.free_slots.is_empty());
            assert!(sockets.remove(&20).unwrap().is_some());
            assert!(sockets.get(&10).is_none());
            sockets.insert(10, event(2));
            let current = sockets.descriptors[&10];
            assert_eq!(current.slot, previous.slot);
            assert_ne!(current.id, previous.id);
            assert_eq!(sockets.descriptions.len(), 1);
            assert_eq!(counter(&sockets, 10), 2);
            #[cfg(target_os = "linux")]
            {
                assert!(sockets.get_identity(previous.id).is_none());
                assert!(matches!(
                    sockets.get_identity(current.id),
                    Some(Sock::Event { counter: 2, .. })
                ));
            }
            sockets.insert(30, event(3));
            let replaced = sockets.identity(30).unwrap();
            assert!(sockets.remove(&30).unwrap().is_some());
            sockets.alias(10, 30);
            assert_eq!(sockets.identity(30), Some(current.id));
            assert_eq!(counter(&sockets, 30), 2);
            #[cfg(target_os = "linux")]
            assert!(sockets.get_identity(replaced).is_none());
            #[cfg(not(target_os = "linux"))]
            let _ = replaced;
        });
    }

    #[test]
    fn description_iteration_uses_one_smallest_live_descriptor_per_alias_group() {
        crate::Sim::new().run(|| {
            let mut sockets = Sockets::default();
            sockets.insert(30, event(1));
            sockets.alias(30, 10);
            sockets.alias(30, 20);
            sockets.insert(40, event(2));
            let mut descriptors: Vec<_> = sockets.iter().map(|(fd, _)| *fd).collect();
            descriptors.sort();
            assert_eq!(descriptors, [10, 20, 30, 40]);
            let mut representatives: Vec<_> = sockets.iter_mut().map(|(fd, _)| *fd).collect();
            representatives.sort();
            assert_eq!(representatives, [10, 40]);
            assert!(sockets.remove(&10).unwrap().is_none());
            representatives = sockets.iter_mut().map(|(fd, _)| *fd).collect();
            representatives.sort();
            assert_eq!(representatives, [20, 40]);
            assert_eq!(sockets.descriptions.iter().flatten().count(), 2);
        });
    }
}

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

    #[test]
    fn inline_and_heap_payloads_preserve_bytes_and_owned_conversion() {
        crate::Sim::new().run(|| {
            println!(
                "Datagram={} Payload={} Vec={} alignments={}/{}",
                std::mem::size_of::<Datagram>(),
                std::mem::size_of::<Payload>(),
                std::mem::size_of::<Vec<u8>>(),
                std::mem::align_of::<Payload>(),
                std::mem::align_of::<Vec<u8>>()
            );
            for len in [0, 127, 128, 129, 65_507] {
                let mut bytes: Vec<_> = (0..len).map(|i| (i % 251) as u8).collect();
                let expected = bytes.clone();
                let payload = Payload::copy_from(&bytes);
                bytes.fill(255);
                assert_eq!(&*payload, expected);
                assert_eq!(&*payload.clone(), expected);
                assert_eq!(matches!(payload, Payload::Inline { .. }), len <= 128);
                let ptr = payload.as_ptr();
                let converted = payload.into_vec();
                assert_eq!(converted, expected);
                if len > 128 {
                    assert_eq!(converted.as_ptr(), ptr);
                }
            }
        });
    }
}

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

    fn listener(addr: &str, tester: bool) -> Arc<Listener> {
        Arc::new(Listener {
            rec: None,
            addr: addr.parse().unwrap(),
            dual: false,
            pending: Mutex::default(),
            capacity: AtomicUsize::new(usize::MAX),
            occupied: AtomicUsize::new(0),
            tester,
            arrivals: AtomicU64::new(0),
            ready_order: AtomicU64::new(0),
            ready_at: AtomicU64::new(0),
        })
    }

    #[test]
    fn listeners_share_an_address_and_a_tester_replaces_them() {
        let ip: IpAddr = "127.0.0.5".parse().unwrap();
        let first = listener("127.0.0.5:9400", true);
        let second = listener("127.0.0.5:9401", true);
        let socket = listener("127.0.0.5:9400", false);
        let mut listeners = Listeners::default();
        listeners.insert(first.addr, first.clone());
        listeners.insert(second.addr, second.clone());
        listeners.insert(first.addr, socket.clone());
        assert_eq!(listeners.at(&first.addr).len(), 2);
        assert_eq!(listeners.testers.get(&ip), Some(&2));
        listeners.remove(&second);
        assert_eq!(listeners.testers.get(&ip), Some(&1));
        listeners.remove(&first);
        assert!(listeners.testers.is_empty());
        assert!(Arc::ptr_eq(&listeners.at(&first.addr)[0], &socket));
        listeners.insert(first.addr, first.clone());
        listeners.insert(first.addr, first.clone());
        assert_eq!(listeners.at(&first.addr).len(), 1);
        assert_eq!(listeners.testers.get(&ip), Some(&1));
        assert_eq!(listeners.on_port(9400).count(), 1);
        listeners.remove(&first);
        assert!(listeners.testers.is_empty());
        assert!(listeners.is_empty());
        assert_eq!(listeners.on_port(9400).count(), 0);
    }

    #[test]
    fn endpoints_and_sockets_share_an_address_until_each_leaves() {
        use std::os::fd::AsRawFd;

        crate::Sim::new().run(|| {
            let socket = std::net::UdpSocket::bind("127.0.0.1:9000").unwrap();
            let rec = current()
                .shared
                .sockets
                .lookup_fd(socket.as_raw_fd())
                .unwrap();
            let ordinary = Arc::new(DgramQueue {
                rec: Some(rec),
                ..DgramQueue::default()
            });
            let endpoint = Arc::new(DgramQueue::default());
            let mut registry = UdpRegistry::default();
            let first: SocketAddr = "127.0.0.5:9400".parse().unwrap();
            let second: SocketAddr = "127.0.0.5:9401".parse().unwrap();
            registry.insert(first, endpoint.clone());
            registry.insert(second, endpoint.clone());
            registry.insert(first, ordinary.clone());
            assert_eq!(registry.endpoints.get(&first.ip()), Some(&2));
            registry.remove(&second, &endpoint);
            assert_eq!(registry.endpoints.get(&first.ip()), Some(&1));
            registry.insert(first, endpoint.clone());
            assert_eq!(registry.endpoints.get(&first.ip()), Some(&1));
            registry.remove(&first, &endpoint);
            assert!(!registry.endpoints.contains_key(&first.ip()));
            let left = registry.candidates(first, false);
            assert_eq!(left.len(), 1);
            assert!(Arc::ptr_eq(&left[0].q, &ordinary));
            registry.remove(&first, &ordinary);
            assert!(registry.candidates(first, false).is_empty());
            assert!(registry.bound.is_empty());
        });
    }

    #[test]
    fn port_candidates_follow_bindings_through_bucket_removals() {
        crate::Sim::new().run(|| {
            let mut registry = UdpRegistry::default();
            let addresses: Vec<SocketAddr> = [
                "127.0.0.1:9400",
                "0.0.0.0:9400",
                "127.0.0.2:9400",
                "[::1]:9400",
                "127.0.0.1:9401",
            ]
            .map(|addr| addr.parse().unwrap())
            .to_vec();
            let mut bound = Vec::new();
            for _ in 0..2 {
                for &address in &addresses {
                    let queue = Arc::new(DgramQueue::default());
                    registry.insert(address, queue.clone());
                    bound.push((address, queue));
                }
            }
            let key = |q: &Arc<DgramQueue>| Arc::as_ptr(q) as usize;
            while let Some((removed, queue)) = bound.pop() {
                for &destination in &addresses {
                    let mut actual: Vec<_> = registry
                        .candidates(destination, false)
                        .into_iter()
                        .map(|candidate| {
                            assert!(
                                registry.bound[&candidate.addr]
                                    .iter()
                                    .any(|q| Arc::ptr_eq(q, &candidate.q))
                            );
                            (candidate.addr, key(&candidate.q))
                        })
                        .collect();
                    let mut expected: Vec<_> = bound
                        .iter()
                        .chain(std::iter::once(&(removed, queue.clone())))
                        .filter(|(addr, _)| addr.port() == destination.port())
                        .map(|(addr, q)| (*addr, key(q)))
                        .collect();
                    actual.sort();
                    expected.sort();
                    assert_eq!(actual, expected);
                }
                registry.remove(&removed, &queue);
            }
            assert!(registry.by_port.is_empty());
            assert!(registry.bound.is_empty());
        });
    }

    #[test]
    fn allocation_wraps_and_reuses_both_edges_of_a_full_range() {
        crate::Sim::new().run(|| {
            let mut ports = UdpPorts::default();
            ports.insert(UdpPorts::FIRST);
            assert_eq!(ports.alloc_from(UdpPorts::FIRST), UdpPorts::FIRST + 1);
            assert_eq!(ports.alloc_from(u16::MAX), u16::MAX);
            ports.remove(UdpPorts::FIRST);
            for port in UdpPorts::FIRST..=u16::MAX {
                ports.insert(port);
            }
            assert_eq!(ports.alloc_from(UdpPorts::FIRST), 0);
            assert_eq!(ports.alloc_from(u16::MAX), 0);
            ports.remove(UdpPorts::FIRST);
            assert_eq!(ports.alloc_from(u16::MAX), UdpPorts::FIRST);
            ports.remove(u16::MAX);
            assert_eq!(ports.alloc_from(u16::MAX - 1), u16::MAX);
            assert_eq!(ports.alloc_from(UdpPorts::FIRST), UdpPorts::FIRST);
            ports.insert(UdpPorts::FIRST);
            assert_eq!(ports.alloc_from(UdpPorts::FIRST), u16::MAX);
            ports.insert(u16::MAX);
            assert_eq!(ports.alloc_from(UdpPorts::FIRST), 0);
        });
    }

    #[test]
    fn scoped_addresses_and_queue_replacement_keep_ports_occupied() {
        crate::Sim::new().run(|| {
            let mut registry = UdpRegistry::default();
            let ip: Ipv6Addr = "fe80::1".parse().unwrap();
            let first = SocketAddr::V6(std::net::SocketAddrV6::new(ip, 49152, 0, 1));
            let second = SocketAddr::V6(std::net::SocketAddrV6::new(ip, 49152, 0, 2));
            let queue = Arc::new(DgramQueue::default());
            let sharing = Arc::new(DgramQueue::default());
            registry.insert(first, queue.clone());
            registry.insert(first, sharing.clone());
            registry.insert(second, queue.clone());
            registry.remove(&first, &queue);
            assert_eq!(registry.alloc_port(IpAddr::V6(ip), false), 49153);
            registry.remove(&first, &sharing);
            assert_eq!(registry.alloc_port(IpAddr::V6(ip), false), 49153);
            assert_eq!(
                registry.alloc_port(IpAddr::V6(Ipv6Addr::UNSPECIFIED), false),
                49153
            );
            registry.remove(&second, &queue);
            assert_eq!(registry.alloc_port(IpAddr::V6(ip), false), 49152);
            assert_eq!(
                registry.alloc_port(IpAddr::V6(Ipv6Addr::UNSPECIFIED), false),
                49152
            );
        });
    }
}