safeptrace 0.5.8

Safe, ergonomic Rust wrappers around the Linux ptrace(2) API.
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
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

#![deny(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]
#![cfg(target_os = "linux")]

//! A safe ptrace API. This API forces correct usage of ptrace in that it is
//! not possible to call ptrace on a process not in a stopped state.
//!
//! With `notifier`, generic wait and exit futures retain their Send contract
//! and require native thread pidfds (Linux 6.9 or newer). A native
//! `PIDFD_THREAD` acquisition refusal with `EINVAL` reports this requirement
//! to stderr on a best-effort basis and returns the same typed errno.
//! Select the named `_on_ptracer_thread`
//! constructors and waits to permit a retained legacy fallback. Their local
//! wrappers are !Send and !Sync on every kernel; their Send manual drivers
//! do not implement Future. Borrow and retain the same driver through refusal
//! and cancellation, and progress it only on its original ptracer OS thread.
//! The explicit mode requires procfs aligned with the caller's PID namespace;
//! mismatched inherited mounts are refused with EXDEV. Descriptor SIGKILL
//! remains available; exact thread SIGSTOP requires a native thread pidfd.
#[cfg(feature = "memory")]
mod memory;
#[cfg(feature = "notifier")]
mod notifier;
mod regs;
mod syscall_info;
#[cfg(test)]
mod test_fork;
mod waitid;

use core::mem::MaybeUninit;
use std::fmt;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;

use nix::sys::ptrace;
// Re-exports so that nothing else needs to depend on `nix`.
pub use nix::sys::ptrace::Options;
pub use nix::sys::signal::Signal;
use nix::sys::wait::WaitPidFlag;
use nix::sys::wait::WaitStatus;
pub use reverie_process::ExitStatus;
pub use reverie_process::Pid;
pub use syscalls::Errno;
use syscalls::Sysno;
use thiserror::Error;

#[cfg(feature = "notifier")]
pub use crate::notifier::ExitFuture;
#[cfg(feature = "notifier")]
pub use crate::notifier::GuardedPendingStatusReservation;
#[cfg(feature = "notifier")]
pub use crate::notifier::PendingStatusReservation;
#[cfg(feature = "notifier")]
pub use crate::notifier::ProcStatError;
#[cfg(feature = "notifier")]
pub use crate::notifier::PtracerCleanupDriver;
#[cfg(feature = "notifier")]
pub use crate::notifier::PtracerExitDriver;
#[cfg(feature = "notifier")]
pub use crate::notifier::PtracerExitFuture;
#[cfg(feature = "notifier")]
pub use crate::notifier::PtracerOwnedWaitFuture;
#[cfg(feature = "notifier")]
pub use crate::notifier::PtracerPendingStatusReservation;
#[cfg(feature = "notifier")]
pub use crate::notifier::PtracerSyncDriver;
#[cfg(feature = "notifier")]
pub use crate::notifier::PtracerSyncWait;
#[cfg(feature = "notifier")]
pub use crate::notifier::PtracerTerminalCleanup;
#[cfg(feature = "notifier")]
pub use crate::notifier::PtracerThreadGuard;
#[cfg(feature = "notifier")]
pub use crate::notifier::PtracerWaitDriver;
#[cfg(feature = "notifier")]
pub use crate::notifier::PtracerWaitFuture;
#[cfg(feature = "notifier")]
pub use crate::notifier::StopObservationError;
#[cfg(feature = "notifier")]
pub use crate::notifier::StopObservationSample;
#[cfg(feature = "notifier")]
pub use crate::notifier::StopSiginfo;
#[cfg(feature = "notifier")]
pub use crate::notifier::StoppedObservation;
#[cfg(feature = "notifier")]
pub use crate::notifier::SupersededStopRefusal;
#[cfg(feature = "notifier")]
pub use crate::notifier::TerminalCleanup;
pub use crate::regs::*;
pub use crate::syscall_info::SyscallInfo;
pub use crate::syscall_info::SyscallInfoError;
pub use crate::syscall_info::SyscallInfoOp;
use crate::waitid::IdType;
use crate::waitid::wait_status;

/// Immutable generation token carried through every typed tracee state.
#[derive(Clone, Debug)]
struct TraceeToken {
    #[cfg(feature = "notifier")]
    event: notifier::EventHandle,
    #[cfg(feature = "notifier")]
    policy: notifier::WaitPolicy,
    #[cfg(feature = "notifier")]
    ptracer_owner: Option<std::sync::Arc<notifier::LegacyWaitOwner>>,
    #[cfg(feature = "notifier")]
    // Host selection alone does not authorize a wait for this generation.
    // Retain an actual attachment/real-parent proof through later retirement.
    ptracer_wait_role: bool,
}

impl PartialEq for TraceeToken {
    fn eq(&self, other: &Self) -> bool {
        #[cfg(feature = "notifier")]
        return self.event == other.event;
        #[cfg(not(feature = "notifier"))]
        {
            let _ = other;
            true
        }
    }
}
impl Eq for TraceeToken {}
impl std::hash::Hash for TraceeToken {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        #[cfg(feature = "notifier")]
        {
            std::hash::Hash::hash(&self.event, state);
        }
        #[cfg(not(feature = "notifier"))]
        let _ = state;
    }
}

impl TraceeToken {
    fn new() -> Self {
        Self {
            #[cfg(feature = "notifier")]
            event: notifier::EventHandle::new(),
            #[cfg(feature = "notifier")]
            policy: notifier::WaitPolicy::Native,
            #[cfg(feature = "notifier")]
            ptracer_owner: None,
            #[cfg(feature = "notifier")]
            ptracer_wait_role: false,
        }
    }

    fn current_or_new(pid: Pid) -> Result<Self, Errno> {
        #[cfg(not(feature = "notifier"))]
        let _ = pid;
        Ok(Self {
            #[cfg(feature = "notifier")]
            event: notifier::EventHandle::current_or_new(pid)?,
            #[cfg(feature = "notifier")]
            policy: notifier::WaitPolicy::Native,
            #[cfg(feature = "notifier")]
            ptracer_owner: None,
            #[cfg(feature = "notifier")]
            ptracer_wait_role: false,
        })
    }

    /// The generation that `pid` names now, shared with every other
    /// capability for it as `current_or_new` shares it, or a fresh token if
    /// the task's identity cannot be captured. A fresh token is bound to no
    /// generation, so its requests are not held off by the TID gate that the
    /// task's reaper marks.
    fn current_or_fresh(pid: Pid) -> Self {
        Self::current_or_new(pid).unwrap_or_else(|_| Self::new())
    }

    fn current_or_error(pid: Pid) -> Self {
        #[cfg(not(feature = "notifier"))]
        let _ = pid;
        Self {
            #[cfg(feature = "notifier")]
            event: notifier::EventHandle::current_or_error(pid),
            #[cfg(feature = "notifier")]
            policy: notifier::WaitPolicy::Native,
            #[cfg(feature = "notifier")]
            ptracer_owner: None,
            #[cfg(feature = "notifier")]
            ptracer_wait_role: false,
        }
    }

    #[cfg(feature = "notifier")]
    fn from_event(event: notifier::EventHandle) -> Self {
        Self::from_event_for_policy(event, notifier::WaitPolicy::Native)
    }

    #[cfg(feature = "notifier")]
    fn from_event_for_policy(event: notifier::EventHandle, policy: notifier::WaitPolicy) -> Self {
        let ptracer_owner = (policy == notifier::WaitPolicy::PtracerThread)
            .then(|| event.capture_current_ptracer_owner().ok())
            .flatten();
        let ptracer_wait_role = ptracer_owner.is_some();
        Self {
            event,
            policy,
            ptracer_owner,
            ptracer_wait_role,
        }
    }

    #[cfg(feature = "notifier")]
    fn current_on_ptracer_thread(pid: Pid) -> Result<Self, Errno> {
        let mut token = Self::from_event_for_policy(
            notifier::EventHandle::current_or_new_on_ptracer_thread(pid)?,
            notifier::WaitPolicy::PtracerThread,
        );
        if token.ptracer_owner.is_none() && token.event().current_tracer_pid()?.as_raw() == 0 {
            token.ptracer_owner = Some(token.event().capture_current_constructor_owner()?);
            // Selecting an untraced nonchild remains available for a later
            // attachment. It grants no wait role. A positive direct-parent
            // proof can be retained now, before the target later disappears;
            // any refusal is rechecked by the first named wait operation.
            token.ptracer_wait_role = token
                .event()
                .authenticates_wait_role(token.ptracer_owner.as_ref().unwrap())
                .unwrap_or(false);
        }
        Ok(token)
    }

    #[cfg(feature = "notifier")]
    fn capture_child(&self, pid: Pid) -> Result<Running, Errno> {
        // Adopting the child's Event can run `Waker` callbacks. Those go
        // through `WakerSlot`, which records them; recording them here too
        // is deliberately cautious.
        notifier::note_waker_callbacks();
        let child = if self.policy == notifier::WaitPolicy::PtracerThread {
            Running::new_on_ptracer_thread(pid)
        } else {
            Running::from_current_or_new(pid)
        };
        notifier::note_waker_callbacks();
        child
    }

    #[cfg(not(feature = "notifier"))]
    fn capture_child(&self, pid: Pid) -> Result<Running, Errno> {
        Running::from_current_or_new(pid)
    }

    #[cfg(feature = "notifier")]
    fn event(&self) -> &notifier::EventHandle {
        &self.event
    }

    /// Runs one numeric request on this generation's TID.
    ///
    /// Under the notifier, a fatal signal can end the stop that a capability
    /// names, and the generation's reaper can then release the TID for reuse
    /// while the capability is still held. Once that reap has marked this
    /// generation's gate, the request fails with `ESRCH` without reaching the
    /// kernel, so it does not name a replacement task. A reap that marks no
    /// gate lets the request through while nothing else has marked it: a
    /// reap while the generation is unbound, a bulk wait, or an order in
    /// <https://github.com/rrnewton/reverie/issues/860>. Without the notifier
    /// the request always runs.
    fn on_held_tid<T>(&self, request: impl FnOnce() -> Result<T, Errno>) -> Result<T, Errno> {
        #[cfg(feature = "notifier")]
        if let Some(error) = self.event.initial_capture_error() {
            return Err(error);
        }
        #[cfg(feature = "notifier")]
        let Some(_held) = self.event.hold_tid() else {
            return Err(Errno::ESRCH);
        };
        #[cfg(feature = "notifier")]
        if self.policy == notifier::WaitPolicy::PtracerThread {
            // A retained task generation cannot make a copied numeric PID
            // meaningful in another host task or PID namespace. Use this
            // token's original owner; never recapture one from the number.
            let owner = self.ptracer_owner.as_ref().ok_or(Errno::EPERM)?;
            if !owner.is_current()? {
                return Err(Errno::EPERM);
            }
            // Nonleader exec can release its former TID before an
            // unregistered Event has any reaper to close the gate. Refuse
            // an already-retired retained target before a numeric request
            // can address its replacement. This is a lifetime precheck,
            // not an atomic descriptor-valued ptrace operation.
            self.event.check_numeric_target_lifetime(owner)?;
        }
        request()
    }
}

fn nix_errno(err: nix::Error) -> Errno {
    Errno::new(err as i32)
}

#[cfg(target_arch = "x86_64")]
const NT_X86_XSTATE: i32 = 0x202;

/// An error that occurred during tracing.
#[derive(Error, Debug, Eq, PartialEq)]
pub enum Error {
    /// A low-level errno.
    #[error(transparent)]
    Errno(#[from] Errno),

    /// The tracee died unexpectedly. This should be handled gracefully by
    /// reaping the zombie.
    #[error("tracee {0} is a zombie")]
    Died(Zombie),
}

impl From<nix::errno::Errno> for Error {
    fn from(err: nix::errno::Errno) -> Self {
        Self::Errno(Errno::new(err as i32))
    }
}

#[cfg(feature = "notifier")]
pub use notifier::OwnedWaitError;
#[cfg(feature = "notifier")]
pub use notifier::OwnedWaitFuture;

/// Represents an invalid state. Useful for errors.
#[derive(Debug, Eq, PartialEq)]
struct InvalidState(pub TryWait);

impl From<InvalidState> for TryWait {
    fn from(error: InvalidState) -> TryWait {
        error.0
    }
}

impl fmt::Display for InvalidState {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "got unexpected status {}", self.0)
    }
}

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

/// Indicates how a child was created (i.e., via `fork`, `vfork`, or `clone`).
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ChildOp {
    /// Stop before return from `fork(2)` or `clone(2)` with the exit signal set
    /// to `SIGCHLD`.
    Fork,

    /// Stop before return from `vfork(2)` or `clone(2)` with the `CLONE_VFORK`
    /// flag. When the tracee is continued after this stop, it will wait for
    /// child to exit/exec before continuing its execution (in other words, the
    /// usual behavior on `vfork(2)`).
    Vfork,

    /// Stop before return from `clone(2)`.
    Clone,
}

/// A signal number, including one `nix`'s [`Signal`] cannot name: Linux's
/// signals run from 1 to 64, and `nix` names only 1 to 31. Realtime signals
/// (32 to 64; glibc reserves 32 and 33, so `SIGRTMIN()` is 34) are real and
/// deliverable. It compares equal to the `nix` signal with the same number
/// (<https://github.com/rrnewton/reverie/issues/207>).
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct AnySignal(i32);

impl AnySignal {
    /// The signal numbered `raw`, if Linux has one (1 to 64).
    pub fn new(raw: i32) -> Option<Self> {
        (1..=64).contains(&raw).then_some(Self(raw))
    }

    /// The raw signal number.
    pub fn raw(self) -> i32 {
        self.0
    }

    /// The `nix` signal, `None` for one it cannot name.
    pub fn as_nix(self) -> Option<Signal> {
        Signal::try_from(self.0).ok()
    }
}

impl From<Signal> for AnySignal {
    fn from(signal: Signal) -> Self {
        Self(signal as i32)
    }
}

impl PartialEq<Signal> for AnySignal {
    fn eq(&self, other: &Signal) -> bool {
        self.0 == *other as i32
    }
}

impl PartialEq<AnySignal> for Signal {
    fn eq(&self, other: &AnySignal) -> bool {
        *self as i32 == other.0
    }
}

impl std::fmt::Debug for AnySignal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.as_nix() {
            Some(signal) => write!(f, "{signal:?}"),
            None => write!(f, "SIG{}", self.0),
        }
    }
}

impl std::fmt::Display for AnySignal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.as_nix() {
            Some(signal) => write!(f, "{signal}"),
            None => write!(f, "SIG{}", self.0),
        }
    }
}

/// A stop event. Documentation is from `ptrace(2)`.
#[derive(Debug, Eq, PartialEq)]
pub enum Event {
    /// Stop event after a new child has been created (i.e., via `fork`, `vfork`,
    /// or `clone`).
    NewChild(ChildOp, Running),

    /// Stop before return from `execve(2)`. Since Linux 3.0,
    /// `PTRACE_GETEVENTMSG` returns the former thread ID.
    Exec(Pid),

    /// Stop before return from `vfork(2)` or `clone(2)` with the `CLONE_VFORK`
    /// flag, but after the child unblocked this tracee by exiting or execing.
    VforkDone,

    /// Stop before exit (including death from `exit_group(2)`), signal death, or
    /// exit caused by `execve(2)` in a multithreaded process.
    /// `PTRACE_GETEVENTMSG` returns the exit status. Registers can be examined
    /// (unlike when "real" exit happens). The tracee is still alive; it needs to
    /// be `PTRACE_CONT`ed or `PTRACE_DETACH`ed to finish exiting.
    Exit,

    /// Stop triggered by a `seccomp(2)` rule on tracee syscall entry when
    /// `PTRACE_O_TRACESECCOMP` has been set by the tracer. The seccomp event
    /// message data (from the `SECCOMP_RET_DATA` portion of the seccomp filter
    /// rule) can be retrieved with `PTRACE_GETEVENTMSG`. The semantics of this
    /// stop are described in detail in a separate section below.
    Seccomp,

    /// Stop induced by PTRACE_INTERRUPT command, or group-stop, or initial
    /// ptrace-stop when a new child is attached (only if attached using
    /// PTRACE_SEIZE).
    Stop,

    /// The tracee was stopped by execution of a system call.
    Syscall,

    /// The tracee was stopped by delivery of a signal.
    Signal(Signal),

    /// The tracee was stopped by delivery of a signal that `nix`'s `Signal`
    /// cannot name: a realtime signal, 32 to 64 (glibc reserves 32 and 33,
    /// so `SIGRTMIN()` is 34). It is the raw signal number, always 32 to 64.
    /// Resume with [`Stopped::resume_raw`] or [`Stopped::syscall_raw`] to
    /// deliver it. Before, such a stop failed to decode with EINVAL, or, on
    /// the wait paths without the `notifier` feature, was reported as a
    /// SIGSTOP (<https://github.com/rrnewton/reverie/issues/207>).
    RawSignal(i32),
}

impl Event {
    /// The signal of a signal-delivery stop ([`Event::Signal`] or
    /// [`Event::RawSignal`]), or `None` for any other stop.
    pub fn signal(&self) -> Option<AnySignal> {
        match *self {
            Event::Signal(sig) => Some(sig.into()),
            Event::RawSignal(raw) => AnySignal::new(raw),
            _ => None,
        }
    }

    /// The signal-delivery stop event for `sig`: [`Event::Signal`] when nix
    /// names it, else [`Event::RawSignal`].
    pub fn from_signal(sig: AnySignal) -> Self {
        match sig.as_nix() {
            Some(sig) => Event::Signal(sig),
            None => Event::RawSignal(sig.raw()),
        }
    }

    /// Converts a raw i32 to a ptrace event and gets any associated data.
    fn from_ptrace_event(task: &Stopped, event: i32) -> Result<Self, Error> {
        // Note that there is no danger in calling ptrace here because the
        // process is guaranteed to be in a ptrace-stop state when this function
        // is called.
        match event {
            libc::PTRACE_EVENT_FORK => {
                // Get the pid of the child immediately since we almost always
                // want that.
                let child_pid = Pid::from_raw(task.getevent()? as i32);
                #[cfg(all(test, feature = "notifier"))]
                notifier::register_new_child_for_test_cleanup(task.1.event(), child_pid)?;
                Ok(Self::NewChild(
                    ChildOp::Fork,
                    task.1.capture_child(child_pid)?,
                ))
            }
            libc::PTRACE_EVENT_VFORK => {
                // Get the pid of the child immediately since we almost always
                // want that.
                let child_pid = Pid::from_raw(task.getevent()? as i32);
                #[cfg(all(test, feature = "notifier"))]
                notifier::register_new_child_for_test_cleanup(task.1.event(), child_pid)?;
                Ok(Self::NewChild(
                    ChildOp::Vfork,
                    task.1.capture_child(child_pid)?,
                ))
            }
            libc::PTRACE_EVENT_CLONE => {
                // Get the pid of the child immediately since we almost always
                // want that.
                let child_pid = Pid::from_raw(task.getevent()? as i32);
                #[cfg(all(test, feature = "notifier"))]
                notifier::register_new_child_for_test_cleanup(task.1.event(), child_pid)?;
                Ok(Self::NewChild(
                    ChildOp::Clone,
                    task.1.capture_child(child_pid)?,
                ))
            }
            libc::PTRACE_EVENT_EXEC => {
                // The event arrives under the current leader TID. GETEVENTMSG
                // identifies the executing thread's former TID; it is not a
                // newly allocated PID or a terminal status for that thread.
                let former_tid = Pid::from_raw(task.getevent()? as i32);
                // Only a task in its exec stop reports that message. A fatal
                // signal takes a tracee out of any stop without a tracer
                // request, into its exit stop, whose message is the exit
                // code. PTRACE_GETSIGINFO after GETEVENTMSG confirms the task
                // was still in its exec stop when the message was read: the
                // task never returns to an exec stop once it has left it, so
                // an exec-stop si_code here proves the message above is the
                // former TID. Any other si_code, or ESRCH, is a death under
                // ptrace: this status names a stop the tracee has left.
                let siginfo = task.getsiginfo()?;
                if siginfo.si_code != libc::SIGTRAP | (libc::PTRACE_EVENT_EXEC << 8) {
                    return Err(Error::Died(Zombie::from_token(task.0, task.1.clone())));
                }
                Ok(Self::Exec(former_tid))
            }
            libc::PTRACE_EVENT_VFORK_DONE => Ok(Self::VforkDone),
            libc::PTRACE_EVENT_EXIT => {
                // Note that we can get the exit status here using `getevent`,
                // but that's almost never what we want to do. It is better to
                // get that during the final exit event.
                Ok(Self::Exit)
            }
            libc::PTRACE_EVENT_SECCOMP => Ok(Self::Seccomp),
            libc::PTRACE_EVENT_STOP => Ok(Self::Stop),
            _ => unreachable!("unknown ptrace event {:#x}", event),
        }
    }
}

/// `NT_ARM_HW_BREAK` (include/uapi/linux/elf.h): a thread's hardware
/// breakpoint registers.
#[cfg(target_arch = "aarch64")]
const NT_ARM_HW_BREAK: i32 = 0x402;

/// `NT_ARM_TLS` (include/uapi/linux/elf.h): a thread's TPIDR_EL0.
#[cfg(target_arch = "aarch64")]
const NT_ARM_TLS: i32 = 0x401;

/// `NT_ARM_SYSTEM_CALL` (include/uapi/linux/elf.h): a thread's
/// syscall number and restart control.
#[cfg(target_arch = "aarch64")]
const NT_ARM_SYSTEM_CALL: i32 = 0x404;

/// The libc `ptrace` request word is `c_uint` on glibc and `c_int` on musl.
#[cfg(target_env = "musl")]
type PtraceRequest = libc::c_int;
#[cfg(not(target_env = "musl"))]
type PtraceRequest = libc::c_uint;

/// `PTRACE_SINGLEBLOCK` (arch/x86/include/uapi/asm/ptrace-abi.h), which the
/// libc crate does not define. Linux accepts it on every x86-64 processor
/// (`arch_has_block_step`).
#[cfg(target_arch = "x86_64")]
const PTRACE_SINGLEBLOCK: PtraceRequest = 33;

/// `ptrace(request, pid, 0, sig)` for a resuming request, with the signal as a
/// raw number so that one `nix` cannot name can be delivered.
fn ptrace_resume_raw(request: PtraceRequest, pid: Pid, sig: i32) -> Result<(), Errno> {
    Errno::result(unsafe {
        libc::ptrace(
            request,
            pid.as_raw(),
            std::ptr::null_mut::<libc::c_void>(),
            sig as libc::c_long as *mut libc::c_void,
        )
    })
    .map(drop)
}

/// Helper function for waiting on one or more processes: the PID that
/// changed state and its raw wait status, which `Wait::from_wait_helper`
/// decodes.
/// Returns `None` if `WaitPidFlag::WNOHANG` was specified and the process is
/// still running.
///
/// A raw status keeps a realtime signal's number, which `nix`'s `WaitStatus`
/// cannot hold (<https://github.com/rrnewton/reverie/issues/207>). A stop
/// whose signal is 0 is reported as a SIGSTOP, as through `WaitStatus`: the
/// status can sometimes be 0 when using PTRACE_SEIZE.
fn wait(id: IdType, flags: WaitPidFlag) -> Result<Option<(Pid, i32)>, Errno> {
    loop {
        let result = wait_status(id, flags).map(|changed| {
            changed.map(|(pid, status)| {
                if libc::WIFSTOPPED(status) && libc::WSTOPSIG(status) == 0 {
                    (pid.into(), status | (libc::SIGSTOP << 8))
                } else {
                    (pid.into(), status)
                }
            })
        });

        if result == Err(Errno::EINTR) {
            continue;
        }

        return result;
    }
}

/// The result of a non-blocking wait. A process can be in one of three main
/// states: running, ptrace-stopped, or exited.
///
/// Both `Clone` and `Copy` are intentionally not implemented. This is to enforce
/// type safety.
#[derive(Debug, Eq, PartialEq)]
pub enum TryWait {
    /// The process is in either a stopped state or an exited state.
    Wait(Wait),

    /// The process is in a running state and thus can only be waited on.
    ///
    /// When the process is successfully waited on, it transitions to a waited
    /// state.
    Running(Running),
}

impl TryWait {
    /// Returns the PID for this attempted wait.
    pub fn pid(&self) -> Pid {
        match self {
            Self::Wait(wait) => wait.pid(),
            Self::Running(running) => running.pid(),
        }
    }

    /// Returns true if we're in a running state. Note that this may not reflect
    /// the real *current* state that we may not yet have observed.
    pub fn is_running(&self) -> bool {
        matches!(self, Self::Running(_))
    }

    /// Returns true if we're in a stopped state. Note that this may not reflect
    /// the real *current* state that we may not yet have observed.
    pub fn is_stopped(&self) -> bool {
        matches!(self, Self::Wait(Wait::Stopped(_, _)))
    }

    /// Assumes the process is in a stopped state. Panics if it isn't.
    pub fn assume_stopped(self) -> (Stopped, Event) {
        match self {
            Self::Wait(Wait::Stopped(stopped, event)) => (stopped, event),
            status => panic!("{:?}", InvalidState(status)),
        }
    }

    /// Assumes the process is in a running state. Panics if it isn't.
    pub fn assume_running(self) -> Running {
        match self {
            Self::Running(running) => running,
            status => panic!("{:?}", InvalidState(status)),
        }
    }

    /// Assumes the process is in an exited state. Panics if it isn't.
    pub fn assume_exited(self) -> (Pid, ExitStatus) {
        match self {
            Self::Wait(Wait::Exited(pid, exit_status)) => (pid, exit_status),
            status => panic!("{:?}", InvalidState(status)),
        }
    }
}

impl fmt::Display for TryWait {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Wait(wait) => write!(f, "{}", wait),
            Self::Running(running) => write!(f, "pid {} is running", running.pid()),
        }
    }
}

impl From<Running> for TryWait {
    fn from(status: Running) -> Self {
        Self::Running(status)
    }
}

impl From<Wait> for TryWait {
    fn from(wait: Wait) -> Self {
        Self::Wait(wait)
    }
}

/// The result of a blocking wait. A process in this state is guaranteed to not
/// be in a running state.
///
/// Both `Clone` and `Copy` are intentionally not implemented. This is to enforce
/// type safety.
#[derive(Debug, Eq, PartialEq)]
pub enum Wait {
    /// The process is in a stopped state and thus only operations that can be
    /// done during a stopped state are allowed (i.e., ptrace operations).
    ///
    /// When the process is resumed, it transitions to a running state.
    Stopped(Stopped, Event),

    /// The process has exited with an exit status.
    Exited(Pid, ExitStatus),
}

impl Wait {
    /// Returns the PID for this state.
    pub fn pid(&self) -> Pid {
        match self {
            Self::Stopped(stopped, _) => stopped.pid(),
            Self::Exited(pid, _exit_status) => *pid,
        }
    }

    /// Assumes the process is in a stopped state. Panics if it isn't.
    pub fn assume_stopped(self) -> (Stopped, Event) {
        match self {
            Self::Stopped(stopped, event) => (stopped, event),
            state => panic!("{:?}", InvalidState(state.into())),
        }
    }

    /// Assumes the process is in an exited state. Panics if it isn't.
    pub fn assume_exited(self) -> (Pid, ExitStatus) {
        match self {
            Self::Exited(pid, exit_status) => (pid, exit_status),
            state => panic!("{:?}", InvalidState(state.into())),
        }
    }

    /// Converts a raw `i32` status to this type.
    ///
    /// Preconditions:
    /// The process must not be in a running state.
    pub fn from_raw(pid: Pid, status: i32) -> Result<Self, Error> {
        let token = if libc::WIFSTOPPED(status) {
            TraceeToken::current_or_fresh(pid)
        } else {
            TraceeToken::new()
        };
        Self::from_raw_with_token(pid, status, token)
    }

    fn from_raw_with_token(pid: Pid, status: i32, token: TraceeToken) -> Result<Self, Error> {
        #[cfg(feature = "notifier")]
        token.event().invalidate_numeric_auth();
        let wait = Self::decode_raw(pid, status, token)?;
        #[cfg(all(test, feature = "notifier"))]
        if let Wait::Stopped(task, Event::NewChild(..)) = &wait {
            notifier::pause_sync_new_child_decode(task.1.event());
        }
        Ok(wait)
    }

    /// Decodes a status that one of the plain wait helpers (`wait_all`,
    /// `wait_group`, `peek_all` and the like) returned. It is decoded as
    /// [`Wait::from_raw`] decodes it, but without the notifier's bookkeeping
    /// on the tracee's event handle, which these helpers never did.
    fn from_wait_helper(pid: Pid, status: i32) -> Result<Self, Error> {
        let token = if libc::WIFSTOPPED(status) {
            TraceeToken::current_or_fresh(pid)
        } else {
            TraceeToken::new()
        };
        Self::decode_raw(pid, status, token)
    }

    /// Decodes a raw wait status, keeping a realtime stop signal's number
    /// (`Event::RawSignal`).
    fn decode_raw(pid: Pid, status: i32, token: TraceeToken) -> Result<Self, Error> {
        Ok(if libc::WIFEXITED(status) {
            Wait::Exited(pid, ExitStatus::Exited(libc::WEXITSTATUS(status)))
        } else if libc::WIFSIGNALED(status) {
            // A realtime signal is `ExitStatus::SignaledRaw`
            // (<https://github.com/rrnewton/reverie/issues/997>).
            Wait::Exited(
                pid,
                ExitStatus::signaled(libc::WTERMSIG(status), libc::WCOREDUMP(status)),
            )
        } else if libc::WIFSTOPPED(status) {
            let task = Stopped::from_token(pid, token);

            let event = if libc::WSTOPSIG(status) == libc::SIGTRAP | 0x80 {
                Event::Syscall
            } else if (status >> 16) == 0 {
                let raw = libc::WSTOPSIG(status);
                match (Signal::try_from(raw), AnySignal::new(raw)) {
                    (Ok(sig), _) => Event::Signal(sig),
                    (Err(_), Some(_)) => Event::RawSignal(raw),
                    (Err(_), None) => return Err(Errno::EINVAL.into()),
                }
            } else {
                let event = status >> 16;

                // PTRACE_EVENT_STOP is not guaranteed to return the correct
                // signal, so we ignore it here. Compare raw numbers: the signal
                // of a PTRACE_EVENT_STOP can be one nix cannot name.
                debug_assert!(
                    event == libc::PTRACE_EVENT_STOP || libc::WSTOPSIG(status) == libc::SIGTRAP
                );

                Event::from_ptrace_event(&task, event)?
            };

            Wait::Stopped(task, event)
        } else if libc::WIFCONTINUED(status) {
            // TODO: Handle continued status.
            unimplemented!("Continued status not yet handled")
        } else {
            panic!("PID {} got unexpected status: {:#x}", pid, status)
        })
    }
}

impl TryFrom<WaitStatus> for Wait {
    type Error = Error;

    /// Converts a `WaitStatus` to this type.
    ///
    /// Preconditions:
    /// The process must not be in a `StillAlive` state.
    fn try_from(wait_status: WaitStatus) -> Result<Self, Error> {
        let token = match wait_status {
            WaitStatus::Stopped(pid, _)
            | WaitStatus::PtraceEvent(pid, ..)
            | WaitStatus::PtraceSyscall(pid) => TraceeToken::current_or_fresh(pid.into()),
            _ => TraceeToken::new(),
        };
        Self::from_wait_status_with_token(wait_status, token)
    }
}

impl Wait {
    fn from_wait_status_with_token(
        wait_status: WaitStatus,
        token: TraceeToken,
    ) -> Result<Self, Error> {
        Ok(match wait_status {
            WaitStatus::Exited(pid, code) => Self::Exited(pid.into(), ExitStatus::Exited(code)),
            WaitStatus::Signaled(pid, sig, coredump) => {
                Self::Exited(pid.into(), ExitStatus::Signaled(sig, coredump))
            }
            WaitStatus::Stopped(pid, sig) => {
                let event = Event::Signal(sig);
                Self::Stopped(Stopped::from_token(pid.into(), token), event)
            }
            WaitStatus::PtraceEvent(pid, sig, event) => {
                // PTRACE_EVENT_STOP is not guaranteed to return the correct
                // signal, so we ignore it here.
                debug_assert!(event == libc::PTRACE_EVENT_STOP || sig == Signal::SIGTRAP);
                let task = Stopped::from_token(pid.into(), token);
                let event = Event::from_ptrace_event(&task, event)?;
                Self::Stopped(task, event)
            }
            WaitStatus::PtraceSyscall(pid) => {
                let event = Event::Syscall;
                Self::Stopped(Stopped::from_token(pid.into(), token), event)
            }
            WaitStatus::Continued(_pid) => {
                // Not possible because we aren't using WaitPidFlag::WCONTINUED
                // anywhere.
                unreachable!("unexpected WaitStatus::Continued");
            }
            WaitStatus::StillAlive => {
                // The precondition of this function forbids this.
                unreachable!("precondition violated with WaitStatus::StillAlive");
            }
        })
    }
}

impl fmt::Display for Wait {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Stopped(stopped, event) => {
                write!(f, "pid {} stopped ({:?})", stopped.pid(), event)
            }
            Self::Exited(pid, exit_status) => write!(f, "pid {} exited ({:?})", pid, exit_status),
        }
    }
}

// libc crate doesn't provide this struct
#[repr(C)]
struct ptrace_peeksiginfo_args {
    off: u64,
    flags: u32,
    nr: u32,
}

bitflags::bitflags! {
    /// Flags for ptrace peeksiginfo
    #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
    pub struct PeekSigInfoFlags: u32 {
        /// dumping signals from the process-wide signal queue. signals are
        /// read from the per-thread queue of the specified thread if this
        /// flag is not set.
        const SHARED = 1;
    }
}

/// The tracee generation a [`Stopped`] capability is bound to. It grants no
/// ptrace operation by itself.
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct TraceeGeneration(Pid, TraceeToken);

impl TraceeGeneration {
    /// Returns the process ID of the tracee.
    pub fn pid(&self) -> Pid {
        self.0
    }

    /// Retains a passive descriptor/observation facade for this generation.
    /// This does not register a worker, recapture the numeric PID, or grant a
    /// stopped capability. Registration starts on a later explicit request.
    #[cfg(feature = "notifier")]
    pub fn terminal_cleanup(&self) -> TerminalCleanup {
        TerminalCleanup::new_unregistered(self.0, &self.1)
    }

    /// Retains this token's host anchor, or binds the current controller host
    /// through the generation's original proc mount when none was captured.
    /// This selects only a host thread; it grants no attachment or wait role.
    /// Bind before callbacks or suspension, then keep that same guard rather
    /// than capturing another after a foreign poll, error or cancellation.
    #[cfg(feature = "notifier")]
    pub fn ptracer_thread_guard(&self) -> Result<PtracerThreadGuard, Errno> {
        if let Some(error) = self.1.event().initial_capture_error() {
            return Err(error);
        }
        match &self.1.ptracer_owner {
            Some(owner) => Ok(PtracerThreadGuard::from_owner(owner.clone())),
            None => self.1.event().capture_host_thread_guard(),
        }
    }

    /// Returns an existing host anchor only when this token already retains
    /// a positive wait-role witness for its original generation.
    ///
    /// This passive accessor captures nothing and does not check the current
    /// attachment or upgrade a constructor-only role. Authenticate a returned
    /// guard with [`PtracerThreadGuard::check_current`] before controller use.
    /// It remains the same host anchor after genuine target retirement.
    #[cfg(feature = "notifier")]
    pub fn retained_ptracer_thread_guard(&self) -> Result<Option<PtracerThreadGuard>, Errno> {
        if let Some(error) = self.1.event().initial_capture_error() {
            return Err(error);
        }
        Ok(self
            .1
            .ptracer_wait_role
            .then(|| self.1.ptracer_owner.clone())
            .flatten()
            .map(PtracerThreadGuard::from_owner))
    }

    /// Binds a controller host only after proving its current wait role for
    /// this original live generation. The proof requires the actual ptracer
    /// TID, or the real parent TGID for an untraced descriptor waiter.
    ///
    /// Use this fallible cold binder before callbacks or suspension when no
    /// previously bound controller guard is available. Retain the same guard
    /// thereafter, including for children and terminal results. A refusal
    /// registers no worker and leaves this generation available for its real
    /// owner; a retired task cannot supply a missing controller anchor.
    #[cfg(feature = "notifier")]
    pub fn ptracer_thread_guard_for_wait(&self) -> Result<PtracerThreadGuard, Errno> {
        let guard = self.ptracer_thread_guard()?;
        guard.check_wait_role(self.1.event())?;
        Ok(guard)
    }

    /// Creates a stopped state for this generation. Like
    /// [`Stopped::new_unchecked`], the caller must independently know that the
    /// tracee is stopped. Unlike it, with the `notifier` feature and once this
    /// generation's identity has been captured, requests through the result
    /// are refused once the notifier or [`Running::wait`] reaps this
    /// generation, even if another task has reused the TID. Without that
    /// feature, or while the generation is unbound because its identity could
    /// not be captured, requests go to the numeric TID unchecked. A reap
    /// through [`wait_all`], [`try_wait_all`] or [`wait_group`], and the
    /// registration orders in <https://github.com/rrnewton/reverie/issues/860>,
    /// do not refuse them yet.
    pub fn assume_stopped(&self) -> Stopped {
        Stopped::from_token(self.0, self.1.clone())
    }
}

/// A process that is in a stopped state and allows ptrace operations to be
/// performed.
#[derive(Hash, Eq, PartialEq)]
pub struct Stopped(Pid, TraceeToken, ExitStopMark);

/// How [`Stopped::transition_unless_left_for_exit_with`] probes whether the
/// tracee has left the stop a capability names for its exit stop.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ExitProbe {
    /// For any held stop: stat flags first (`PF_SIGNALED`), then
    /// `PTRACE_GETSIGINFO` last. Correct even when someone wrote the stop's
    /// siginfo. Five system calls.
    Full,
    /// For a stop whose siginfo nobody has written since the kernel reported
    /// it, such as a single step's trap: `PTRACE_GETSIGINFO`, then the flags
    /// only to confirm an exit signature. One system call in the common case.
    ReportedSiginfo,
}

/// A resuming request for [`Stopped::transition_unless_left_for_exit`]. Each
/// signal is a raw number, so that one nix cannot name can be delivered; 0
/// delivers none.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Transition {
    /// `PTRACE_CONT`.
    Cont(i32),
    /// `PTRACE_SYSCALL`.
    Syscall(i32),
    /// `PTRACE_SINGLESTEP`.
    Step(i32),
    /// `PTRACE_SINGLEBLOCK`, delivering no signal.
    #[cfg(target_arch = "x86_64")]
    BlockStep,
}

impl fmt::Debug for Stopped {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Stopped")
            .field(&self.0)
            .field(&self.1)
            .finish()
    }
}

/// Marks the one [`Stopped`] minted by an exit future for a published
/// `PTRACE_EVENT_EXIT` stop, with the exit epoch that publication belongs to.
/// It is not part of the value's identity: equality and hashing ignore it.
#[derive(Clone, Copy, Default)]
#[cfg_attr(not(feature = "notifier"), allow(dead_code))]
struct ExitStopMark(Option<usize>);

impl PartialEq for ExitStopMark {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}

impl Eq for ExitStopMark {}

impl std::hash::Hash for ExitStopMark {
    fn hash<H: std::hash::Hasher>(&self, _: &mut H) {}
}

/// Native Linux PTRACE_GET_RSEQ_CONFIGURATION reply, without Tool interpretation.
#[repr(C)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct RseqConfiguration {
    /// Registered userspace address, or zero.
    pub address: u64,
    /// Registered region size.
    pub length: u32,
    /// Registered instruction signature.
    pub signature: u32,
    /// Kernel-reported flags.
    pub flags: u32,
    /// Reserved ABI padding, retained for exact native request size.
    pub padding: u32,
}

impl Stopped {
    /// Helper for converting from the Errno type.
    ///
    /// # Why is this needed?
    ///
    /// According to ptrace(2), any ptrace operation may return ESRCH
    /// ("No such process") for one of three reasons:
    ///  1. The process was observed to be in a stopped state and died
    ///     unexpectedly.
    ///  2. The process is not currently being traced by the caller.
    ///  3. The process is not in a stopped state.
    ///
    /// Since we know that reasons (2) and (3) only occur due to
    /// programmer errors that this API is designed to prevent, we can
    /// safely assume that this ESRCH means the tracee has died
    /// unexpectedly while in a stopped state.
    ///
    /// For more information, please see the "Death under ptrace" section
    /// in `man 2 ptrace`.
    ///
    /// On the capability for a published exit stop, ESRCH also retires the
    /// statuses queued before that exit stop (see
    /// [`Stopped::retire_statuses_before_exit_stop`]). That relies on the
    /// same assumption as the mapping to `Died` above: every ptrace request
    /// for this tracee comes from its one tracer thread, so reason (2), which
    /// the kernel also reports to a thread that is not the tracer, does not
    /// apply. The kernel also returns ESRCH when it cannot freeze the stop
    /// because a fatal signal is pending; the tracee is then being killed out
    /// of the exit stop, so the queued stops ahead of it are still dead.
    fn map_err(&self, err: Errno) -> Error {
        if err == Errno::ESRCH {
            // The tracee has left the stop this capability names.
            #[cfg(feature = "notifier")]
            {
                self.1.event().invalidate_regs();
                self.1.event().stop_may_have_ended();
            }
            self.retire_statuses_before_exit_stop();
            Error::Died(Zombie::from_token(self.0, self.1.clone()))
        } else {
            Error::Errno(err)
        }
    }

    /// Returns a future that is notified when the next exit stop occurs. This
    /// is received asynchronously regardless of what the process was doing at
    /// the time. This is useful for canceling futures when a process enters a
    /// `PTRACE_EVENT_EXIT` (such as when one thread calls `exit_group` and
    /// causes all other threads to suddenly exit).
    ///
    /// Exactly one future for this immutable tracee generation can claim the
    /// exit stop and return a [`Stopped`] capability. Duplicate or re-polled
    /// futures return [`Errno::EALREADY`]. An unclaimed capability also expires
    /// before terminal publication or cancellation cleanup advances the
    /// tracee.
    #[cfg(feature = "notifier")]
    pub fn exit_event(&self) -> notifier::ExitFuture {
        notifier::ExitFuture::new(self.0, &self.1)
    }

    /// Observes this exact exit epoch using the explicit ptracer-thread mode.
    /// The new interface is !Send and !Sync, including on native kernels.
    #[cfg(feature = "notifier")]
    pub fn exit_event_on_ptracer_thread(&self) -> PtracerExitFuture {
        PtracerExitFuture::new(self.0, &self.1)
    }

    /// Returns a generation-bound terminal cleanup acknowledgment.
    ///
    /// This is primarily useful with [`Stopped::new_unchecked`] during
    /// cancellation after the caller has independently validated that the TID
    /// still names the expected ptrace generation.
    #[cfg(feature = "notifier")]
    pub fn terminal_cleanup(&self) -> TerminalCleanup {
        TerminalCleanup::new(self.0, &self.1)
    }

    /// Retains explicit ptracer-thread progress for this same stopped state.
    /// Its separate shared facade performs only descriptor signaling and
    /// observation; construction never recaptures this numeric identity.
    #[cfg(feature = "notifier")]
    pub fn terminal_cleanup_on_ptracer_thread(&self) -> PtracerTerminalCleanup {
        PtracerTerminalCleanup::new(self.0, &self.1)
    }

    /// Retain a read-only observer for this actual token and its current exec epoch.
    /// It cannot resume, wait, or mint another owning capability, and makes no
    /// new PID/proc capture. Use it only while the original current stop remains
    /// under this caller's execution-control ownership.
    #[cfg(feature = "notifier")]
    pub fn observation(&self) -> StoppedObservation {
        StoppedObservation::new(self.0, &self.1)
    }

    /// Creates a new stopped state. This is useful when we know the process is
    /// in a stopped state already.
    ///
    /// Using this method is unsound because there is no check to verify that the
    /// pid really is in a stopped state. It is better to arrive at a stopped
    /// state via other methods such as `Running::wait`.
    pub fn new_unchecked(pid: Pid) -> Self {
        Self::from_token(pid, TraceeToken::current_or_error(pid))
    }

    /// Creates an unchecked stopped state joined to the currently registered
    /// proc generation for `pid`.
    ///
    /// Like [`Stopped::new_unchecked`], the caller must independently prove
    /// that the exact TID is stopped. Unlike that constructor, generation
    /// capture/read failures are returned rather than creating an unbound
    /// notifier state.
    #[cfg(feature = "notifier")]
    pub fn try_new_current_unchecked(pid: Pid) -> Result<Self, Errno> {
        Ok(Self::from_token(pid, TraceeToken::current_or_new(pid)?))
    }

    /// Captures the original identity for explicit ptracer-thread waits.
    /// Like [`Self::new_unchecked`], the caller must prove this exact task is
    /// physically stopped. Capture failures return without an unbound token.
    #[cfg(feature = "notifier")]
    pub fn new_unchecked_on_ptracer_thread(pid: Pid) -> Result<Self, Errno> {
        Ok(Self::from_token(
            pid,
            TraceeToken::current_on_ptracer_thread(pid)?,
        ))
    }

    fn from_token(pid: Pid, token: TraceeToken) -> Self {
        Self(pid, token, ExitStopMark(None))
    }

    /// The capability for the `PTRACE_EVENT_EXIT` stop published in exit
    /// `epoch`. See [`Stopped::retire_statuses_before_exit_stop`] for when the
    /// statuses queued before that exit stop are retired.
    #[cfg(feature = "notifier")]
    fn from_exit_token(pid: Pid, token: TraceeToken, epoch: usize) -> Self {
        Self(pid, token, ExitStopMark(Some(epoch)))
    }

    /// On the capability for a published exit stop, retires the statuses the
    /// notifier queued before that exit stop. The tracee had already left
    /// each of those stops when it entered the exit stop, so none of them
    /// names a stop it can still be in.
    ///
    /// This runs on every terminal disposition of the capability: a ptrace
    /// request that moves the tracee out of the exit stop, and an ESRCH from
    /// any request on it (resume, step, GETEVENTMSG, ...), which means the
    /// tracee is no longer in the exit stop. Statuses queued after the exit
    /// stop, such as the Exec or the terminal wait status, are never removed.
    /// A mark from an earlier exit epoch retires nothing, so a stale
    /// capability cannot remove the prefix of a later exit stop. Does nothing
    /// on any other capability.
    fn retire_statuses_before_exit_stop(&self) {
        #[cfg(feature = "notifier")]
        if let Some(epoch) = self.2.0 {
            self.1.event().retire_statuses_before_exit_stop(epoch);
        }
    }

    /// On the capability for a published exit stop, refuses the stop when a
    /// fork, vfork or clone stop was queued before it.
    ///
    /// Such a stop names a live child only through its event message. The
    /// tracee left it for the exit stop, whose message (the exit status) has
    /// replaced the child's PID: decoding it now would read the exit status
    /// as a PID, and once this exit stop is resumed the read fails with
    /// ESRCH and the child is never captured. The refusal names the queued
    /// status instead. This makes no ptrace request and changes no queue; a
    /// prefix holding such a stop is also never retired (see
    /// `Stopped::retire_statuses_before_exit_stop`). Always succeeds on any
    /// other capability.
    #[cfg(feature = "notifier")]
    pub fn superseded_new_child(&self) -> Result<(), SupersededStopRefusal> {
        match self.2.0 {
            Some(epoch) => self.1.event().superseded_new_child(epoch),
            None => Ok(()),
        }
    }

    /// Converts this capability into the running state after a successful
    /// ptrace request moved the tracee out of its stop.
    fn into_running(self) -> Running {
        self.leave_stop(false)
    }

    /// [`Self::into_running`]. With `resumed`, the request was a resumption,
    /// after which the actual ptracer waits for the next stop: a legacy
    /// observation worker is then notified by that wait's first empty assist
    /// rather than at once (`EventHandle::expect_stop_on_poll`).
    fn leave_stop(self, resumed: bool) -> Running {
        #[cfg(feature = "notifier")]
        {
            // The resume that ends this stop may run arbitrary guest
            // code, a syscall, or a signal handler: none of the cached
            // registers survive it (see `Event::regs_cache`).
            self.1.event().invalidate_regs();
            self.1.event().invalidate_numeric_auth();
            if resumed {
                self.1.event().expect_stop_on_poll();
            } else {
                self.1.event().expect_stop();
            }
        }
        #[cfg(not(feature = "notifier"))]
        let _ = resumed;
        self.retire_statuses_before_exit_stop();
        Running::from_token(self.0, self.1)
    }

    /// [`Self::into_running`] after a successful resume request on this stop
    /// (`PTRACE_CONT`, `PTRACE_SYSCALL`, `PTRACE_SINGLESTEP` or
    /// `PTRACE_SINGLEBLOCK`), never after `PTRACE_DETACH`: the result carries
    /// the [`ResumeMark`] that lets its wait skip the detached-wait TracerPid
    /// read.
    fn into_running_resumed(self) -> Running {
        // The owner of a ptracer-thread token is the thread that issued the
        // request: `on_held_tid` checked it is current, and the kernel
        // accepted the request only from the tracer. Any other token's
        // proof records no owner.
        #[cfg(feature = "notifier")]
        let mark = ResumeMark(Some(
            self.1.event().resume_proof(
                self.0,
                self.1
                    .ptracer_owner
                    .as_ref()
                    .filter(|_| self.1.policy == notifier::WaitPolicy::PtracerThread),
            ),
        ));
        #[cfg(not(feature = "notifier"))]
        let mark = ResumeMark::default();
        let mut running = self.leave_stop(true);
        running.2 = mark;
        running
    }

    /// Returns the generation this capability is bound to, so a caller that
    /// later rebuilds an unchecked capability for this tracee keeps the
    /// generation's TID gate instead of joining whatever task holds the TID
    /// by then.
    pub fn generation(&self) -> TraceeGeneration {
        TraceeGeneration(self.0, self.1.clone())
    }

    /// Returns the process ID of the tracee.
    pub fn pid(&self) -> Pid {
        self.0
    }

    /// Sets the ptracer options.
    pub fn setoptions(&self, options: ptrace::Options) -> Result<(), Error> {
        self.1
            .on_held_tid(|| ptrace::setoptions(self.0.into(), options).map_err(nix_errno))
            .map_err(|err| self.map_err(err))
    }

    /// Gets a set of registers.
    ///
    /// `which` corresponds to one of:
    ///  * `libc::NT_PRSTATUS` for the general registers.
    ///  * `libc::NT_PRFPREG` for the floating point registers.
    ///
    /// There are others, but we don't use them.
    fn getregset<T>(&self, which: i32) -> Result<T, Error> {
        let mut regs = MaybeUninit::<T>::uninit();

        let mut iov = libc::iovec {
            iov_base: regs.as_mut_ptr() as *mut libc::c_void,
            iov_len: core::mem::size_of_val(&regs),
        };

        self.1
            .on_held_tid(|| unsafe {
                syscalls::syscall!(
                    Sysno::ptrace,
                    // PTRACE_GETREGS isn't available on aarch64, so we must use
                    // PTRACE_GETREGSET instead.
                    libc::PTRACE_GETREGSET,
                    self.0.as_raw(),
                    which,
                    &mut iov as *mut _
                )
            })
            .map_err(|err| self.map_err(err))?;

        // GETREGSET selects the target's ABI, which may differ from the
        // tracer's (for example, a compat PRSTATUS reply is shorter). Require
        // the entire typed layout in every build before assuming initialization.
        // Zero-filling the tail would not make a short reply a valid native ABI.
        if iov.iov_len != core::mem::size_of_val(&regs) {
            return Err(Error::Errno(Errno::EPROTO));
        }

        Ok(unsafe { regs.assume_init() })
    }

    fn setregset<T>(&self, which: i32, regs: &T) -> Result<(), Error> {
        self.setregset_prefix(which, regs, core::mem::size_of::<T>())
    }

    /// Like `setregset`, writing only the first `len` bytes of `regs`, for a
    /// regset whose kernel side takes a prefix, such as `NT_ARM_HW_BREAK`.
    fn setregset_prefix<T>(&self, which: i32, regs: &T, len: usize) -> Result<(), Error> {
        assert!(len <= core::mem::size_of::<T>());
        let iov = libc::iovec {
            iov_base: regs as *const _ as *mut _,
            iov_len: len,
        };

        self.1
            .on_held_tid(|| unsafe {
                syscalls::syscall!(
                    Sysno::ptrace,
                    // PTRACE_SETREGS isn't available on aarch64, so we must use
                    // PTRACE_SETREGSET instead.
                    libc::PTRACE_SETREGSET,
                    self.0.as_raw(),
                    which,
                    &iov as *const _
                )
            })
            .map_err(|err| self.map_err(err))?;

        Ok(())
    }

    /// Read the kernel's actual rseq registration under this stopped generation.
    /// A failed request remains an error, never an invented unregistered state.
    pub fn rseq_configuration(&self) -> Result<RseqConfiguration, Errno> {
        let mut config = RseqConfiguration::default();
        let size = core::mem::size_of::<RseqConfiguration>();
        let returned = self.1.on_held_tid(|| unsafe {
            syscalls::syscall!(
                Sysno::ptrace,
                0x420f_u32,
                self.0.as_raw(),
                size,
                &mut config as *mut _
            )
        })?;
        if returned != size {
            return Err(Errno::EPROTO);
        }
        Ok(config)
    }

    /// Reads the word at byte `offset` of the tracee's `struct user`
    /// (`PTRACE_PEEKUSER`), such as one of its debug registers on x86-64
    /// (`offset_of!(libc::user, u_debugreg)` plus eight times its number).
    pub fn peekuser(&self, offset: usize) -> Result<u64, Error> {
        // `struct user` includes the general-purpose register area: a
        // read there must observe the latest `setregs`.
        self.flush_regs()?;
        let mut word: u64 = 0;
        // The raw request stores the word at `data`; only glibc's wrapper
        // returns it.
        self.1
            .on_held_tid(|| unsafe {
                syscalls::syscall!(
                    Sysno::ptrace,
                    libc::PTRACE_PEEKUSER,
                    self.0.as_raw(),
                    offset,
                    &mut word as *mut u64
                )
            })
            .map_err(|err| self.map_err(err))?;
        Ok(word)
    }

    /// Writes `word` at byte `offset` of the tracee's `struct user`
    /// (`PTRACE_POKEUSER`). See [`Stopped::peekuser`].
    pub fn pokeuser(&self, offset: usize, word: u64) -> Result<(), Error> {
        // Order this write after any dirty `setregs`, as the calls were
        // made; the invalidation below then drops the cache it may
        // have changed.
        self.flush_regs()?;
        self.1
            .on_held_tid(|| unsafe {
                syscalls::syscall!(
                    Sysno::ptrace,
                    libc::PTRACE_POKEUSER,
                    self.0.as_raw(),
                    offset,
                    word
                )
            })
            .map_err(|err| self.map_err(err))?;
        // `struct user` includes the general-purpose register area, so a
        // write may have changed the registers outside `setregs`.
        #[cfg(feature = "notifier")]
        self.1.event().invalidate_regs();
        Ok(())
    }

    /// Gets the current state of the general purpose registers.
    ///
    /// With the `notifier` feature, repeated calls at one stop of a
    /// generation with a bound identity serve the registers its first
    /// call read (or its latest [`Stopped::setregs`] wrote) instead of
    /// reading them from the kernel again; see the generation's
    /// register cache. A stop ends at every successful resume, which
    /// clears the cache. The cache assumes what this API already
    /// assumes (see `Stopped::map_err`): every ptrace request for the
    /// tracee comes through this API from its one tracer thread. A
    /// register write made outside it (a raw `PTRACE_SETREGS` on the
    /// same tracee) is not observed until the next resume.
    pub fn getregs(&self) -> Result<Regs, Error> {
        #[cfg(feature = "notifier")]
        if self.1.event().regs_cacheable() {
            if let Some(regs) = self.1.event().cached_regs() {
                // A cache hit skips only the kernel read itself. It
                // still runs under the TID hold, so a tracee whose stop
                // has ended reports `Died` and a foreign ptracer thread
                // is refused exactly as for the kernel request.
                return self
                    .1
                    .on_held_tid(|| Ok(regs))
                    .map_err(|err| self.map_err(err));
            }
            let regs = self.getregset(libc::NT_PRSTATUS)?;
            #[cfg(test)]
            self.1.event().note_regs_kernel_read();
            self.1.event().store_regs(regs);
            return Ok(regs);
        }
        self.getregset(libc::NT_PRSTATUS)
    }

    /// [`Stopped::flush_regs`] as a retaining resume's refusal: the
    /// flush's `Died` becomes the plain `ESRCH` the retaining contract
    /// returns (its stop-ended bookkeeping already ran in `map_err`).
    fn flush_regs_retaining(&self) -> Result<(), Errno> {
        self.flush_regs().map_err(|error| match error {
            Error::Errno(errno) => errno,
            Error::Died(_) => Errno::ESRCH,
        })
    }

    /// Writes this generation's dirty cached registers to the kernel
    /// in one `NT_PRSTATUS` set, if any are dirty. Runs before every
    /// resume and before requests that observe kernel registers
    /// (`peekuser`, `pokeuser`, `getsyscallinfo`), so the kernel never
    /// acts on registers older than the latest [`Stopped::setregs`].
    pub(crate) fn flush_regs(&self) -> Result<(), Error> {
        #[cfg(feature = "notifier")]
        if self.1.event().regs_cacheable()
            && let Some(regs) = self.1.event().dirty_regs()
        {
            self.setregset(libc::NT_PRSTATUS, &regs)?;
            #[cfg(test)]
            self.1.event().note_regs_kernel_write();
            self.1.event().mark_regs_clean();
        }
        Ok(())
    }

    /// Sets the general purpose registers.
    ///
    /// With the `notifier` feature on a generation with a bound
    /// identity, the value replaces the generation's cached registers
    /// as dirty (see [`Stopped::getregs`]) and reaches the kernel in
    /// one write before the next resume, so a run of writes at one
    /// stop costs a single `NT_PRSTATUS` set. The TID-hold refusals
    /// are unchanged: a foreign ptracer thread is refused before
    /// anything is recorded. As a consequence an `ESRCH` the kernel
    /// write would have reported at once can instead surface at the
    /// flush, as that resume's `Died`. Without the cache the write
    /// goes to the kernel immediately.
    pub fn setregs(&self, regs: &Regs) -> Result<(), Error> {
        #[cfg(feature = "notifier")]
        if self.1.event().regs_cacheable() {
            let regs = *regs;
            return self
                .1
                .on_held_tid(|| {
                    // Writing the values the kernel already holds (a
                    // clean cache) changes nothing; e.g. setting a
                    // return value the in-place exit stop already left
                    // in the result register. Only the kernel write is
                    // skipped — the TID-hold refusals above still ran.
                    if !self.1.event().regs_already_current(&regs) {
                        self.1.event().store_regs_dirty(regs);
                    }
                    Ok(())
                })
                .map_err(|err| self.map_err(err));
        }
        self.setregset(libc::NT_PRSTATUS, regs)?;
        #[cfg(all(test, feature = "notifier"))]
        self.1.event().note_regs_kernel_write();
        Ok(())
    }

    /// Gets the floating point registers.
    pub fn getfpregs(&self) -> Result<FpRegs, Error> {
        self.getregset(libc::NT_PRFPREG)
    }

    /// Gets the thread pointer (TPIDR_EL0) via `NT_ARM_TLS`.
    #[cfg(target_arch = "aarch64")]
    pub fn get_thread_pointer(&self) -> Result<u64, Error> {
        self.getregset(NT_ARM_TLS)
    }

    /// Sets the thread pointer (TPIDR_EL0) via `NT_ARM_TLS`.
    #[cfg(target_arch = "aarch64")]
    pub fn set_thread_pointer(&self, value: u64) -> Result<(), Error> {
        self.setregset(NT_ARM_TLS, &value)
    }

    /// Gets the syscall number via `NT_ARM_SYSTEM_CALL`. At an
    /// exec-event stop this is the only place the number survives:
    /// the GPRs (x8 included) are zeroed by `start_thread`. A read
    /// of -1 is NO_SYSCALL (kernels before v6.0 forget the number);
    /// callers must refuse it, not guess.
    #[cfg(target_arch = "aarch64")]
    pub fn get_syscall_number(&self) -> Result<i32, Error> {
        self.getregset(NT_ARM_SYSTEM_CALL)
    }

    /// Sets the floating point registers. Fails with `EPERM` once
    /// [`forbid_fpu_register_writes`] has been called.
    pub fn setfpregs(&self, regs: &FpRegs) -> Result<(), Error> {
        check_fpu_register_write()?;
        self.setregset(libc::NT_PRFPREG, regs)
    }

    /// Gets the complete variable-length x86 XSAVE state for the tracee.
    // TODO-HUMAN-REVIEW(PR-270): Review complete ptrace XSTATE preservation API.
    #[cfg(target_arch = "x86_64")]
    pub fn getxstate(&self) -> Result<XState, Error> {
        // CPUID.(EAX=0xD,ECX=0):ECX reports the maximum XSAVE area for all
        // processor-supported user components. The kernel returns the exact
        // active regset length through iov_len.
        let maximum = core::arch::x86_64::__cpuid_count(0x0d, 0).ecx as usize;
        let mut bytes = vec![0_u8; maximum.max(4096)];
        let mut iov = libc::iovec {
            iov_base: bytes.as_mut_ptr().cast(),
            iov_len: bytes.len(),
        };
        self.1
            .on_held_tid(|| unsafe {
                syscalls::syscall!(
                    Sysno::ptrace,
                    libc::PTRACE_GETREGSET,
                    self.0.as_raw(),
                    NT_X86_XSTATE,
                    &mut iov as *mut _
                )
            })
            .map_err(|err| self.map_err(err))?;
        if iov.iov_len > bytes.len() {
            return Err(Error::Errno(Errno::EOVERFLOW));
        }
        bytes.truncate(iov.iov_len);
        Ok(XState(bytes))
    }

    /// Restores a complete x86 XSAVE state previously returned by
    /// [`Stopped::getxstate`]. Fails with `EPERM` once
    /// [`forbid_fpu_register_writes`] has been called.
    // TODO-HUMAN-REVIEW(PR-270): Review complete ptrace XSTATE preservation API.
    #[cfg(target_arch = "x86_64")]
    pub fn setxstate(&self, state: &XState) -> Result<(), Error> {
        check_fpu_register_write()?;
        let iov = libc::iovec {
            iov_base: state.0.as_ptr() as *mut libc::c_void,
            iov_len: state.0.len(),
        };
        self.1
            .on_held_tid(|| unsafe {
                syscalls::syscall!(
                    Sysno::ptrace,
                    libc::PTRACE_SETREGSET,
                    self.0.as_raw(),
                    NT_X86_XSTATE,
                    &iov as *const _
                )
            })
            .map_err(|err| self.map_err(err))?;
        Ok(())
    }

    /// Resumes the process and transitions it back to a running state.
    pub fn resume<T: Into<Option<Signal>>>(self, sig: T) -> Result<Running, Error> {
        self.flush_regs()?;
        self.1
            .on_held_tid(|| ptrace::cont(self.0.into(), sig).map_err(nix_errno))
            .map_err(|err| self.map_err(err))?;
        Ok(self.into_running_resumed())
    }

    /// Attempts to resume while retaining the original capability on error.
    ///
    /// The error arm returns the same generation-bound value, not a new value
    /// constructed from its numeric PID. This retains ownership; it does not
    /// guarantee that the kernel state is unchanged after every ptrace error.
    /// The refusal is a non-owning errno, including ESRCH: no second Zombie
    /// capability escapes beside the retained Stopped. An errno alone does not
    /// acknowledge terminal status or guarantee the same physical kernel stop.
    /// Callers must use their original event owner before another transition.
    pub fn resume_retaining<T: Into<Option<Signal>>>(
        self,
        sig: T,
    ) -> Result<Running, (Self, Errno)> {
        if let Err(errno) = self.flush_regs_retaining() {
            return Err((self, errno));
        }
        let result = self
            .1
            .on_held_tid(|| ptrace::cont(self.0.into(), sig).map_err(nix_errno));
        self.finish_retained_resume_resumed(result)
    }

    /// Resume to a syscall stop, retaining the same stopped capability on error.
    ///
    /// The error contract is the same as [`Self::resume_retaining`]: the errno
    /// does not establish unchanged kernel state or terminal acknowledgement.
    /// The original event owner must retain and settle the returned capability.
    pub fn syscall_retaining<T: Into<Option<Signal>>>(
        self,
        sig: T,
    ) -> Result<Running, (Self, Errno)> {
        if let Err(errno) = self.flush_regs_retaining() {
            return Err((self, errno));
        }
        let result = self
            .1
            .on_held_tid(|| ptrace::syscall(self.0.into(), sig).map_err(nix_errno));
        self.finish_retained_resume_resumed(result)
    }

    /// Like [`Self::syscall_retaining`], delivering a raw signal number.
    ///
    /// This permits genuine realtime signals without converting them to an
    /// absent signal. Invalid numbers are refused by the original kernel
    /// request, with the same generation-bound capability returned on error.
    pub fn syscall_raw_retaining(self, sig: i32) -> Result<Running, (Self, Errno)> {
        if let Err(errno) = self.flush_regs_retaining() {
            return Err((self, errno));
        }
        let result = self
            .1
            .on_held_tid(|| ptrace_resume_raw(libc::PTRACE_SYSCALL, self.0, sig));
        self.finish_retained_resume_resumed(result)
    }

    /// Transfers the original capability into a retained notifier wait.
    ///
    /// This performs no resume and constructs no replacement running or stopped
    /// value. Use it when an external lifecycle transition may have superseded
    /// this stop, such as an actual ESRCH from [`Stopped::resume_retaining`].
    /// The error is not an exit acknowledgement: only this same generation's
    /// actual next event settles the wait. If the task remains stopped, this
    /// future can remain pending; the caller must retain its ownership and
    /// arrange any necessary termination through its existing supervisor.
    /// Registration/decoding refusals obey [`Running::wait_owned`]'s retry
    /// contract and never return a second owning capability.
    #[cfg(feature = "notifier")]
    pub fn wait_owned(self) -> notifier::OwnedWaitFuture {
        notifier::OwnedWaitFuture::from_stopped(self)
    }

    /// Transfers this same stopped state into an explicit ptracer-thread wait.
    /// Non-owning refusals retain the original state for retry or return to
    /// its ptracer through [`PtracerOwnedWaitFuture::into_driver`].
    #[cfg(feature = "notifier")]
    pub fn wait_owned_on_ptracer_thread(self) -> PtracerOwnedWaitFuture {
        PtracerOwnedWaitFuture::from_stopped(self)
    }

    pub(crate) fn finish_retained_resume(
        self,
        result: Result<(), Errno>,
    ) -> Result<Running, (Self, Errno)> {
        self.finish_retained_transition(result, Self::into_running)
    }

    /// [`Self::finish_retained_resume`] for a resume request, never a detach:
    /// the running state carries the [`ResumeMark`]
    /// ([`Self::into_running_resumed`]).
    fn finish_retained_resume_resumed(
        self,
        result: Result<(), Errno>,
    ) -> Result<Running, (Self, Errno)> {
        self.finish_retained_transition(result, Self::into_running_resumed)
    }

    fn finish_retained_transition(
        self,
        result: Result<(), Errno>,
        into_running: fn(Self) -> Running,
    ) -> Result<Running, (Self, Errno)> {
        match result {
            Ok(()) => Ok(into_running(self)),
            Err(error) => {
                if error == Errno::ESRCH {
                    // The retained value keeps its ownership role, but the
                    // tracee has left the exit stop this capability names.
                    #[cfg(feature = "notifier")]
                    {
                        self.1.event().invalidate_regs();
                        self.1.event().stop_may_have_ended();
                    }
                    self.retire_statuses_before_exit_stop();
                }
                Err((self, error))
            }
        }
    }

    /// Resumes the process, delivering the raw signal `sig`, which may be one
    /// `nix`'s `Signal` cannot name (a realtime signal; see
    /// [`Event::RawSignal`]). `0` delivers nothing.
    pub fn resume_raw(self, sig: i32) -> Result<Running, Error> {
        self.flush_regs()?;
        self.1
            .on_held_tid(|| ptrace_resume_raw(libc::PTRACE_CONT, self.0, sig))
            .map_err(|err| self.map_err(err))?;
        Ok(self.into_running_resumed())
    }

    /// Like [`Stopped::syscall`], delivering the raw signal `sig` (see
    /// [`Stopped::resume_raw`]).
    pub fn syscall_raw(self, sig: i32) -> Result<Running, Error> {
        self.flush_regs()?;
        self.1
            .on_held_tid(|| ptrace_resume_raw(libc::PTRACE_SYSCALL, self.0, sig))
            .map_err(|err| self.map_err(err))?;
        Ok(self.into_running_resumed())
    }

    /// Like [`Stopped::step`], delivering the raw signal `sig` (see
    /// [`Stopped::resume_raw`]).
    pub fn step_raw(self, sig: i32) -> Result<Running, Error> {
        self.flush_regs()?;
        self.1
            .on_held_tid(|| ptrace_resume_raw(libc::PTRACE_SINGLESTEP, self.0, sig))
            .map_err(|err| self.map_err(err))?;
        Ok(self.into_running_resumed())
    }

    /// Runs the process until it next takes a branch, with
    /// `PTRACE_SINGLEBLOCK`, delivering no signal.
    ///
    /// x86 traps after each taken branch (jump, call, return, or conditional
    /// branch that is taken) when the trap flag is set with DEBUGCTL.BTF, and
    /// Linux reports the stop as a single step's: SIGTRAP with TRAP_TRACE.
    /// The step can end earlier, at any stop a single step would also meet
    /// (a signal, a syscall or seccomp stop, a fault), but never later than
    /// just past the first taken branch. Conditional branches that are not
    /// taken do not end it. A processor or hypervisor that ignores BTF steps
    /// a single instruction instead, which is earlier still.
    #[cfg(target_arch = "x86_64")]
    pub fn block_step(self) -> Result<Running, Error> {
        self.flush_regs()?;
        self.1
            .on_held_tid(|| ptrace_resume_raw(PTRACE_SINGLEBLOCK, self.0, 0))
            .map_err(|err| self.map_err(err))?;
        Ok(self.into_running_resumed())
    }

    /// Advances the execution of the process by a single step optionally
    /// delivering a signal specified by `sig`.
    pub fn step<T: Into<Option<Signal>>>(self, sig: T) -> Result<Running, Error> {
        self.flush_regs()?;
        self.1
            .on_held_tid(|| ptrace::step(self.0.into(), sig).map_err(nix_errno))
            .map_err(|err| self.map_err(err))?;
        Ok(self.into_running_resumed())
    }

    /// Like `step`, but arranges for the tracee to be stopped at the next
    /// entry to or exit from a system call.
    pub fn syscall<T: Into<Option<Signal>>>(self, sig: T) -> Result<Running, Error> {
        self.flush_regs()?;
        self.1
            .on_held_tid(|| ptrace::syscall(self.0.into(), sig).map_err(nix_errno))
            .map_err(|err| self.map_err(err))?;
        Ok(self.into_running_resumed())
    }

    /// Sets the syscall to be executed. Only available on `aarch64`.
    ///
    /// Normally, on x86_64, the register `orig_rax` should be set instead to
    /// modify the syscall number, which typically involves 3 ptrace calls:
    ///  1. getregs to get the current registers.
    ///  2. setregs to change `orig_rax` to set the syscall number.
    ///  3. setregs again to restore the original registers after the syscall
    ///     has been executed.
    ///
    /// `set_syscall` on `aarch64` has the advantage of only requiring a single
    /// ptrace call.
    #[cfg(target_arch = "aarch64")]
    pub fn set_syscall(&self, nr: i32) -> Result<(), Error> {
        const NT_ARM_SYSTEM_CALL: i32 = 0x404;
        // Flush first: the invalidation below would otherwise drop a
        // dirty `setregs` recorded at this stop without ever writing it.
        self.flush_regs()?;
        self.setregset(NT_ARM_SYSTEM_CALL, &nr)?;
        // The kernel's syscall number lives outside `NT_PRSTATUS` here,
        // but the register view derived from `x8` and the number the
        // resume runs must not be read as one cached whole.
        #[cfg(feature = "notifier")]
        self.1.event().invalidate_regs();
        Ok(())
    }

    /// Reads this thread's ptrace hardware breakpoints (`NT_ARM_HW_BREAK`).
    /// Breakpoints the thread holds through `perf_event_open` do not appear
    /// here, though they take hardware slots.
    #[cfg(target_arch = "aarch64")]
    pub fn hw_breakpoints(&self) -> Result<HwBreakpoints, Error> {
        self.getregset(NT_ARM_HW_BREAK)
    }

    /// Writes the first `count` breakpoint registers of `breakpoints` to
    /// this thread (`NT_ARM_HW_BREAK`), leaving the others as they are.
    /// Linux registers each written register as a ptrace breakpoint, in
    /// order, and stops at the first that fails, so a failed write may have
    /// applied in part. Writing one the hardware lacks, or more than the
    /// slots that other breakpoints of the thread leave free, fails
    /// (`ENOSPC` or `EINVAL`). A registered breakpoint keeps its hardware
    /// slot, enabled or not, until the thread execs or exits.
    #[cfg(target_arch = "aarch64")]
    pub fn set_hw_breakpoints(
        &self,
        breakpoints: &HwBreakpoints,
        count: usize,
    ) -> Result<(), Error> {
        let count = count.min(breakpoints.regs.len());
        let len = core::mem::offset_of!(HwBreakpoints, regs)
            + count * core::mem::size_of::<HwBreakpoint>();
        self.setregset_prefix(NT_ARM_HW_BREAK, breakpoints, len)
    }

    /// Gets info about the signal that caused the process to be stopped.
    pub fn getsiginfo(&self) -> Result<libc::siginfo_t, Error> {
        self.1
            .on_held_tid(|| ptrace::getsiginfo(self.0.into()).map_err(nix_errno))
            .map_err(|err| self.map_err(err))
    }

    /// Returns [`Error::Died`] if this tracee has left the stop this
    /// capability names and is now in its `PTRACE_EVENT_EXIT` stop, or if
    /// the probe itself reports its death. Returns `None` otherwise.
    ///
    /// A fatal signal takes a tracee out of any ptrace stop without a tracer
    /// request. A request made while the tracee is on its way to its exit
    /// stop fails with `ESRCH`, because the tracee is not in a stop. Once it
    /// is in its exit stop, requests succeed again, so an ordinary probe made
    /// after that `ESRCH` sees a stopped, apparently live tracee.
    /// `PTRACE_GETSIGINFO` tells the two apart: in the exit stop, `si_code`
    /// is `SIGTRAP | (PTRACE_EVENT_EXIT << 8)`.
    ///
    /// Call this only on the capability for a stop other than the exit stop,
    /// after a request on it failed with `ESRCH`. Holding such a stop, the
    /// tracer has not resumed the tracee, so a tracee found in its exit stop
    /// was taken there by a fatal signal and the held stop is dead. Before a
    /// resume, use [`Self::died_into_exit_stop_before_resume`].
    pub fn died_into_exit_stop(&self) -> Option<Error> {
        match self.getsiginfo() {
            Ok(siginfo)
                if siginfo.si_signo == libc::SIGTRAP
                    && siginfo.si_code == libc::SIGTRAP | (libc::PTRACE_EVENT_EXIT << 8) =>
            {
                Some(self.map_err(Errno::ESRCH))
            }
            Err(died @ Error::Died(_)) => Some(died),
            _ => None,
        }
    }

    /// [`Self::died_into_exit_stop`] for a probe made before resuming the stop
    /// this capability names, so that the resume does not land on the exit
    /// stop and consume it (a resume is addressed by PID, not by stop). To
    /// resume, prefer [`Self::transition_unless_left_for_exit`], which makes
    /// the same probe immediately before its request.
    ///
    /// Siginfo contents alone prove nothing here: at a SIGTRAP delivery stop
    /// a thread may queue itself the exit signature (`si_code` 0x605), and
    /// `PTRACE_SETSIGINFO` can overwrite the real exit stop's siginfo (a
    /// replayed signal does) while `PTRACE_GETEVENTMSG` still holds the exit
    /// status. So the probe rests on two other facts:
    /// - `PF_SIGNALED` (0x400) in the thread's stat flags, read through the
    ///   generation's retained proc directory: a task that took a fatal
    ///   signal can only be stopped in its exit stop, and the flag is set
    ///   before that stop is reported. A gone task (`ESRCH`/`ENOENT`) has
    ///   left too.
    /// - `PTRACE_GETSIGINFO` failing with `ESRCH`: the tracee is no longer in
    ///   a stop. Holding one, the tracer has not resumed it, so a fatal signal
    ///   woke it (Linux clears `JOBCTL_TRACED` at once).
    ///
    /// The flags come first and `PTRACE_GETSIGINFO` last, so that in the
    /// common case no system call separates the final check from the
    /// request that follows: each return from a system call is a point where
    /// a loaded scheduler can preempt the tracer while the tracee moves on.
    /// An exit signature seen by that last check, after flags without
    /// `PF_SIGNALED`, re-reads the flags to tell a real exit stop entered in
    /// between from a forged one.
    #[cfg(feature = "notifier")]
    pub fn died_into_exit_stop_before_resume(&self) -> Option<Error> {
        self.died_into_exit_stop_before_resume_with(ExitProbe::Full)
    }

    /// [`Self::died_into_exit_stop_before_resume`] with the given probe.
    /// `Some` refuses the resume: [`Error::Died`] when the tracee left the
    /// stop, or the probe's own error when it could not observe that (then
    /// nothing may resume the stop on its account).
    #[cfg(feature = "notifier")]
    pub fn died_into_exit_stop_before_resume_with(&self, probe: ExitProbe) -> Option<Error> {
        match self.1.on_held_tid(|| self.left_for_exit_stop(probe)) {
            Ok(true) | Err(Errno::ESRCH) => Some(self.map_err(Errno::ESRCH)),
            Ok(false) => None,
            Err(error) => Some(Error::Errno(error)),
        }
    }

    /// Makes `transition` unless the tracee has left the stop this capability
    /// names for its exit stop; then it returns the same [`Error::Died`] as a
    /// request that met `ESRCH`, without issuing the request. The probe (see
    /// [`Self::died_into_exit_stop_before_resume`]) runs inside the same held
    /// TID section, immediately before the request. Nothing makes the two
    /// atomic: a fatal signal arriving between them still takes the tracee
    /// into its exit stop, and the request then resumes it.
    ///
    /// Use it only on the capability for a stop other than the exit stop.
    #[cfg(feature = "notifier")]
    pub fn transition_unless_left_for_exit(self, transition: Transition) -> Result<Running, Error> {
        self.transition_unless_left_for_exit_with(transition, ExitProbe::Full)
    }

    /// [`Self::transition_unless_left_for_exit`] with the given probe.
    #[cfg(feature = "notifier")]
    pub fn transition_unless_left_for_exit_with(
        self,
        transition: Transition,
        probe: ExitProbe,
    ) -> Result<Running, Error> {
        let (request, signal) = match transition {
            Transition::Cont(signal) => (libc::PTRACE_CONT, signal),
            Transition::Syscall(signal) => (libc::PTRACE_SYSCALL, signal),
            Transition::Step(signal) => (libc::PTRACE_SINGLESTEP, signal),
            #[cfg(target_arch = "x86_64")]
            Transition::BlockStep => (PTRACE_SINGLEBLOCK, 0),
        };
        // Before the probe, so no system call is added between the
        // probe's final check and the resume request below.
        self.flush_regs()?;
        self.1
            .on_held_tid(|| {
                // A probe that cannot observe refuses with its own error: no
                // resume on an unknown verdict.
                if self.left_for_exit_stop(probe)? {
                    return Err(Errno::ESRCH);
                }
                ptrace_resume_raw(request, self.0, signal)
            })
            .map_err(|err| self.map_err(err))?;
        Ok(self.into_running_resumed())
    }

    /// The probe shared by [`Self::died_into_exit_stop_before_resume_with`]
    /// and [`Self::transition_unless_left_for_exit_with`], for use inside a
    /// held TID section. `Ok(true)`: the tracee has left the stop for its
    /// exit stop (or is gone). `Ok(false)`: it is still in a stop that is not
    /// its exit stop. `Err`: the observation failed, and no verdict exists.
    ///
    /// Procfs errors are not lifecycle evidence. A failed stat read (for
    /// example `EMFILE`) is an error, not "no `PF_SIGNALED`". `ENOENT` or
    /// `ESRCH` from it can be a permission-shaped denial (procfs `hidepid`
    /// reports `ENOENT`) rather than death, so it counts as gone only when the
    /// retained pidfd also reports the task dead; a live pidfd makes it an
    /// error. Without a captured identity bound to this PID the flags cannot
    /// be read; an exit signature in the siginfo then counts as an exit stop,
    /// which can refuse a forged SIGTRAP but never consumes a real exit stop
    /// the siginfo still shows.
    #[cfg(feature = "notifier")]
    fn left_for_exit_stop(&self, probe: ExitProbe) -> Result<bool, Errno> {
        const PF_SIGNALED: u32 = 0x400;
        let event = self.1.event();
        // Ok(Some(true)) when PF_SIGNALED or the task is proven gone,
        // Ok(Some(false)) when neither, Ok(None) without a bound identity.
        let signaled = || -> Result<Option<bool>, Errno> {
            match event.bound_stat_flags(self.0) {
                None => Ok(None),
                Some(Ok(flags)) => Ok(Some(flags & PF_SIGNALED != 0)),
                Some(Err(notifier::ProcStatError::Io(Errno::ENOENT | Errno::ESRCH))) => {
                    match event.bound_pidfd_live(self.0) {
                        Some(Ok(false)) => Ok(Some(true)),
                        Some(Ok(true)) | None => Err(Errno::ENOENT),
                        Some(Err(error)) => Err(error),
                    }
                }
                Some(Err(notifier::ProcStatError::Io(error))) => Err(error),
                Some(Err(_)) => Err(Errno::EIO),
            }
        };
        if probe == ExitProbe::Full && signaled()? == Some(true) {
            return Ok(true);
        }
        match ptrace::getsiginfo(self.0.into()) {
            Err(nix::Error::ESRCH) => Ok(true),
            // EINVAL: the stop has no siginfo, which only a group-stop of a
            // tracee attached without PTRACE_SEIZE reports (Linux v6.17
            // kernel/ptrace.c:683, kernel/signal.c:2682). The exit stop always
            // has one (ptrace_do_notify, kernel/signal.c:2500), so the tracee
            // is still in a stop that is not its exit stop.
            Err(nix::Error::EINVAL) => Ok(false),
            Err(error) => Err(nix_errno(error)),
            Ok(info)
                if info.si_signo == libc::SIGTRAP
                    && info.si_code == libc::SIGTRAP | (libc::PTRACE_EVENT_EXIT << 8) =>
            {
                Ok(signaled()?.unwrap_or(true))
            }
            Ok(_) => Ok(false),
        }
    }

    /// Sets info about the singal that caused the process to be stopped.
    pub fn setsiginfo(&self, siginfo: &libc::siginfo_t) -> Result<(), Error> {
        self.1
            .on_held_tid(|| ptrace::setsiginfo(self.0.into(), siginfo).map_err(nix_errno))
            .map_err(|err| self.map_err(err))
    }

    /// The bytes of the siginfo of the signal that stopped the tracee
    /// (`PTRACE_GETSIGINFO`), exactly as the kernel wrote them, into storage
    /// that is initialized before the request. Unlike [`Stopped::getsiginfo`],
    /// whose `siginfo_t` a typed move may leave with undefined padding (64-bit
    /// musl's has four bytes after `si_code`), every byte is defined.
    pub fn getsiginfo_bytes(&self) -> Result<[u8; SIGINFO_BYTES], Error> {
        let mut bytes = [0u8; SIGINFO_BYTES];
        self.1
            .on_held_tid(|| {
                Errno::result(unsafe {
                    libc::ptrace(
                        libc::PTRACE_GETSIGINFO,
                        self.0.as_raw(),
                        0,
                        bytes.as_mut_ptr(),
                    )
                })
            })
            .map_err(|err| self.map_err(err))?;
        Ok(bytes)
    }

    /// Sets the siginfo of the signal that stopped the tracee
    /// (`PTRACE_SETSIGINFO`) from `bytes`, the kernel's layout, without
    /// building a `siginfo_t`.
    pub fn setsiginfo_bytes(&self, bytes: &[u8; SIGINFO_BYTES]) -> Result<(), Error> {
        self.1
            .on_held_tid(|| {
                Errno::result(unsafe {
                    libc::ptrace(libc::PTRACE_SETSIGINFO, self.0.as_raw(), 0, bytes.as_ptr())
                })
            })
            .map_err(|err| self.map_err(err))
            .map(drop)
    }

    /// Gets the tracee's blocked signal mask (`PTRACE_GETSIGMASK`). Bit `n - 1`
    /// is set when signal `n` is blocked.
    pub fn getsigmask(&self) -> Result<u64, Error> {
        let mut mask: u64 = 0;
        self.1
            .on_held_tid(|| {
                Errno::result(unsafe {
                    libc::ptrace(
                        libc::PTRACE_GETSIGMASK as _,
                        self.0.as_raw(),
                        core::mem::size_of::<u64>(),
                        &mut mask as *mut u64,
                    )
                })
            })
            .map_err(|err| self.map_err(err))?;
        Ok(mask)
    }

    /// Sets the tracee's blocked signal mask (`PTRACE_SETSIGMASK`). The kernel
    /// ignores the `SIGKILL` and `SIGSTOP` bits. Like any ptrace mask write, it
    /// also clears the tracee's pending restore of a mask saved by a
    /// mask-swapping syscall such as `ppoll` or `rt_sigsuspend`.
    pub fn setsigmask(&self, mask: u64) -> Result<(), Error> {
        self.1
            .on_held_tid(|| {
                Errno::result(unsafe {
                    libc::ptrace(
                        libc::PTRACE_SETSIGMASK as _,
                        self.0.as_raw(),
                        core::mem::size_of::<u64>(),
                        &mask as *const u64,
                    )
                })
            })
            .map_err(|err| self.map_err(err))?;
        Ok(())
    }

    /// Like `getsiginfo`, but do not remove the signal info from an internal
    /// queue.
    pub fn peeksiginfo<T: Into<Option<PeekSigInfoFlags>>>(
        &self,
        flags: T,
    ) -> Result<Vec<libc::siginfo_t>, Error> {
        const SIGNAL_MAX: usize = 8 * core::mem::size_of::<u64>();
        let mut data = MaybeUninit::<[libc::siginfo_t; SIGNAL_MAX]>::zeroed();
        let mut siginfo_args = ptrace_peeksiginfo_args {
            off: 0,
            flags: flags.into().map_or(0, |x| x.bits()),
            nr: SIGNAL_MAX as u32,
        };
        let count = self
            .1
            .on_held_tid(|| {
                Errno::result(unsafe {
                    libc::ptrace(
                        libc::PTRACE_PEEKSIGINFO,
                        self.0.as_raw(),
                        &mut siginfo_args as *mut _,
                        data.as_mut_ptr() as *const _ as *const libc::c_void,
                    )
                })
            })
            .map_err(|err| self.map_err(err))?;
        Ok(unsafe { data.assume_init() }[0..count as usize].to_vec())
    }

    /// Like `peeksiginfo`, but returns the whole queue rather than at most its
    /// first 64 entries.
    ///
    /// The kernel copies at least one entry per call if one exists at the
    /// offset, may stop early when the tracer has a signal pending, and
    /// returns 0 only past the end of the queue, so this reads until it gets 0.
    /// Real-time signals queue one entry each, so a queue can exceed 64 entries.
    pub fn peeksiginfo_all<T: Into<Option<PeekSigInfoFlags>>>(
        &self,
        flags: T,
    ) -> Result<Vec<libc::siginfo_t>, Error> {
        const CHUNK: usize = 64;
        let flags = flags.into().map_or(0, |x| x.bits());
        let mut data = MaybeUninit::<[libc::siginfo_t; CHUNK]>::zeroed();
        let mut all = Vec::new();
        loop {
            let mut siginfo_args = ptrace_peeksiginfo_args {
                off: all.len() as u64,
                flags,
                nr: CHUNK as u32,
            };
            let count = self
                .1
                .on_held_tid(|| {
                    Errno::result(unsafe {
                        libc::ptrace(
                            libc::PTRACE_PEEKSIGINFO,
                            self.0.as_raw(),
                            &mut siginfo_args as *mut _,
                            data.as_mut_ptr() as *const _ as *const libc::c_void,
                        )
                    })
                })
                .map_err(|err| self.map_err(err))? as usize;
            if count == 0 {
                return Ok(all);
            }
            // SAFETY: zero-initialized, and the kernel wrote the first `count`.
            all.extend_from_slice(&unsafe { data.assume_init_ref() }[..count]);
        }
    }

    /// Whether any queued signal matches `matches`, read like
    /// `peeksiginfo_all` but 64 entries at a time with no more kept, and
    /// stopping at the first match.
    pub fn peeksiginfo_any<T, F>(&self, flags: T, mut matches: F) -> Result<bool, Error>
    where
        T: Into<Option<PeekSigInfoFlags>>,
        F: FnMut(&libc::siginfo_t) -> bool,
    {
        const CHUNK: usize = 64;
        let flags = flags.into().map_or(0, |x| x.bits());
        let mut data = MaybeUninit::<[libc::siginfo_t; CHUNK]>::zeroed();
        let mut off = 0u64;
        loop {
            let mut siginfo_args = ptrace_peeksiginfo_args {
                off,
                flags,
                nr: CHUNK as u32,
            };
            let count = self
                .1
                .on_held_tid(|| {
                    Errno::result(unsafe {
                        libc::ptrace(
                            libc::PTRACE_PEEKSIGINFO,
                            self.0.as_raw(),
                            &mut siginfo_args as *mut _,
                            data.as_mut_ptr() as *const _ as *const libc::c_void,
                        )
                    })
                })
                .map_err(|err| self.map_err(err))? as usize;
            if count == 0 {
                return Ok(false);
            }
            // SAFETY: zero-initialized, and the kernel wrote the first `count`.
            if unsafe { data.assume_init_ref() }[..count]
                .iter()
                .any(&mut matches)
            {
                return Ok(true);
            }
            off += count as u64;
        }
    }

    /// Retrieve a message about the ptrace event that just happened.
    ///
    /// It shouldn't be necessary to call this in most cases because `Event`
    /// provides the necessary context for certain ptrace events.
    pub fn getevent(&self) -> Result<i64, Error> {
        self.1
            .on_held_tid(|| ptrace::getevent(self.0.into()).map_err(nix_errno))
            .map_err(|err| self.map_err(err))
    }

    /// Put this seized tracee, stopped in a group stop, into the
    /// kernel's listening state (`PTRACE_LISTEN`): it stays in its
    /// job-control stop like an untraced task until a real SIGCONT
    /// (or SIGKILL) arrives, then re-traps so the tracer can
    /// forward the delivery. The task is not resumed. Valid only
    /// at a `PTRACE_EVENT_STOP` trap under seize; other stops fail
    /// with the kernel errno.
    pub fn listen(self) -> Result<Running, Error> {
        self.flush_regs()?;
        self.1
            .on_held_tid(|| {
                Errno::result(unsafe {
                    libc::ptrace(
                        libc::PTRACE_LISTEN,
                        self.0.as_raw(),
                        std::ptr::null_mut::<libc::c_void>(),
                        std::ptr::null_mut::<libc::c_void>(),
                    )
                })
                .map(drop)
            })
            .map_err(|err| self.map_err(err))?;
        Ok(self.into_running())
    }

    /// Detach while retaining the original generation-bound stop on error.
    /// An errno does not establish unchanged kernel state or terminal status;
    /// the original owner must retain and settle that uncertainty.
    pub fn detach_retaining<T: Into<Option<Signal>>>(
        self,
        sig: T,
    ) -> Result<Running, (Self, Errno)> {
        if let Err(errno) = self.flush_regs_retaining() {
            return Err((self, errno));
        }
        // Counted immediately before the request, once the TID gate lets it
        // through, whatever it returns: an errno does not establish that
        // the detach did not happen ([`ResumeMark`]). A request the gate
        // refuses never reaches the kernel and counts nothing.
        let result = self.1.on_held_tid(|| {
            #[cfg(feature = "notifier")]
            notifier::note_detach(self.0);
            ptrace::detach(self.0.into(), sig).map_err(nix_errno)
        });
        self.finish_retained_resume(result)
    }

    /// Detaches from and then resumes the stopped tracee.
    pub fn detach<T: Into<Option<Signal>>>(self, sig: T) -> Result<Running, Error> {
        self.flush_regs()?;
        // Counted as in [`Self::detach_retaining`].
        self.1
            .on_held_tid(|| {
                #[cfg(feature = "notifier")]
                notifier::note_detach(self.0);
                ptrace::detach(self.0.into(), sig).map_err(nix_errno)
            })
            .map_err(|err| self.map_err(err))?;
        Ok(self.into_running())
    }

    /// Detaches from and then resumes the stopped tracee, delivering
    /// the raw signal `sig`, which may be one `nix`'s `Signal`
    /// cannot name (a realtime signal; see [`Event::RawSignal`]).
    /// `0` delivers nothing.
    pub fn detach_raw(self, sig: i32) -> Result<Running, Error> {
        self.flush_regs()?;
        // Counted as in [`Self::detach_retaining`].
        self.1
            .on_held_tid(|| {
                #[cfg(feature = "notifier")]
                notifier::note_detach(self.0);
                ptrace_resume_raw(libc::PTRACE_DETACH, self.0, sig)
            })
            .map_err(|err| self.map_err(err))?;
        Ok(self.into_running())
    }
}

/// Waits for any child processes to change state, blocking until the next event.
/// This is equivalent to `waitpid(-1)`.
///
/// Reaping a child here does not close its capabilities' TID gates, so a
/// gate that nothing else closed lets them reach a task that reuses its TID
/// (<https://github.com/rrnewton/reverie/issues/860>).
pub fn wait_all() -> Result<Option<Wait>, Error> {
    let result = wait(IdType::All, WaitPidFlag::WEXITED | WaitPidFlag::WSTOPPED)
        .map_err(Error::from)
        .and_then(|status| {
            // Unwrap is OK because the process cannot be left in a running
            // state without WNOHANG.
            let (pid, status) = status.unwrap();
            Wait::from_wait_helper(pid, status)
        });

    match result {
        Ok(state) => Ok(Some(state)),
        Err(Error::Errno(Errno::ECHILD)) => {
            // waitpid(-1) only returns ECHILD when there are no more children
            // to wait for. Returning `None` here makes it easy to write a while
            // loop that terminates when there are no more children left.
            Ok(None)
        }
        Err(err) => Err(err),
    }
}

/// Like `wait_all`, but immediately returns `Ok(None)` if no state transition
/// will occur.
///
/// This is the non-blocking version of `wait_all`.
pub fn try_wait_all() -> Result<Option<Wait>, Error> {
    wait(
        IdType::All,
        WaitPidFlag::WEXITED | WaitPidFlag::WSTOPPED | WaitPidFlag::WNOHANG,
    )?
    .map(|(pid, status)| Wait::from_wait_helper(pid, status))
    .transpose()
}

/// Waits for any child in a process group to change state, blocking until the
/// next event.
///
/// Reaping a child here does not close its capabilities' TID gates, so a
/// gate that nothing else closed lets them reach a task that reuses its TID
/// (<https://github.com/rrnewton/reverie/issues/860>).
pub fn wait_group(pid: Pid) -> Result<Option<Wait>, Error> {
    let result = wait(
        IdType::Pgid(pid.into()),
        WaitPidFlag::WEXITED | WaitPidFlag::WSTOPPED,
    )
    .map_err(Error::from)
    .and_then(|status| {
        // Unwrap is OK because the process cannot be left in a running
        // state without WNOHANG.
        let (pid, status) = status.unwrap();
        Wait::from_wait_helper(pid, status)
    });

    match result {
        Ok(state) => Ok(Some(state)),
        Err(Error::Errno(Errno::ECHILD)) => {
            // This only returns ECHILD when there are no more children to wait
            // for. Returning `None` here makes it easy to write a while loop
            // that terminates when there are no more children left.
            Ok(None)
        }
        Err(err) => Err(err),
    }
}

/// Blocks until a state change is ready to consume, but does not consume it.
/// Returns the pid that has the pending state change. Returns `Ok(None)` if
/// there are no child processes to wait on.
///
/// This is useful for deciding which processes to consume events for.
///
/// # Examples
///
/// ```ignore
/// while let Some(process) = peek_all()? {
///     match process.wait()? {
///         Wait::Stopped(tracee, _event) => {
///             tracee.resume(None)?;
///         }
///         Wait::Exited(pid, exit_status) => {
///             println!("pid {} exited ({})", pid, exit_status);
///         }
///     }
/// }
/// ```
pub fn peek_all() -> Result<Option<Running>, Errno> {
    let result = wait(
        IdType::All,
        WaitPidFlag::WEXITED | WaitPidFlag::WSTOPPED | WaitPidFlag::WNOWAIT,
    )
    .map(|state| {
        // Unwrap is OK because the process cannot be in a running state without
        // WNOHANG.
        state.unwrap()
    });

    match result {
        Ok((pid, _)) => Ok(Some(Running::new(pid))),
        Err(Errno::ECHILD) => {
            // waitpid(-1) only returns ECHILD when there are no more children
            // to wait for. Returning `None` here makes it easy to write a while
            // loop that terminates when there are no more children left.
            Ok(None)
        }
        Err(err) => Err(err),
    }
}

/// Returns a process that is ready to change state. If there are no child
/// processes ready to change, returns immediately.
///
/// This is the non-blocking version of `peek_all`.
pub fn try_peek_all() -> Result<Option<Running>, Errno> {
    let next = wait(
        IdType::All,
        WaitPidFlag::WEXITED | WaitPidFlag::WSTOPPED | WaitPidFlag::WNOHANG | WaitPidFlag::WNOWAIT,
    )?;

    Ok(next.map(|(pid, _)| Running::new(pid)))
}

/// A running child.
#[derive(Debug, Hash, Eq, PartialEq)]
pub struct Running(Pid, TraceeToken, ResumeMark);

/// Whether a [`Running`] came from a successful resume request on its own
/// stop (`PTRACE_CONT`, `PTRACE_SYSCALL`, `PTRACE_SINGLESTEP` or
/// `PTRACE_SINGLEBLOCK`; [`Stopped::into_running_resumed`]), and if so what
/// that proves (`notifier::ResumeProof`): the resuming token's ptracer
/// owner, the Event the request resolved to, and the TID's detach count
/// then.
///
/// A successful resume request passed `ptrace_check_attach` for the calling
/// thread, with the tracee in a ptrace-stop. After it, only that tracer can
/// make the task untraced, by its own `PTRACE_DETACH` (counted per exact
/// TID, through any capability) or by exiting. A wait built on such a value
/// and driven by that same owner, while the Event and the TID's detach count
/// are unchanged, therefore skips the TracerPid read that looks for a
/// detached wait (`notifier::note_detached_wait_if_untraced`, which also
/// states the de_thread exception). A proof from an ownerless token never
/// holds: a sibling thread can drive a later wait after the tracer exits.
/// Every other producer (detach, listen) leaves it unset. Those waits read
/// as before.
///
/// It carries no identity of its own: equality and hashing ignore it.
/// Without the `notifier` feature it is empty.
#[derive(Clone, Debug, Default)]
struct ResumeMark(#[cfg(feature = "notifier")] Option<notifier::ResumeProof>);

impl PartialEq for ResumeMark {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}
impl Eq for ResumeMark {}
impl std::hash::Hash for ResumeMark {
    fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {}
}

impl Running {
    /// Creates a new running process. This is generally the entry point for a
    /// new process as soon as it is created.
    ///
    /// The state shares the generation that other states for the same live
    /// task already carry. With the `notifier` feature, once that
    /// generation's identity has been captured, a numeric request through any
    /// of them stops reaching the TID once the notifier or [`Running::wait`]
    /// reaps that task, except in the orders listed in
    /// <https://github.com/rrnewton/reverie/issues/860>. If the identity
    /// cannot be captured, the state gets a fresh, unbound generation, which
    /// no reap gates until a later registration binds it.
    pub fn new(pid: Pid) -> Self {
        Self::from_token(pid, TraceeToken::current_or_fresh(pid))
    }

    /// Captures a running generation using the generic native thread-pidfd
    /// interface and returns its exact acquisition error. This preserves the
    /// same sibling-pollable contract as [`Self::new`] and enables no legacy
    /// fallback.
    #[cfg(feature = "notifier")]
    pub fn try_new(pid: Pid) -> Result<Self, Errno> {
        Self::from_current_or_new(pid)
    }

    /// Captures this original generation for explicit ptracer-thread waits.
    /// Only this named mode enables the retained legacy fallback when
    /// PIDFD_THREAD is unavailable. A failed capture returns no unbound state.
    #[cfg(feature = "notifier")]
    pub fn new_on_ptracer_thread(pid: Pid) -> Result<Self, Errno> {
        Ok(Self::from_token(
            pid,
            TraceeToken::current_on_ptracer_thread(pid)?,
        ))
    }

    fn from_token(pid: Pid, token: TraceeToken) -> Self {
        Self(pid, token, ResumeMark::default())
    }

    fn from_current_or_new(pid: Pid) -> Result<Self, Errno> {
        Ok(Self::from_token(pid, TraceeToken::current_or_new(pid)?))
    }

    fn newly_attached(pid: Pid) -> Self {
        let running = Self::new(pid);
        #[cfg(feature = "notifier")]
        return Self::from_token(
            pid,
            TraceeToken::from_event(running.1.event().reconnect_attachment(pid)),
        );
        #[cfg(not(feature = "notifier"))]
        running
    }

    /// Attaches to a running process. The process becomes a tracee and a SIGSTOP
    /// is sent to it. By the time this function ends, the tracee may not yet
    /// have actually stopped. Thus, the tracee is still considered to be in a
    /// running state and needs to be waited upon to observe the SIGSTOP.
    pub fn attach(pid: Pid) -> Result<Self, Errno> {
        ptrace::attach(pid.into()).map_err(|err| Errno::new(err as i32))?;
        Ok(Self::newly_attached(pid))
    }

    /// Similar to attach, but does not stop the process. This also affects the
    /// events that are later delivered. Upon clone, fork, or vfork, an
    /// `Event::Stop` is delivered instead of `Event::Signal(Signal::SIGSTOP)`.
    ///
    /// Unlike other modes, a seized process can also accept interrupts.
    pub fn seize(pid: Pid, options: Options) -> Result<Self, Errno> {
        ptrace::seize(pid.into(), options).map_err(|err| Errno::new(err as i32))?;
        Ok(Self::newly_attached(pid))
    }

    /// Attaches, then captures the task that the atomic ptrace request owns.
    /// If that first exact capture is refused, the successful attachment is
    /// retained in the returned state with its original errno. Local waits
    /// refuse that unbound state without capturing a replacement generation.
    #[cfg(feature = "notifier")]
    pub fn attach_on_ptracer_thread(pid: Pid) -> Result<Self, Errno> {
        let owner = notifier::EventHandle::capture_current_host_owner()?;
        let original = notifier::AttachmentAnchor::capture(pid)?;
        ptrace::attach(pid.into()).map_err(nix_errno)?;
        #[cfg(test)]
        notifier::after_initial_attachment_for_test(pid, &original);
        let mut token = TraceeToken::from_event_for_policy(
            notifier::EventHandle::attachment_on_ptracer_thread(pid, &original),
            notifier::WaitPolicy::PtracerThread,
        );
        token.ptracer_owner = Some(owner);
        // attachment_on_ptracer_thread validated the same retained original
        // generation after the successful atomic request. A later transient
        // host lookup cannot erase that established attachment role.
        token.ptracer_wait_role = token.event().initial_capture_error().is_none();
        Ok(Self::from_token(pid, token))
    }

    /// Seizes, then captures the task actually owned by that ptrace request.
    /// Capture refusals retain the successful attached state as described by
    /// [`Self::attach_on_ptracer_thread`]; no later local recapture is allowed.
    #[cfg(feature = "notifier")]
    pub fn seize_on_ptracer_thread(pid: Pid, options: Options) -> Result<Self, Errno> {
        let owner = notifier::EventHandle::capture_current_host_owner()?;
        let original = notifier::AttachmentAnchor::capture(pid)?;
        ptrace::seize(pid.into(), options).map_err(nix_errno)?;
        #[cfg(test)]
        notifier::after_initial_attachment_for_test(pid, &original);
        let mut token = TraceeToken::from_event_for_policy(
            notifier::EventHandle::attachment_on_ptracer_thread(pid, &original),
            notifier::WaitPolicy::PtracerThread,
        );
        token.ptracer_owner = Some(owner);
        token.ptracer_wait_role = token.event().initial_capture_error().is_none();
        Ok(Self::from_token(pid, token))
    }

    /// Interrupts the running process, even if it is in the middle of a syscall.
    /// The next time the process is waited on, the process transitions to a
    /// stopped state and `Event::Stop` is returned.
    ///
    /// # Limitations
    ///
    /// This only works for processes being traced via `Running::seize`.
    /// The request addresses a numeric TID. A concurrent nonleader exec can
    /// release that TID and allow a same-ptracer replacement to receive the
    /// request, including after an explicit interface's lifetime precheck.
    /// Native thread pidfds do not make this ptrace request atomic. See
    /// <https://github.com/rrnewton/reverie/issues/860>.
    pub fn interrupt(&self) -> Result<(), Errno> {
        // nix doesn't provide `ptrace::interrupt` yet, so we need to roll our
        // own.
        self.1.on_held_tid(|| {
            Errno::result(unsafe {
                libc::ptrace(
                    libc::PTRACE_INTERRUPT,
                    self.0.as_raw(),
                    std::ptr::null_mut::<libc::c_void>(),
                    std::ptr::null_mut::<libc::c_void>(),
                )
            })
            .map(drop)
        })?;
        // The caller waits for the interrupt's stop: its first empty assist
        // notifies a legacy observation worker.
        #[cfg(feature = "notifier")]
        self.1.event().expect_stop_on_poll();
        Ok(())
    }

    /// Returns the pid of the running process.
    pub fn pid(&self) -> Pid {
        self.0
    }

    /// Retains this exact task generation without granting a ptrace request.
    /// The caller must independently establish a real stop before using
    /// [`TraceeGeneration::assume_stopped`].
    pub fn generation(&self) -> TraceeGeneration {
        TraceeGeneration(self.0, self.1.clone())
    }

    /// Blocks until a state change occurs. This may transition the process to
    /// either a stopped state or exited state, but never a running state.
    pub fn wait(self) -> Result<Wait, Error> {
        let pid = self.0;
        let token = self.1;
        #[cfg(feature = "notifier")]
        {
            notifier::wait_sync(pid, token)
        }
        #[cfg(not(feature = "notifier"))]
        {
            wait(
                IdType::Pid(pid.into()),
                WaitPidFlag::WEXITED | WaitPidFlag::WSTOPPED,
            )
            .map_err(Error::from)
            .and_then(|status| {
                // Unwrap is OK because the process cannot be in a running state without
                // WNOHANG.
                let (_, status) = status.unwrap();
                Wait::decode_raw(pid, status, token)
            })
        }
    }

    /// Creates a retaining synchronous wait for this exact ptracer thread.
    /// Its explicit wait operation permits the legacy descriptor mode and
    /// keeps the same original input on a foreign-thread or backend refusal.
    #[cfg(feature = "notifier")]
    pub fn wait_sync_on_ptracer_thread(self) -> PtracerSyncWait {
        PtracerSyncWait::new(self)
    }

    /// Like `wait`, but filters out events we don't care about by resuming the
    /// tracee when encountering them. This is useful for skipping past spurious
    /// events until a point we know the tracee must stop.
    #[cfg(feature = "notifier")]
    pub async fn wait_until<F>(mut self, mut pred: F) -> Result<Wait, Error>
    where
        F: FnMut(&Event) -> bool,
    {
        loop {
            match self.next_state().await? {
                Wait::Stopped(stopped, event) => {
                    if pred(&event) {
                        break Ok(Wait::Stopped(stopped, event));
                    }
                    // Forward a signal, named or not
                    // (<https://github.com/rrnewton/reverie/issues/207>): a
                    // resume without one would suppress it.
                    self = match event {
                        Event::Signal(sig) => stopped.resume(Some(sig))?,
                        Event::RawSignal(raw) => stopped.resume_raw(raw)?,
                        _ => stopped.resume(None)?,
                    };
                }
                task => break Ok(task),
            }
        }
    }

    /// Waits until we receive a specific stop signal. Useful for skipping past
    /// spurious signals.
    #[cfg(feature = "notifier")]
    pub async fn wait_for_signal(self, sig: Signal) -> Result<Wait, Error> {
        self.wait_until(|event| event == &Event::Signal(sig)).await
    }

    /// Waits for the next exit stop to occur. This is received asynchronously
    /// regardless of what the process was doing at the time. This is useful for
    /// canceling futures when a process enters a `PTRACE_EVENT_EXIT` (such as
    /// when one thread calls `exit_group` and causes all other threads to
    /// suddenly exit).
    ///
    /// Exactly one future for this immutable tracee generation can claim the
    /// exit stop and return a [`Stopped`] capability. Duplicate or re-polled
    /// futures return [`Errno::EALREADY`]. An unclaimed capability also expires
    /// before terminal publication or cancellation cleanup advances the
    /// tracee.
    #[cfg(feature = "notifier")]
    pub fn exit_event(&self) -> notifier::ExitFuture {
        notifier::ExitFuture::new(self.0, &self.1)
    }

    /// Waits for this same exit epoch in the explicit ptracer-thread mode.
    /// The returned future is !Send and !Sync on every supported kernel.
    #[cfg(feature = "notifier")]
    pub fn exit_event_on_ptracer_thread(&self) -> PtracerExitFuture {
        PtracerExitFuture::new(self.0, &self.1)
    }

    /// Registers this process with the async notifier and returns a bounded
    /// synchronous acknowledgment handle for terminal cleanup.
    #[cfg(feature = "notifier")]
    pub fn terminal_cleanup(&self) -> TerminalCleanup {
        TerminalCleanup::new(self.0, &self.1)
    }

    /// Retains explicit ptracer-thread cleanup for this original generation.
    /// The returned progressing facade is !Send and !Sync on every kernel.
    #[cfg(feature = "notifier")]
    pub fn terminal_cleanup_on_ptracer_thread(&self) -> PtracerTerminalCleanup {
        PtracerTerminalCleanup::new(self.0, &self.1)
    }

    /// Transfers this generation into an owned notifier wait.
    ///
    /// Unlike the convenience async wrapper, this future retains its original
    /// generation after a returned error. It may be polled again after the
    /// caller has handled a registration or status-decoding refusal. An error
    /// does not prove exit. Its [`OwnedWaitError`] contains no second owning
    /// Zombie. After a successful state return this future releases its old
    /// owner and every subsequent poll returns `OwnedWaitError::Completed`.
    #[cfg(feature = "notifier")]
    pub fn wait_owned(self) -> notifier::OwnedWaitFuture {
        notifier::OwnedWaitFuture::new(self)
    }

    /// Transfers this original generation into an explicit owner-thread wait.
    /// Every refusal preserves that same state; no numeric recapture occurs.
    #[cfg(feature = "notifier")]
    pub fn wait_owned_on_ptracer_thread(self) -> PtracerOwnedWaitFuture {
        PtracerOwnedWaitFuture::new(self)
    }

    /// Waits through the explicitly selected ptracer-thread interface.
    /// This has the retained, non-owning error contract of
    /// [`Self::wait_owned_on_ptracer_thread`], rather than a sibling-pollable
    /// generic future. Use the explicit constructor before first capture.
    #[cfg(feature = "notifier")]
    pub fn next_state_on_ptracer_thread(self) -> PtracerWaitFuture {
        self.wait_owned_on_ptracer_thread()
    }

    /// Like `wait`, but wait asynchronously for the next state change.
    ///
    /// NOTE: This call should not be mixed with [`Running::wait`]!! Once
    /// [`Running::next_state`] is called once, [`Running::wait`] should never
    /// be called again for that PID. This is because a notifier thread takes
    /// over and calls `wait` in a continuous loop.
    #[cfg(feature = "notifier")]
    pub async fn next_state(self) -> Result<Wait, Error> {
        notifier::WaitFuture::new(self).await
    }
}

/// A process that is no longer running, but hasn't yet fully exited. The only
/// thing zombie can do is exit.
#[derive(Debug, Hash, Eq, PartialEq)]
pub struct Zombie(Running);

impl Zombie {
    /// Creates a new instance.
    fn from_token(pid: Pid, token: TraceeToken) -> Self {
        Zombie(Running::from_token(pid, token))
    }

    /// Returns the PID of the zombie.
    pub fn pid(&self) -> Pid {
        self.0.pid()
    }

    /// Retains this zombie's original generation without capturing a target
    /// or registering another wait owner.
    pub fn generation(&self) -> TraceeGeneration {
        self.0.generation()
    }

    /// Transfers the original generation into a retained notifier wait.
    ///
    /// The same retry contract as [`Running::wait_owned`] applies. A subsequent
    /// stop still requires its actual stopped capability to be continued; this
    /// method does not manufacture or acknowledge terminal status.
    #[cfg(feature = "notifier")]
    pub fn wait_owned(self) -> notifier::OwnedWaitFuture {
        self.0.wait_owned()
    }

    /// Retains this same zombie generation in an explicit ptracer-thread wait.
    #[cfg(feature = "notifier")]
    pub fn wait_owned_on_ptracer_thread(self) -> PtracerOwnedWaitFuture {
        self.0.wait_owned_on_ptracer_thread()
    }

    /// Reaps the zombie by waiting for it to fully exit.
    #[cfg(feature = "notifier")]
    pub async fn reap(self) -> Result<ExitStatus, Error> {
        // The tracee may not be fully dead yet. It is still possible for it to
        // still enter an `Event::Exit` state by waiting on it. For more info,
        // see the "BUGS" section in `man 2 ptrace`.
        let mut next_state = self.0.next_state().await;

        loop {
            match next_state {
                Ok(wait) => match wait {
                    Wait::Stopped(stopped, event) => {
                        if let Event::Exit = event {
                            next_state = match stopped.resume(None) {
                                Ok(task) => task.next_state().await,
                                Err(err) => Err(err),
                            };
                        } else {
                            panic!("Task {:?} unexpected stop event {:?}", stopped, event)
                        }
                    }
                    Wait::Exited(_pid, exit_status) => break Ok(exit_status),
                },
                Err(Error::Died(zombie)) => next_state = zombie.0.next_state().await,
                Err(error) => break Err(error),
            }
        }
    }
}

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

/// Sets up this process to be traced by its parent and raises a SIGSTOP.
pub fn traceme_and_stop() -> Result<(), Errno> {
    ptrace::traceme()
        .and_then(|()| nix::sys::signal::raise(Signal::SIGSTOP))
        .map_err(|e| Errno::new(e as i32))?;
    Ok(())
}

/// The size of Linux's `siginfo_t`, the unit of [`Stopped::getsiginfo_bytes`]
/// and [`Stopped::setsiginfo_bytes`].
pub const SIGINFO_BYTES: usize = 128;

static FPU_REGISTER_WRITES_FORBIDDEN: AtomicBool = AtomicBool::new(false);

/// Makes every later [`Stopped::setfpregs`] and [`Stopped::setxstate`] in this
/// process fail with `EPERM`. It cannot be undone.
///
/// A tool calls this when a write to a tracee's floating-point or extended
/// state would void a guarantee it gives. Hermit's x86-64-v3 CPU profile
/// qualifies a host on the in-use bits a guest's own XSAVE reads, and the
/// kernel's regset write forces some of those bits
/// (<https://github.com/rrnewton/hermit/issues/4243>). The check sits at this
/// layer, where every such write passes, so a caller added later cannot bypass
/// it.
///
/// A caller that writes several register sets can be left part way: the
/// gdbstub's `G` packet writes the general registers before the FP registers,
/// so after this call such a packet is partly applied before it fails with
/// EPERM. Hermit refuses `--gdbserver` under that profile, so it never reaches
/// this.
pub fn forbid_fpu_register_writes() {
    FPU_REGISTER_WRITES_FORBIDDEN.store(true, Ordering::SeqCst);
}

/// Whether [`forbid_fpu_register_writes`] has been called in this process.
pub fn fpu_register_writes_forbidden() -> bool {
    FPU_REGISTER_WRITES_FORBIDDEN.load(Ordering::SeqCst)
}

fn check_fpu_register_write() -> Result<(), Error> {
    if fpu_register_writes_forbidden() {
        Err(Error::Errno(Errno::EPERM))
    } else {
        Ok(())
    }
}

/// These tests are meant to test this API but also to show how ptrace works.
#[cfg(test)]
mod test {
    use std::io;
    use std::os::fd::BorrowedFd;
    use std::thread;

    use nix::sys::signal;
    use nix::sys::signal::Signal;
    use nix::unistd::ForkResult;
    // Make sure tokio is referenced in all configurations.
    use tokio as _;

    use super::*;
    use crate::test_fork::fork;

    // Traces a closure in a forked process. The forked process starts in a
    // stopped state so that ptrace options may be set.
    fn trace<F>(f: F, options: Options) -> Result<(Pid, Stopped), Error>
    where
        F: FnOnce() -> i32,
    {
        match unsafe { fork() }? {
            ForkResult::Parent { child, .. } => {
                let mut running = Running::seize(child.into(), options)?;

                // Keep consuming events until we reach a SIGSTOP or group stop.
                let stopped = loop {
                    match running.wait()? {
                        Wait::Stopped(stopped, event) => {
                            if event == Event::Signal(Signal::SIGSTOP) || event == Event::Stop {
                                break stopped;
                            } else if let Event::Signal(sig) = event {
                                running = stopped.resume(Some(sig))?;
                            } else if let Event::RawSignal(raw) = event {
                                running = stopped.resume_raw(raw)?;
                            } else {
                                running = stopped.resume(None)?;
                            }
                        }
                        task => panic!("Got unexpected exit: {:?}", task),
                    }
                };

                Ok((stopped.pid(), stopped))
            }
            ForkResult::Child => {
                // Create a new process group so we can wait on this process and
                // every child more efficiently.
                let _ = unsafe { libc::setpgid(0, 0) };

                // Suppress core dumps for testing purposes.
                let limit = libc::rlimit {
                    rlim_cur: 0,
                    rlim_max: 0,
                };
                let _ = unsafe { libc::setrlimit(libc::RLIMIT_CORE, &limit) };

                // PTRACE_SEIZE is inherently racey, so we stop the child
                // process here.
                signal::raise(Signal::SIGSTOP).unwrap();

                // Run the child when the process is resumed.
                let exit_code = f();

                // Note: We can't use the normal exit function here because we
                // don't want to call atexit handlers since `execve` was never
                // called. `_exit` diverges (`-> !`), so there is nothing to bind.
                unsafe { ::libc::_exit(exit_code) };
            }
        }
    }

    #[cfg(target_arch = "x86_64")]
    fn exercise_retained_syscall_stops(raw: bool) -> Result<(), Box<dyn std::error::Error>> {
        let (pid, mut stopped) = trace(
            || {
                // No Rust work is required between this actual syscall and
                // the test helper's ordinary _exit.
                unsafe {
                    libc::syscall(libc::SYS_getpid);
                }
                23
            },
            Options::PTRACE_O_EXITKILL | Options::PTRACE_O_TRACESYSGOOD,
        )?;
        let generation = stopped.generation();
        let mut found = false;
        // libc raise's return may first expose its syscall exit or mask repair.
        // Discover the actual GET_SYSCALL_INFO ENTRY, never alternate a phase bit.
        for _ in 0..8 {
            let running = if raw {
                stopped.syscall_raw_retaining(0)
            } else {
                stopped.syscall_retaining(None)
            }
            .map_err(|(_, error)| error)?;
            let (next, event) = running.wait()?.assume_stopped();
            stopped = next;
            assert_eq!(event, Event::Syscall);
            assert_eq!(stopped.generation(), generation);
            let info = stopped.getsyscallinfo()?;
            assert_eq!(info.architecture, 0xc000_003e);
            if matches!(info.operation, SyscallInfoOp::Entry { number, .. } if number == libc::SYS_getpid as u64)
            {
                found = true;
                break;
            }
        }
        assert!(
            found,
            "did not observe the actual getpid entry within the fixture bound"
        );
        let entry = stopped.getsyscallinfo()?;
        let running = if raw {
            stopped.syscall_raw_retaining(0)
        } else {
            stopped.syscall_retaining(None)
        }
        .map_err(|(_, error)| error)?;
        let (stopped, event) = running.wait()?.assume_stopped();
        assert_eq!(event, Event::Syscall);
        assert_eq!(stopped.generation(), generation);
        let exit = stopped.getsyscallinfo()?;
        assert_eq!(exit.architecture, entry.architecture);
        assert_eq!(exit.instruction_pointer, entry.instruction_pointer);
        assert_eq!(exit.stack_pointer, entry.stack_pointer);
        assert_eq!(
            exit.operation,
            SyscallInfoOp::Exit {
                return_value: i64::from(pid.as_raw()),
                is_error: false,
            }
        );
        assert_eq!(
            stopped
                .resume_retaining(None)
                .map_err(|(_, error)| error)?
                .wait()?,
            Wait::Exited(pid, ExitStatus::Exited(23)),
        );
        Ok(())
    }

    #[cfg(target_arch = "x86_64")]
    #[test]
    fn syscall_retaining_reaches_actual_entry_and_exit() -> Result<(), Box<dyn std::error::Error>> {
        exercise_retained_syscall_stops(false)
    }

    #[cfg(target_arch = "x86_64")]
    #[test]
    fn syscall_raw_retaining_reaches_actual_entry_and_exit()
    -> Result<(), Box<dyn std::error::Error>> {
        exercise_retained_syscall_stops(true)
    }

    #[cfg(target_arch = "x86_64")]
    #[test]
    fn syscall_raw_retaining_kernel_refusal_keeps_original_stop()
    -> Result<(), Box<dyn std::error::Error>> {
        let (pid, stopped) = trace(|| 23, Options::PTRACE_O_EXITKILL)?;
        let generation = stopped.generation();
        let before = stopped.getregs()?;
        let mask = stopped.getsigmask()?;
        // Linux ptrace_resume rejects an invalid signal with EIO before resume.
        // This is a real failed kernel request, not an injected mock errno.
        let (stopped, error) = stopped.syscall_raw_retaining(i32::MAX).unwrap_err();
        let after = stopped.getregs()?;
        let after_mask = stopped.getsigmask()?;
        let same_generation = stopped.generation() == generation;
        // Confirm progress and terminal reap BEFORE assertions on the refusal.
        let terminal = stopped
            .resume_retaining(None)
            .map_err(|(_, error)| error)?
            .wait()?;
        assert_eq!(terminal, Wait::Exited(pid, ExitStatus::Exited(23)));
        assert_eq!(error, Errno::EIO);
        assert!(same_generation);
        assert_eq!(after, before);
        assert_eq!(after_mask, mask);
        Ok(())
    }

    #[test]
    fn listen_keeps_group_stop_until_sigcont() -> Result<(), Box<dyn std::error::Error>> {
        let (pid, stopped) = trace(
            || {
                // Process-directed, not raise(): a thread-directed
                // stop signal reports as a signal-delivery stop,
                // while the shared-pending stop takes the group-stop
                // trap LISTEN is defined for.
                signal::kill(nix::unistd::Pid::this(), Signal::SIGSTOP).unwrap();
                7
            },
            Options::PTRACE_O_EXITKILL,
        )?;
        let mut running = stopped.resume(None)?;
        // A stop signal first reports as a signal-delivery stop;
        // forwarding it lets the kernel take the group-stop trap.
        // (The helper's initial stop was already suppressed above.)
        let stopped = loop {
            match running.wait()?.assume_stopped() {
                (stopped, Event::Stop) => break stopped,
                (stopped, Event::Signal(sig)) => {
                    running = stopped.resume(Some(sig))?;
                }
                (_stopped, event) => panic!("expected group stop, got {event:?}"),
            }
        };
        let mut running = stopped.listen()?;
        let status = std::fs::read_to_string(format!("/proc/{}/status", pid.as_raw())).unwrap();
        let state = status
            .lines()
            .find(|line| line.starts_with("State:"))
            .expect("proc status state");
        assert!(
            state.contains("(stopped)") || state.contains("(tracing stop)"),
            "listening task must stay stopped, got {state}"
        );
        signal::kill(nix::unistd::Pid::from_raw(pid.as_raw()), Signal::SIGCONT)?;
        for _ in 0..8 {
            match running.wait()? {
                Wait::Exited(got, status) => {
                    assert_eq!((got, status), (pid, ExitStatus::Exited(7)));
                    return Ok(());
                }
                Wait::Stopped(task, Event::Signal(Signal::SIGCONT)) => {
                    running = task.resume(Some(Signal::SIGCONT))?;
                }
                Wait::Stopped(task, _) => {
                    running = task.resume(None)?;
                }
            }
        }
        panic!("listened child did not exit after SIGCONT");
    }

    #[cfg(feature = "notifier")]
    #[test]
    fn process_sigkill_kills_group_of_exited_leader_thread()
    -> Result<(), Box<dyn std::error::Error>> {
        let (pid, stopped) = trace(
            || {
                // A raw pthread, not `std::thread::spawn`: see
                // `spawn_tracee_thread`, which this test does not share
                // because it also runs in sanitized builds.
                extern "C" fn sleep_then_exit(_: *mut libc::c_void) -> *mut libc::c_void {
                    let mut left = 5;
                    while left > 0 {
                        left = unsafe { libc::sleep(left) };
                    }
                    unsafe { libc::_exit(0) }
                }
                let mut sibling = std::mem::MaybeUninit::<libc::pthread_t>::uninit();
                let created = unsafe {
                    libc::pthread_create(
                        sibling.as_mut_ptr(),
                        std::ptr::null(),
                        sleep_then_exit,
                        std::ptr::null_mut(),
                    )
                };
                if created != 0 {
                    unsafe { libc::_exit(126) };
                }
                // End only the traced main thread. The sibling keeps the
                // group alive, leaving a zombie group leader.
                loop {
                    unsafe { libc::syscall(libc::SYS_exit, 0) };
                }
            },
            Options::PTRACE_O_EXITKILL,
        )?;
        let cleanup = stopped.terminal_cleanup();
        let running = stopped.resume(None)?;
        let status_path = format!("/proc/{}/status", pid.as_raw());
        let zombie = (0..200).any(|_| {
            let state = std::fs::read_to_string(&status_path).unwrap_or_default();
            if state
                .lines()
                .any(|line| line.starts_with("State:") && line.contains("zombie"))
            {
                return true;
            }
            thread::sleep(std::time::Duration::from_millis(10));
            false
        });
        assert!(zombie, "traced leader thread did not become a zombie");
        // A thread-directed SIGKILL would stay pending on the zombie and
        // the sibling would exit 0 after 5 s instead.
        let started = std::time::Instant::now();
        cleanup.request_process_sigkill()?;
        match running.wait()? {
            Wait::Exited(got, status) => {
                assert_eq!(got, pid);
                assert!(
                    matches!(status, ExitStatus::Signaled(Signal::SIGKILL, _)),
                    "unexpected status {status:?}"
                );
            }
            other => panic!("expected the group's terminal status, got {other:?}"),
        }
        assert!(started.elapsed() < std::time::Duration::from_secs(3));
        Ok(())
    }

    #[test]
    fn fpu_register_writes_fail_once_forbidden() -> Result<(), Box<dyn std::error::Error + 'static>>
    {
        // No other test in this binary writes FP registers, so forbidding them
        // process-wide here does not disturb one.
        let (pid, tracee) = trace(|| 0, Options::PTRACE_O_EXITKILL)?;
        let fpregs = tracee.getfpregs()?;
        tracee.setfpregs(&fpregs)?;
        #[cfg(target_arch = "x86_64")]
        let xstate = tracee.getxstate()?;
        #[cfg(target_arch = "x86_64")]
        tracee.setxstate(&xstate)?;
        forbid_fpu_register_writes();
        assert!(fpu_register_writes_forbidden());
        assert!(matches!(
            tracee.setfpregs(&fpregs),
            Err(Error::Errno(Errno::EPERM))
        ));
        #[cfg(target_arch = "x86_64")]
        assert!(matches!(
            tracee.setxstate(&xstate),
            Err(Error::Errno(Errno::EPERM))
        ));
        // Reads are unaffected.
        tracee.getfpregs()?;
        assert_eq!(
            tracee.resume(None)?.wait()?,
            Wait::Exited(pid, ExitStatus::Exited(0))
        );
        Ok(())
    }

    #[test]
    fn basic() -> Result<(), Box<dyn std::error::Error + 'static>> {
        // Do nothing but exit.
        let (pid, tracee) = trace(|| 42, Options::empty())?;
        assert_eq!(
            tracee.resume(None)?.wait()?,
            Wait::Exited(pid, ExitStatus::Exited(42))
        );

        Ok(())
    }

    #[test]
    fn stop_on_exit() -> Result<(), Box<dyn std::error::Error + 'static>> {
        let (pid, tracee) = trace(
            || 42,
            Options::PTRACE_O_EXITKILL | Options::PTRACE_O_TRACEEXIT,
        )?;

        let running = tracee.resume(None)?;
        let (stopped, event) = running.wait()?.assume_stopped();

        // The tracee has stopped just before exiting. Resuming or detaching now
        // will let the process exit.
        assert_eq!(event, Event::Exit);

        assert_eq!(
            stopped.resume(None)?.wait()?,
            Wait::Exited(pid, ExitStatus::Exited(42))
        );

        Ok(())
    }

    #[cfg(target_arch = "x86_64")]
    const PRSTATUS_BYTES: usize = core::mem::size_of::<libc::user_regs_struct>();
    #[cfg(target_arch = "x86_64")]
    const PRSTATUS_CS: usize = core::mem::offset_of!(libc::user_regs_struct, cs);

    // Independent raw observation: this deliberately does not call
    // Stopped::getregs or any decoder that assumes a native reply size.
    #[cfg(target_arch = "x86_64")]
    fn raw_prstatus(tid: i32) -> Result<([u8; PRSTATUS_BYTES], usize), Errno> {
        let mut bytes = [0xa5u8; PRSTATUS_BYTES];
        let mut iov = libc::iovec {
            iov_base: bytes.as_mut_ptr().cast(),
            iov_len: bytes.len(),
        };
        Errno::result(unsafe {
            libc::ptrace(
                libc::PTRACE_GETREGSET,
                tid,
                libc::NT_PRSTATUS as usize as *mut libc::c_void,
                &mut iov as *mut libc::iovec,
            )
        })?;
        Ok((bytes, iov.iov_len))
    }

    #[cfg(target_arch = "x86_64")]
    fn set_native_prstatus(tid: i32, bytes: &[u8; PRSTATUS_BYTES]) -> Result<(), Errno> {
        // On x86-64, PTRACE_SETREGS uses the native tracer layout even when the
        // stopped target's current CS selects compat GETREGSET. This permits
        // exact restoration without executing a single instruction in compat
        // mode.
        Errno::result(unsafe {
            libc::ptrace(
                libc::PTRACE_SETREGS,
                tid,
                std::ptr::null_mut::<libc::c_void>(),
                bytes.as_ptr(),
            )
        })
        .map(|_| ())
    }

    #[cfg(target_arch = "x86_64")]
    #[test]
    fn generic_getregs_refuses_actual_compat_and_restores()
    -> Result<(), Box<dyn std::error::Error + 'static>> {
        let (pid, tracee) = trace(|| 42, Options::PTRACE_O_EXITKILL)?;
        let tid = pid.as_raw();
        let (original, length) = raw_prstatus(tid)?;
        assert_eq!(length, PRSTATUS_BYTES);
        assert_eq!(tracee.getregs()?.cs, 0x33);
        let mut compat = original;
        compat[PRSTATUS_CS..PRSTATUS_CS + 8].copy_from_slice(&0x23u64.to_ne_bytes());
        set_native_prstatus(tid, &compat)?;
        // The raw write above bypasses `Stopped::setregs`, so the
        // generation's register cache still holds the native registers
        // read before it. Drop them explicitly, as any writer outside
        // the `Stopped` API must: the refusal below has to observe the
        // kernel's current compat reply, not the cached native one.
        #[cfg(feature = "notifier")]
        tracee.1.event().invalidate_regs();
        let (reply, length) = raw_prstatus(tid)?;
        assert_eq!(length, 68, "actual short kernel PRSTATUS, never a mock");
        assert_eq!(u16::from_ne_bytes(reply[52..54].try_into().unwrap()), 0x23);
        assert!(reply[length..].iter().all(|byte| *byte == 0xa5));

        // The fixed generic API must refuse before constructing Regs. Restore
        // the native registers before asserting, so the child can exit
        // normally. (Before the fix, debug builds panicked on the length
        // assertion and release builds constructed Regs from 148
        // uninitialized bytes.)
        let result = tracee.getregs();
        set_native_prstatus(tid, &original)?;
        let (restored, length) = raw_prstatus(tid)?;
        assert_eq!(length, PRSTATUS_BYTES);
        assert_eq!(restored, original);
        assert!(
            matches!(result, Err(Error::Errno(Errno::EPROTO))),
            "{result:?}"
        );
        assert_eq!(tracee.getregs()?.cs, 0x33);
        assert_eq!(
            tracee.resume(None)?.wait()?,
            Wait::Exited(pid, ExitStatus::Exited(42))
        );
        Ok(())
    }

    #[test]
    #[cfg(not(sanitized))]
    fn serialized_threads() -> Result<(), Box<dyn std::error::Error + 'static>> {
        const THREAD_COUNT: usize = 8;

        let (pid, tracee) = trace(
            move || {
                // Create a handful of threads that do nothing but exit. They
                // are raw pthreads: see `spawn_tracee_thread`.
                extern "C" fn exit_at_once(_: *mut libc::c_void) -> *mut libc::c_void {
                    std::ptr::null_mut()
                }
                let threads = (0..THREAD_COUNT)
                    .map(|_| spawn_tracee_thread(exit_at_once, std::ptr::null_mut()))
                    .collect::<Vec<_>>();

                for t in threads {
                    assert_eq!(unsafe { libc::pthread_join(t, std::ptr::null_mut()) }, 0);
                }

                42
            },
            Options::PTRACE_O_EXITKILL
                | Options::PTRACE_O_TRACEEXIT
                | ptrace::Options::PTRACE_O_TRACECLONE,
        )?;

        let mut parent = tracee.resume(None)?;

        // We should observe threads getting created.
        for _ in 0..THREAD_COUNT {
            let (stopped, event) = parent.wait()?.assume_stopped();

            let child = match event {
                Event::NewChild(ChildOp::Clone, child) => child,
                e => panic!("Expected clone event, got {:?}", e),
            };

            // Should be at a group stop.
            let (child, event) = child.wait()?.assume_stopped();
            assert_eq!(event, Event::Stop);

            // Resume the child.
            let child = child.resume(None)?;

            // Wait for it to exit.
            let (child, event) = child.wait()?.assume_stopped();
            assert_eq!(event, Event::Exit);

            // Resume one last time to let it fully exit.
            let (_child_pid, exit_status) = child.resume(None)?.wait()?.assume_exited();
            assert_eq!(exit_status, ExitStatus::Exited(0));

            // Resume the parent.
            parent = stopped.resume(None)?;
        }

        // ptrace stop just before fully exiting.
        let (parent, event) = parent.wait()?.assume_stopped();
        assert_eq!(event, Event::Exit);

        // Fully exited.
        let parent = parent.resume(None)?;
        assert_eq!(parent.wait()?, Wait::Exited(pid, ExitStatus::Exited(42)));

        Ok(())
    }

    /// Starts a thread in a tracee forked by [`trace`] with a raw
    /// `pthread_create`.
    ///
    /// The test harness is multithreaded, and `fork` copies only the calling
    /// thread. A lock another harness thread held at the fork stays held in
    /// the child forever. `std::thread::spawn` takes such a lock (the thread
    /// info lock of std's stack overflow handler), so a tracee that uses it
    /// can block before its first clone. `pthread_create` needs no lock that
    /// glibc does not reset in the child of a fork.
    #[cfg(not(sanitized))]
    fn spawn_tracee_thread(
        start: extern "C" fn(*mut libc::c_void) -> *mut libc::c_void,
        arg: *mut libc::c_void,
    ) -> libc::pthread_t {
        let mut thread = std::mem::MaybeUninit::<libc::pthread_t>::uninit();
        let rc = unsafe { libc::pthread_create(thread.as_mut_ptr(), std::ptr::null(), start, arg) };
        assert_eq!(rc, 0, "pthread_create in a tracee failed");
        unsafe { thread.assume_init() }
    }

    #[cfg(not(sanitized))]
    fn group_exit(thread_count: usize) -> Result<(), Box<dyn std::error::Error + 'static>> {
        use std::sync::Arc;
        use std::sync::atomic::AtomicUsize;
        use std::sync::atomic::Ordering;
        use std::time::Duration;

        let (parent_pid, tracee) = trace(
            move || {
                let counter = Arc::new(AtomicUsize::new(0));

                // Create a handful of threads that sleep forever. They are
                // raw pthreads: see `spawn_tracee_thread`.
                extern "C" fn count_and_sleep(counter: *mut libc::c_void) -> *mut libc::c_void {
                    // SAFETY: `counter` comes from `Arc::into_raw` below and
                    // owns one strong count, which this thread never drops:
                    // it sleeps until exit_group ends the process.
                    let counter = unsafe { &*(counter as *const AtomicUsize) };
                    counter.fetch_add(1, Ordering::Relaxed);
                    unsafe { libc::sleep(Duration::from_mins(1).as_secs() as libc::c_uint) };
                    std::ptr::null_mut()
                }
                let _threads = (0..thread_count)
                    .map(|_i| {
                        let counter = Arc::into_raw(counter.clone()) as *mut libc::c_void;
                        spawn_tracee_thread(count_and_sleep, counter)
                    })
                    .collect::<Vec<_>>();

                // Wait for each of the threads to actually get initialized.
                while counter.load(Ordering::Relaxed) != thread_count {
                    thread::yield_now();
                }

                // All threads should be alive at this point. SYS_exit_group
                // should force all threads to exit.
                let _ = unsafe { libc::syscall(libc::SYS_exit_group, 42) };

                unreachable!()
            },
            Options::PTRACE_O_EXITKILL
                | Options::PTRACE_O_TRACEEXIT
                | ptrace::Options::PTRACE_O_TRACECLONE,
        )?;

        tracee.resume(None)?;

        let mut exited = Vec::new();

        // Keep consuming events until everything has exited.
        while let Some(wait) = wait_group(parent_pid)? {
            match wait {
                Wait::Stopped(tracee, _event) => {
                    tracee.resume(None)?;
                }
                Wait::Exited(pid, exit_status) => {
                    exited.push((pid, exit_status));
                }
            }
        }

        // The parent should have exited last.
        assert_eq!(exited.pop(), Some((parent_pid, ExitStatus::Exited(42))));

        // The only things left should be the threads that were spawned.
        assert_eq!(exited.len(), thread_count);

        // All others should have exited with the same exit status.
        for (_pid, exit_status) in exited {
            assert_eq!(exit_status, ExitStatus::Exited(42));
        }

        Ok(())
    }

    /// Tests that we receive an exit for all threads in the right order even
    /// when the main thread calls `exit_group`.
    #[test]
    #[cfg(not(sanitized))]
    fn group_exit_stress() {
        // Test a variety of thread counts. Super-high thread counts makes
        // ptrace very slow, so we keep this to a relatively low number.
        for i in 0..100 {
            group_exit(i / 2).unwrap();
        }
    }

    /// Tests that trying to trace from another thread does not work.
    #[test]
    fn trace_from_another_thread() -> Result<(), Box<dyn std::error::Error + 'static>> {
        let (pid, tracee) = trace(|| 42, Options::empty()).unwrap();

        // Try resuming from another thread, which should fail. The process
        // didn't actually die; this is just how ESRCH is interpreted.
        let error = thread::spawn(move || tracee.resume(None))
            .join()
            .unwrap()
            .unwrap_err();
        assert!(matches!(error, Error::Died(zombie) if zombie.pid() == pid));

        assert_eq!(
            Stopped::new_unchecked(pid).resume(None)?.wait()?,
            Wait::Exited(pid, ExitStatus::Exited(42))
        );

        Ok(())
    }

    #[test]
    fn trace_killed_by_signal() -> Result<(), Box<dyn std::error::Error + 'static>> {
        let (pid, tracee) = trace(
            || {
                signal::raise(Signal::SIGILL).unwrap();
                unreachable!()
            },
            Options::PTRACE_O_EXITKILL,
        )?;

        let running = tracee.resume(None)?;

        let (stopped, event) = running.wait()?.assume_stopped();

        // The tracee has stopped just before exiting. Resuming or detaching now
        // will let the process exit.
        assert_eq!(event, Event::Signal(Signal::SIGILL));

        assert_eq!(
            stopped.resume(Some(Signal::SIGILL))?.wait()?,
            Wait::Exited(pid, ExitStatus::Signaled(Signal::SIGILL, true))
        );

        Ok(())
    }

    #[cfg(feature = "notifier")]
    #[cfg(not(sanitized))]
    #[tokio::test]
    async fn notifier_basic() -> Result<(), Box<dyn std::error::Error + 'static>> {
        let (pid, tracee) = trace(|| 42, Options::empty())?;
        assert_eq!(
            tracee.resume(None)?.next_state().await?,
            Wait::Exited(pid, ExitStatus::Exited(42))
        );

        Ok(())
    }

    #[cfg(feature = "notifier")]
    #[cfg(not(sanitized))]
    #[tokio::test]
    async fn notifier_generation_preserves_exit_and_signal_status()
    -> Result<(), Box<dyn std::error::Error>> {
        let (pid, tracee) = trace(|| 42, Options::empty())?;
        let token = tracee.1.clone();
        let stale_running = Running::from_token(pid, token.clone());
        let stale_zombie = Zombie::from_token(pid, token);
        let expected = ExitStatus::Exited(42);

        assert_eq!(
            tracee.resume(None)?.next_state().await?,
            Wait::Exited(pid, expected)
        );
        assert_eq!(
            stale_running.next_state().await?,
            Wait::Exited(pid, expected),
            "old Running rebound after terminal registry removal"
        );
        assert_eq!(stale_zombie.reap().await?, expected);
        assert_eq!(
            Running::new(pid).next_state().await,
            Err(Error::Errno(Errno::ECHILD)),
            "fresh generation inherited stale terminal status"
        );

        let (pid, tracee) = trace(
            || {
                signal::raise(Signal::SIGILL).unwrap();
                unreachable!()
            },
            Options::PTRACE_O_EXITKILL,
        )?;
        let token = tracee.1.clone();
        let stale_running = Running::from_token(pid, token.clone());
        let stale_zombie = Zombie::from_token(pid, token);
        let expected = ExitStatus::Signaled(Signal::SIGILL, true);
        let (stopped, event) = tracee.resume(None)?.next_state().await?.assume_stopped();
        assert_eq!(event, Event::Signal(Signal::SIGILL));

        assert_eq!(
            stopped.resume(Some(Signal::SIGILL))?.next_state().await?,
            Wait::Exited(pid, expected)
        );
        assert_eq!(
            stale_running.next_state().await?,
            Wait::Exited(pid, expected),
            "old Running lost the terminating signal"
        );
        assert_eq!(stale_zombie.reap().await?, expected);
        assert_eq!(
            Running::new(pid).next_state().await,
            Err(Error::Errno(Errno::ECHILD))
        );

        Ok(())
    }

    #[cfg(feature = "notifier")]
    #[cfg(not(sanitized))]
    #[tokio::test(flavor = "current_thread")]
    async fn owned_wait_clone_parent_decode_refusal_retains_same_owner()
    -> Result<(), Box<dyn std::error::Error>> {
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
        for injected in [Errno::EMFILE, Errno::EIO] {
            let (pid, tracee) = trace(
                || {
                    let flags = libc::CLONE_PARENT | libc::SIGCHLD;
                    let result = unsafe {
                        libc::syscall(libc::SYS_clone, flags, 0usize, 0usize, 0usize, 0usize)
                    };
                    if result == 0 {
                        unsafe { libc::_exit(0) };
                    }
                    i32::from(result == -1)
                },
                Options::PTRACE_O_EXITKILL | Options::PTRACE_O_TRACEFORK,
            )?;
            let running = tracee.resume_retaining(None).map_err(|(_, error)| error)?;
            let cleanup = running.terminal_cleanup();
            let mut owner = running.wait_owned();

            notifier::inject_capture_error_for_current_thread(injected);
            assert_eq!(
                tokio::time::timeout(
                    deadline.saturating_duration_since(std::time::Instant::now()),
                    &mut owner
                )
                .await?,
                Err(OwnedWaitError::Errno(injected)),
                "first CLONE_PARENT decode did not surface the injected capture error"
            );

            let (parent, event) = tokio::time::timeout(
                deadline.saturating_duration_since(std::time::Instant::now()),
                &mut owner,
            )
            .await??
            .assume_stopped();
            assert_eq!(parent.pid(), pid);
            assert!(parent.terminal_cleanup().same_generation(&cleanup));
            assert!(matches!((&mut owner).await, Err(OwnedWaitError::Completed)));
            let child = match event {
                Event::NewChild(ChildOp::Fork, child) => child,
                event => panic!("retry lost the CLONE_PARENT event: {event:?}"),
            };
            let (child, event) = tokio::time::timeout(
                deadline.saturating_duration_since(std::time::Instant::now()),
                child.wait_owned(),
            )
            .await??
            .assume_stopped();
            assert!(matches!(
                event,
                Event::Stop | Event::Signal(Signal::SIGSTOP)
            ));
            assert_eq!(
                tokio::time::timeout(
                    deadline.saturating_duration_since(std::time::Instant::now()),
                    child.resume(None)?.wait_owned()
                )
                .await??
                .assume_exited()
                .1,
                ExitStatus::Exited(0)
            );
            assert_eq!(
                tokio::time::timeout(
                    deadline.saturating_duration_since(std::time::Instant::now()),
                    parent.resume(None)?.wait_owned()
                )
                .await??
                .assume_exited()
                .1,
                ExitStatus::Exited(0)
            );
        }
        Ok(())
    }

    #[cfg(feature = "notifier")]
    #[cfg(not(sanitized))]
    #[tokio::test(flavor = "current_thread")]
    async fn notifier_clone_parent_decode_error_preserves_fifo_front()
    -> Result<(), Box<dyn std::error::Error>> {
        for injected in [Errno::EMFILE, Errno::EIO] {
            let (pid, tracee) = trace(
                || {
                    let flags = libc::CLONE_PARENT | libc::SIGCHLD;
                    let result = unsafe {
                        libc::syscall(libc::SYS_clone, flags, 0usize, 0usize, 0usize, 0usize)
                    };
                    if result == 0 {
                        unsafe { libc::_exit(0) };
                    }
                    i32::from(result == -1)
                },
                Options::PTRACE_O_EXITKILL | Options::PTRACE_O_TRACEFORK,
            )?;
            let token = tracee.1.clone();
            let running = tracee.resume(None)?;
            let retry = Running::from_token(pid, token);
            let _cleanup = running.terminal_cleanup();

            notifier::inject_capture_error_for_current_thread(injected);
            assert_eq!(
                running.next_state().await,
                Err(Error::Errno(injected)),
                "first CLONE_PARENT decode did not surface the injected capture error"
            );

            let (parent, event) = retry.next_state().await?.assume_stopped();
            let child = match event {
                Event::NewChild(ChildOp::Fork, child) => child,
                event => panic!("retry lost the CLONE_PARENT event: {event:?}"),
            };
            let (child, event) = child.next_state().await?.assume_stopped();
            assert!(matches!(
                event,
                Event::Stop | Event::Signal(Signal::SIGSTOP)
            ));
            assert_eq!(
                child.resume(None)?.next_state().await?.assume_exited().1,
                ExitStatus::Exited(0)
            );
            assert_eq!(
                parent.resume(None)?.next_state().await?.assume_exited().1,
                ExitStatus::Exited(0)
            );
        }
        Ok(())
    }

    #[cfg(feature = "notifier")]
    #[cfg(not(sanitized))]
    #[test]
    fn synchronous_clone_parent_decode_error_preserves_fifo_front()
    -> Result<(), Box<dyn std::error::Error>> {
        for injected in [Errno::EMFILE, Errno::EIO] {
            let (pid, tracee) = trace(
                || {
                    let flags = libc::CLONE_PARENT | libc::SIGCHLD;
                    let result = unsafe {
                        libc::syscall(libc::SYS_clone, flags, 0usize, 0usize, 0usize, 0usize)
                    };
                    if result == 0 {
                        unsafe { libc::_exit(0) };
                    }
                    i32::from(result == -1)
                },
                Options::PTRACE_O_EXITKILL | Options::PTRACE_O_TRACEFORK,
            )?;
            let token = tracee.1.clone();
            let running = tracee.resume(None)?;
            let retry = Running::from_token(pid, token);

            notifier::inject_sync_decode_capture_error(pid, injected);
            assert_eq!(
                running.wait(),
                Err(Error::Errno(injected)),
                "first synchronous CLONE_PARENT decode did not surface the injected error"
            );

            let (parent, event) = retry.wait()?.assume_stopped();
            let child = match event {
                Event::NewChild(ChildOp::Fork, child) => child,
                event => panic!("synchronous retry lost the CLONE_PARENT event: {event:?}"),
            };
            let (child, event) = child.wait()?.assume_stopped();
            assert!(matches!(
                event,
                Event::Stop | Event::Signal(Signal::SIGSTOP)
            ));
            assert_eq!(
                child.resume(None)?.wait()?.assume_exited().1,
                ExitStatus::Exited(0)
            );
            assert_eq!(
                parent.resume(None)?.wait()?.assume_exited().1,
                ExitStatus::Exited(0)
            );
        }
        Ok(())
    }

    #[cfg(feature = "notifier")]
    #[cfg(not(sanitized))]
    #[tokio::test]
    async fn late_waits_after_terminal_reap_return_echild() -> Result<(), Box<dyn std::error::Error>>
    {
        let (pid, tracee) = trace(|| 42, Options::empty())?;
        assert_eq!(
            tracee.resume(None)?.next_state().await?,
            Wait::Exited(pid, ExitStatus::Exited(42))
        );

        assert_eq!(
            tokio::time::timeout(
                std::time::Duration::from_secs(1),
                Running::new(pid).next_state(),
            )
            .await
            .expect("late next_state hung after terminal reap"),
            Err(Error::Errno(Errno::ECHILD))
        );
        assert_eq!(
            tokio::time::timeout(
                std::time::Duration::from_secs(1),
                Running::new(pid).exit_event(),
            )
            .await
            .expect("late exit_event hung after terminal reap"),
            Err(Error::Errno(Errno::ECHILD))
        );

        Ok(())
    }

    // kernel_sigset_t used by naked syscall
    #[derive(Clone, Copy, PartialEq, Eq, Debug)]
    struct KernelSigset(u64);

    impl From<&[Signal]> for KernelSigset {
        fn from(signals: &[Signal]) -> Self {
            let mut set: u64 = 0;
            for &sig in signals {
                set |= 1u64 << (sig as usize - 1);
            }
            KernelSigset(set)
        }
    }

    #[unsafe(no_mangle)]
    extern "C" fn sigalrm_handler(
        _sig: i32,
        _siginfo: *mut libc::siginfo_t,
        _ucontext: *const libc::c_void,
    ) {
        nix::unistd::write(unsafe { BorrowedFd::borrow_raw(2) }, b"caught SIGALRM!").unwrap();
    }

    #[allow(dead_code)]
    unsafe fn install_sigalrm_handler() -> i32 {
        unsafe {
            let mut sa: libc::sigaction = MaybeUninit::zeroed().assume_init();
            sa.sa_flags = libc::SA_RESTART | libc::SA_SIGINFO | libc::SA_NODEFER;
            sa.sa_sigaction = sigalrm_handler as *const () as _;

            libc::sigaction(libc::SIGALRM, &sa as *const _, std::ptr::null_mut())
        }
    }

    #[allow(dead_code)]
    // unblock signal(s) and set its handler to SIG_DFL
    unsafe fn unblock_signals(signals: &[Signal]) -> io::Result<KernelSigset> {
        unsafe {
            let set = KernelSigset::from(signals);
            let mut oldset = MaybeUninit::<u64>::uninit();

            if libc::syscall(
                libc::SYS_rt_sigprocmask,
                libc::SIG_UNBLOCK,
                &set as *const _,
                oldset.as_mut_ptr(),
                8,
            ) != 0
            {
                Err(io::Error::last_os_error())
            } else {
                Ok(KernelSigset(oldset.assume_init()))
            }
        }
    }

    #[allow(dead_code)]
    unsafe fn block_signals(signals: &[Signal]) -> io::Result<KernelSigset> {
        unsafe {
            let set = KernelSigset::from(signals);
            let mut oldset = MaybeUninit::<u64>::uninit();

            if libc::syscall(
                libc::SYS_rt_sigprocmask,
                libc::SIG_BLOCK,
                &set as *const _,
                oldset.as_mut_ptr(),
                8,
            ) != 0
            {
                Err(io::Error::last_os_error())
            } else {
                Ok(KernelSigset(oldset.assume_init()))
            }
        }
    }

    /// The calling thread's blocked-signal mask, as the kernel reports it.
    #[cfg(not(sanitized))]
    fn own_sigmask() -> u64 {
        let mut mask = 0u64;
        let ret = unsafe {
            libc::syscall(
                libc::SYS_rt_sigprocmask,
                libc::SIG_BLOCK,
                std::ptr::null::<u64>(),
                &mut mask as *mut u64,
                8,
            )
        };
        assert_eq!(ret, 0);
        mask
    }

    /// Stops the calling thread with a raw `tgkill(getpid(), gettid(),
    /// SIGSTOP)`, so no userspace mask save and restore wraps the stop. libc
    /// `raise()` in glibc 2.26 to 2.33, and in musl, blocks signals around its
    /// tgkill and restores the saved mask afterwards; that restore would run
    /// after the tracer's PTRACE_SETSIGMASK at this stop and overwrite it.
    #[cfg(not(sanitized))]
    fn stop_self_with_raw_tgkill() {
        let ret = unsafe {
            let pid = libc::syscall(libc::SYS_getpid);
            let tid = libc::syscall(libc::SYS_gettid);
            libc::syscall(libc::SYS_tgkill, pid, tid, libc::SIGSTOP)
        };
        assert_eq!(ret, 0);
    }

    /// Waits for the tracee's next stop, which must be a signal-delivery stop
    /// for `signal`.
    #[cfg(not(sanitized))]
    fn expect_signal_stop(running: Running, signal: Signal) -> Stopped {
        match running.wait().unwrap() {
            Wait::Stopped(stopped, Event::Signal(got)) if got == signal => stopped,
            other => panic!("expected a {signal:?} delivery stop, got {other:?}"),
        }
    }

    /// PTRACE_GETSIGMASK reads the mask the tracee set itself, and
    /// PTRACE_SETSIGMASK replaces it (minus SIGKILL and SIGSTOP, which the
    /// kernel never blocks) as the tracee then observes.
    #[cfg(not(sanitized))]
    #[test]
    fn getsigmask_and_setsigmask_read_and_replace_the_tracee_mask()
    -> Result<(), Box<dyn std::error::Error + 'static>> {
        let replacement = KernelSigset::from(&[Signal::SIGUSR1, Signal::SIGALRM][..]).0;
        let unblockable = KernelSigset::from(&[Signal::SIGKILL, Signal::SIGSTOP][..]).0;
        let (pid, tracee) = trace(
            move || {
                unsafe { block_signals(&[Signal::SIGUSR1, Signal::SIGUSR2]) }.unwrap();
                stop_self_with_raw_tgkill();
                if own_sigmask() == replacement { 0 } else { 1 }
            },
            Options::PTRACE_O_EXITKILL,
        )?;
        let stopped = expect_signal_stop(tracee.resume(None)?, Signal::SIGSTOP);
        let blocked = KernelSigset::from(&[Signal::SIGUSR1, Signal::SIGUSR2][..]).0;
        let mask = stopped.getsigmask()?;
        assert_eq!(mask & blocked, blocked, "mask {mask:#x}");
        stopped.setsigmask(replacement | unblockable)?;
        assert_eq!(stopped.getsigmask()?, replacement);
        // Suppress the SIGSTOP; the tracee checks its own mask and exits.
        assert_eq!(
            stopped.resume(None)?.wait()?,
            Wait::Exited(pid, ExitStatus::Exited(0))
        );
        Ok(())
    }

    #[cfg(not(sanitized))]
    static SIGUSR1_HANDLED: std::sync::atomic::AtomicBool =
        std::sync::atomic::AtomicBool::new(false);

    #[cfg(not(sanitized))]
    extern "C" fn note_sigusr1(_signal: libc::c_int) {
        SIGUSR1_HANDLED.store(true, std::sync::atomic::Ordering::SeqCst);
    }

    /// A mask set by the tracer holds a signal sent meanwhile pending (no
    /// delivery stop, no handler), and restoring the saved mask releases it
    /// to an ordinary delivery stop and the handler.
    #[cfg(not(sanitized))]
    #[test]
    fn setsigmask_holds_a_signal_pending_until_the_mask_is_restored()
    -> Result<(), Box<dyn std::error::Error + 'static>> {
        let (pid, tracee) = trace(
            || {
                let mut action: libc::sigaction = unsafe { MaybeUninit::zeroed().assume_init() };
                action.sa_sigaction = note_sigusr1 as *const () as usize;
                assert_eq!(
                    unsafe { libc::sigaction(libc::SIGUSR1, &action, std::ptr::null_mut()) },
                    0
                );
                unsafe { unblock_signals(&[Signal::SIGUSR1]) }.unwrap();
                stop_self_with_raw_tgkill();
                // The tracer blocked everything and sent SIGUSR1.
                let mut pending = 0u64;
                unsafe { libc::syscall(libc::SYS_rt_sigpending, &mut pending as *mut u64, 8) };
                let usr1 = KernelSigset::from(&[Signal::SIGUSR1][..]).0;
                if pending & usr1 == 0 {
                    return 2;
                }
                if SIGUSR1_HANDLED.load(std::sync::atomic::Ordering::SeqCst) {
                    return 3;
                }
                stop_self_with_raw_tgkill();
                // The tracer restored the mask: SIGUSR1 has been handled.
                if SIGUSR1_HANDLED.load(std::sync::atomic::Ordering::SeqCst) {
                    0
                } else {
                    4
                }
            },
            Options::PTRACE_O_EXITKILL,
        )?;
        let stopped = expect_signal_stop(tracee.resume(None)?, Signal::SIGSTOP);
        let saved = stopped.getsigmask()?;
        stopped.setsigmask(!0)?;
        signal::kill(pid.into(), Signal::SIGUSR1)?;
        // SIGUSR1 is blocked: the next stop is the second SIGSTOP.
        let stopped = expect_signal_stop(stopped.resume(None)?, Signal::SIGSTOP);
        stopped.setsigmask(saved)?;
        assert_eq!(stopped.getsigmask()?, saved);
        let stopped = expect_signal_stop(stopped.resume(None)?, Signal::SIGUSR1);
        assert_eq!(
            stopped.resume(Some(Signal::SIGUSR1))?.wait()?,
            Wait::Exited(pid, ExitStatus::Exited(0))
        );
        Ok(())
    }

    /// A tracee's debug registers, read and written in its `struct user`:
    /// an address and a slot's controls read back as written, and DR6 reads
    /// back in the hardware's polarity, its hit bits as written.
    #[cfg(target_arch = "x86_64")]
    #[test]
    fn debug_registers_round_trip_through_peekuser_and_pokeuser()
    -> Result<(), Box<dyn std::error::Error + 'static>> {
        static WATCHED: u64 = 0;
        let debugreg = |n: usize| core::mem::offset_of!(libc::user, u_debugreg) + 8 * n;
        let (parent_pid, tracee) = trace(
            || {
                let _ = unsafe { libc::syscall(libc::SYS_exit_group, 0) };
                unreachable!()
            },
            Options::PTRACE_O_EXITKILL,
        )?;
        let addr = &WATCHED as *const u64 as u64;
        tracee.pokeuser(debugreg(0), addr)?;
        assert_eq!(tracee.peekuser(debugreg(0))?, addr);
        // Slot 0 enabled, watching writes of 8 bytes.
        tracee.pokeuser(debugreg(7), 0x0009_0001)?;
        assert_eq!(tracee.peekuser(debugreg(7))?, 0x0009_0001);
        let dr6 = tracee.peekuser(debugreg(6))?;
        assert_eq!(dr6 & 0xf, 0, "{dr6:#x}");
        tracee.pokeuser(debugreg(6), dr6 | 0b0100)?;
        assert_eq!(tracee.peekuser(debugreg(6))?, dr6 | 0b0100);
        tracee.pokeuser(debugreg(6), dr6)?;
        tracee.pokeuser(debugreg(7), 0)?;
        // There is no DR4.
        assert_eq!(
            tracee.pokeuser(debugreg(4), 0),
            Err(Error::Errno(Errno::EIO))
        );
        tracee.resume(None)?;
        while wait_group(parent_pid)?.is_some() {}
        Ok(())
    }

    #[cfg(not(sanitized))]
    #[test]
    fn peeksiginfo_returns_pending_siginfo() -> Result<(), Box<dyn std::error::Error + 'static>> {
        let (parent_pid, tracee) = trace(
            move || {
                let _ = unsafe {
                    block_signals(&[Signal::SIGALRM, Signal::SIGVTALRM, Signal::SIGPROF])
                };
                assert!(signal::raise(Signal::SIGALRM).is_ok());
                assert!(signal::raise(Signal::SIGVTALRM).is_ok());
                assert!(signal::raise(Signal::SIGPROF).is_ok());

                // All threads should be alive at this point. SYS_exit_group
                // should force all threads to exit.
                let _ = unsafe { libc::syscall(libc::SYS_exit_group, 0) };

                unreachable!()
            },
            Options::PTRACE_O_EXITKILL
                | Options::PTRACE_O_TRACEEXIT
                | ptrace::Options::PTRACE_O_TRACECLONE,
        )?;

        tracee.resume(None)?;

        let mut exited = Vec::new();

        // Keep consuming events until everything has exited.
        while let Some(wait) = wait_group(parent_pid)? {
            match wait {
                Wait::Stopped(tracee, Event::Exit) => {
                    let pending: Vec<_> = tracee
                        .peeksiginfo(None)?
                        .iter()
                        .map(|&si| Signal::try_from(si.si_signo).unwrap())
                        .collect();
                    assert_eq!(
                        pending,
                        [Signal::SIGALRM, Signal::SIGVTALRM, Signal::SIGPROF]
                    );
                    // do a second peek here to demostrate peek doesn't
                    // *pop* pending signals.
                    let pending: Vec<_> = tracee
                        .peeksiginfo(None)?
                        .iter()
                        .map(|&si| Signal::try_from(si.si_signo).unwrap())
                        .collect();
                    assert_eq!(
                        pending,
                        [Signal::SIGALRM, Signal::SIGVTALRM, Signal::SIGPROF]
                    );
                    tracee.resume(None)?;
                }
                Wait::Stopped(tracee, _event) => {
                    tracee.resume(None)?;
                }
                Wait::Exited(pid, exit_status) => {
                    exited.push((pid, exit_status));
                }
            }
        }

        // The parent should have exited last
        assert_eq!(exited.pop(), Some((parent_pid, ExitStatus::Exited(0))));

        Ok(())
    }

    #[cfg(not(sanitized))]
    #[test]
    fn peeksiginfo_all_returns_the_whole_queue() -> Result<(), Box<dyn std::error::Error + 'static>>
    {
        // Real-time signals queue one entry each, so this exceeds one 64-entry
        // read twice over.
        const QUEUED: usize = 150;
        let (parent_pid, tracee) = trace(
            move || {
                let rt = libc::SIGRTMIN();
                unsafe {
                    let mut set: libc::sigset_t = core::mem::zeroed();
                    libc::sigemptyset(&mut set);
                    libc::sigaddset(&mut set, rt);
                    libc::sigaddset(&mut set, libc::SIGALRM);
                    assert_eq!(
                        libc::sigprocmask(libc::SIG_BLOCK, &set, core::ptr::null_mut()),
                        0
                    );
                    for _ in 0..QUEUED {
                        assert_eq!(
                            libc::syscall(libc::SYS_tgkill, libc::getpid(), libc::gettid(), rt),
                            0
                        );
                    }
                    assert_eq!(
                        libc::syscall(
                            libc::SYS_tgkill,
                            libc::getpid(),
                            libc::gettid(),
                            libc::SIGALRM
                        ),
                        0
                    );
                    libc::syscall(libc::SYS_exit_group, 0);
                }
                unreachable!()
            },
            Options::PTRACE_O_EXITKILL | Options::PTRACE_O_TRACEEXIT,
        )?;

        tracee.resume(None)?;

        let mut peeked = false;
        while let Some(wait) = wait_group(parent_pid)? {
            match wait {
                Wait::Stopped(tracee, Event::Exit) => {
                    let signos = |v: Vec<libc::siginfo_t>| -> Vec<i32> {
                        v.iter().map(|si| si.si_signo).collect()
                    };
                    let mut expected = vec![libc::SIGRTMIN(); QUEUED];
                    expected.push(libc::SIGALRM);
                    assert_eq!(signos(tracee.peeksiginfo(None)?), expected[..64]);
                    assert_eq!(signos(tracee.peeksiginfo_all(None)?), expected);
                    peeked = true;
                    tracee.resume(None)?;
                }
                Wait::Stopped(tracee, _event) => {
                    tracee.resume(None)?;
                }
                Wait::Exited(_, exit_status) => {
                    assert_eq!(exit_status, ExitStatus::Exited(0));
                }
            }
        }
        assert!(peeked, "the tracee never reached its exit stop");

        Ok(())
    }

    #[cfg(not(sanitized))]
    #[test]
    fn getsiginfo_should_success() -> Result<(), Box<dyn std::error::Error + 'static>> {
        let (parent_pid, tracee) = trace(
            move || {
                let _ = unsafe { unblock_signals(&[Signal::SIGALRM]) };
                let _ = unsafe { block_signals(&[Signal::SIGVTALRM, Signal::SIGPROF]) };
                assert_eq!(unsafe { install_sigalrm_handler() }, 0);
                assert!(signal::raise(Signal::SIGALRM).is_ok());

                // All threads should be alive at this point. SYS_exit_group
                // should force all threads to exit.
                let _ = unsafe { libc::syscall(libc::SYS_exit_group, 0) };

                unreachable!()
            },
            Options::PTRACE_O_EXITKILL
                | Options::PTRACE_O_TRACEEXIT
                | ptrace::Options::PTRACE_O_TRACECLONE,
        )?;

        tracee.resume(None)?;

        let mut exited = Vec::new();

        // Keep consuming events until everything has exited.
        while let Some(wait) = wait_group(parent_pid)? {
            match wait {
                Wait::Stopped(tracee, Event::Signal(Signal::SIGALRM)) => {
                    let siginfo = tracee.getsiginfo()?;
                    assert_eq!(siginfo.si_signo, Signal::SIGALRM as i32);
                    tracee.resume(Signal::SIGALRM)?;
                }
                Wait::Stopped(tracee, Event::Signal(other_signal)) => {
                    tracee.resume(other_signal)?;
                }
                Wait::Stopped(tracee, _event) => {
                    tracee.resume(None)?;
                }
                Wait::Exited(pid, exit_status) => {
                    exited.push((pid, exit_status));
                }
            }
        }

        // The parent should have exited last
        assert_eq!(exited.pop(), Some((parent_pid, ExitStatus::Exited(0))));

        Ok(())
    }

    #[cfg(not(sanitized))]
    static RT_HANDLED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

    #[cfg(not(sanitized))]
    extern "C" fn note_realtime(signal: libc::c_int) {
        RT_HANDLED.fetch_or(1 << (signal - 1), std::sync::atomic::Ordering::SeqCst);
    }

    /// A realtime signal-delivery stop decodes as `Event::RawSignal` with its
    /// number, 32 and 33 included, and `resume_raw` delivers it to the
    /// tracee's handler or, with 0, suppresses it
    /// (<https://github.com/rrnewton/reverie/issues/207>). Standard signals
    /// still decode as `Event::Signal`.
    #[cfg(not(sanitized))]
    #[test]
    fn realtime_signal_stops_decode_raw_and_resume_raw_delivers_them()
    -> Result<(), Box<dyn std::error::Error + 'static>> {
        let delivered = [34, 50, 64];
        let (pid, tracee) = trace(
            move || {
                for signal in delivered {
                    let mut action: libc::sigaction =
                        unsafe { MaybeUninit::zeroed().assume_init() };
                    action.sa_sigaction = note_realtime as *const () as usize;
                    assert_eq!(
                        unsafe { libc::sigaction(signal, &action, std::ptr::null_mut()) },
                        0
                    );
                }
                for signal in [32, 33, 34, 50, 64] {
                    let ret = unsafe {
                        let pid = libc::syscall(libc::SYS_getpid);
                        let tid = libc::syscall(libc::SYS_gettid);
                        libc::syscall(libc::SYS_tgkill, pid, tid, signal)
                    };
                    assert_eq!(ret, 0);
                }
                stop_self_with_raw_tgkill();
                let want = delivered.iter().fold(0, |bits, s| bits | 1 << (s - 1));
                if RT_HANDLED.load(std::sync::atomic::Ordering::SeqCst) == want {
                    0
                } else {
                    1
                }
            },
            Options::PTRACE_O_EXITKILL,
        )?;
        let mut running = tracee.resume(None)?;
        for signal in [32, 33, 34, 50, 64] {
            let stopped = match running.wait()? {
                Wait::Stopped(stopped, Event::RawSignal(got)) if got == signal => stopped,
                other => panic!("expected a raw {signal} delivery stop, got {other:?}"),
            };
            let any = AnySignal::new(signal).unwrap();
            assert_eq!(Event::RawSignal(signal).signal(), Some(any));
            assert_eq!(Event::from_signal(any), Event::RawSignal(signal));
            assert_eq!(any.as_nix(), None);
            assert_eq!(format!("{any}"), format!("SIG{signal}"));
            // 32 and 33 are suppressed: their default action would end the
            // tracee. The others reach the handler.
            let deliver = if signal < 34 { 0 } else { signal };
            running = stopped.resume_raw(deliver)?;
        }
        let stopped = expect_signal_stop(running, Signal::SIGSTOP);
        assert_eq!(
            Event::Signal(Signal::SIGSTOP).signal(),
            Some(AnySignal::from(Signal::SIGSTOP))
        );
        assert_eq!(
            stopped.resume(None)?.wait()?,
            Wait::Exited(pid, ExitStatus::Exited(0))
        );
        Ok(())
    }

    #[cfg(not(sanitized))]
    #[test]
    fn detach_raw_delivers_a_realtime_signal() -> Result<(), Box<dyn std::error::Error + 'static>> {
        let (pid, tracee) = trace(
            || {
                RT_HANDLED.store(0, std::sync::atomic::Ordering::SeqCst);
                let mut action: libc::sigaction = unsafe { MaybeUninit::zeroed().assume_init() };
                action.sa_sigaction = note_realtime as *const () as usize;
                assert_eq!(
                    unsafe { libc::sigaction(40, &action, std::ptr::null_mut()) },
                    0
                );
                let ret = unsafe {
                    let pid = libc::syscall(libc::SYS_getpid);
                    let tid = libc::syscall(libc::SYS_gettid);
                    libc::syscall(libc::SYS_tgkill, pid, tid, 40)
                };
                assert_eq!(ret, 0);
                if RT_HANDLED.load(std::sync::atomic::Ordering::SeqCst) == 1 << 39 {
                    0
                } else {
                    1
                }
            },
            Options::PTRACE_O_EXITKILL,
        )?;
        let stopped = match tracee.resume(None)?.wait()? {
            Wait::Stopped(stopped, Event::RawSignal(40)) => stopped,
            other => panic!("expected a raw 40 delivery stop, got {other:?}"),
        };
        let running = stopped.detach_raw(40)?;
        // The fixture child's pre-seize group stop can still be
        // reported to its natural parent after detach; continue it
        // so its handler/exit path can finish.
        let _ = signal::kill(nix::unistd::Pid::from_raw(pid.as_raw()), Signal::SIGCONT);
        assert_eq!(running.wait()?, Wait::Exited(pid, ExitStatus::Exited(0)));
        Ok(())
    }

    #[test]
    fn any_signal_names_only_1_to_64() {
        assert_eq!(AnySignal::new(0), None);
        assert_eq!(AnySignal::new(65), None);
        assert_eq!(AnySignal::new(-1), None);
        assert_eq!(AnySignal::new(31).unwrap().as_nix(), Some(Signal::SIGSYS));
        assert_eq!(AnySignal::new(32).unwrap().as_nix(), None);
        assert_eq!(AnySignal::new(64).unwrap().raw(), 64);
        assert_eq!(AnySignal::from(Signal::SIGUSR1), Signal::SIGUSR1);
        assert_eq!(Event::Seccomp.signal(), None);
        assert_eq!(
            Event::from_signal(Signal::SIGUSR1.into()),
            Event::Signal(Signal::SIGUSR1)
        );
    }

    /// The plain wait helpers decode a realtime stop as `Event::RawSignal`
    /// too, with and without the `notifier` feature. Before, they reported
    /// it as a SIGSTOP (<https://github.com/rrnewton/reverie/issues/207>).
    /// `wait_all` and `try_wait_all` decode as `wait_group` does
    /// (`Wait::from_wait_helper`); the peeks return only the PID. Waiting
    /// by process group keeps this test to its own tracee.
    #[cfg(not(sanitized))]
    #[test]
    fn wait_group_decodes_a_realtime_stop() -> Result<(), Box<dyn std::error::Error + 'static>> {
        let (pid, tracee) = trace(
            || {
                let mut action: libc::sigaction = unsafe { MaybeUninit::zeroed().assume_init() };
                action.sa_sigaction = libc::SIG_IGN;
                assert_eq!(
                    unsafe { libc::sigaction(40, &action, std::ptr::null_mut()) },
                    0
                );
                let ret = unsafe {
                    let pid = libc::syscall(libc::SYS_getpid);
                    let tid = libc::syscall(libc::SYS_gettid);
                    libc::syscall(libc::SYS_tgkill, pid, tid, 40)
                };
                if ret == 0 { 0 } else { 1 }
            },
            Options::PTRACE_O_EXITKILL,
        )?;
        let _running = tracee.resume(None)?;
        let stopped = match wait_group(pid)? {
            Some(Wait::Stopped(stopped, Event::RawSignal(40))) => stopped,
            other => panic!("expected a raw 40 delivery stop, got {other:?}"),
        };
        let _running = stopped.resume_raw(40)?;
        assert_eq!(
            wait_group(pid)?,
            Some(Wait::Exited(pid, ExitStatus::Exited(0)))
        );
        Ok(())
    }

    #[cfg(all(feature = "notifier", not(sanitized)))]
    static FIRST_SIGNAL_DELIVERIES: std::sync::atomic::AtomicUsize =
        std::sync::atomic::AtomicUsize::new(0);

    #[cfg(all(feature = "notifier", not(sanitized)))]
    extern "C" fn count_first_signal(_signal: libc::c_int) {
        FIRST_SIGNAL_DELIVERIES.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
    }

    #[cfg(all(feature = "notifier", not(sanitized)))]
    extern "C" fn ignore_target_signal(_signal: libc::c_int) {}

    /// `wait_for_signal` forwards a signal it passes over, named or realtime,
    /// rather than suppress it (from the Codex review of
    /// <https://github.com/rrnewton/reverie/pull/995>). The tracee sends
    /// itself a caught `first` signal, then SIGUSR1; the wait selects
    /// SIGUSR1, and the tracee exits 0 only if `first`'s handler ran once.
    /// Before, a realtime `first` was resumed with no signal and dropped
    /// (exit 42); SIGUSR2 is the named control.
    #[cfg(all(feature = "notifier", not(sanitized)))]
    #[test]
    fn wait_for_signal_forwards_an_intervening_signal_named_or_realtime()
    -> Result<(), Box<dyn std::error::Error + 'static>> {
        for first in [libc::SIGUSR2, 40] {
            let (pid, tracee) = trace(
                move || {
                    for (signal, handler) in [
                        (first, count_first_signal as *const () as usize),
                        (libc::SIGUSR1, ignore_target_signal as *const () as usize),
                    ] {
                        let mut action: libc::sigaction =
                            unsafe { MaybeUninit::zeroed().assume_init() };
                        action.sa_sigaction = handler;
                        assert_eq!(
                            unsafe { libc::sigaction(signal, &action, std::ptr::null_mut()) },
                            0
                        );
                    }
                    for signal in [first, libc::SIGUSR1] {
                        let ret = unsafe {
                            let pid = libc::syscall(libc::SYS_getpid);
                            let tid = libc::syscall(libc::SYS_gettid);
                            libc::syscall(libc::SYS_tgkill, pid, tid, signal)
                        };
                        assert_eq!(ret, 0);
                    }
                    let calls = FIRST_SIGNAL_DELIVERIES.load(std::sync::atomic::Ordering::SeqCst);
                    if calls == 1 { 0 } else { 42 }
                },
                Options::PTRACE_O_EXITKILL,
            )?;
            let runtime = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()?;
            let status = runtime.block_on(async {
                let selected = tracee
                    .resume(None)?
                    .wait_for_signal(Signal::SIGUSR1)
                    .await?;
                let stopped = match selected {
                    Wait::Stopped(stopped, Event::Signal(Signal::SIGUSR1)) => stopped,
                    other => panic!("expected the SIGUSR1 stop, got {other:?}"),
                };
                stopped.resume(Some(Signal::SIGUSR1))?.next_state().await
            })?;
            assert_eq!(
                status,
                Wait::Exited(pid, ExitStatus::Exited(0)),
                "first signal {first}"
            );
        }
        Ok(())
    }

    /// A tracee that a realtime signal kills decodes as
    /// `ExitStatus::SignaledRaw` with its number; it failed with EINVAL
    /// (<https://github.com/rrnewton/reverie/issues/997>).
    #[cfg(not(sanitized))]
    #[test]
    fn a_tracee_killed_by_a_realtime_signal_exits_signaled_raw()
    -> Result<(), Box<dyn std::error::Error + 'static>> {
        let (pid, tracee) = trace(
            || {
                unsafe { libc::raise(40) };
                0
            },
            Options::PTRACE_O_EXITKILL,
        )?;
        let stopped = match tracee.resume(None)?.wait()? {
            Wait::Stopped(stopped, Event::RawSignal(40)) => stopped,
            other => panic!("expected a raw 40 delivery stop, got {other:?}"),
        };
        assert_eq!(
            stopped.resume_raw(40)?.wait()?,
            Wait::Exited(pid, ExitStatus::SignaledRaw(40, false))
        );
        Ok(())
    }
}