hermit-detcore 0.5.2

Detcore: the deterministic scheduler and syscall determinization core of the Hermit execution engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
/*
 * 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.
 */

//! Keeping each thread's [`SignalShadow`] in step with the guest.
//!
//! On unless `Config::signal_state_copy` is off (`--no-signal-state-copy`;
//! docs/SIGNAL_STATE_CHECK.md).
//!
//! Every function here runs after the guest operation it records has
//! committed, uses only values Detcore already holds for that operation, and
//! issues no injection and no scheduler request: recording changes nothing the
//! guest or the schedule can observe, and adds no log line at INFO or above
//! while the copy matches (one TRACE line per check, for counting). The
//! scheduler learns the copy's dispositions separately, from
//! [`publish_dispositions`], a message that carries no logical time.
//!
//! Where the backend's kernel signal state is the guest's own
//! ([`kernel_state_is_the_guests`]), the
//! copy is checked against the kernel after each recorded call: the old action
//! or old mask the kernel wrote back, and `SigBlk`, `SigIgn` and `SigCgt`. A
//! mismatch is logged once, by name, and the thread's copy is dropped: it is
//! never repaired from the kernel, which would hide the defect the check is
//! for.

use detcore_model::bundled_signal_facts;
use reverie::Errno;
use reverie::Guest;
use reverie::Pid;
use reverie::syscalls::Addr;
use reverie::syscalls::AddrMut;
use reverie::syscalls::MemoryAccess;
use serde::Deserialize;
use serde::Serialize;
use tracing::debug;
use tracing::trace;
use tracing::warn;

use super::threads::KernelSigaction;
use super::threads::KernelSigset;
use super::threads::host_signal_state_reads_refused;
use super::threads::read_thread_signal_state;
use crate::Detcore;
use crate::record_or_replay::RecordOrReplay;
use crate::signal_state::Action;
use crate::signal_state::Dispositions;
use crate::signal_state::SignalShadow;
use crate::signal_state::ThreadSignals;
use crate::signal_state::sigbit;

/// The prefix of the one WARN line a divergence produces, for log searches.
pub(crate) const DIVERGED: &str = "SIGNAL_STATE_COPY_DIVERGED";

/// The signal whose kernel state differs from the guest's by design, left out
/// of every comparison: Reverie's preemption signal is Hermit's, and Detcore
/// keeps the guest from installing or blocking it (`handle_rt_sigaction`,
/// `rt_sigprocmask_inner`).
fn reserved() -> KernelSigset {
    sigbit(reverie::PERF_EVENT_SIGNAL as i32)
}

/// The signals Linux force-delivers (`force_sig_info_to_task`): forcing one
/// that is blocked or ignored, or caught but blocked, unblocks it and resets
/// its action to the default, for the whole group sharing the actions,
/// before any ptrace stop. The copy sees none of these:
/// - SIGTRAP from the ptrace backend's single-step (Reverie characterizes it
///   in `sigtrap_profile_follows_each_handler_shape`);
/// - SIGSEGV from the backend's own trapped `rdtsc` or `cpuid`, which it
///   emulates and suppresses;
/// - a guest's own fault (SIGSEGV, SIGBUS, SIGILL, SIGFPE), and SIGSYS from a
///   guest's seccomp `RET_TRAP` filter.
///
/// So a difference confined to these signals makes the copy unknown (it is
/// given up quietly) rather than reported, and never passes as a match.
fn forced() -> KernelSigset {
    [
        libc::SIGTRAP,
        libc::SIGSEGV,
        libc::SIGBUS,
        libc::SIGILL,
        libc::SIGFPE,
        libc::SIGSYS,
    ]
    .into_iter()
    .fold(0, |set, signal| set | sigbit(signal))
}

/// What comparing one of the copy's sets with the kernel's found.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Compared {
    Same,
    /// Only signals Linux force-delivers differ ([`forced`]).
    ForcedOnly,
    Different,
}

/// A forced delivery only ever clears a signal's bit (it unblocks the
/// signal and resets its action to the default), so a difference is
/// [`Compared::ForcedOnly`] only when every differing bit is a signal Linux
/// force-delivers and the kernel holds none the copy lacks. Anything else is
/// a real difference.
fn compare(kernel: KernelSigset, copy: KernelSigset) -> Compared {
    match (kernel ^ copy) & !reserved() {
        0 => Compared::Same,
        difference if difference & !forced() == 0 && kernel & !copy & !reserved() == 0 => {
            Compared::ForcedOnly
        }
        _ => Compared::Different,
    }
}

/// Gives the copy up quietly: the kernel's state of a signal Linux
/// force-delivers differs from it in a way only a forced delivery explains
/// ([`forced`]).
fn forced_changed<G, T>(guest: &mut G, at: &str)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    debug!(
        "[dtid {}] signal-state copy dropped at {at}: a force-delivered signal's kernel state \
         differs (SIGTRAP from a ptrace single-step, SIGSEGV from a trapped rdtsc or cpuid, \
         or a fault)",
        guest.thread_state().dettid
    );
    drop_copy(guest);
}

impl From<KernelSigaction> for Action {
    fn from(action: KernelSigaction) -> Self {
        Action {
            handler: action.handler,
            flags: action.flags,
            restorer: action.restorer,
            mask: action.mask,
        }
    }
}

/// Whether this backend's kernel signal state for a guest thread is the
/// guest's own: the guest thread is a host task, and no runtime in the
/// guest's process installs handlers or masks of its own
/// (`bundled_signal_facts::kernel_signal_state_is_guests`: ptrace, and
/// e9patch, which runs under ptrace). Threads must also be
/// serialized: otherwise two threads sharing actions could change them in the
/// kernel in one order and in the copy in another. Elsewhere the copy is
/// neither seeded from the kernel nor checked against it.
fn kernel_state_is_the_guests<G, T>(guest: &G) -> bool
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    let config = guest.config();
    config.signal_state_copy
        && config.sequentialize_threads
        && bundled_signal_facts::kernel_signal_state_is_guests(&config.backend)
        && !host_signal_state_reads_refused()
}

/// Applies `change` to this thread's copy: the actions its group shares and
/// its own masks. Returns `None`, and drops the thread's copy without a new
/// report, when the shared actions are unknown because another thread
/// sharing them lost its copy (that loss was reported).
fn with_copy<G, T, R>(
    guest: &mut G,
    change: impl FnOnce(&mut Dispositions, &mut ThreadSignals) -> R,
) -> Option<R>
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    let shadow = guest.thread_state_mut().signal_shadow.as_mut()?;
    let actions = std::sync::Arc::clone(&shadow.dispositions);
    let mut actions = actions.lock().unwrap();
    match actions.as_mut() {
        Some(dispositions) => Some(change(dispositions, &mut shadow.thread)),
        None => {
            drop(actions);
            debug!(
                "[dtid {}] signal-state copy dropped: a thread sharing its actions lost its copy",
                guest.thread_state().dettid
            );
            drop_copy(guest);
            None
        }
    }
}

/// Gives this thread's copy up quietly, for a call whose effect cannot be
/// known (`reason` says why).
pub(crate) fn give_up<G, T>(guest: &mut G, reason: &str)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    if guest.thread_state().signal_shadow.is_some() {
        debug!(
            "[dtid {}] signal-state copy dropped: {reason}",
            guest.thread_state().dettid
        );
        drop_copy(guest);
    }
}

/// Drops this thread's copy: threads it creates start without one, and the
/// actions it shares become unknown, because this thread's later changes to
/// them would go unrecorded. A copy given up quietly is seeded again at the
/// thread's next exec, whose ignored set and mask describe the whole state
/// (nothing of the old image is repaired); [`diverged`] marks a copy that
/// diverged as never to be seeded again.
fn drop_copy<G, T>(guest: &mut G)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    drop_thread_copy(guest.thread_state_mut());
}

/// [`drop_copy`] given only the thread's state.
fn drop_thread_copy<T>(thread: &mut crate::tool_local::ThreadState<T>) {
    if let Some(shadow) = thread.signal_shadow.as_ref() {
        shadow.forget_dispositions();
    }
    thread.signal_shadow = None;
}

/// At a syscall's entry, the thread has run guest code since its last event:
/// a temporary-mask restore no handler took has happened, a signal may have
/// reached a handler unreported, and an open handler frame may have returned
/// unseen. Accounts for all three before the call can depend on the mask (a
/// clone copies it; an exec keeps it). No guest memory is read here: a wait's
/// temporary mask is recorded by its handler, in the call's own turn
/// ([`note_wait_mask`]).
pub(crate) fn at_syscall_entry<G, T>(guest: &mut G)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    take_unreported(guest);
    let Some(shadow) = guest.thread_state_mut().signal_shadow.as_mut() else {
        return;
    };
    shadow.thread.settle();
    shadow.thread.wait_mask = None;
    reconcile_returns(guest, "syscall entry");
}

/// Signals the backend passed on to a thread without a report (the ptrace
/// backend does so for many signals it held during a Tool injection), as
/// (host pid, host tid, signal). They are recorded where the copy lives, in
/// this process (`Tool::filter_unreported_signal`), and consumed at that
/// thread's next operation, whether or not it has a copy. Realtime signals
/// are shown and recorded like any other
/// (<https://github.com/rrnewton/reverie/issues/207>).
#[cfg(not(test))]
static UNREPORTED: std::sync::Mutex<Vec<(i32, i32, i32)>> = std::sync::Mutex::new(Vec::new());

/// Whether [`UNREPORTED`] may hold an entry, so that threads on a backend
/// that never notes one (or with none noted) never take its lock.
#[cfg(not(test))]
static ANY_UNREPORTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

// Tests keep their notes per test thread, so concurrent tests cannot see each
// other's.
#[cfg(test)]
thread_local! {
    static UNREPORTED_NOTES: std::cell::RefCell<Vec<(i32, i32, i32)>> =
        const { std::cell::RefCell::new(Vec::new()) };
}

/// Runs `f` on the notes.
fn with_notes<R>(f: impl FnOnce(&mut Vec<(i32, i32, i32)>) -> R) -> R {
    #[cfg(not(test))]
    {
        let mut notes = UNREPORTED.lock().unwrap();
        let result = f(&mut notes);
        ANY_UNREPORTED.store(!notes.is_empty(), std::sync::atomic::Ordering::SeqCst);
        result
    }
    #[cfg(test)]
    {
        UNREPORTED_NOTES.with(|notes| f(&mut notes.borrow_mut()))
    }
}

/// Whether any note may exist, without taking a lock.
fn any_notes() -> bool {
    #[cfg(not(test))]
    {
        ANY_UNREPORTED.load(std::sync::atomic::Ordering::SeqCst)
    }
    #[cfg(test)]
    {
        UNREPORTED_NOTES.with(|notes| !notes.borrow().is_empty())
    }
}

/// Records that `signal` reached host thread `tid` of process `pid` without a
/// report.
pub(crate) fn note_unreported(pid: i32, tid: i32, signal: i32) {
    trace!("[tid {tid}] signal-state copy: signal {signal} was passed on unreported");
    with_notes(|notes| notes.push((pid, tid, signal)));
}

/// Whether another live thread has an unreported signal noted: if it shares
/// this thread's actions, its handler may have changed them (`SA_RESETHAND`)
/// unseen, until it gives its own copy up. Entries of threads that no longer
/// exist are removed here.
fn unreported_elsewhere(tid: i32) -> bool {
    if !any_notes() {
        return false;
    }
    with_notes(|notes| {
        notes.retain(|(_, t, _)| {
            !super::threads::thread_is_gone(Pid::from_raw(*t), Pid::from_raw(*t))
        });
        // Any other thread: a CLONE_SIGHAND group need not be one process.
        notes.iter().any(|(_, t, _)| *t != tid)
    })
}

/// Whether any unreported signal is noted and not yet consumed: a clone now
/// could copy actions a handler has already changed unseen.
pub(crate) fn unreported_pending() -> bool {
    any_notes()
        && with_notes(|notes| {
            notes.retain(|(_, t, _)| {
                !super::threads::thread_is_gone(Pid::from_raw(*t), Pid::from_raw(*t))
            });
            !notes.is_empty()
        })
}

/// A signal that reached this thread unreported may have entered a handler
/// the copy never saw, with the action as it stood at delivery, which the
/// copy cannot know any more: the copy is given up. This thread's notes are
/// consumed whether or not it has a copy.
fn take_unreported<G, T>(guest: &mut G)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    if !any_notes() {
        return;
    }
    let (pid, tid) = (guest.pid().as_raw(), guest.tid().as_raw());
    let signals: Vec<i32> = with_notes(|notes| {
        let (mine, others): (Vec<_>, Vec<_>) = notes
            .drain(..)
            .partition(|(p, t, _)| *p == pid && *t == tid);
        *notes = others;
        mine.into_iter().map(|(_, _, signal)| signal).collect()
    });
    if let Some(signal) = signals.first() {
        give_up(guest, &format!("signal {signal} was passed on unreported"));
    }
}

/// Before a transition that depends on the mask: where the backend reports
/// `rt_sigreturn`, checks that the kernel holds the mask the copy predicts
/// (with a handler frame open, or after a report); elsewhere, accounts for
/// handler returns the kernel ran without a report, from the kernel's
/// current mask. Does nothing otherwise, or where the kernel's state is not
/// the guest's.
fn reconcile_returns<G, T>(guest: &mut G, before: &str)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    let open_frames = guest
        .thread_state()
        .signal_shadow
        .as_ref()
        .is_some_and(|shadow| !shadow.thread.activations.is_empty());
    let verify = guest
        .thread_state()
        .signal_shadow
        .as_ref()
        .is_some_and(|shadow| shadow.thread.verify_at_entry);
    if !(open_frames || verify) || !kernel_state_is_the_guests(guest) {
        return;
    }
    let Some(kernel) = read_or_give_up(guest, before) else {
        return;
    };
    // Where the backend reports rt_sigreturn, frames close only on its
    // reports, so nothing is inferred. The kernel must still hold the mask
    // the copy predicts, for an open handler or after a report; otherwise a
    // report was missed (the capability names the calls it does not
    // report), the kernel did not follow one, or the handler's frame was
    // never written, and the copy fails closed.
    if observes_sigreturns(guest.config()) {
        let Some(shadow) = guest.thread_state_mut().signal_shadow.as_mut() else {
            return;
        };
        shadow.thread.verify_at_entry = false;
        match compare(kernel.blocked, shadow.thread.blocked) {
            Compared::Same => shadow.thread.observe_handler_mask(),
            Compared::ForcedOnly => forced_changed(guest, before),
            Compared::Different => give_up(
                guest,
                "the kernel's mask is not the one the copy predicts after a reported return or \
                 for an open handler frame",
            ),
        }
        return;
    }
    let Some(shadow) = guest.thread_state_mut().signal_shadow.as_mut() else {
        return;
    };
    let copy = shadow.thread.blocked;
    let open = shadow.thread.activations.len();
    let innermost_observed = shadow.thread.innermost_observed();
    if shadow
        .thread
        .reconcile_returns(kernel.blocked, reserved() | forced())
    {
        let closed = open - shadow.thread.activations.len();
        if closed > 1 {
            // An outer frame's mask: several returns, or an inner handler
            // that rewrote its uc_sigmask. Mask equality cannot tell which.
            debug!(
                "[dtid {}] signal-state copy dropped at {before}: the kernel's mask matches an \
                 outer handler frame ({closed} frames), which is ambiguous",
                guest.thread_state().dettid
            );
            drop_copy(guest);
        } else {
            if closed == 1 {
                debug!(
                    "[dtid {}] signal-state copy: a handler frame taken as returned at {before}",
                    guest.thread_state().dettid
                );
                if !innermost_observed {
                    // A return, or a handler entry the copy predicted wrongly
                    // (or a frame the kernel failed to write): mask equality
                    // cannot tell which.
                    #[cfg(test)]
                    UNVERIFIED_ENTRIES.with(|count| count.set(count.get() + 1));
                    return give_up(
                        guest,
                        "a handler frame was taken as returned before any check saw its \
                         handler's mask",
                    );
                }
            } else if let Some(shadow) = guest.thread_state_mut().signal_shadow.as_mut() {
                // The kernel holds the mask the copy predicts for the open
                // handler.
                shadow.thread.observe_handler_mask();
            }
            let blocked = guest
                .thread_state()
                .signal_shadow
                .as_ref()
                .map(|shadow| shadow.thread.blocked);
            // The frames were matched with the forced signals left out; the
            // whole mask must still be the copy's, or differ only as a forced
            // delivery leaves it.
            match blocked.map(|blocked| compare(kernel.blocked, blocked)) {
                Some(Compared::ForcedOnly) => forced_changed(guest, before),
                Some(Compared::Different) => give_up(
                    guest,
                    "the kernel's mask holds a force-delivered signal the copy's mask does not",
                ),
                Some(Compared::Same) | None => {}
            }
        }
    } else if open > 0 {
        // A handler may install any mask by rewriting its frame's uc_sigmask
        // before an unseen return.
        give_up(
            guest,
            &format!(
                "at {before} the kernel's mask matches no open handler frame, which a \
                 handler's rewritten uc_sigmask could explain"
            ),
        );
    } else {
        diverged(
            guest,
            before,
            &format!(
                "SigBlk kernel {:#018x} is neither the copy's {:#018x} nor an open handler frame's",
                kernel.blocked & !reserved(),
                copy & !reserved()
            ),
        );
    }
}

/// Seeds the first image's copy, or applies `execve`'s reset to a later one.
/// Called from the new image's first callback. The first image's ignored set
/// and mask are what it inherited from the launcher, read from the kernel
/// before it runs a guest instruction; where that read is unavailable, the
/// copy stays unknown. Seeding there needs the backend to report the first
/// image's inherited state, which the A5 design puts in the `Guest` contract
/// (its step 3).
pub(crate) fn at_exec<G, T>(guest: &mut G)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    // A nonleader exec takes the leader's tid, whose entry the scheduler
    // drops with the old leader, and the copy may not survive the exec: what
    // the scheduler holds is unknown, so the mask, or its withdrawal, is
    // published again.
    guest.thread_state_mut().published_mask = None;
    if let Some(shadow) = guest.thread_state_mut().signal_shadow.as_mut() {
        if !shadow.exec() {
            drop_copy(guest);
            return;
        }
        trace!(
            "[dtid {}] signal-state copy: reset for execve",
            guest.thread_state().dettid
        );
        check_against_kernel(guest, "execve");
        return;
    }
    // A thread with no copy is seeded at its exec, where the ignored set and
    // the mask describe the whole state. One whose copy diverged, or whose
    // creator's did, is never seeded again.
    if guest.thread_state().signal_shadow_lost || !kernel_state_is_the_guests(guest) {
        return;
    }
    match read_thread_signal_state(guest.pid(), guest.tid()) {
        Ok(state) => {
            guest.thread_state_mut().signal_shadow =
                Some(SignalShadow::seeded(state.ignored, state.blocked));
            trace!(
                "[dtid {}] signal-state copy: seeded from the first image",
                guest.thread_state().dettid
            );
        }
        Err(errno) => debug!(
            "[dtid {}] signal-state copy not seeded: the kernel state is unreadable ({errno})",
            guest.thread_state().dettid
        ),
    }
}

/// Records a committed `rt_sigaction`. `new` is the action the kernel
/// installed (Detcore's sanitized copy of an action the kernel validated),
/// `None` for a query. `result` is the call's result: an `EFAULT` after the
/// new action was read can only come from writing `old_action`, after the new
/// action is installed.
pub(super) fn record_rt_sigaction<G, T>(
    guest: &mut G,
    signum: i32,
    new: Option<KernelSigaction>,
    old_action: Option<AddrMut<'_, libc::sigaction>>,
    result: &Result<i64, Errno>,
) where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    let committed = result.is_ok() || (new.is_some() && *result == Err(Errno::EFAULT));
    if !committed {
        return;
    }
    let Some(predicted) = with_copy(guest, |dispositions, _| {
        dispositions.sigaction(signum, new.map(Action::from))
    }) else {
        return;
    };
    let old = match predicted {
        Ok(old) => old,
        Err(errno) => {
            return diverged(
                guest,
                "rt_sigaction",
                &format!(
                    "the kernel accepted signal {signum}, which the copy refuses with {errno}"
                ),
            );
        }
    };
    let written = match (result.is_ok(), old_action) {
        (true, Some(address)) => match guest
            .memory()
            .read_value::<_, KernelSigaction>(address.cast::<KernelSigaction>())
        {
            Ok(written) => Some(written),
            Err(_) => {
                return give_up(guest, "the old action the kernel wrote cannot be read back");
            }
        },
        _ => None,
    };
    // A sibling's unreported handler may have reset this action unseen
    // (SA_RESETHAND): the old action is not compared while one is noted.
    if let Some(written) = written
        && Action::from(written) != old
        && !unreported_elsewhere(guest.tid().as_raw())
    {
        // A forced delivery changes only the handler, to the default. Whether
        // the signal was blocked when it was forced is not knowable here (see
        // `check_against_kernel`).
        if forced() & sigbit(signum) != 0
            && Action::from(written)
                == (Action {
                    handler: libc::SIG_DFL as u64,
                    ..old
                })
            && old.handler != libc::SIG_DFL as u64
        {
            return forced_changed(guest, "rt_sigaction");
        }
        return diverged(
            guest,
            "rt_sigaction",
            &format!(
                "old action of signal {signum}: the kernel wrote {:?}, the copy holds {old:?}",
                Action::from(written)
            ),
        );
    }
    check_against_kernel(guest, "rt_sigaction");
}

/// What Detcore knows of an `rt_sigprocmask` call's set.
#[derive(Clone, Copy, Debug)]
pub(super) enum SetInput {
    /// The call passed no set: a query.
    None,
    /// Detcore never injected the call: its own check of the set failed
    /// first, so the kernel did nothing.
    NotRun,
    /// The kernel read this set and accepted it (the `SIG_BLOCK` and
    /// `SIG_SETMASK` paths validate it before injecting). It is the set
    /// without Hermit's reserved signal.
    Validated(KernelSigset),
    /// The call ran with a set the kernel validated only by running; Detcore
    /// reads it after a successful call, from memory the kernel just read
    /// (`None` when the old mask overwrote it, or the read failed).
    Unvalidated(Option<KernelSigset>),
}

/// Records a committed `rt_sigprocmask`. An `EFAULT` is a committed change
/// only when it can come from writing `oldset` alone.
pub(super) fn record_rt_sigprocmask<G, T>(
    guest: &mut G,
    how: i32,
    set: SetInput,
    oldset: Option<AddrMut<'_, libc::sigset_t>>,
    result: &Result<i64, Errno>,
) where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    let valid_how = matches!(how, libc::SIG_BLOCK | libc::SIG_UNBLOCK | libc::SIG_SETMASK);
    let set = match (set, result) {
        (SetInput::NotRun, _) => return,
        (SetInput::None, Ok(_)) => None,
        (SetInput::Validated(set), Ok(_) | Err(Errno::EFAULT)) => Some(set),
        (SetInput::Unvalidated(Some(set)), Ok(_)) => Some(set),
        (SetInput::Unvalidated(None), Ok(_)) => {
            debug!(
                "[dtid {}] signal-state copy dropped: rt_sigprocmask's set is not known after \
                 the call (it aliases the old mask, or could not be read)",
                guest.thread_state().dettid
            );
            drop_copy(guest);
            return;
        }
        // The kernel reads the set before checking `how`, and before writing
        // the old mask: without an old mask, or with an invalid `how`, the
        // fault was the set's and nothing changed.
        (SetInput::Unvalidated(_), Err(Errno::EFAULT)) if oldset.is_none() || !valid_how => {
            return;
        }
        (SetInput::Unvalidated(_), Err(Errno::EFAULT)) => {
            // The set or the old mask: Linux leaves no way to tell which.
            debug!(
                "[dtid {}] signal-state copy dropped: rt_sigprocmask's EFAULT may come from \
                 its set or its old mask",
                guest.thread_state().dettid
            );
            drop_copy(guest);
            return;
        }
        _ => return,
    };
    let Some(predicted) = with_copy(guest, |_, thread| thread.sigprocmask(how, set)) else {
        return;
    };
    let old = match predicted {
        Ok(old) => old,
        Err(errno) => {
            return diverged(
                guest,
                "rt_sigprocmask",
                &format!("the kernel accepted how={how}, which the copy refuses with {errno}"),
            );
        }
    };
    let written = match (result.is_ok(), oldset) {
        (true, Some(address)) => match guest
            .memory()
            .read_value::<_, KernelSigset>(address.cast::<KernelSigset>())
        {
            Ok(written) => Some(written),
            Err(_) => return give_up(guest, "the old mask the kernel wrote cannot be read back"),
        },
        _ => None,
    };
    if let Some(written) = written {
        match compare(written, old) {
            Compared::Same => {}
            Compared::ForcedOnly => return forced_changed(guest, "rt_sigprocmask"),
            Compared::Different => {
                return diverged(
                    guest,
                    "rt_sigprocmask",
                    &format!(
                        "old mask: the kernel wrote {:#x}, the copy holds {:#x}",
                        written & !reserved(),
                        old & !reserved()
                    ),
                );
            }
        }
    }
    check_against_kernel(guest, "rt_sigprocmask");
}

/// Records that the Tool approved `signal` for delivery to this thread, so the
/// backend delivers it now: a caught signal enters its handler with
/// `sa_mask` added, and `SA_RESETHAND` puts the default back. The handler
/// mask is checked at the thread's next recorded call, when the frame has been
/// written. A delivery whose frame cannot be written becomes a SIGSEGV and
/// leaves the old mask, which the check can take for the frame's return: that
/// case is not told apart.
///
/// Before the copy changes, a caught signal's delivery is checked against the
/// kernel through the backend (`check_delivery`, A5 step 3.2). Checking adds
/// only reads and a refusal: the copy changes exactly as it would unchecked,
/// at the same point, unless a check fails, which drops the copy, or the
/// backend reports that the kernel will not deliver the signal at this
/// resume, when nothing is recorded until a later delivery. This must
/// be the last thing the signal callback does before it returns the signal:
/// a later injection would void the backend's approval.
pub(crate) async fn check_and_record_delivery<G, T>(guest: &mut G, signal: i32)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    let had_copy = guest.thread_state().signal_shadow.is_some();
    // At a delivery stop the kernel has not installed the handler mask yet.
    take_unreported(guest);
    take_wait_outcome(guest);
    reconcile_returns(guest, "signal delivery");
    // A signal the kernel does not deliver at this resume is delivered, and
    // recorded, at a later stop, if at all.
    if check_delivery(guest, signal, had_copy).await {
        commit_delivery(guest, signal);
    }
}

/// [`check_and_record_delivery`] without the check, for a delivery the
/// backend makes with no check (and for tests).
#[cfg(test)]
fn record_delivery<G, T>(guest: &mut G, signal: i32)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    take_unreported(guest);
    take_wait_outcome(guest);
    reconcile_returns(guest, "signal delivery");
    commit_delivery(guest, signal);
}

/// The copy's half of [`check_and_record_delivery`], after reconciliation:
/// `signal` is delivered as the copy holds it.
fn commit_delivery<G, T>(guest: &mut G, signal: i32)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    let Some(delivered) = with_copy(guest, |dispositions, thread| {
        crate::signal_state::deliver(dispositions, thread, signal)
    }) else {
        return;
    };
    match delivered {
        Ok(Some(action)) => {
            trace!(
                "[dtid {}] signal-state copy: recorded the delivery of signal {signal}",
                guest.thread_state().dettid
            );
            // A handler whose mask equals an open frame's saved mask cannot
            // be told from that frame's return: the next check verifies
            // nothing about this entry.
            if let Some(shadow) = guest.thread_state().signal_shadow.as_ref()
                && action.handler > 1
                && shadow.thread.activations.last() == Some(&shadow.thread.blocked)
            {
                debug!(
                    "[dtid {}] signal-state copy: the handler mask of signal {signal} equals the \
                     mask its frame saves, so its entry cannot be told from its return",
                    guest.thread_state().dettid
                );
            }
        }
        Ok(None) => {
            debug!(
                "[dtid {}] signal-state copy dropped: more than {} handler frames open",
                guest.thread_state().dettid,
                crate::signal_state::MAX_OPEN_FRAMES
            );
            drop_copy(guest);
        }
        Err(errno) => diverged(
            guest,
            "signal delivery",
            &format!("the backend delivers signal {signal}, which the copy refuses with {errno}"),
        ),
    }
}

/// One thread's counts of the deliveries [`check_delivery`] saw (A5 step 3.2):
/// approved (and of those, approved at a held signal's report), contradicted,
/// checked with the interruption taken from the registers
/// (`delivery_interruption`), and not checked, by reason; and the signals the
/// backend passed on without reporting them, which no check saw, by the
/// backend's reason ([`reverie::UnreportedSignalReason`]). Logged at TRACE
/// when the thread exits, below INFO so the logs that runs compare are
/// unchanged.
#[derive(Clone, Debug, Default)]
pub(crate) struct DeliveryCounters {
    /// The thread the counts were taken under. A non-leader exec gives the
    /// thread its leader's identity before it exits, so the counts keep the
    /// identity they were taken under.
    owner: Option<crate::types::DetTid>,
    approved: u64,
    /// Approved deliveries of a signal the backend held during an injection
    /// and reported after the callback that held it
    /// ([`reverie::SignalReportPath::Held`]).
    held: u64,
    /// Approved deliveries whose interruption was a syscall result Detcore
    /// finished, so the backend compared `rax` with it.
    result_checked: u64,
    mismatched: u64,
    interruption_from_registers: u64,
    skipped: std::collections::BTreeMap<&'static str, u64>,
    /// Signals the backend passed on without a report, by the backend's
    /// reason: those that could reach a guest handler, as the copy notes them
    /// (`note_unreported`). Each pass is counted: at that resume the kernel
    /// delivers the signal, puts it back in the queue when the thread's mask
    /// blocks it (a later stop can take the same instance again), queues a
    /// new instance with a kernel siginfo (a syscall stop), or discards it
    /// (an ignored signal, or a ptrace event stop or group stop). Signals the
    /// filter dropped are not counted.
    unreported: std::collections::BTreeMap<&'static str, u64>,
}

impl DeliveryCounters {
    fn skip(&mut self, reason: &'static str) {
        *self.skipped.entry(reason).or_default() += 1;
    }

    /// Counts a signal the backend passed on unreported for `reason`, taken
    /// by thread `dettid`.
    pub(crate) fn count_unreported(
        &mut self,
        dettid: crate::types::DetTid,
        reason: reverie::UnreportedSignalReason,
    ) {
        self.owner.get_or_insert(dettid);
        *self.unreported.entry(reason.name()).or_default() += 1;
    }

    /// Logs the counts, if any delivery was seen, under the identity they
    /// were taken under (`dettid` if none was recorded).
    pub(crate) fn log(&self, dettid: crate::types::DetTid) {
        if self.approved + self.mismatched == 0
            && self.skipped.is_empty()
            && self.unreported.is_empty()
        {
            return;
        }
        let dettid = self.owner.unwrap_or(dettid);
        trace!(
            target: "detcore::signal_delivery",
            "[dtid {dettid}] signal deliveries: approved={} held={} result_checked={} mismatched={} interruption_from_registers={} skipped={:?} unreported={:?}",
            self.approved,
            self.held,
            self.result_checked,
            self.mismatched,
            self.interruption_from_registers,
            self.skipped,
            self.unreported
        );
    }
}

/// The name of a reason the backend could not check a delivery, for
/// [`DeliveryCounters`].
fn unavailable_reason(reason: reverie::SignalDeliveryUnavailable) -> &'static str {
    use reverie::SignalDeliveryUnavailable as U;
    match reason {
        U::NotInSignalCallback => "not in signal callback",
        U::NotTheReportedSignal { .. } => "not the reported signal",
        U::NoSignalRecord => "no signal record",
        U::NotADeliveryStop => "not a delivery stop",
        U::FrameModeStop => "frame-mode stop",
        U::TracerFiltered => "tracer filtered",
        U::AlreadyApproved => "already approved",
        U::AfterMismatch => "after mismatch",
        U::UncheckedSignal => "unchecked signal",
        U::BlockedAtResume => "blocked at resume",
        U::Gone => "gone",
        U::Unreadable(_) => "unreadable",
        U::UnsupportedArchitecture => "unsupported architecture",
    }
}

/// Whether Detcore sees syscall number `nr` through a Tool callback: a number
/// in Reverie's syscall table. Another number (beyond the table, or negative)
/// reaches the kernel with no callback.
fn sees_syscall(nr: i64) -> bool {
    usize::try_from(nr).is_ok_and(|nr| reverie::syscalls::Sysno::new(nr).is_some())
}

/// What the thread was doing at this delivery stop, for the backend's check of
/// the syscall registers, and whether it was taken from the registers
/// themselves rather than from Detcore's record.
///
/// Detcore's record (`ThreadState::delivery_interruption`) is set at each
/// guest event: the syscall entered, the result Detcore finished it with, a
/// handler frame built at this exit, or no syscall (a preemption or a trapped
/// instruction). Between events the guest runs unseen, so the record cannot
/// know whether the thread is still where the record left it or has run on in
/// user code since. The registers answer that one question, and nothing else:
/// - `orig_ax` is -1 once the thread entered the kernel other than by a
///   syscall, so a syscall record with `orig_ax` -1 means the thread returned
///   to user code since: no syscall.
/// - A frame's chained delivery at the same exit stops before any guest
///   instruction, at the handler's first instruction. Anywhere else, either
///   the guest ran since, and with `orig_ax` -1 that is no syscall, or the
///   frame was not built (a frame fault, whose SIGSEGV comes at the same
///   exit), and the registers' answer is used.
/// - A record naming the syscall `orig_ax` names is sent as it stands, so
///   `rax` is compared with the result Detcore finished the call with.
/// - Where `orig_ax` names a syscall Detcore cannot see (a number outside
///   Reverie's table, or a negative one), no callback updated the record, and
///   the registers' answer is used.
/// - A record that disagrees with a known syscall in `orig_ax` is sent as it
///   stands, so the backend reports the contradiction.
/// - With no record (a new thread or image), or where Detcore does not see
///   every syscall (`--passthru-opt`), the registers' answer is used, and the
///   check of the syscall registers verifies nothing.
async fn delivery_interruption<G, T>(guest: &mut G) -> (reverie::Interruption, bool)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    use reverie::Interruption;
    let record = guest.thread_state().delivery_interruption;
    // Only x86-64's registers are read here; elsewhere nothing is checked.
    #[cfg(not(target_arch = "x86_64"))]
    {
        let _ = record;
        (Interruption::AfterFrame, true)
    }
    #[cfg(target_arch = "x86_64")]
    {
        let regs = guest.regs().await;
        let orig = regs.orig_rax as i64;
        // Only -1 means no syscall: another negative number is a syscall the
        // kernel refused with ENOSYS.
        let from_registers = if orig == -1 {
            Interruption::NotInSyscall
        } else {
            Interruption::KernelRun { syscall: orig }
        };
        if guest.config().passthru_opt {
            return (from_registers, true);
        }
        match record {
            Some(Interruption::AfterFrame)
                if regs.rip == guest.thread_state().delivery_frame_handler =>
            {
                (Interruption::AfterFrame, false)
            }
            Some(
                record @ (Interruption::Return { syscall, .. }
                | Interruption::KernelRun { syscall }),
            ) if syscall == orig => (record, false),
            Some(Interruption::NotInSyscall) if orig == -1 => (Interruption::NotInSyscall, false),
            // The record does not describe this stop, and the registers
            // decide:
            // - there is no record (a new thread or image);
            // - the guest ran on since the record (`orig_ax` -1 after a
            //   syscall or a frame);
            // - still at the syscall's exit away from the handler, the frame
            //   was not built (a frame fault raises SIGSEGV at the same exit);
            // - the thread is in a syscall Detcore cannot see: a number
            //   outside Reverie's table, or a negative one the kernel refuses,
            //   reaches no Tool callback, so the record still names an earlier
            //   event.
            None | Some(Interruption::AfterFrame) => (from_registers, true),
            _ if orig == -1 || !sees_syscall(orig) => (from_registers, true),
            // A known syscall that the record does not name: Detcore missed an
            // event it subscribes to. Sent as it stands, so the backend reports
            // the contradiction.
            Some(record) => (record, false),
        }
    }
}

/// Checks a caught signal's delivery against the kernel through the backend
/// (`Guest::deliver_signal`), from the reconciled copy, before the copy
/// records it (A5 step 3.2). Reads only:
/// - the backend's approval binds the guest's resume to exactly this signal
///   and these masks;
/// - a contradiction, where the copy and the kernel are both certain, is a
///   Detcore defect: it is reported once, as a divergence, and the copy is
///   dropped, so the delivery goes on as the kernel makes it;
/// - a point the backend cannot check is counted by reason and changes
///   nothing.
///
/// Not checked, and counted: no copy (told apart from a copy this delivery's
/// reconciliation gave up, `had_copy`), the shared actions unknown, a signal
/// that is not caught (the kernel ignores it or takes its default action).
///
/// Returns false only when the backend says the kernel will not deliver the
/// signal at this resume, so the copy must not record a delivery:
/// [`reverie::SignalDeliveryUnavailable::BlockedAtResume`] (it requeues it)
/// and [`reverie::SignalDeliveryUnavailable::NotADeliveryStop`] (it queues
/// it anew or drops it).
async fn check_delivery<G, T>(guest: &mut G, signal: i32, had_copy: bool) -> bool
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    if !kernel_state_is_the_guests(guest) {
        return true;
    }
    let dettid = guest.thread_state().dettid;
    guest
        .thread_state_mut()
        .delivery_counters
        .owner
        .get_or_insert(dettid);
    let state = guest.thread_state().signal_shadow.as_ref().map(|shadow| {
        let actions = shadow.dispositions.lock().unwrap();
        (
            actions
                .as_ref()
                .map(|dispositions| dispositions.action(signal)),
            shadow.thread.saved.unwrap_or(shadow.thread.blocked),
            shadow.thread.blocked,
            shadow.thread.clone(),
        )
    });
    let skip = |guest: &mut G, reason| {
        guest.thread_state_mut().delivery_counters.skip(reason);
        true
    };
    let (action, frame_mask, current_mask, mut entered) = match state {
        None if had_copy => return skip(guest, "copy given up at this delivery"),
        None => return skip(guest, "no copy"),
        Some((None, ..)) => return skip(guest, "dispositions unknown"),
        Some((Some(Err(_)), ..)) => return skip(guest, "invalid signal"),
        Some((Some(Ok(action)), frame, current, thread)) => (action, frame, current, thread),
    };
    // A force-delivered signal the copy holds blocked or ignored was
    // unblocked, and its action reset to the default, by the kernel before
    // this stop (`force_sig_info_to_task`), which the copy did not see: it is
    // not the copy's to check, and the copy no longer knows the action.
    // - Blocked: the kernel never dequeues a signal the thread blocks, so a
    //   delivery stop for one the copy blocks shows the forced unblock,
    //   whichever instance was dequeued (a pending `raise` of it, say).
    // - Ignored: only a signal the kernel generated (`si_code` > 0: a fault
    //   or SI_KERNEL) can have been forced; a guest's `kill` of the same
    //   number changed nothing. Without a siginfo nothing shows it was forced
    //   (and the backend cannot check the delivery either: `NoSignalRecord`).
    if forced() & sigbit(signal) != 0 {
        if current_mask & sigbit(signal) != 0 {
            forced_changed(guest, "signal delivery");
            return skip(guest, "forced while blocked");
        }
        let kernel_generated = guest
            .signal_info()
            .is_some_and(|info| i32::from_ne_bytes(info[8..12].try_into().unwrap()) > 0);
        if kernel_generated && action.is_ignored() {
            forced_changed(guest, "signal delivery");
            return skip(guest, "forced while ignored");
        }
    }
    if !action.is_caught() {
        return skip(guest, "not caught");
    }
    // The handler's mask as the copy will record it (`enter_handler`), which
    // the backend compares with Linux's rule over the same masks and action.
    if !entered.enter_handler(signal, &action) {
        // One frame more than the copy follows: recording drops the copy.
        return skip(guest, "too many frames");
    }
    let handler_mask = entered.blocked;
    // Force-delivered bits are exempt in each of the copy's masks that holds
    // them, and only there: a forced delivery the copy did not see can only
    // have taken such a bit out of the kernel's masks. Inside a
    // temporary-mask wait the two masks differ, and a forced bit in only one
    // of them stays checked in the other.
    let forced_frame = forced() & frame_mask & !sigbit(signal);
    let forced_current = forced() & current_mask & !sigbit(signal);
    let (interruption, from_registers) = delivery_interruption(guest).await;
    let action = reverie::SignalAction {
        handler: action.handler,
        flags: action.flags,
        restorer: action.restorer,
        mask: action.mask,
    };
    let delivery = reverie::SignalDelivery {
        signal,
        action,
        frame_mask,
        current_mask,
        handler_mask,
        // Reverie's preemption signal, whose kernel state differs from the
        // copy's by design; and in each mask, the force-delivered signals
        // the copy blocks there: a forced delivery the copy did not see can
        // only have unblocked one (`compare`), so one the copy holds
        // unblocked stays checked. The delivered signal is always checked.
        unchecked_mask: reserved() & !sigbit(signal),
        unchecked_frame_mask: forced_frame,
        unchecked_current_mask: forced_current,
        interruption,
    };
    let result_checked = matches!(interruption, reverie::Interruption::Return { .. });
    let held = guest.signal_report_path() == Some(reverie::SignalReportPath::Held);
    let outcome = guest.deliver_signal(delivery).await;
    let not_delivered = matches!(
        outcome,
        reverie::SignalDeliveryOutcome::Unavailable(
            reverie::SignalDeliveryUnavailable::BlockedAtResume
                | reverie::SignalDeliveryUnavailable::NotADeliveryStop
        )
    );
    if !not_delivered {
        // The kernel builds this handler's frame as the guest resumes: a
        // further delivery before a guest instruction runs is at the handler's
        // first instruction.
        let state = guest.thread_state_mut();
        state.delivery_interruption = Some(reverie::Interruption::AfterFrame);
        state.delivery_frame_handler = action.handler;
    }
    let counters = &mut guest.thread_state_mut().delivery_counters;
    counters.interruption_from_registers += u64::from(from_registers);
    match outcome {
        reverie::SignalDeliveryOutcome::Accepted => {
            counters.approved += 1;
            counters.held += u64::from(held);
            counters.result_checked += u64::from(result_checked);
            trace!(
                target: "detcore::signal_delivery",
                "[dtid {}] signal-state copy: the delivery of signal {signal} is approved, \
                 interrupting {interruption:?}",
                guest.thread_state().dettid
            );
        }
        reverie::SignalDeliveryOutcome::Mismatch(mismatch) => {
            counters.mismatched += 1;
            let what = format!(
                "the kernel contradicts the delivery of signal {signal} in {:?}: the copy holds \
                 {:#x}, the kernel {:#x}",
                mismatch.field, mismatch.expected, mismatch.actual
            );
            if guest.config().signal_delivery_check_fatal {
                // A Detcore defect where both sides are certain: a strict run
                // ends rather than continue on the kernel's word alone.
                let failure = format!(
                    "HERMIT_INTERNAL_FAILURE class=signal-delivery-check dtid={} {what}",
                    guest.thread_state().dettid
                );
                tracing::error!("{failure}");
                panic!("{failure}");
            }
            diverged(guest, "signal delivery", &what);
        }
        reverie::SignalDeliveryOutcome::Unavailable(reason) => {
            counters.skip(unavailable_reason(reason));
        }
        reverie::SignalDeliveryOutcome::Refused(_) => counters.skip("backend refuses"),
        // Only a frame-building backend answers these, and no backend that
        // keeps a copy builds frames.
        reverie::SignalDeliveryOutcome::Installed | reverie::SignalDeliveryOutcome::FrameFault => {
            counters.skip("frame-building outcome");
        }
    }
    !not_delivered
}

/// At a delivery stop inside a temporary-mask wait, Linux holds one of two
/// masks: the wait's, when the kernel ran the call (the handler's frame then
/// saves the thread's own mask), or the thread's own, when the signal arrived
/// before the call started, which depends on host timing (see
/// `record_or_replay_rt_sigsuspend`). The kernel's current mask tells which;
/// any other mask is left for the checks that follow to report.
fn take_wait_outcome<G, T>(guest: &mut G)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    let Some((wait_mask, saved)) = guest
        .thread_state()
        .signal_shadow
        .as_ref()
        .map(|shadow| (shadow.thread.wait_mask, shadow.thread.saved))
    else {
        return;
    };
    if (wait_mask.is_none() && saved.is_none()) || !kernel_state_is_the_guests(guest) {
        return;
    }
    let Some(kernel) = read_or_give_up(guest, "signal delivery") else {
        return;
    };
    let Some(shadow) = guest.thread_state_mut().signal_shadow.as_mut() else {
        return;
    };
    let compared = !(reserved() | forced());
    let same = |a: KernelSigset, b: KernelSigset| a & compared == b & compared;
    // A temporary-mask restore no handler took has happened if the kernel
    // already shows the restored mask (the wait returned to the guest).
    if let Some(saved) = saved
        && same(kernel.blocked, saved)
    {
        shadow.thread.settle();
    }
    if let Some(wait_mask) = wait_mask
        && same(kernel.blocked, wait_mask)
        && !same(shadow.thread.blocked, wait_mask)
    {
        shadow.thread.interrupted_under_temporary_mask(wait_mask);
    }
    // The outcome was chosen with the forced signals left out. A forced
    // delivery's clear gives the copy up now; any other difference is left to
    // the next check, which reports it.
    if compare(kernel.blocked, shadow.thread.blocked) == Compared::ForcedOnly {
        forced_changed(guest, "signal delivery");
    }
}

/// The guest's dispositions as Detcore's copy holds them, in the kernel's bit
/// layout: the signals it ignores and the signals it catches.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct CopiedDispositions {
    /// Signals whose action is `SIG_IGN`.
    pub(crate) ignored: KernelSigset,
    /// Signals with a handler.
    pub(crate) caught: KernelSigset,
}

/// A process's record of its publications to the scheduler
/// ([`publish_dispositions`]), shared by its threads. Each publication takes
/// the next generation under this record's lock, with the copy read under the
/// same lock, so a later generation always carries a later reading of the
/// copy. The scheduler keeps the latest generation it received, in whatever
/// order publications arrive, and stores this same type per process.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct PublishedDispositions {
    /// The latest generation a thread of the process used, or the scheduler
    /// was found to hold; 0 before the first.
    pub(crate) generation: u64,
    /// The latest generation the scheduler held when it answered one of this
    /// process's publications: the one `dispositions` came from. Unused in
    /// the scheduler's own entry.
    #[serde(default)]
    pub(crate) accepted: u64,
    /// The dispositions the scheduler holds; `None` when it holds none.
    pub(crate) dispositions: Option<CopiedDispositions>,
}

/// The scheduler's answer to a publication
/// (`Scheduler::publish_signal_dispositions`).
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PublicationAnswer {
    /// The generation the scheduler holds for the process afterwards.
    pub(crate) held: u64,
    /// Whether this publication is what it holds now: its generation was
    /// later than any the scheduler held.
    pub(crate) taken: bool,
}

/// This thread's dispositions from Detcore's copy, for a decision that needs
/// only them (A5 step 2a). `None` where the copy cannot answer: none is kept,
/// the actions it shares are unknown, or an unreported signal is noted
/// anywhere (a handler may have changed the actions unseen). The caller then
/// reads the kernel's `/proc` view as before. Where the copy answers, it holds
/// what the kernel holds: it is checked against the kernel after each
/// recorded call and gives itself up on any mismatch.
///
/// The bits of the signals Linux force-delivers ([`forced`]) and of the
/// preemption signal are not modelled exactly (their kernel state changes
/// unseen), so a decision about one of those signals uses
/// [`copied_dispositions_for`].
pub(crate) fn copied_dispositions<G, T>(guest: &G) -> Option<CopiedDispositions>
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    if any_notes() {
        return None;
    }
    table_dispositions(guest.thread_state())
}

/// The dispositions `thread`'s copy holds for the actions it shares, whether
/// or not an unreported signal is noted: `None` without a copy, or with the
/// shared actions unknown.
fn table_dispositions<T>(thread: &crate::tool_local::ThreadState<T>) -> Option<CopiedDispositions> {
    let shadow = thread.signal_shadow.as_ref()?;
    let actions = shadow.dispositions.lock().unwrap();
    let dispositions = actions.as_ref()?;
    Some(CopiedDispositions {
        ignored: dispositions.ignored(),
        caught: dispositions.caught(),
    })
}

/// [`copied_dispositions`] for a decision about `signal` alone: also `None`
/// for a signal Linux force-delivers ([`forced`]) and for Reverie's
/// preemption signal, whose kernel state changes without the copy seeing it.
pub(crate) fn copied_dispositions_for<G, T>(guest: &G, signal: i32) -> Option<CopiedDispositions>
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    if !models(signal) {
        return None;
    }
    copied_dispositions(guest)
}

/// Whether the copy holds `signal`'s state exactly: it is neither a signal
/// Linux force-delivers ([`forced`]) nor Reverie's preemption signal
/// ([`reserved`]), whose kernel state changes without the copy seeing it.
fn models(signal: i32) -> bool {
    (forced() | reserved()) & sigbit(signal) == 0
}

/// The publication this thread has to make for its process
/// ([`publish_dispositions`]), with the next generation, taken under the
/// record's lock with the copy read under the same lock: the copy's
/// dispositions, or `None` to withdraw them, because it has no copy or the
/// shared actions became unknown. Nothing when the scheduler already holds
/// that for the process, and where no copy is kept.
fn next_publication<G, T>(guest: &G) -> Option<(u64, Option<CopiedDispositions>)>
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    if !kernel_state_is_the_guests(guest) {
        return None;
    }
    let mut record = guest.thread_state().published_dispositions.lock().unwrap();
    let current = table_dispositions(guest.thread_state());
    if current == record.dispositions {
        return None;
    }
    record.generation += 1;
    Some((record.generation, current))
}

/// Applies the scheduler's `answer` to publication `generation` of `current`,
/// and returns whether to publish again at once.
/// - Taken, and no later answer was applied: the record takes its
///   dispositions.
/// - Not taken: the scheduler holds a generation at least as late, from a
///   later publication of this process or from an entry this process never
///   made. The record carries on after it, keeping its dispositions, and the
///   thread publishes again at once, before its request can let another
///   thread read the entry.
/// - Refused (`None`, a thread the scheduler does not know): nothing changes,
///   and the thread publishes again at its next request.
fn settle_publication(
    record: &mut PublishedDispositions,
    generation: u64,
    current: Option<CopiedDispositions>,
    answer: Option<PublicationAnswer>,
) -> bool {
    let Some(answer) = answer else {
        return false;
    };
    if answer.taken {
        if generation > record.accepted {
            record.accepted = generation;
            record.dispositions = current;
        }
        return false;
    }
    if answer.held > record.generation {
        record.generation = answer.held;
    }
    true
}

/// Publishes this thread's copied dispositions to the scheduler as its
/// process's (A5 step 2b), where they differ from what the scheduler holds
/// for it (`ThreadState::published_dispositions`), so that a decision about another thread reads them in
/// place of the kernel's `/proc` view (`Scheduler::published_dispositions_for`).
///
/// Called before each of the thread's requests that can let another thread
/// run (`tool_global::send_and_update_time`). Every change to the actions is
/// recorded in the operations of the thread that makes it, which publishes it
/// before its next request, so the scheduler holds the new actions before any
/// other thread can read them. Threads that do not hold the turn publish too
/// (a thread rejoining the schedule after a host call, a new thread's start,
/// a control message at a signal stop), so publications can arrive out of
/// order: each carries a generation ([`PublishedDispositions`]) and the
/// scheduler keeps the latest. A thread the scheduler has not registered yet
/// is refused, and publishes again at its next request
/// ([`settle_publication`]).
///
/// Every thread sharing the actions holds them behind one reference, so a
/// thread publishes them as they are now, whoever changed them. (After an
/// exec, the old image's other threads keep the old actions until the kernel
/// has killed them and their teardown runs; they make no request in
/// between.) The scheduler keys them by process, which is right because the
/// actions of a process are never shared with another one: [`before_clone`]
/// makes them unknown first.
///
/// That the scheduler's entry is never older than the copy rests on two
/// facts: where a copy is kept (ptrace), a publication is answered inline,
/// within the sender's own call, so it cannot be delayed past its sender;
/// and backends whose messages could be delayed keep no copy. The
/// generations, the scheduler's refusal of retired incarnations, and the
/// immediate republication after an answer that did not take it, guard
/// against an entry that should not be there all the same.
pub(crate) async fn publish_dispositions<G, T>(guest: &mut G)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    // A publication that was not taken is made again once, with a
    // generation past the one the scheduler holds, so it is taken.
    for _ in 0..2 {
        let Some((generation, current)) = next_publication(guest) else {
            return;
        };
        let answer =
            crate::tool_global::publish_signal_dispositions(guest, generation, current).await;
        trace!(
            "[dtid {}] signal-state copy: published its process's dispositions {:?} (generation {}, answer: {:?})",
            guest.thread_state().dettid,
            current,
            generation,
            answer
        );
        let mut record = guest.thread_state().published_dispositions.lock().unwrap();
        if !settle_publication(&mut record, generation, current, answer) {
            return;
        }
    }
}

/// Whether dispositions a process published ([`publish_dispositions`])
/// decide about `signal` now: the copy holds it exactly ([`models`]), and no
/// unreported signal is noted, whose handler may have changed the actions
/// unseen (`SA_RESETHAND`) until its thread consumes the note at its next
/// syscall and gives its copy up.
pub(crate) fn published_dispositions_decide(signal: i32) -> bool {
    models(signal) && !any_notes()
}

/// The mask this thread publishes to the scheduler (A5 step 2b,
/// [`publish_mask`]): the copy's `blocked`, where that is the mask the kernel
/// holds for the thread whenever it is stopped at a request. `None` (nothing
/// to publish) without a copy, and while it may not be:
/// - inside a temporary-mask wait (`wait_mask`), whose mask the kernel may
///   have installed, or with an interrupted wait's mask still to put back
///   (`saved`);
/// - before the next syscall entry verifies a mask a backend report set
///   (`verify_at_entry`);
/// - with a handler frame open where its return would go unseen
///   (`observes_returns` false), or whose entry no check has seen yet (the
///   kernel keeps the old mask when it cannot write the frame).
///
/// A mask Detcore installs privately is not this one either. While one is
/// installed the scheduler reads no published mask: discard at send, poll
/// admission and real-time timer fate take the guest's mask from
/// `Scheduler::saved_guest_sigmasks`, and the choice of a process-directed
/// signal's thread and the first SIGCHLD taker read the kernel's.
fn mask_to_publish<T>(
    thread: &crate::tool_local::ThreadState<T>,
    observes_returns: bool,
) -> Option<KernelSigset> {
    let masks = &thread.signal_shadow.as_ref()?.thread;
    let uncertain = masks.wait_mask.is_some()
        || masks.saved.is_some()
        || masks.verify_at_entry
        || (!masks.activations.is_empty() && !(observes_returns && masks.innermost_observed()));
    (!uncertain).then_some(masks.blocked)
}

/// Publishes this thread's mask from Detcore's copy to the scheduler
/// ([`mask_to_publish`]), or withdraws it, where that differs from what it
/// last had taken or what the scheduler holds is unknown
/// (`ThreadState::published_mask`), so that a decision about
/// this thread reads it in place of the kernel's `SigBlk`
/// (`Scheduler::published_mask_for`). Called with [`publish_dispositions`],
/// before each request that can let another thread run. A mask is the
/// thread's own and only the thread changes or publishes it, so its
/// publications cannot overtake each other. A thread the scheduler has not
/// registered yet is refused, and publishes again at its next request.
pub(crate) async fn publish_mask<G, T>(guest: &mut G)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    if !kernel_state_is_the_guests(guest) {
        return;
    }
    let current = mask_to_publish(guest.thread_state(), observes_sigreturns(guest.config()));
    if guest.thread_state().published_mask == Some(current) {
        return;
    }
    let taken = crate::tool_global::publish_signal_mask(guest, current).await;
    trace!(
        "[dtid {}] signal-state copy: published its mask {:?} (taken: {})",
        guest.thread_state().dettid,
        current.map(|mask| format!("{mask:#x}")),
        taken
    );
    if taken {
        guest.thread_state_mut().published_mask = Some(current);
    }
}

/// Before this thread runs a clone with `flags`: a child that shares the
/// actions from another process (`CLONE_SIGHAND` without `CLONE_THREAD`)
/// could change them where the scheduler, which keeps the published
/// dispositions per process, would not see it for this one. The actions
/// become unknown to every thread sharing them, and are withdrawn before the
/// child exists, also for a clone that then fails. Such a child gets no copy
/// (`SignalShadow::for_clone`).
pub(crate) async fn before_clone<G, T>(guest: &mut G, flags: u64)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    let shares_actions = flags & libc::CLONE_SIGHAND as u64 != 0;
    let new_process = flags & libc::CLONE_THREAD as u64 == 0;
    if shares_actions
        && new_process
        && let Some(shadow) = guest.thread_state().signal_shadow.as_ref()
    {
        debug!(
            "[dtid {}] signal-state copy: the actions become unknown, a clone shares them with a new process",
            guest.thread_state().dettid
        );
        shadow.forget_dispositions();
    }
    publish_dispositions(guest).await;
}

/// Whether this tool asks the backend to report every guest `rt_sigreturn`
/// (`Tool::observes_sigreturns`): where the copy is kept (serialized
/// threads), the backend can report them, no gdbserver is attached (the
/// ptrace backend does not report then), and the guest is known to inherit
/// no seccomp filter. An inherited filter could let an `rt_sigreturn` run
/// unreported (`BackendCapabilities::reports_sigreturns`) where nothing would
/// check the copy before a later check reports a divergence. Handler frames then close only on those reports
/// ([`record_sigreturn_report`]), not by inference ([`reconcile_returns`]).
///
/// Not under `--imprecise-timers` either. A reported return within the keep
/// margin of a precise preemption event requests it again at the same target
/// (Reverie `Timer::disregard_sigreturn_stop`), but an imprecise one past its
/// period is cancelled, and nothing would preempt a thread that then runs
/// without a syscall (A5 step 2c). Without the reports, the copy infers
/// returns from the kernel's mask, as it does wherever they are off.
pub(crate) fn observes_sigreturns(config: &crate::Config) -> bool {
    config.signal_state_copy
        && config.sequentialize_threads
        && !config.gdbserver
        && !config.imprecise_timers
        && config.backend.reports_sigreturns
        && config.inherited_seccomp == detcore_model::config::InheritedSeccomp::Disabled
}

/// `sizeof(struct rt_sigframe)` on x86-64: the return address (8), the
/// `ucontext` (304) and the `siginfo` (128).
const RT_SIGFRAME_SIZE: u64 = 8 + 304 + 128;

/// The end of the x86-64 user address space under 4-level paging
/// (`TASK_SIZE_MAX`). Under 5-level paging it is higher.
const USER_ADDRESS_LIMIT_4_LEVEL: u64 = 0x7fff_ffff_f000;

/// Records a guest `rt_sigreturn` the backend reported before it runs
/// (`Tool::handle_sigreturn`). x86-64 `rt_sigreturn` installs the frame's
/// mask once `access_ok` accepts the whole frame at `sp - 8` and the frame's
/// `uc_sigmask` and `uc_flags` read without a fault, before restoring the
/// registers can fail (`arch/x86/kernel/signal_64.c`): the innermost handler
/// frame then closes and the mask is installed. A frame that fails either
/// (an overflowing range, or an unmapped word) changes no mask; the kernel
/// then sends SIGSEGV. The copy gives itself up quietly where it cannot tell
/// what Linux does: a frame that reaches past 4-level paging's user limit,
/// which the paging mode accepts or not, and a protected frame, whose
/// protection decides whether the kernel's read faults. For every report
/// that keeps the copy, the next syscall entry compares the copy with the
/// kernel ([`reconcile_returns`]), so a report the kernel did not follow (a
/// protection key, say) fails closed there.
pub(crate) fn record_sigreturn_report<T>(
    thread: &mut crate::tool_local::ThreadState<T>,
    report: reverie::SigreturnReport,
) {
    let dettid = thread.dettid;
    if thread.signal_shadow.is_none() {
        return;
    }
    let frame_end = report
        .stack_pointer()
        .checked_sub(8)
        .and_then(|frame| frame.checked_add(RT_SIGFRAME_SIZE));
    let installed = match (report.frame(), frame_end) {
        (reverie::SigreturnFrame::Readable { mask }, Some(end))
            if end <= USER_ADDRESS_LIMIT_4_LEVEL =>
        {
            Some(mask)
        }
        (reverie::SigreturnFrame::Readable { .. }, Some(_)) => {
            debug!(
                "[dtid {dettid}] signal-state copy dropped: rt_sigreturn's frame reaches past \
                 the 4-level user address limit"
            );
            return drop_thread_copy(thread);
        }
        (reverie::SigreturnFrame::Protected, Some(_)) => {
            debug!(
                "[dtid {dettid}] signal-state copy dropped: rt_sigreturn's frame is mapped but \
                 protected from the guest"
            );
            return drop_thread_copy(thread);
        }
        _ => None,
    };
    let Some(shadow) = thread.signal_shadow.as_mut() else {
        return;
    };
    shadow.thread.verify_at_entry = true;
    match installed {
        Some(mask) => {
            shadow.thread.sigreturn(mask & !reserved());
            #[cfg(test)]
            REPORTED_RETURNS.with(|count| count.set(count.get() + 1));
            trace!(
                "[dtid {dettid}] signal-state copy: rt_sigreturn reported, installing {:#x}",
                shadow.thread.blocked
            );
        }
        None => {
            trace!("[dtid {dettid}] signal-state copy: rt_sigreturn's frame faults, no mask change")
        }
    }
}

/// For a backend that shows `rt_sigreturn` as a syscall, which none does
/// today; the ptrace backend reports it through [`record_sigreturn_report`].
///
/// Records an `rt_sigreturn` at its entry, before it runs: Linux installs the
/// frame's `uc_sigmask` as soon as it can read it, before restoring the
/// registers can fail (`arch/x86/kernel/signal_64.c`). A frame whose mask
/// cannot be read changes no mask; the kernel then sends SIGSEGV.
pub(crate) async fn record_rt_sigreturn<G, T>(guest: &mut G)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    if guest.thread_state().signal_shadow.is_none() {
        return;
    }
    let sp = guest.regs().await.rsp as usize;
    let restored = Addr::<u64>::from_raw(sp.wrapping_add(super::signal::UC_SIGMASK_OFFSET))
        .and_then(|address| guest.memory().read_value(address).ok());
    if let Some(mask) = restored {
        with_copy(guest, |_, thread| thread.sigreturn(mask & !reserved()));
    }
}

/// Compares the copy with the kernel's `/proc` view of this thread, where that
/// view is the guest's own.
fn check_against_kernel<G, T>(guest: &mut G, after: &str)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    take_unreported(guest);
    if !kernel_state_is_the_guests(guest) || guest.thread_state().signal_shadow.is_none() {
        return;
    }
    let Some(kernel) = read_or_give_up(guest, after) else {
        return;
    };
    let Some(copy) = with_copy(guest, |dispositions, thread| {
        (
            thread.blocked,
            dispositions.ignored(),
            dispositions.caught(),
        )
    }) else {
        return;
    };
    let (blocked, ignored, caught) = copy;
    // A sibling's unreported handler may have changed the shared actions
    // unseen; that sibling gives the copy up at its own next operation.
    let shared_unsure = unreported_elsewhere(guest.tid().as_raw());
    // Linux resets a caught action only for a signal that was blocked when it
    // was forced. That mask is not this check's: the guest may have blocked or
    // unblocked the signal since, unseen by the reset, and a sibling sharing
    // the actions may have taken it. So a caught bit the kernel cleared counts
    // as forced on its direction alone (`compare`).
    let fields = [
        ("SigBlk", kernel.blocked, blocked, true),
        ("SigIgn", kernel.ignored, ignored, !shared_unsure),
        ("SigCgt", kernel.caught, caught, !shared_unsure),
    ];
    let mut forced_only = false;
    let mut mismatches = Vec::new();
    for (field, kernel, copy, checked) in fields {
        if !checked {
            continue;
        }
        match compare(kernel, copy) {
            Compared::Same => {}
            Compared::ForcedOnly => forced_only = true,
            Compared::Different => mismatches.push(format!(
                "{field} kernel {:#018x} copy {:#018x}",
                kernel & !reserved(),
                copy & !reserved()
            )),
        }
    }
    if !mismatches.is_empty() {
        diverged(guest, after, &mismatches.join(", "));
    } else if forced_only {
        forced_changed(guest, after);
    } else if shared_unsure {
        trace!(
            "[dtid {}] signal-state copy matches the kernel's mask at {after} (actions not \
             compared: a sibling's signal was passed on unreported)",
            guest.thread_state().dettid
        );
    } else {
        if let Some(shadow) = guest.thread_state_mut().signal_shadow.as_mut() {
            shadow.thread.observe_handler_mask();
        }
        #[cfg(test)]
        CHECKS_MATCHED.with(|count| count.set(count.get() + 1));
        trace!(
            "[dtid {}] signal-state copy matches the kernel at {after}",
            guest.thread_state().dettid
        );
    }
}

#[cfg(test)]
thread_local! {
    /// This test thread's kernel checks that found the copy matching.
    static CHECKS_MATCHED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
    /// This test thread's reported divergences.
    static DIVERGENCES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
    /// This test thread's handler entries taken as returned before any
    /// check saw their mask.
    static UNVERIFIED_ENTRIES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
    /// This test thread's `rt_sigreturn` reports applied to a copy.
    static REPORTED_RETURNS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}

/// This thread's kernel signal state, where a check or a choice needs it.
/// A thread whose state cannot be read (it may be exiting) gives up its copy
/// without a divergence report, rather than go on unchecked.
fn read_or_give_up<G, T>(guest: &mut G, at: &str) -> Option<super::threads::KernelSignalState>
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    match read_thread_signal_state(guest.pid(), guest.tid()) {
        Ok(state) => Some(state),
        Err(errno) => {
            debug!(
                "[dtid {}] signal-state copy dropped at {at}: the kernel state is unreadable ({errno})",
                guest.thread_state().dettid
            );
            drop_copy(guest);
            None
        }
    }
}

/// The temporary mask a wait's handler copied in the wait's own turn, the
/// mask the kernel installs; it replaces the one read at the call's entry
/// ([`ThreadSignals::wait_mask`]), which a sibling could change before the
/// turn.
pub(crate) fn note_wait_mask<G, T>(guest: &mut G, mask: KernelSigset)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    if let Some(shadow) = guest.thread_state_mut().signal_shadow.as_mut() {
        shadow.thread.wait_mask = Some(super::signal::kernel_installed_signal_mask(mask));
    }
}

/// Reports a divergence once, by name, drops this thread's copy and marks the
/// actions it shares unknown, so no sharing thread reports the consequence
/// again. Every source of a copy error that host timing could decide gives
/// the copy up quietly first (an unreported delivery, a pending note at a
/// clone), so this line is not host-timed.
fn diverged<G, T>(guest: &mut G, after: &str, what: &str)
where
    G: Guest<Detcore<T>>,
    T: RecordOrReplay,
{
    #[cfg(test)]
    DIVERGENCES.with(|count| count.set(count.get() + 1));
    guest.thread_state_mut().signal_shadow_lost = true;
    warn!(
        "[dtid {}] {DIVERGED} at {after}: {what}; this thread's copy is dropped",
        guest.thread_state().dettid
    );
    drop_copy(guest);
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;
    use std::rc::Rc;

    use reverie::GlobalRPC;
    use reverie::GlobalTool;
    use reverie::Pid;
    use reverie::syscalls::LocalMemory;
    use reverie::syscalls::SyscallInfo;

    use super::*;
    use crate::Config;
    use crate::GlobalState;
    use crate::ThreadState;
    use crate::syscalls::threads::KernelSignalState;
    use crate::syscalls::threads::signal_state_read_seam;
    use crate::types::DetPid;

    /// A guest whose memory is this process's own and whose `/proc` signal
    /// state is scripted; anything else it is asked to do fails the test.
    struct ShadowGuest {
        config: Config,
        thread: ThreadState<()>,
        delivery: DeliveryScript,
    }

    /// What the scripted backend answers `Guest::deliver_signal`, and what it
    /// was asked, with the `orig_rax` its registers show.
    #[derive(Default)]
    struct DeliveryScript {
        answer: Option<reverie::SignalDeliveryOutcome>,
        /// The siginfo `Guest::signal_info` reports, if any.
        signal_info: Option<[u8; reverie::SIGNAL_INFO_SIZE]>,
        asked: Vec<reverie::SignalDelivery>,
        /// What `Guest::signal_report_path` answers.
        report_path: Option<reverie::SignalReportPath>,
        orig_rax: Option<i64>,
        rip: u64,
        registers_read: usize,
    }

    struct NoStack;
    struct NoStackGuard;

    impl Drop for NoStackGuard {
        fn drop(&mut self) {}
    }

    impl reverie::Stack for NoStack {
        type StackGuard = NoStackGuard;
        fn size(&self) -> usize {
            panic!("recording uses no scratch stack")
        }
        fn capacity(&self) -> usize {
            panic!("recording uses no scratch stack")
        }
        fn push<'stack, T>(&mut self, _: T) -> Addr<'stack, T> {
            panic!("recording uses no scratch stack")
        }
        fn reserve<'stack, T>(&mut self) -> AddrMut<'stack, T> {
            panic!("recording uses no scratch stack")
        }
        fn commit(self) -> Result<Self::StackGuard, Errno> {
            Ok(NoStackGuard)
        }
    }

    #[reverie::tool]
    impl GlobalRPC<GlobalState> for ShadowGuest {
        async fn send_rpc(
            &self,
            message: <GlobalState as GlobalTool>::Request,
        ) -> <GlobalState as GlobalTool>::Response {
            panic!("recording must not send an RPC: {:?}", message.2)
        }
        fn config(&self) -> &Config {
            &self.config
        }
    }

    #[reverie::tool]
    impl Guest<Detcore> for ShadowGuest {
        type Memory = LocalMemory;
        type Stack = NoStack;

        fn tid(&self) -> Pid {
            // This test's own thread: the notes of unreported signals are
            // keyed by tid and must not reach another test.
            // SAFETY: gettid has no preconditions.
            Pid::from_raw(unsafe { libc::gettid() })
        }
        fn pid(&self) -> Pid {
            Pid::from_raw(std::process::id() as i32)
        }
        fn ppid(&self) -> Option<Pid> {
            None
        }
        fn memory(&self) -> Self::Memory {
            LocalMemory::new()
        }
        fn thread_state_mut(&mut self) -> &mut ThreadState<()> {
            &mut self.thread
        }
        fn thread_state(&self) -> &ThreadState<()> {
            &self.thread
        }
        async fn regs(&mut self) -> libc::user_regs_struct {
            let orig_rax = self
                .delivery
                .orig_rax
                .expect("recording on a ptrace-like backend reads no registers");
            self.delivery.registers_read += 1;
            // SAFETY: an all-zero `user_regs_struct` is a valid value.
            let mut regs: libc::user_regs_struct = unsafe { std::mem::zeroed() };
            regs.orig_rax = orig_rax as u64;
            regs.rip = self.delivery.rip;
            regs
        }
        fn signal_report_path(&self) -> Option<reverie::SignalReportPath> {
            self.delivery.report_path
        }
        fn signal_info(&self) -> Option<[u8; reverie::SIGNAL_INFO_SIZE]> {
            self.delivery.signal_info
        }
        async fn deliver_signal(
            &mut self,
            delivery: reverie::SignalDelivery,
        ) -> reverie::SignalDeliveryOutcome {
            self.delivery.asked.push(delivery);
            self.delivery
                .answer
                .expect("this test does not expect a delivery check")
        }
        async fn stack(&mut self) -> Self::Stack {
            NoStack
        }
        async fn daemonize(&mut self) {
            panic!("recording must not daemonize")
        }
        async fn inject<S: SyscallInfo>(&mut self, _: S) -> Result<i64, Errno> {
            panic!("recording must not inject")
        }
        async fn tail_inject<S: SyscallInfo>(&mut self, _: S) -> reverie::Never {
            panic!("recording must not retire the guest")
        }
        fn set_timer(&mut self, _: reverie::TimerSchedule) -> Result<(), reverie::Error> {
            panic!("recording must not set a timer")
        }
        fn set_timer_precise(&mut self, _: reverie::TimerSchedule) -> Result<(), reverie::Error> {
            panic!("recording must not set a timer")
        }
        fn read_clock(&mut self) -> Result<u64, reverie::Error> {
            panic!("recording must not read a clock")
        }
    }

    /// The kernel's signal state as the scripted `/proc` reports it.
    #[derive(Clone, Default)]
    struct Kernel(Rc<Cell<(KernelSigset, KernelSigset, KernelSigset)>>);

    impl Kernel {
        fn set(&self, blocked: KernelSigset, ignored: KernelSigset, caught: KernelSigset) {
            self.0.set((blocked, ignored, caught));
        }
        fn install(&self) -> signal_state_read_seam::Installed {
            let state = self.0.clone();
            signal_state_read_seam::install(move |_, _| {
                let (blocked, ignored, caught) = state.get();
                Some(Ok(KernelSignalState {
                    blocked,
                    ignored,
                    caught,
                    ..KernelSignalState::default()
                }))
            })
        }
    }

    /// A guest on the ptrace backend, whose first image inherited `blocked`
    /// and nothing ignored, seeded through `at_exec` from the scripted
    /// kernel. Its kernel signal state is the guest's own, and it reports
    /// each `rt_sigreturn`.
    fn seeded(kernel: &Kernel, blocked: KernelSigset) -> ShadowGuest {
        seeded_on(kernel, blocked, reverie::BackendCapabilities::PTRACE)
    }

    /// As [`seeded`], with the capabilities of a backend that runs
    /// `rt_sigreturn` without reporting it, so the copy infers handler
    /// returns: Reverie's `E9PATCH` value, ptrace's facts without sigreturn
    /// reports. No Hermit run has these capabilities (Hermit runs e9patch
    /// preprocessing as a ptrace run, which reports), so this exercises the
    /// inference that a backend without reports would need.
    fn seeded_inferring(kernel: &Kernel, blocked: KernelSigset) -> ShadowGuest {
        seeded_on(kernel, blocked, reverie::BackendCapabilities::E9PATCH)
    }

    /// As [`seeded`], on a backend with capabilities `backend`.
    fn seeded_on(
        kernel: &Kernel,
        blocked: KernelSigset,
        backend: reverie::BackendCapabilities,
    ) -> ShadowGuest {
        let config = Config {
            sequentialize_threads: true,
            backend,
            inherited_seccomp: detcore_model::config::InheritedSeccomp::Disabled,
            ..Config::default()
        };
        let thread = ThreadState::new(DetPid::from_raw(1), &config, ());
        let mut guest = ShadowGuest {
            config,
            thread,
            delivery: DeliveryScript::default(),
        };
        kernel.set(blocked, 0, 0);
        at_exec(&mut guest);
        assert!(
            guest.thread.signal_shadow.is_some(),
            "the first image is seeded"
        );
        guest
    }

    fn blocked(guest: &ShadowGuest) -> Option<KernelSigset> {
        guest
            .thread
            .signal_shadow
            .as_ref()
            .map(|shadow| shadow.thread.blocked)
    }

    const USR1: KernelSigset = 1 << (libc::SIGUSR1 - 1);
    const USR2: KernelSigset = 1 << (libc::SIGUSR2 - 1);

    #[test]
    fn a_matching_mask_change_is_recorded_and_checked() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = seeded(&kernel, 0);
        kernel.set(USR1, 0, 0);
        let matched = CHECKS_MATCHED.with(std::cell::Cell::get);
        // The old mask the kernel wrote: none was blocked.
        let mut old: KernelSigset = 0;
        let oldset = AddrMut::from_raw(&mut old as *mut KernelSigset as usize);
        record_rt_sigprocmask(
            &mut guest,
            libc::SIG_BLOCK,
            SetInput::Validated(USR1),
            oldset,
            &Ok(0),
        );
        assert_eq!(blocked(&guest), Some(USR1));
        assert!(!guest.thread.signal_shadow_lost);
        assert!(
            CHECKS_MATCHED.with(std::cell::Cell::get) > matched,
            "the check ran and matched"
        );
    }

    #[test]
    fn a_wait_mask_lasts_until_the_next_syscall_and_never_holds_sigkill() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = seeded(&kernel, 0);
        let wait_mask = |guest: &ShadowGuest| {
            guest
                .thread
                .signal_shadow
                .as_ref()
                .and_then(|shadow| shadow.thread.wait_mask)
        };
        note_wait_mask(&mut guest, USR1 | (1 << (libc::SIGKILL - 1)));
        assert_eq!(wait_mask(&guest), Some(USR1));
        at_syscall_entry(&mut guest);
        assert_eq!(wait_mask(&guest), None, "the next call is not in the wait");
    }

    #[test]
    fn any_signal_passed_on_unreported_gives_the_copy_up_and_its_note_is_consumed() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = seeded(&kernel, 0);
        let (pid, tid) = (guest.pid().as_raw(), guest.tid().as_raw());
        // The action at delivery cannot be known any more, so even a signal
        // the copy holds as default gives it up.
        note_unreported(pid, tid, libc::SIGURG);
        at_syscall_entry(&mut guest);
        assert!(guest.thread.signal_shadow.is_none());
        assert!(
            !guest.thread.signal_shadow_lost,
            "a quiet drop is seeded again at exec"
        );
        at_exec(&mut guest);
        assert!(guest.thread.signal_shadow.is_some(), "seeded again");
        // A thread without a copy still consumes its notes.
        guest.thread.signal_shadow = None;
        note_unreported(pid, tid, libc::SIGUSR1);
        at_syscall_entry(&mut guest);
        assert!(!with_notes(|notes| notes.iter().any(|(_, t, _)| *t == tid)));
    }

    #[test]
    fn a_match_with_an_outer_frame_is_ambiguous_and_gives_the_copy_up() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = seeded_inferring(&kernel, 0);
        let action = |mask| KernelSigaction {
            handler: 0x4000,
            flags: (libc::SA_SIGINFO | 0x0400_0000) as u64,
            restorer: 0x7000,
            mask,
        };
        kernel.set(0, 0, USR1 | USR2);
        record_rt_sigaction(&mut guest, libc::SIGUSR1, Some(action(0)), None, &Ok(0));
        record_rt_sigaction(&mut guest, libc::SIGUSR2, Some(action(0)), None, &Ok(0));
        record_delivery(&mut guest, libc::SIGUSR1);
        kernel.set(USR1, 0, USR1 | USR2);
        record_delivery(&mut guest, libc::SIGUSR2);
        // Back to the outermost saved mask in one step.
        kernel.set(0, 0, USR1 | USR2);
        at_syscall_entry(&mut guest);
        assert!(guest.thread.signal_shadow.is_none());
    }

    #[test]
    fn a_silent_drop_leaves_no_sharer_reporting_its_consequence() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = seeded(&kernel, 0);
        let sharer = guest
            .thread
            .signal_shadow
            .as_ref()
            .unwrap()
            .for_clone(libc::CLONE_SIGHAND as u64 | libc::CLONE_VM as u64)
            .unwrap();
        let before = DIVERGENCES.with(std::cell::Cell::get);
        // An ambiguous EFAULT gives the copy up without a report.
        let mut old: KernelSigset = 0;
        let oldset = AddrMut::from_raw(&mut old as *mut KernelSigset as usize);
        record_rt_sigprocmask(
            &mut guest,
            libc::SIG_UNBLOCK,
            SetInput::Unvalidated(Some(USR1)),
            oldset,
            &Err(Errno::EFAULT),
        );
        assert!(guest.thread.signal_shadow.is_none());
        assert!(sharer.dispositions.lock().unwrap().is_none());
        assert_eq!(
            DIVERGENCES.with(std::cell::Cell::get),
            before,
            "nothing was reported"
        );
    }

    #[test]
    fn an_old_action_the_kernel_wrote_differently_is_a_divergence() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = seeded(&kernel, 0);
        // The kernel says SIGUSR1 was ignored; the copy holds the default.
        let mut written = KernelSigaction {
            handler: 1,
            flags: 0,
            restorer: 0,
            mask: 0,
        };
        let old_action = AddrMut::from_raw(&mut written as *mut KernelSigaction as usize);
        let reported = DIVERGENCES.with(std::cell::Cell::get);
        record_rt_sigaction(&mut guest, libc::SIGUSR1, None, old_action, &Ok(0));
        assert!(guest.thread.signal_shadow.is_none());
        assert!(
            DIVERGENCES.with(std::cell::Cell::get) > reported,
            "reported"
        );
    }

    #[test]
    fn a_mismatch_drops_the_copy_for_good_and_its_sharers_quietly() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = seeded(&kernel, 0);
        let sharer = guest
            .thread
            .signal_shadow
            .as_ref()
            .unwrap()
            .for_clone(libc::CLONE_SIGHAND as u64 | libc::CLONE_VM as u64)
            .unwrap();
        // The kernel says USR2 is blocked; the copy, told USR1, disagrees.
        kernel.set(USR2, 0, 0);
        let reported = DIVERGENCES.with(std::cell::Cell::get);
        record_rt_sigprocmask(
            &mut guest,
            libc::SIG_BLOCK,
            SetInput::Validated(USR1),
            None,
            &Ok(0),
        );
        assert_eq!(blocked(&guest), None, "the copy is dropped");
        assert!(
            DIVERGENCES.with(std::cell::Cell::get) > reported,
            "the divergence was reported"
        );
        assert!(guest.thread.signal_shadow_lost);
        assert!(
            sharer.dispositions.lock().unwrap().is_none(),
            "the actions it shared are unknown now"
        );
        at_exec(&mut guest);
        assert!(
            guest.thread.signal_shadow.is_none(),
            "a lost copy is never reseeded"
        );
    }

    #[test]
    fn an_efault_counts_only_when_the_kernel_ran_the_call_and_the_fault_was_the_old_masks() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = seeded(&kernel, 0);
        let mut old: KernelSigset = 0;
        let oldset = AddrMut::from_raw(&mut old as *mut KernelSigset as usize);
        // Detcore's own check of the set failed: nothing ran.
        record_rt_sigprocmask(
            &mut guest,
            libc::SIG_BLOCK,
            SetInput::NotRun,
            oldset,
            &Err(Errno::EFAULT),
        );
        assert_eq!(blocked(&guest), Some(0));
        // A validated set whose old-mask write failed: the change happened.
        kernel.set(USR1, 0, 0);
        record_rt_sigprocmask(
            &mut guest,
            libc::SIG_BLOCK,
            SetInput::Validated(USR1),
            oldset,
            &Err(Errno::EFAULT),
        );
        assert_eq!(blocked(&guest), Some(USR1));
        // An unvalidated set without an old mask: the set faulted.
        record_rt_sigprocmask(
            &mut guest,
            libc::SIG_UNBLOCK,
            SetInput::Unvalidated(Some(USR1)),
            None,
            &Err(Errno::EFAULT),
        );
        assert_eq!(blocked(&guest), Some(USR1));
        // With an old mask, either could have faulted: the copy is given up,
        // without a divergence report.
        record_rt_sigprocmask(
            &mut guest,
            libc::SIG_UNBLOCK,
            SetInput::Unvalidated(Some(USR1)),
            oldset,
            &Err(Errno::EFAULT),
        );
        assert_eq!(blocked(&guest), None);
        assert!(!guest.thread.signal_shadow_lost, "a quiet drop");
    }

    #[test]
    fn a_delivery_inside_a_wait_follows_the_mask_the_kernel_holds() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let action = KernelSigaction {
            handler: 0x4000,
            flags: (libc::SA_SIGINFO | 0x0400_0000) as u64,
            restorer: 0x7000,
            mask: 0,
        };
        let int = 1 << (libc::SIGINT - 1);
        for kernel_ran_the_wait in [true, false] {
            let mut guest = seeded(&kernel, USR1 | USR2);
            kernel.set(USR1 | USR2, 0, 1 << (libc::SIGINT - 1));
            record_rt_sigaction(&mut guest, libc::SIGINT, Some(action), None, &Ok(0));
            // rt_sigsuspend(&{USR1}).
            let temporary: KernelSigset = USR1;
            at_syscall_entry(&mut guest);
            // The wait's handler copies its mask in the call's turn.
            note_wait_mask(&mut guest, temporary);
            // The delivery stop: the kernel holds the wait's mask if it ran the
            // call, else the thread's own (the not-run case of
            // record_or_replay_rt_sigsuspend).
            kernel.set(
                if kernel_ran_the_wait {
                    USR1
                } else {
                    USR1 | USR2
                },
                0,
                int,
            );
            record_delivery(&mut guest, libc::SIGINT);
            let shadow = guest.thread.signal_shadow.as_ref().unwrap();
            let expected = if kernel_ran_the_wait {
                USR1
            } else {
                USR1 | USR2
            };
            assert_eq!(
                shadow.thread.blocked,
                expected | int,
                "{kernel_ran_the_wait}"
            );
            assert_eq!(
                shadow.thread.activations,
                vec![USR1 | USR2],
                "the frame saves the thread's own mask either way"
            );
        }
    }

    #[test]
    fn an_unreported_return_is_recognised_at_the_next_syscall() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = seeded_inferring(&kernel, 0);
        let action = KernelSigaction {
            handler: 0x4000,
            flags: (libc::SA_SIGINFO | 0x0400_0000) as u64,
            restorer: 0x7000,
            mask: USR2,
        };
        kernel.set(0, 0, USR1);
        record_rt_sigaction(&mut guest, libc::SIGUSR1, Some(action), None, &Ok(0));
        record_delivery(&mut guest, libc::SIGUSR1);
        assert_eq!(blocked(&guest), Some(USR1 | USR2));
        // A syscall inside the handler: the kernel holds its mask.
        kernel.set(USR1 | USR2, 0, USR1);
        at_syscall_entry(&mut guest);
        assert_eq!(blocked(&guest), Some(USR1 | USR2));
        // The handler returned unseen; the next syscall finds the old mask.
        kernel.set(0, 0, USR1);
        at_syscall_entry(&mut guest);
        assert_eq!(blocked(&guest), Some(0));
        // With a frame open, a mask that is neither could be a rewritten
        // uc_sigmask: given up quietly, not reported.
        record_delivery(&mut guest, libc::SIGUSR1);
        kernel.set(USR2, 0, USR1);
        let reported = DIVERGENCES.with(std::cell::Cell::get);
        at_syscall_entry(&mut guest);
        assert_eq!(blocked(&guest), None);
        assert_eq!(DIVERGENCES.with(std::cell::Cell::get), reported);
    }

    #[test]
    fn a_sigtrap_change_gives_the_copy_up_quietly() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let trap = 1 << (libc::SIGTRAP - 1);
        let mut guest = seeded(&kernel, trap);
        let reported = DIVERGENCES.with(std::cell::Cell::get);
        // The kernel unblocked SIGTRAP behind the guest's back (a single-step).
        kernel.set(0, 0, 0);
        let mut old: KernelSigset = 0;
        let oldset = AddrMut::from_raw(&mut old as *mut KernelSigset as usize);
        record_rt_sigprocmask(&mut guest, libc::SIG_BLOCK, SetInput::None, oldset, &Ok(0));
        assert!(
            guest.thread.signal_shadow.is_none(),
            "the copy is unknown now"
        );
        assert_eq!(
            DIVERGENCES.with(std::cell::Cell::get),
            reported,
            "and nothing was reported"
        );
    }

    #[test]
    fn a_forced_sigsegv_reset_gives_the_copy_up_quietly() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let segv = 1 << (libc::SIGSEGV - 1);
        let handler = KernelSigaction {
            handler: 0x4000,
            flags: (libc::SA_SIGINFO | 0x0400_0000) as u64,
            restorer: 0x7000,
            mask: 0,
        };
        let mut guest = seeded(&kernel, segv);
        kernel.set(segv, 0, segv);
        record_rt_sigaction(&mut guest, libc::SIGSEGV, Some(handler), None, &Ok(0));
        assert_eq!(
            copied_dispositions(&guest).map(|copied| copied.caught),
            Some(segv)
        );
        let reported = DIVERGENCES.with(std::cell::Cell::get);
        // A forced SIGSEGV (the backend's trapped rdtsc, say) found it caught
        // but blocked: the kernel unblocked it and reset it to the default.
        kernel.set(0, 0, 0);
        let mut old: KernelSigset = 0;
        let oldset = AddrMut::from_raw(&mut old as *mut KernelSigset as usize);
        record_rt_sigprocmask(&mut guest, libc::SIG_BLOCK, SetInput::None, oldset, &Ok(0));
        assert!(
            guest.thread.signal_shadow.is_none(),
            "the copy is unknown now"
        );
        assert_eq!(
            DIVERGENCES.with(std::cell::Cell::get),
            reported,
            "and nothing was reported"
        );
    }

    /// A query of the mask, which checks the copy against the kernel. The old
    /// mask the kernel writes back is `kernel_blocked`.
    fn query_mask_written(guest: &mut ShadowGuest, kernel_blocked: KernelSigset) {
        let mut old: KernelSigset = kernel_blocked;
        let oldset = AddrMut::from_raw(&mut old as *mut KernelSigset as usize);
        record_rt_sigprocmask(guest, libc::SIG_BLOCK, SetInput::None, oldset, &Ok(0));
    }

    /// [`query_mask_written`] where the kernel's mask is empty.
    fn query_mask(guest: &mut ShadowGuest) {
        let mut old: KernelSigset = 0;
        let oldset = AddrMut::from_raw(&mut old as *mut KernelSigset as usize);
        record_rt_sigprocmask(guest, libc::SIG_BLOCK, SetInput::None, oldset, &Ok(0));
    }

    #[test]
    fn a_forced_reset_of_an_ignored_sigsegv_is_quiet() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let segv = 1 << (libc::SIGSEGV - 1);
        let ignore = KernelSigaction {
            handler: libc::SIG_IGN as u64,
            flags: 0x0400_0000,
            restorer: 0x7000,
            mask: 0,
        };
        let reported = DIVERGENCES.with(std::cell::Cell::get);
        // Only SigIgn changes: an ignored, unblocked SIGSEGV reset to the
        // default.
        let mut guest = seeded(&kernel, 0);
        kernel.set(0, segv, 0);
        record_rt_sigaction(&mut guest, libc::SIGSEGV, Some(ignore), None, &Ok(0));
        kernel.set(0, 0, 0);
        query_mask(&mut guest);
        assert!(guest.thread.signal_shadow.is_none(), "given up");
        // The old action the kernel writes back is the copy's with the
        // handler reset to the default.
        let mut guest = seeded(&kernel, 0);
        kernel.set(0, segv, 0);
        record_rt_sigaction(&mut guest, libc::SIGSEGV, Some(ignore), None, &Ok(0));
        kernel.set(0, 0, 0);
        let mut written = KernelSigaction {
            handler: libc::SIG_DFL as u64,
            ..ignore
        };
        let old_action = AddrMut::from_raw(&mut written as *mut KernelSigaction as usize);
        record_rt_sigaction(&mut guest, libc::SIGSEGV, None, old_action, &Ok(0));
        assert!(guest.thread.signal_shadow.is_none(), "given up");
        assert_eq!(
            DIVERGENCES.with(std::cell::Cell::get),
            reported,
            "nothing reported"
        );
    }

    #[test]
    fn forced_signal_differences_a_reset_cannot_make_are_divergences() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let segv = 1 << (libc::SIGSEGV - 1);
        let reported = || DIVERGENCES.with(std::cell::Cell::get);
        // The kernel gained SIGSEGV in SigIgn: a reset only clears.
        let mut guest = seeded(&kernel, 0);
        let before = reported();
        kernel.set(0, segv, 0);
        query_mask(&mut guest);
        assert!(reported() > before, "the kernel ignores more than the copy");
        // SIGSEGV and SIGUSR1 both differ.
        let mut guest = seeded(&kernel, segv | USR1);
        let before = reported();
        kernel.set(0, 0, 0);
        query_mask(&mut guest);
        assert!(
            reported() > before,
            "a difference beyond the forced signals"
        );
        // The kernel wrote a different handler for SIGSEGV.
        let mut guest = seeded(&kernel, 0);
        let before = reported();
        let mut written = KernelSigaction {
            handler: 0x5000,
            flags: 0x0400_0000,
            restorer: 0x7000,
            mask: 0,
        };
        let old_action = AddrMut::from_raw(&mut written as *mut KernelSigaction as usize);
        record_rt_sigaction(&mut guest, libc::SIGSEGV, None, old_action, &Ok(0));
        assert!(reported() > before, "a handler a reset cannot install");
        // The kernel wrote the default, but with other flags than the
        // copy's handler had.
        let mut guest = seeded(&kernel, 0);
        let handler = KernelSigaction {
            handler: 0x4000,
            flags: (libc::SA_SIGINFO | 0x0400_0000) as u64,
            restorer: 0x7000,
            mask: 0,
        };
        kernel.set(0, 0, segv);
        record_rt_sigaction(&mut guest, libc::SIGSEGV, Some(handler), None, &Ok(0));
        let before = reported();
        kernel.set(0, 0, 0);
        let mut written = KernelSigaction {
            handler: libc::SIG_DFL as u64,
            flags: 0x0400_0000,
            ..handler
        };
        let old_action = AddrMut::from_raw(&mut written as *mut KernelSigaction as usize);
        record_rt_sigaction(&mut guest, libc::SIGSEGV, None, old_action, &Ok(0));
        assert!(reported() > before, "flags a reset does not change");
    }

    #[test]
    fn a_caught_signal_reset_counts_as_forced_whatever_the_mask_is_now() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let trap = 1 << (libc::SIGTRAP - 1);
        let handler = KernelSigaction {
            handler: 0x4000,
            flags: (libc::SA_SIGINFO | 0x0400_0000) as u64,
            restorer: 0x7000,
            mask: 0,
        };
        let reported = || DIVERGENCES.with(std::cell::Cell::get);
        // As on the ptrace e2e corpus: SIGTRAP caught and blocked, a
        // single-step resets and unblocks it unseen, and the guest blocks
        // every signal again before its next recorded call. The kernel and
        // the copy then both have SIGTRAP blocked, and only SigCgt differs.
        let mut guest = seeded(&kernel, trap);
        kernel.set(trap, 0, trap);
        record_rt_sigaction(&mut guest, libc::SIGTRAP, Some(handler), None, &Ok(0));
        let before = reported();
        kernel.set(trap, 0, 0);
        query_mask_written(&mut guest, trap);
        assert!(guest.thread.signal_shadow.is_none(), "given up");
        assert_eq!(reported(), before, "quietly");
        // The kernel catching a signal the copy does not is still reported.
        let mut guest = seeded(&kernel, 0);
        let before = reported();
        kernel.set(0, 0, 1 << (libc::SIGSEGV - 1));
        query_mask(&mut guest);
        assert!(reported() > before, "the kernel catches more than the copy");
    }

    #[test]
    fn reconciliation_follows_the_forced_rule() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let segv = 1 << (libc::SIGSEGV - 1);
        let reported = || DIVERGENCES.with(std::cell::Cell::get);
        let before = reported();
        // Where returns are reported: the kernel gained a forced signal while a
        // frame is open, which no forced delivery explains.
        let mut guest = in_handler(&kernel, reverie::BackendCapabilities::PTRACE);
        kernel.set(USR1 | USR2 | segv, 0, USR1);
        at_syscall_entry(&mut guest);
        assert_eq!(blocked(&guest), None, "given up");
        // A forced clear while the frame is open.
        let mut guest = seeded(&kernel, segv);
        let handler = KernelSigaction {
            handler: 0x4000,
            flags: (libc::SA_SIGINFO | 0x0400_0000) as u64,
            restorer: 0x7000,
            mask: 0,
        };
        kernel.set(segv, 0, USR1);
        record_rt_sigaction(&mut guest, libc::SIGUSR1, Some(handler), None, &Ok(0));
        record_delivery(&mut guest, libc::SIGUSR1);
        kernel.set(USR1, 0, USR1);
        at_syscall_entry(&mut guest);
        assert_eq!(blocked(&guest), None, "given up");
        // Where returns are inferred: the frame matched with the forced signals
        // left out, but the kernel holds one the copy does not.
        let mut guest = in_handler(&kernel, reverie::BackendCapabilities::E9PATCH);
        kernel.set(USR1 | USR2, 0, USR1);
        at_syscall_entry(&mut guest);
        kernel.set(segv, 0, USR1);
        at_syscall_entry(&mut guest);
        assert_eq!(blocked(&guest), None, "given up");
        assert_eq!(reported(), before, "none of these is a divergence");
    }

    #[test]
    fn the_preemption_signal_is_left_out_of_old_values() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = seeded(&kernel, 0);
        // The kernel's mask holds Reverie's own signal; the guest never sees it.
        let perf = 1 << (reverie::PERF_EVENT_SIGNAL as i32 - 1);
        kernel.set(perf, 0, perf);
        let mut old: KernelSigset = perf;
        let oldset = AddrMut::from_raw(&mut old as *mut KernelSigset as usize);
        record_rt_sigprocmask(&mut guest, libc::SIG_BLOCK, SetInput::None, oldset, &Ok(0));
        assert!(guest.thread.signal_shadow.is_some());
    }

    #[test]
    fn a_wait_mask_from_sigfillset_matches_what_the_kernel_installs() {
        // sigfillset sets SIGKILL and SIGSTOP; Linux never installs them.
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let int = 1 << (libc::SIGINT - 1);
        let action = KernelSigaction {
            handler: 0x4000,
            flags: (libc::SA_SIGINFO | 0x0400_0000) as u64,
            restorer: 0x7000,
            mask: 0,
        };
        let filled: KernelSigset = !(int | (1 << 31) | (1 << 32));
        let installed = filled & !((1 << (libc::SIGKILL - 1)) | (1 << (libc::SIGSTOP - 1)));
        for kernel_ran_the_wait in [true, false] {
            let mut guest = seeded(&kernel, USR1);
            kernel.set(USR1, 0, int);
            record_rt_sigaction(&mut guest, libc::SIGINT, Some(action), None, &Ok(0));
            at_syscall_entry(&mut guest);
            // The wait's handler copies its mask in the call's turn.
            note_wait_mask(&mut guest, filled);
            let at_stop = if kernel_ran_the_wait { installed } else { USR1 };
            kernel.set(at_stop, 0, int);
            record_delivery(&mut guest, libc::SIGINT);
            let shadow = guest.thread.signal_shadow.as_ref().unwrap();
            assert_eq!(
                shadow.thread.blocked,
                at_stop | int,
                "{kernel_ran_the_wait}"
            );
            assert_eq!(shadow.thread.activations, vec![USR1]);
        }
    }

    #[test]
    fn an_old_mask_the_kernel_wrote_differently_is_a_divergence() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = seeded(&kernel, 0);
        // The kernel says the old mask was USR2; the copy holds 0.
        let mut old: KernelSigset = USR2;
        let oldset = AddrMut::from_raw(&mut old as *mut KernelSigset as usize);
        let reported = DIVERGENCES.with(std::cell::Cell::get);
        record_rt_sigprocmask(&mut guest, libc::SIG_BLOCK, SetInput::None, oldset, &Ok(0));
        assert_eq!(blocked(&guest), None);
        assert!(
            DIVERGENCES.with(std::cell::Cell::get) > reported,
            "reported"
        );
    }

    #[test]
    fn rt_sigaction_installs_even_when_the_old_action_cannot_be_written() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = seeded(&kernel, 0);
        let action = KernelSigaction {
            handler: 0x4000,
            flags: (libc::SA_SIGINFO | 0x0400_0000) as u64,
            restorer: 0x7000,
            mask: 0,
        };
        kernel.set(0, 0, USR1);
        record_rt_sigaction(
            &mut guest,
            libc::SIGUSR1,
            Some(action),
            None,
            &Err(Errno::EFAULT),
        );
        let shadow = guest.thread.signal_shadow.as_ref().unwrap();
        let caught = shadow
            .dispositions
            .lock()
            .unwrap()
            .as_ref()
            .unwrap()
            .caught();
        assert_eq!(caught, USR1);
    }

    #[test]
    fn a_handler_entry_no_check_saw_gives_the_copy_up_when_taken_as_returned() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let action = KernelSigaction {
            handler: 0x4000,
            flags: (libc::SA_SIGINFO | 0x0400_0000) as u64,
            restorer: 0x7000,
            mask: USR2,
        };
        // Seen first, then returned: kept.
        let mut guest = seeded_inferring(&kernel, 0);
        kernel.set(0, 0, USR1);
        record_rt_sigaction(&mut guest, libc::SIGUSR1, Some(action), None, &Ok(0));
        record_delivery(&mut guest, libc::SIGUSR1);
        kernel.set(USR1 | USR2, 0, USR1);
        at_syscall_entry(&mut guest);
        kernel.set(0, 0, USR1);
        let before = UNVERIFIED_ENTRIES.with(std::cell::Cell::get);
        at_syscall_entry(&mut guest);
        assert!(guest.thread.signal_shadow.is_some());
        assert_eq!(UNVERIFIED_ENTRIES.with(std::cell::Cell::get), before);
        // The copy predicts USR1|USR2 for the handler, but the kernel shows
        // the saved mask at once: a return, or a wrong prediction. The copy
        // cannot tell, so it is given up, quietly.
        let reported = DIVERGENCES.with(std::cell::Cell::get);
        record_delivery(&mut guest, libc::SIGUSR1);
        at_syscall_entry(&mut guest);
        assert_eq!(UNVERIFIED_ENTRIES.with(std::cell::Cell::get), before + 1);
        assert!(guest.thread.signal_shadow.is_none());
        assert_eq!(DIVERGENCES.with(std::cell::Cell::get), reported);
    }

    /// A handler for SIGUSR1 that also blocks SIGUSR2, installed and entered
    /// on `backend`, with one frame open.
    fn in_handler(kernel: &Kernel, backend: reverie::BackendCapabilities) -> ShadowGuest {
        let mut guest = seeded_on(kernel, 0, backend);
        let action = KernelSigaction {
            handler: 0x4000,
            flags: (libc::SA_SIGINFO | 0x0400_0000) as u64,
            restorer: 0x7000,
            mask: USR2,
        };
        kernel.set(0, 0, USR1);
        record_rt_sigaction(&mut guest, libc::SIGUSR1, Some(action), None, &Ok(0));
        record_delivery(&mut guest, libc::SIGUSR1);
        assert_eq!(blocked(&guest), Some(USR1 | USR2));
        guest
    }

    fn open_frames(guest: &ShadowGuest) -> usize {
        guest
            .thread
            .signal_shadow
            .as_ref()
            .map_or(0, |shadow| shadow.thread.activations.len())
    }

    #[test]
    fn copied_dispositions_answer_only_where_the_copy_can() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = seeded(&kernel, 0);
        let handler = KernelSigaction {
            handler: 0x4000,
            flags: (libc::SA_SIGINFO | 0x0400_0000) as u64,
            restorer: 0x7000,
            mask: 0,
        };
        let ignore = KernelSigaction {
            handler: libc::SIG_IGN as u64,
            flags: 0x0400_0000,
            restorer: 0x7000,
            mask: 0,
        };
        kernel.set(0, 0, USR1);
        record_rt_sigaction(&mut guest, libc::SIGUSR1, Some(handler), None, &Ok(0));
        kernel.set(0, USR2, USR1);
        record_rt_sigaction(&mut guest, libc::SIGUSR2, Some(ignore), None, &Ok(0));
        let expected = Some(CopiedDispositions {
            ignored: USR2,
            caught: USR1,
        });
        assert_eq!(
            copied_dispositions(&guest),
            expected,
            "what the kernel holds"
        );
        assert_eq!(copied_dispositions_for(&guest, libc::SIGUSR1), expected);
        // Linux can force-deliver these, resetting their kernel state
        // unseen.
        for signal in [
            libc::SIGTRAP,
            libc::SIGSEGV,
            libc::SIGBUS,
            libc::SIGILL,
            libc::SIGFPE,
            libc::SIGSYS,
        ] {
            assert_eq!(copied_dispositions_for(&guest, signal), None, "{signal}");
        }
        assert_eq!(
            copied_dispositions_for(&guest, reverie::PERF_EVENT_SIGNAL as i32),
            None
        );
        // An unreported signal noted anywhere: a handler may have changed the
        // actions unseen.
        note_unreported(1, i32::MAX - 1, libc::SIGUSR1);
        assert_eq!(copied_dispositions(&guest), None);
        with_notes(|notes| notes.clear());
        assert_eq!(copied_dispositions(&guest), expected);
        // Shared actions another thread lost are unknown.
        guest
            .thread
            .signal_shadow
            .as_ref()
            .unwrap()
            .forget_dispositions();
        assert_eq!(copied_dispositions(&guest), None);
        // No copy at all.
        guest.thread.signal_shadow = None;
        assert_eq!(copied_dispositions(&guest), None);
    }

    /// The publication `guest` has to make (`next_publication`), without its
    /// generation. Each call that finds one uses a generation.
    fn due(guest: &ShadowGuest) -> Option<Option<CopiedDispositions>> {
        next_publication(guest).map(|(_, dispositions)| dispositions)
    }

    /// A5 step 2b: the scheduler's answers settle the record in whatever
    /// order they arrive. Only the latest answered publication sets the
    /// dispositions; a refusal leaves them, so the next request publishes
    /// again; a generation the process never used moves its counter past.
    #[test]
    fn answers_settle_the_record_in_any_order() {
        let one = Some(CopiedDispositions {
            ignored: USR1,
            caught: 0,
        });
        let two = Some(CopiedDispositions {
            ignored: USR1 | USR2,
            caught: 0,
        });
        let answer = |held, taken| Some(PublicationAnswer { held, taken });
        // Generations 1 and 2 were used; 2's answer arrives first.
        let mut record = PublishedDispositions {
            generation: 2,
            accepted: 0,
            dispositions: None,
        };
        assert!(!settle_publication(&mut record, 2, two, answer(2, true)));
        assert!(
            settle_publication(&mut record, 1, one, answer(2, false)),
            "superseded: publish again"
        );
        assert_eq!((record.accepted, record.dispositions), (2, two));
        // In order, each answer applies.
        let mut record = PublishedDispositions {
            generation: 2,
            accepted: 0,
            dispositions: None,
        };
        assert!(!settle_publication(&mut record, 1, one, answer(1, true)));
        assert_eq!((record.accepted, record.dispositions), (1, one));
        assert!(!settle_publication(&mut record, 2, two, answer(2, true)));
        assert_eq!((record.accepted, record.dispositions), (2, two));
        // A refusal changes nothing and waits for the next request; the
        // dispositions still differ from the copy's, so that request publishes.
        let before = record;
        record.generation = 3;
        assert!(!settle_publication(&mut record, 3, None, None));
        assert_eq!(record.dispositions, before.dispositions);
        // A refused publication does not block a later one's answer.
        record.generation = 4;
        assert!(!settle_publication(&mut record, 4, None, answer(4, true)));
        assert_eq!((record.accepted, record.dispositions), (4, None));
        // The scheduler holds generation 50, which this process never used:
        // the counter carries on after it, the dispositions stay, and the
        // thread publishes again at once.
        record.generation = 5;
        assert!(settle_publication(&mut record, 5, one, answer(50, false)));
        assert_eq!(record.generation, 50);
        assert_eq!((record.accepted, record.dispositions), (4, None));
        // The same with an entry of this very generation, the likeliest
        // stale shape (every process starts at 1): not taken, so not
        // mistaken for this publication.
        record.generation = 51;
        assert!(settle_publication(&mut record, 51, one, answer(51, false)));
        assert_eq!(record.generation, 51);
        assert_eq!((record.accepted, record.dispositions), (4, None));
    }

    /// A5 step 2b: a thread has its process's dispositions to publish
    /// whenever the scheduler holds anything else for the process, and
    /// withdraws them once the copy is given up. Recording sends nothing
    /// (this guest fails any RPC): publication waits for the thread's next
    /// request.
    #[test]
    fn a_publication_is_due_whenever_the_scheduler_holds_other_dispositions() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = seeded(&kernel, 0);
        let published = |guest: &ShadowGuest, dispositions| {
            guest
                .thread
                .published_dispositions
                .lock()
                .unwrap()
                .dispositions = dispositions;
        };
        let nothing = CopiedDispositions {
            ignored: 0,
            caught: 0,
        };
        assert_eq!(due(&guest), Some(Some(nothing)), "seeded");
        published(&guest, Some(nothing));
        assert_eq!(due(&guest), None, "the scheduler holds them");
        let ignore = KernelSigaction {
            handler: libc::SIG_IGN as u64,
            flags: 0x0400_0000,
            restorer: 0x7000,
            mask: 0,
        };
        kernel.set(0, USR1, 0);
        record_rt_sigaction(&mut guest, libc::SIGUSR1, Some(ignore), None, &Ok(0));
        let ignoring = CopiedDispositions {
            ignored: USR1,
            caught: 0,
        };
        assert_eq!(due(&guest), Some(Some(ignoring)));
        published(&guest, Some(ignoring));
        // A noted unreported signal does not stop the publication: the
        // scheduler consults the notes itself.
        note_unreported(1, i32::MAX - 1, libc::SIGUSR1);
        assert_eq!(due(&guest), None);
        with_notes(|notes| notes.clear());
        give_up(&mut guest, "a test");
        assert_eq!(due(&guest), Some(None), "withdrawn");
        published(&guest, None);
        assert_eq!(due(&guest), None);
    }

    /// A5 step 2b: a thread publishes its copy's mask only where it is what
    /// the kernel holds whenever the thread is stopped at a request.
    #[test]
    fn the_mask_is_published_only_where_the_kernel_holds_it() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = seeded(&kernel, USR1);
        let publish = |guest: &ShadowGuest, observes| mask_to_publish(&guest.thread, observes);
        assert_eq!(publish(&guest, true), Some(USR1));
        fn masks(guest: &mut ShadowGuest) -> &mut ThreadSignals {
            &mut guest.thread.signal_shadow.as_mut().unwrap().thread
        }
        masks(&mut guest).wait_mask = Some(0);
        assert_eq!(publish(&guest, true), None, "inside a temporary-mask wait");
        masks(&mut guest).wait_mask = None;
        masks(&mut guest).saved = Some(USR1);
        assert_eq!(
            publish(&guest, true),
            None,
            "an interrupted wait's mask to put back"
        );
        masks(&mut guest).saved = None;
        masks(&mut guest).verify_at_entry = true;
        assert_eq!(
            publish(&guest, true),
            None,
            "a reported mask not yet verified"
        );
        masks(&mut guest).verify_at_entry = false;
        masks(&mut guest).activations.push(0);
        masks(&mut guest).observed.push(false);
        assert_eq!(
            publish(&guest, true),
            None,
            "a handler entry no check has seen"
        );
        *masks(&mut guest).observed.last_mut().unwrap() = true;
        assert_eq!(
            publish(&guest, true),
            Some(USR1),
            "a checked frame whose return is reported"
        );
        assert_eq!(
            publish(&guest, false),
            None,
            "a frame whose return would go unseen"
        );
        guest.thread.signal_shadow = None;
        assert_eq!(publish(&guest, true), None, "no copy");
    }

    /// Where no copy is kept nothing is published, even with the switch on.
    #[test]
    fn nothing_is_published_where_no_copy_is_kept() {
        let config = Config {
            sequentialize_threads: true,
            backend: reverie::BackendCapabilities::KVM,
            ..Config::default()
        };
        let thread = ThreadState::new(DetPid::from_raw(1), &config, ());
        let guest = ShadowGuest {
            config,
            thread,
            delivery: DeliveryScript::default(),
        };
        guest
            .thread
            .published_dispositions
            .lock()
            .unwrap()
            .dispositions = Some(CopiedDispositions {
            ignored: USR1,
            caught: 0,
        });
        assert_eq!(due(&guest), None);
    }

    /// Published dispositions decide only about a signal the copy holds
    /// exactly, and only while no unreported signal is noted.
    #[test]
    fn published_dispositions_decide_where_the_copy_does() {
        assert!(published_dispositions_decide(libc::SIGUSR1));
        assert!(published_dispositions_decide(libc::SIGCHLD));
        for signal in [
            libc::SIGTRAP,
            libc::SIGSEGV,
            libc::SIGBUS,
            libc::SIGILL,
            libc::SIGFPE,
            libc::SIGSYS,
            reverie::PERF_EVENT_SIGNAL as i32,
        ] {
            assert!(!published_dispositions_decide(signal), "{signal}");
        }
        note_unreported(1, i32::MAX - 1, libc::SIGUSR1);
        assert!(!published_dispositions_decide(libc::SIGUSR1));
        with_notes(|notes| notes.clear());
    }

    /// A clone that shares the actions with a new process makes them unknown
    /// before it runs, so its child gets no copy and the scheduler, which
    /// keys the published dispositions by process, holds none for them. A
    /// thread shares them within its process and changes nothing.
    #[test]
    fn a_clone_sharing_the_actions_with_a_new_process_makes_them_unknown() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let sighand = (libc::CLONE_VM | libc::CLONE_SIGHAND) as u64;
        let nothing = CopiedDispositions {
            ignored: 0,
            caught: 0,
        };

        let mut guest = seeded(&kernel, 0);
        guest
            .thread
            .published_dispositions
            .lock()
            .unwrap()
            .dispositions = Some(nothing);
        let thread = sighand | libc::CLONE_THREAD as u64;
        futures::executor::block_on(before_clone(&mut guest, thread));
        assert_eq!(copied_dispositions(&guest), Some(nothing), "a thread");

        // Withdrawing what the scheduler holds is an RPC, which this guest
        // fails, so it starts with nothing published.
        let mut guest = seeded(&kernel, 0);
        futures::executor::block_on(before_clone(&mut guest, sighand));
        assert_eq!(copied_dispositions(&guest), None);
        let shadow = guest.thread.signal_shadow.as_ref().unwrap();
        assert!(
            shadow.for_clone(sighand).is_none(),
            "the child gets no copy"
        );
    }

    /// The threads of a process share the record of what the scheduler holds
    /// for it; a new process starts with nothing published. A thread created
    /// inside a handler gets no copy and makes the shared actions unknown, so
    /// it has their withdrawal due at its first request, before it runs any
    /// guest code.
    #[test]
    fn a_thread_shares_its_process_record_and_one_denied_a_copy_withdraws() {
        use reverie::Tool;

        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut parent = seeded(&kernel, 0);
        let nothing = CopiedDispositions {
            ignored: 0,
            caught: 0,
        };
        parent
            .thread
            .published_dispositions
            .lock()
            .unwrap()
            .dispositions = Some(nothing);
        let tool = <Detcore as Tool>::new(Pid::from_raw(1), &parent.config);
        let child = |parent: &mut ShadowGuest, flags: u64| {
            parent.thread.clone_flags = Some(crate::CloneFlags::from_bits_truncate(flags));
            let thread = <Detcore as Tool>::init_thread_state(
                &tool,
                Pid::from_raw(2),
                Some((Pid::from_raw(1), &parent.thread)),
            );
            parent.thread.clone_flags = None;
            ShadowGuest {
                config: parent.config.clone(),
                thread,
                delivery: DeliveryScript::default(),
            }
        };
        let thread_flags = (libc::CLONE_VM | libc::CLONE_SIGHAND | libc::CLONE_THREAD) as u64;

        let fork = child(&mut parent, libc::SIGCHLD as u64);
        assert!(!std::sync::Arc::ptr_eq(
            &fork.thread.published_dispositions,
            &parent.thread.published_dispositions
        ));
        assert_eq!(
            due(&fork),
            Some(Some(nothing)),
            "a new process publishes its own"
        );

        let sibling = child(&mut parent, thread_flags);
        assert!(std::sync::Arc::ptr_eq(
            &sibling.thread.published_dispositions,
            &parent.thread.published_dispositions
        ));
        assert_eq!(due(&sibling), None, "already published");

        // Inside a handler: the child gets no copy and the actions become
        // unknown to every sharer.
        let handler = KernelSigaction {
            handler: 0x4000,
            flags: (libc::SA_SIGINFO | 0x0400_0000) as u64,
            restorer: 0x7000,
            mask: 0,
        };
        kernel.set(0, 0, USR1);
        record_rt_sigaction(&mut parent, libc::SIGUSR1, Some(handler), None, &Ok(0));
        let caught = CopiedDispositions {
            ignored: 0,
            caught: USR1,
        };
        parent
            .thread
            .published_dispositions
            .lock()
            .unwrap()
            .dispositions = Some(caught);
        kernel.set(USR1, 0, USR1);
        record_delivery(&mut parent, libc::SIGUSR1);
        assert_eq!(open_frames(&parent), 1);
        let denied = child(&mut parent, thread_flags);
        assert!(denied.thread.signal_shadow.is_none());
        assert_eq!(due(&denied), Some(None), "withdrawn first");
        assert_eq!(due(&parent), Some(None));
    }

    #[test]
    fn sigreturns_are_observed_only_where_the_backend_reports_them() {
        let config = |backend| Config {
            backend,
            sequentialize_threads: true,
            inherited_seccomp: detcore_model::config::InheritedSeccomp::Disabled,
            ..Config::default()
        };
        assert!(observes_sigreturns(&config(
            reverie::BackendCapabilities::PTRACE
        )));
        // Unless the guest is known to inherit no seccomp filter.
        for inherited in [
            detcore_model::config::InheritedSeccomp::Unknown,
            detcore_model::config::InheritedSeccomp::Strict,
            detcore_model::config::InheritedSeccomp::Filter(Some(1)),
        ] {
            let config = Config {
                inherited_seccomp: inherited,
                ..config(reverie::BackendCapabilities::PTRACE)
            };
            assert!(!observes_sigreturns(&config), "{inherited:?}");
        }
        // Nor with a gdbserver attached, whose runs the backend does not
        // report, nor without serialized threads, where no copy is kept.
        let attached = Config {
            gdbserver: true,
            ..config(reverie::BackendCapabilities::PTRACE)
        };
        assert!(!observes_sigreturns(&attached));
        let parallel = Config {
            sequentialize_threads: false,
            ..config(reverie::BackendCapabilities::PTRACE)
        };
        assert!(!observes_sigreturns(&parallel));
        // Nor with the copy off.
        let off = Config {
            signal_state_copy: false,
            ..config(reverie::BackendCapabilities::PTRACE)
        };
        assert!(!observes_sigreturns(&off));
        // Nor under --imprecise-timers, whose preemption events a reported
        // return would lose.
        let imprecise = Config {
            imprecise_timers: true,
            ..config(reverie::BackendCapabilities::PTRACE)
        };
        assert!(!observes_sigreturns(&imprecise));
        for backend in [
            reverie::BackendCapabilities::E9PATCH,
            reverie::BackendCapabilities::KVM,
            reverie::BackendCapabilities::DBT,
            reverie::BackendCapabilities::SABRE,
            reverie::BackendCapabilities::LITEINST_IN_GUEST,
        ] {
            assert!(!observes_sigreturns(&config(backend)));
        }
    }

    #[test]
    fn a_reported_return_installs_the_frame_mask_the_handler_left() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = in_handler(&kernel, reverie::BackendCapabilities::PTRACE);
        let (reported, matched, returns) = (
            DIVERGENCES.with(std::cell::Cell::get),
            CHECKS_MATCHED.with(std::cell::Cell::get),
            REPORTED_RETURNS.with(std::cell::Cell::get),
        );
        // The handler rewrote its frame's uc_sigmask to SIGUSR2, which no
        // frame saved; inference would have had to give the copy up.
        let tid = guest.tid();
        record_sigreturn_report(
            &mut guest.thread,
            reverie::SigreturnReport::new(
                tid,
                0x7fff_0000_0000,
                reverie::SigreturnFrame::Readable { mask: USR2 },
            ),
        );
        assert_eq!(REPORTED_RETURNS.with(std::cell::Cell::get), returns + 1);
        assert_eq!(blocked(&guest), Some(USR2));
        assert_eq!(open_frames(&guest), 0);
        kernel.set(USR2, 0, USR1);
        at_syscall_entry(&mut guest);
        check_against_kernel(&mut guest, "a test check");
        assert_eq!(blocked(&guest), Some(USR2), "the copy is kept");
        assert_eq!(CHECKS_MATCHED.with(std::cell::Cell::get), matched + 1);
        assert_eq!(DIVERGENCES.with(std::cell::Cell::get), reported);
    }

    #[test]
    fn a_reported_return_whose_frame_mask_cannot_be_read_changes_nothing() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = in_handler(&kernel, reverie::BackendCapabilities::PTRACE);
        let tid = guest.tid();
        record_sigreturn_report(
            &mut guest.thread,
            reverie::SigreturnReport::new(tid, 0x7fff_0000_0000, reverie::SigreturnFrame::Unmapped),
        );
        assert_eq!(blocked(&guest), Some(USR1 | USR2));
        assert_eq!(open_frames(&guest), 1);
    }

    #[test]
    fn the_frame_range_rule_follows_linux() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let readable = reverie::SigreturnFrame::Readable { mask: USR2 };
        // sp - 8 + 440 ends exactly at the limit: accepted.
        let at_limit = USER_ADDRESS_LIMIT_4_LEVEL - RT_SIGFRAME_SIZE + 8;
        let cases = [
            (at_limit, readable, Some(Some(USR2))),
            // One byte past the limit: the paging mode would decide.
            (at_limit + 1, readable, None),
            // sp - 8 underflows: access_ok refuses, no mask change.
            (4, readable, Some(Some(USR1 | USR2))),
            // A protected frame: its protection would decide.
            (0x7fff_0000_0000, reverie::SigreturnFrame::Protected, None),
        ];
        for (sp, frame, expected) in cases {
            let mut guest = in_handler(&kernel, reverie::BackendCapabilities::PTRACE);
            let tid = guest.tid();
            let reported = DIVERGENCES.with(std::cell::Cell::get);
            record_sigreturn_report(
                &mut guest.thread,
                reverie::SigreturnReport::new(tid, sp, frame),
            );
            assert_eq!(
                blocked(&guest).map(Some),
                expected,
                "sp {sp:#x}, {frame:?}: None means given up"
            );
            assert_eq!(DIVERGENCES.with(std::cell::Cell::get), reported);
        }
    }

    #[test]
    fn a_report_the_kernel_did_not_follow_fails_closed_at_the_next_entry() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = in_handler(&kernel, reverie::BackendCapabilities::PTRACE);
        let tid = guest.tid();
        // The report closes the last frame with SIGUSR2's mask, but the
        // kernel kept the handler's (as a protection key could make it).
        record_sigreturn_report(
            &mut guest.thread,
            reverie::SigreturnReport::new(
                tid,
                0x7fff_0000_0000,
                reverie::SigreturnFrame::Readable { mask: USR2 },
            ),
        );
        assert_eq!(open_frames(&guest), 0);
        let reported = DIVERGENCES.with(std::cell::Cell::get);
        kernel.set(USR1 | USR2, 0, USR1);
        at_syscall_entry(&mut guest);
        assert_eq!(blocked(&guest), None, "given up at the next entry, quietly");
        assert_eq!(DIVERGENCES.with(std::cell::Cell::get), reported);
        // Where the kernel followed the report, the check passes once and is
        // not repeated.
        let mut guest = in_handler(&kernel, reverie::BackendCapabilities::PTRACE);
        record_sigreturn_report(
            &mut guest.thread,
            reverie::SigreturnReport::new(
                tid,
                0x7fff_0000_0000,
                reverie::SigreturnFrame::Readable { mask: USR2 },
            ),
        );
        kernel.set(USR2, 0, USR1);
        at_syscall_entry(&mut guest);
        assert_eq!(blocked(&guest), Some(USR2));
        let verify_pending = |guest: &ShadowGuest| {
            guest
                .thread
                .signal_shadow
                .as_ref()
                .is_some_and(|shadow| shadow.thread.verify_at_entry)
        };
        assert!(!verify_pending(&guest), "checked once");
    }

    #[test]
    fn where_returns_are_reported_none_is_inferred_and_a_mismatch_fails_closed() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        for (backend, inferred) in [
            (reverie::BackendCapabilities::PTRACE, false),
            (reverie::BackendCapabilities::E9PATCH, true),
        ] {
            let mut guest = in_handler(&kernel, backend);
            // A syscall inside the handler: the kernel holds its mask.
            kernel.set(USR1 | USR2, 0, USR1);
            at_syscall_entry(&mut guest);
            assert_eq!(open_frames(&guest), 1, "{backend:?}");
            // The kernel holds the mask the frame saved, as after a return.
            let reported = DIVERGENCES.with(std::cell::Cell::get);
            kernel.set(0, 0, USR1);
            at_syscall_entry(&mut guest);
            if inferred {
                assert_eq!(blocked(&guest), Some(0), "the return is inferred");
                assert_eq!(open_frames(&guest), 0);
            } else {
                // With reports, a return no report announced is a missed
                // report or a frame never written: the copy fails closed,
                // quietly.
                assert_eq!(blocked(&guest), None, "the copy is given up");
            }
            assert_eq!(
                DIVERGENCES.with(std::cell::Cell::get),
                reported,
                "{backend:?}"
            );
        }
    }

    #[test]
    fn a_caught_realtime_handler_is_followed_until_one_is_passed_on_unreported() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = seeded(&kernel, 0);
        let (pid, tid) = (guest.pid().as_raw(), guest.tid().as_raw());
        let action = KernelSigaction {
            handler: 0x4000,
            flags: (libc::SA_SIGINFO | 0x0400_0000) as u64,
            restorer: 0x7000,
            mask: 0,
        };
        let reported = DIVERGENCES.with(std::cell::Cell::get);
        kernel.set(0, 0, 1 << (40 - 1));
        record_rt_sigaction(&mut guest, 40, Some(action), None, &Ok(0));
        assert!(
            guest.thread.signal_shadow.is_some(),
            "installing a caught realtime handler keeps the copy"
        );
        // Reverie shows a realtime signal passed on unreported
        // (https://github.com/rrnewton/reverie/issues/207); its note gives
        // the copy up at the thread's next operation.
        note_unreported(pid, tid, 40);
        at_syscall_entry(&mut guest);
        assert!(guest.thread.signal_shadow.is_none());
        assert_eq!(DIVERGENCES.with(std::cell::Cell::get), reported);
    }

    #[test]
    fn a_siblings_note_makes_checks_compare_only_the_mask() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = seeded(&kernel, 0);
        // This test thread's id stands for a live sibling of the guest.
        let sibling = guest.tid().as_raw();
        guest.thread.signal_shadow.as_mut().unwrap().thread.blocked = 0;
        let action = KernelSigaction {
            handler: 0x4000,
            flags: (libc::SA_SIGINFO | 0x0400_0000 | libc::SA_RESETHAND) as u64,
            restorer: 0x7000,
            mask: 0,
        };
        kernel.set(0, 0, USR1);
        record_rt_sigaction(&mut guest, libc::SIGUSR1, Some(action), None, &Ok(0));
        // The sibling's note: pretend it belongs to another live thread by
        // keying it to this one and asking as a different tid.
        note_unreported(guest.pid().as_raw(), sibling, libc::SIGUSR1);
        assert!(unreported_elsewhere(sibling + 1));
        assert!(
            !unreported_elsewhere(sibling),
            "a thread's own note is not a sibling's"
        );
    }

    #[test]
    fn notes_of_threads_that_are_gone_are_dropped() {
        // No live thread has this tid (pid_max is far below it).
        note_unreported(1, i32::MAX - 1, libc::SIGUSR1);
        assert!(!unreported_elsewhere(1));
        assert!(!unreported_pending());
    }

    #[test]
    fn nothing_is_seeded_without_serialized_threads() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let ptrace = Config {
            sequentialize_threads: true,
            backend: reverie::BackendCapabilities::PTRACE,
            ..Config::default()
        };
        // Nor with the copy turned off (`--no-signal-state-copy`), which is
        // otherwise on.
        assert!(ptrace.signal_state_copy);
        for config in [
            Config {
                sequentialize_threads: false,
                ..ptrace.clone()
            },
            Config {
                signal_state_copy: false,
                ..ptrace.clone()
            },
        ] {
            let thread = ThreadState::new(DetPid::from_raw(1), &config, ());
            let mut guest = ShadowGuest {
                config,
                thread,
                delivery: DeliveryScript::default(),
            };
            at_exec(&mut guest);
            assert!(guest.thread.signal_shadow.is_none());
        }
    }

    #[test]
    fn nothing_is_seeded_where_the_kernel_state_is_not_the_guests() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let config = Config {
            sequentialize_threads: true,
            backend: reverie::BackendCapabilities::KVM,
            ..Config::default()
        };
        let thread = ThreadState::new(DetPid::from_raw(1), &config, ());
        let mut guest = ShadowGuest {
            config,
            thread,
            delivery: DeliveryScript::default(),
        };
        at_exec(&mut guest);
        assert!(guest.thread.signal_shadow.is_none());
    }

    /// A guest whose copy catches SIGUSR1 with `sa_mask` SIGUSR2, blocks
    /// SIGINT, and whose scripted backend answers delivery checks `answer`.
    fn catching(kernel: &Kernel, answer: reverie::SignalDeliveryOutcome) -> ShadowGuest {
        let int = sigbit(libc::SIGINT);
        let mut guest = seeded(kernel, int);
        let action = KernelSigaction {
            handler: 0x4000,
            flags: (libc::SA_SIGINFO | 0x0400_0000) as u64,
            restorer: 0x7000,
            mask: USR2,
        };
        kernel.set(int, 0, USR1);
        record_rt_sigaction(&mut guest, libc::SIGUSR1, Some(action), None, &Ok(0));
        assert!(guest.thread.signal_shadow.is_some());
        guest.delivery.answer = Some(answer);
        guest
    }

    /// The siginfo of a fault the kernel generated: `si_code` SEGV_MAPERR (1).
    fn fault_siginfo(signal: i32) -> [u8; reverie::SIGNAL_INFO_SIZE] {
        let mut info = [0u8; reverie::SIGNAL_INFO_SIZE];
        info[0..4].copy_from_slice(&signal.to_ne_bytes());
        info[8..12].copy_from_slice(&1i32.to_ne_bytes());
        info
    }

    fn check(guest: &mut ShadowGuest, signal: i32) {
        futures::executor::block_on(check_and_record_delivery(guest, signal));
    }

    /// The delivery a check builds is the copy's, before it records the
    /// delivery: the caught action, the frame and current masks, Linux's
    /// handler mask, every reserved and forced signal unchecked except the
    /// delivered one, and the interruption Detcore recorded.
    #[test]
    fn a_checked_delivery_is_built_from_the_copy_and_recorded_as_unchecked() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let int = sigbit(libc::SIGINT);
        let mut guest = catching(&kernel, reverie::SignalDeliveryOutcome::Accepted);
        let mut unchecked = catching(&kernel, reverie::SignalDeliveryOutcome::Accepted);
        let interruption = reverie::Interruption::Return {
            syscall: libc::SYS_read,
            result: -514,
        };
        guest.thread.delivery_interruption = Some(interruption);
        guest.delivery.orig_rax = Some(libc::SYS_read);
        check(&mut guest, libc::SIGUSR1);
        record_delivery(&mut unchecked, libc::SIGUSR1);
        let asked = guest.delivery.asked.clone();
        assert_eq!(asked.len(), 1);
        let d = asked[0];
        assert_eq!(d.signal, libc::SIGUSR1);
        assert_eq!(d.action.handler, 0x4000);
        assert_eq!(d.action.mask, USR2);
        assert_eq!((d.frame_mask, d.current_mask), (int, int));
        assert_eq!(d.handler_mask, int | USR2 | USR1);
        assert_eq!(d.unchecked_mask, reserved());
        assert_eq!((d.unchecked_frame_mask, d.unchecked_current_mask), (0, 0));
        assert_eq!(d.interruption, interruption);
        assert_eq!(guest.thread.delivery_counters.approved, 1);
        assert_eq!(
            guest.thread.delivery_counters.held, 0,
            "the backend does not say the signal was held"
        );
        // Checking changes the copy exactly as not checking does.
        assert_eq!(
            guest
                .thread
                .signal_shadow
                .as_ref()
                .map(|shadow| shadow.thread.clone()),
            unchecked
                .thread
                .signal_shadow
                .as_ref()
                .map(|shadow| shadow.thread.clone()),
        );
        assert_eq!(
            guest.thread.delivery_interruption,
            Some(reverie::Interruption::AfterFrame),
            "the next delivery at this exit follows this frame"
        );
    }

    /// Inside a temporary-mask wait whose restore is pending, the frame saves
    /// the mask from before the wait, and the current mask is the wait's.
    #[test]
    fn a_delivery_inside_a_temporary_mask_wait_saves_the_mask_from_before_it() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let int = sigbit(libc::SIGINT);
        let mut guest = catching(&kernel, reverie::SignalDeliveryOutcome::Accepted);
        let shadow = guest.thread.signal_shadow.as_mut().unwrap();
        shadow.thread.blocked = int | USR1;
        shadow.thread.interrupted_under_temporary_mask(0);
        guest.thread.delivery_interruption = Some(reverie::Interruption::NotInSyscall);
        guest.delivery.orig_rax = Some(-1);
        kernel.set(0, 0, USR1);
        check(&mut guest, libc::SIGUSR1);
        let d = guest.delivery.asked[0];
        assert_eq!((d.frame_mask, d.current_mask), (int | USR1, 0));
        assert_eq!(d.handler_mask, USR2 | USR1);
    }

    /// A contradiction where both sides are certain is a divergence: it is
    /// counted, the copy is dropped, and nothing more is recorded.
    #[test]
    fn a_mismatch_is_a_divergence_that_drops_the_copy() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mismatch = reverie::SignalDeliveryMismatch {
            field: reverie::SignalDeliveryField::FrameMask,
            expected: 1,
            actual: 2,
        };
        let mut guest = catching(&kernel, reverie::SignalDeliveryOutcome::Mismatch(mismatch));
        guest.delivery.orig_rax = Some(-1);
        guest.thread.delivery_interruption = Some(reverie::Interruption::NotInSyscall);
        let before = DIVERGENCES.with(Cell::get);
        check(&mut guest, libc::SIGUSR1);
        assert_eq!(DIVERGENCES.with(Cell::get), before + 1);
        assert!(guest.thread.signal_shadow.is_none());
        assert!(guest.thread.signal_shadow_lost);
        assert_eq!(guest.thread.delivery_counters.mismatched, 1);
    }

    /// Under `--strict` (`Config::signal_delivery_check_fatal`) the same
    /// contradiction ends the run as an internal failure.
    #[test]
    #[should_panic(expected = "HERMIT_INTERNAL_FAILURE class=signal-delivery-check")]
    fn a_mismatch_ends_a_strict_run() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mismatch = reverie::SignalDeliveryMismatch {
            field: reverie::SignalDeliveryField::InterruptedResult,
            expected: 1,
            actual: 2,
        };
        let mut guest = catching(&kernel, reverie::SignalDeliveryOutcome::Mismatch(mismatch));
        guest.config.signal_delivery_check_fatal = true;
        guest.delivery.orig_rax = Some(-1);
        guest.thread.delivery_interruption = Some(reverie::Interruption::NotInSyscall);
        check(&mut guest, libc::SIGUSR1);
    }

    /// A point the backend cannot check is counted by reason, and the copy
    /// records the delivery as it does unchecked; but a signal the kernel will
    /// not deliver at this resume (`BlockedAtResume`, which requeues it, and
    /// `NotADeliveryStop`, which queues it anew or drops it) is not recorded,
    /// and no handler frame follows it.
    #[test]
    fn an_unavailable_check_is_counted_and_an_undelivered_signal_is_not_recorded() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let unavailable = reverie::SignalDeliveryOutcome::Unavailable;
        let mut guest = catching(
            &kernel,
            unavailable(reverie::SignalDeliveryUnavailable::TracerFiltered),
        );
        let mut unchecked = catching(&kernel, reverie::SignalDeliveryOutcome::Accepted);
        guest.delivery.orig_rax = Some(-1);
        guest.thread.delivery_interruption = Some(reverie::Interruption::NotInSyscall);
        check(&mut guest, libc::SIGUSR1);
        record_delivery(&mut unchecked, libc::SIGUSR1);
        assert_eq!(
            guest
                .thread
                .delivery_counters
                .skipped
                .get("tracer filtered"),
            Some(&1)
        );
        assert_eq!(
            guest
                .thread
                .signal_shadow
                .as_ref()
                .map(|shadow| shadow.thread.clone()),
            unchecked
                .thread
                .signal_shadow
                .as_ref()
                .map(|shadow| shadow.thread.clone()),
        );
        assert_eq!(
            guest.thread.delivery_interruption,
            Some(reverie::Interruption::AfterFrame)
        );

        for (reason, name) in [
            (
                reverie::SignalDeliveryUnavailable::BlockedAtResume,
                "blocked at resume",
            ),
            (
                reverie::SignalDeliveryUnavailable::NotADeliveryStop,
                "not a delivery stop",
            ),
        ] {
            let mut undelivered = catching(&kernel, unavailable(reason));
            undelivered.delivery.orig_rax = Some(-1);
            undelivered.thread.delivery_interruption = Some(reverie::Interruption::NotInSyscall);
            let before = undelivered
                .thread
                .signal_shadow
                .as_ref()
                .map(|shadow| shadow.thread.clone());
            check(&mut undelivered, libc::SIGUSR1);
            assert_eq!(
                undelivered.thread.delivery_counters.skipped.get(name),
                Some(&1)
            );
            assert_eq!(
                undelivered
                    .thread
                    .signal_shadow
                    .as_ref()
                    .map(|shadow| shadow.thread.clone()),
                before,
                "nothing is recorded for a signal the kernel does not deliver ({name})"
            );
            assert_eq!(
                undelivered.thread.delivery_interruption,
                Some(reverie::Interruption::NotInSyscall),
                "no frame follows an undelivered signal ({name})"
            );
        }
    }

    /// A frame's chained delivery at the same exit stops at the handler's
    /// first instruction and is `AfterFrame`; once the guest has run on
    /// (anywhere else, with `orig_ax` -1) it is no syscall; and still at the
    /// syscall's exit away from the handler, where a frame fault's SIGSEGV
    /// stops, the registers decide.
    #[test]
    fn after_frame_holds_only_at_the_handlers_first_instruction() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = catching(&kernel, reverie::SignalDeliveryOutcome::Accepted);
        guest.delivery.orig_rax = Some(-1);
        guest.thread.delivery_interruption = Some(reverie::Interruption::NotInSyscall);
        check(&mut guest, libc::SIGUSR1);
        assert_eq!(guest.thread.delivery_frame_handler, 0x4000);
        // The kernel now shows the handler's mask, as at a chained stop.
        let int = sigbit(libc::SIGINT);
        kernel.set(int | USR2 | USR1, 0, USR1);
        guest.delivery.rip = 0x4000;
        check(&mut guest, libc::SIGUSR1);
        assert_eq!(
            guest.delivery.asked[1].interruption,
            reverie::Interruption::AfterFrame
        );
        guest.delivery.rip = 0x5123;
        check(&mut guest, libc::SIGUSR1);
        assert_eq!(
            guest.delivery.asked[2].interruption,
            reverie::Interruption::NotInSyscall
        );
        guest.delivery.orig_rax = Some(libc::SYS_tgkill);
        check(&mut guest, libc::SIGUSR1);
        assert_eq!(
            guest.delivery.asked[3].interruption,
            reverie::Interruption::KernelRun {
                syscall: libc::SYS_tgkill
            }
        );
        assert_eq!(
            guest.thread.delivery_counters.interruption_from_registers,
            2
        );
    }

    /// A caught force-delivered signal the copy holds blocked reaches its stop
    /// unblocked and reset to the default by the kernel: the copy is given up
    /// quietly, and nothing is checked.
    #[test]
    fn a_forced_signal_the_copy_blocks_gives_the_copy_up_unchecked() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = catching(&kernel, reverie::SignalDeliveryOutcome::Accepted);
        let segv = sigbit(libc::SIGSEGV);
        let action = KernelSigaction {
            handler: 0x4100,
            flags: (libc::SA_SIGINFO | 0x0400_0000) as u64,
            restorer: 0x7000,
            mask: 0,
        };
        kernel.set(sigbit(libc::SIGINT), 0, USR1 | segv);
        record_rt_sigaction(&mut guest, libc::SIGSEGV, Some(action), None, &Ok(0));
        guest.thread.signal_shadow.as_mut().unwrap().thread.blocked |= segv;
        let before = DIVERGENCES.with(Cell::get);
        // The instance dequeued can be a pending raise of the same signal
        // (SI_TKILL), the fault's own having been dropped as a duplicate: a
        // stop for a signal the copy blocks still shows the forced unblock.
        let mut raised = fault_siginfo(libc::SIGSEGV);
        raised[8..12].copy_from_slice(&libc::SI_TKILL.to_ne_bytes());
        guest.delivery.signal_info = Some(raised);
        check(&mut guest, libc::SIGSEGV);
        assert!(guest.delivery.asked.is_empty());
        assert!(guest.thread.signal_shadow.is_none());
        assert!(!guest.thread.signal_shadow_lost, "given up quietly");
        assert_eq!(DIVERGENCES.with(Cell::get), before);
        assert_eq!(
            guest
                .thread
                .delivery_counters
                .skipped
                .get("forced while blocked"),
            Some(&1)
        );
    }

    /// A force-delivered signal the copy holds ignored reaches its stop reset
    /// to the default by the kernel: the copy is given up quietly, and nothing
    /// is checked.
    #[test]
    fn a_forced_signal_the_copy_ignores_gives_the_copy_up_unchecked() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = catching(&kernel, reverie::SignalDeliveryOutcome::Accepted);
        let segv = sigbit(libc::SIGSEGV);
        let ignore = KernelSigaction {
            handler: 1,
            flags: 0x0400_0000,
            restorer: 0x7000,
            mask: 0,
        };
        kernel.set(sigbit(libc::SIGINT), segv, USR1);
        record_rt_sigaction(&mut guest, libc::SIGSEGV, Some(ignore), None, &Ok(0));
        assert!(guest.thread.signal_shadow.is_some());
        let before = DIVERGENCES.with(Cell::get);
        // A fault: the kernel generated it (SEGV_MAPERR).
        guest.delivery.signal_info = Some(fault_siginfo(libc::SIGSEGV));
        check(&mut guest, libc::SIGSEGV);
        assert!(guest.delivery.asked.is_empty());
        assert!(guest.thread.signal_shadow.is_none());
        assert!(!guest.thread.signal_shadow_lost, "given up quietly");
        assert_eq!(DIVERGENCES.with(Cell::get), before);
        assert_eq!(
            guest
                .thread
                .delivery_counters
                .skipped
                .get("forced while ignored"),
            Some(&1)
        );

        // The same number sent by a guest's kill (SI_USER) was not forced: the
        // copy is kept, and the ignored signal is not caught.
        let mut sent = catching(&kernel, reverie::SignalDeliveryOutcome::Accepted);
        kernel.set(sigbit(libc::SIGINT), segv, USR1);
        record_rt_sigaction(&mut sent, libc::SIGSEGV, Some(ignore), None, &Ok(0));
        let mut info = [0u8; reverie::SIGNAL_INFO_SIZE];
        info[0..4].copy_from_slice(&libc::SIGSEGV.to_ne_bytes());
        info[8..12].copy_from_slice(&libc::SI_USER.to_ne_bytes());
        sent.delivery.signal_info = Some(info);
        check(&mut sent, libc::SIGSEGV);
        assert!(sent.thread.signal_shadow.is_some(), "kept");
        assert_eq!(
            sent.thread.delivery_counters.skipped.get("not caught"),
            Some(&1)
        );
    }

    /// A force-delivered bit that the copy holds in only one of the frame and
    /// current masks (a temporary-mask wait) is exempt in that mask's
    /// comparison only, and the delivery is checked; the copy records it as
    /// it records an unchecked one.
    #[test]
    fn a_forced_bit_in_only_one_mask_is_exempt_in_that_mask_only() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = catching(&kernel, reverie::SignalDeliveryOutcome::Accepted);
        let mut unchecked = catching(&kernel, reverie::SignalDeliveryOutcome::Accepted);
        let trap = sigbit(libc::SIGTRAP);
        for g in [&mut guest, &mut unchecked] {
            let shadow = g.thread.signal_shadow.as_mut().unwrap();
            shadow.thread.blocked |= trap;
            shadow.thread.interrupted_under_temporary_mask(0);
            g.thread.delivery_interruption = Some(reverie::Interruption::NotInSyscall);
            g.delivery.orig_rax = Some(-1);
        }
        kernel.set(0, 0, USR1);
        check(&mut guest, libc::SIGUSR1);
        record_delivery(&mut unchecked, libc::SIGUSR1);
        let d = guest.delivery.asked[0];
        assert_eq!(
            d.frame_mask & trap,
            trap,
            "the frame's mask holds the forced bit"
        );
        assert_eq!(d.current_mask & trap, 0, "the wait's mask does not");
        assert_eq!(d.unchecked_mask, reserved());
        assert_eq!(
            (d.unchecked_frame_mask, d.unchecked_current_mask),
            (trap, 0),
            "exempt in the frame's comparison only"
        );
        assert_eq!(guest.thread.delivery_counters.approved, 1);
        assert!(guest.thread.delivery_counters.skipped.is_empty());
        assert_eq!(
            guest
                .thread
                .signal_shadow
                .as_ref()
                .map(|shadow| shadow.thread.clone()),
            unchecked
                .thread
                .signal_shadow
                .as_ref()
                .map(|shadow| shadow.thread.clone()),
        );
    }

    /// The unchecked signals are Reverie's preemption signal and the
    /// force-delivered signals the copy blocks; a forced signal the copy holds
    /// unblocked, and the delivered signal, stay checked.
    #[test]
    fn only_blocked_forced_signals_are_left_unchecked() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = catching(&kernel, reverie::SignalDeliveryOutcome::Accepted);
        let trap = sigbit(libc::SIGTRAP);
        guest.thread.signal_shadow.as_mut().unwrap().thread.blocked |= trap;
        guest.delivery.orig_rax = Some(-1);
        guest.thread.delivery_interruption = Some(reverie::Interruption::NotInSyscall);
        check(&mut guest, libc::SIGUSR1);
        let d = guest.delivery.asked[0];
        assert_eq!(d.unchecked_mask, reserved());
        assert_eq!(
            (d.unchecked_frame_mask, d.unchecked_current_mask),
            (trap, trap)
        );
    }

    /// An approval at a held signal's report counts as held as well.
    #[test]
    fn an_approval_at_a_held_report_is_counted_as_held() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = catching(&kernel, reverie::SignalDeliveryOutcome::Accepted);
        guest.delivery.report_path = Some(reverie::SignalReportPath::Held);
        guest.delivery.orig_rax = Some(-1);
        guest.thread.delivery_interruption = Some(reverie::Interruption::NotInSyscall);
        check(&mut guest, libc::SIGUSR1);
        let counters = &guest.thread.delivery_counters;
        assert_eq!((counters.approved, counters.held), (1, 1));
        let mut refused = catching(
            &kernel,
            reverie::SignalDeliveryOutcome::Unavailable(
                reverie::SignalDeliveryUnavailable::TracerFiltered,
            ),
        );
        refused.delivery.report_path = Some(reverie::SignalReportPath::Held);
        refused.delivery.orig_rax = Some(-1);
        refused.thread.delivery_interruption = Some(reverie::Interruption::NotInSyscall);
        check(&mut refused, libc::SIGUSR1);
        let counters = &refused.thread.delivery_counters;
        assert_eq!(
            (counters.approved, counters.held),
            (0, 0),
            "only an approval counts"
        );
    }

    /// A signal the backend passes on unreported is counted by its reason.
    #[test]
    fn unreported_signals_are_counted_by_reason() {
        let mut counters = DeliveryCounters::default();
        let dettid = crate::types::DetTid::from_raw(7);
        let count = |counters: &mut DeliveryCounters, reason| {
            counters.count_unreported(dettid, reason);
        };
        count(
            &mut counters,
            reverie::UnreportedSignalReason::HeldRestorePending,
        );
        count(
            &mut counters,
            reverie::UnreportedSignalReason::HeldRestorePending,
        );
        count(
            &mut counters,
            reverie::UnreportedSignalReason::DuringSyscallSkip,
        );
        assert_eq!(counters.owner, Some(dettid));
        assert_eq!(
            counters.unreported.into_iter().collect::<Vec<_>>(),
            vec![("during a syscall skip", 1), ("held, restore pending", 2)]
        );
    }

    /// A signal that is not caught, and a thread with no copy, are not
    /// checked; each is counted.
    #[test]
    fn uncaught_signals_and_threads_without_a_copy_are_not_checked() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = catching(&kernel, reverie::SignalDeliveryOutcome::Accepted);
        check(&mut guest, libc::SIGUSR2);
        assert!(guest.delivery.asked.is_empty());
        assert_eq!(
            guest.thread.delivery_counters.skipped.get("not caught"),
            Some(&1)
        );
        guest.thread.signal_shadow = None;
        check(&mut guest, libc::SIGUSR1);
        assert!(guest.delivery.asked.is_empty());
        assert_eq!(
            guest.thread.delivery_counters.skipped.get("no copy"),
            Some(&1)
        );
    }

    /// A copy that this delivery's reconciliation gives up is counted apart
    /// from a thread that had no copy at the stop.
    #[test]
    fn a_copy_given_up_by_the_deliverys_reconciliation_is_counted_apart() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let mut guest = catching(&kernel, reverie::SignalDeliveryOutcome::Accepted);
        guest.delivery.orig_rax = Some(-1);
        guest.thread.delivery_interruption = Some(reverie::Interruption::NotInSyscall);
        check(&mut guest, libc::SIGUSR1);
        assert_eq!(guest.thread.delivery_counters.approved, 1);
        // The handler's frame is open, and the kernel does not hold its mask.
        kernel.set(sigbit(libc::SIGINT) | sigbit(libc::SIGHUP), 0, USR1);
        check(&mut guest, libc::SIGUSR1);
        assert!(guest.thread.signal_shadow.is_none());
        assert_eq!(guest.delivery.asked.len(), 1);
        assert_eq!(
            guest
                .thread
                .delivery_counters
                .skipped
                .get("copy given up at this delivery"),
            Some(&1)
        );
        assert_eq!(guest.thread.delivery_counters.skipped.get("no copy"), None);
    }

    /// The interruption sent is Detcore's record where the registers say the
    /// thread is at that syscall (or in none, for a no-syscall record); the
    /// registers' own answer, counted, where there is no record, Detcore does
    /// not see every syscall, the thread has run on, or it is in a syscall
    /// Detcore cannot see; and the record as it stands where it disagrees with
    /// a known syscall, so the backend reports it. Only `orig_ax` -1 is no
    /// syscall.
    #[test]
    fn the_interruption_is_the_record_where_the_registers_agree_on_the_syscall() {
        let kernel = Kernel::default();
        let _seam = kernel.install();
        let read = reverie::Interruption::Return {
            syscall: libc::SYS_read,
            result: -512,
        };
        let cases = [
            (Some(read), libc::SYS_read, false, read, false),
            (
                Some(read),
                -1,
                false,
                reverie::Interruption::NotInSyscall,
                true,
            ),
            // A known syscall the record does not name: sent as it stands, so
            // the contradiction is reported.
            (Some(read), libc::SYS_write, false, read, false),
            // A syscall Detcore cannot see (a number outside Reverie's table):
            // the record names an earlier event, so the registers decide.
            (
                Some(read),
                1000,
                false,
                reverie::Interruption::KernelRun { syscall: 1000 },
                true,
            ),
            // Only -1 is no syscall; another negative number is a refused one.
            (
                Some(read),
                -5,
                false,
                reverie::Interruption::KernelRun { syscall: -5 },
                true,
            ),
            (
                None,
                libc::SYS_read,
                false,
                reverie::Interruption::KernelRun {
                    syscall: libc::SYS_read,
                },
                true,
            ),
            (None, -1, false, reverie::Interruption::NotInSyscall, true),
            (
                Some(read),
                libc::SYS_write,
                true,
                reverie::Interruption::KernelRun {
                    syscall: libc::SYS_write,
                },
                true,
            ),
            // A preemption record, but the thread is in a known syscall:
            // reported.
            (
                Some(reverie::Interruption::NotInSyscall),
                libc::SYS_read,
                false,
                reverie::Interruption::NotInSyscall,
                false,
            ),
            // In a syscall Detcore cannot see since the preemption.
            (
                Some(reverie::Interruption::NotInSyscall),
                1000,
                false,
                reverie::Interruption::KernelRun { syscall: 1000 },
                true,
            ),
            (
                Some(reverie::Interruption::NotInSyscall),
                -1,
                false,
                reverie::Interruption::NotInSyscall,
                false,
            ),
        ];
        for (record, orig, passthru, expected, from_registers) in cases {
            let mut guest = catching(&kernel, reverie::SignalDeliveryOutcome::Accepted);
            guest.config.passthru_opt = passthru;
            guest.thread.delivery_interruption = record;
            guest.delivery.orig_rax = Some(orig);
            check(&mut guest, libc::SIGUSR1);
            assert_eq!(
                guest.delivery.asked[0].interruption, expected,
                "record {record:?}, orig_rax {orig}, passthru {passthru}"
            );
            assert_eq!(
                guest.thread.delivery_counters.interruption_from_registers,
                u64::from(from_registers),
                "record {record:?}, orig_rax {orig}, passthru {passthru}"
            );
        }
    }
}