ktstr 0.5.2

Test harness for Linux process schedulers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
use super::*;
use std::io::Write;

/// Append a NUL-terminated string to the BTF strings buffer and
/// return its byte offset. Shared across the cast_analysis test
/// fixtures so each `let push_name = |s, name| { ... }` closure
/// stays out of the per-test setup.
fn push_name(s: &mut Vec<u8>, name: &str) -> u32 {
    let off = s.len() as u32;
    s.extend_from_slice(name.as_bytes());
    s.push(0);
    off
}

// ----- BTF synthesizers ---------------------------------------
//
// The BTF library is read-only; tests build a raw BTF byte blob
// with a small writer and parse it via Btf::from_bytes. The
// BTF wire format (header + type section + string section) is
// documented in linux Documentation/bpf/btf.rst. The helpers
// below cover only the kinds the cast analyzer needs to see:
// BTF_KIND_INT (1), BTF_KIND_PTR (2), BTF_KIND_STRUCT (4),
// BTF_KIND_FUNC (12), BTF_KIND_FUNC_PROTO (13).

const BTF_MAGIC: u16 = 0xEB9F;
const BTF_VERSION: u8 = 1;
const BTF_HEADER_LEN: u32 = 24;

const BTF_KIND_INT: u32 = 1;
const BTF_KIND_PTR: u32 = 2;
/// `BTF_KIND_ARRAY = 3` — fixed-length array. Wire layout:
/// header + `btf_array { u32 type, u32 index_type, u32 nelems }`
/// (12 bytes after the 12-byte common header). Per linux uapi
/// `btf.h` and `btf-rs::cbtf::btf_array`, an Array's `size_type`
/// field in the common header is 0 (storage size derives from
/// `elem_size * nelems`, not the header).
const BTF_KIND_ARRAY: u32 = 3;
const BTF_KIND_STRUCT: u32 = 4;
const BTF_KIND_UNION: u32 = 5;
const BTF_KIND_FWD: u32 = 7;
const BTF_KIND_TYPEDEF: u32 = 8;
const BTF_KIND_VOLATILE: u32 = 9;
const BTF_KIND_CONST: u32 = 10;
const BTF_KIND_FUNC: u32 = 12;
const BTF_KIND_FUNC_PROTO: u32 = 13;
/// `BTF_KIND_VAR = 14` — global variable declaration.
/// References its underlying type via the post-header `type`
/// u32 and carries a linkage u32 (static / global / extern).
const BTF_KIND_VAR: u32 = 14;
/// `BTF_KIND_DATASEC = 15` — global section (`.bss`,
/// `.data`, `.rodata`, `.data.<name>`). Carries a list of
/// `VarSecinfo` records that point at `BTF_KIND_VAR` entries.
const BTF_KIND_DATASEC: u32 = 15;

/// `info` field bit 31: encodes bitfield-style member offset / vs
/// regular union for Fwd. Per linux uapi `btf.h` and
/// `btf-rs::cbtf::btf_type::kind_flag`. Splitting the constant out
/// keeps the OR expressions in `build_btf` readable when emitting
/// kind_flag=1 structs / fwd-union.
const KIND_FLAG_BIT: u32 = 1 << 31;

/// One member in a synthetic struct.
#[derive(Clone, Copy)]
struct SynMember {
    name_off: u32,
    type_id: u32,
    /// Byte offset; converted to bit offset on emit.
    byte_offset: u32,
}

/// One parameter in a synthetic FuncProto. `type_id` is the BTF
/// type id of the parameter's type (0 + name_off=0 marks the
/// variadic sentinel — tests don't emit it).
#[derive(Clone, Copy)]
struct SynParam {
    name_off: u32,
    type_id: u32,
}

/// One member in a synthetic struct/union built with kind_flag=1.
/// Encodes `bit_offset` in the low 24 bits and `bitfield_size_bits`
/// in the upper 8 bits of the member's `offset` u32 (per linux uapi
/// `btf.h` and `btf-rs::Member::bitfield_size`). Used by tests that
/// exercise bitfield handling in `build_layout_index` and
/// `struct_member_at`.
#[derive(Clone, Copy)]
struct SynMemberBits {
    name_off: u32,
    type_id: u32,
    /// Member offset in BITS (NOT bytes). For non-bit-aligned
    /// members the test sets a bit position that is not a multiple
    /// of 8.
    bit_offset: u32,
    /// 0 for a non-bitfield member in a kind_flag=1 struct, > 0
    /// for an actual bitfield. Production skips members with
    /// `bitfield_size > 0` AND members whose `bit_offset % 8 != 0`.
    bitfield_size_bits: u32,
}

/// One synthetic BTF type. Tests build a Vec<SynType>; the
/// writer assigns ids starting at 1 (id 0 is Void) and emits
/// the type section in order.
#[allow(dead_code)] // not all variants are used by every test
enum SynType {
    Int {
        name_off: u32,
        size: u32,
        encoding: u32,
        offset: u32,
        bits: u32,
    },
    Ptr {
        type_id: u32,
    },
    /// `BTF_KIND_ARRAY` — fixed-length array. Wire layout:
    /// header (with `name_off=0`, `vlen=0`, `kind_flag=0`,
    /// `size_type=0` per linux uapi `btf.h`) followed by
    /// `btf_array { u32 type, u32 index_type, u32 nelems }`
    /// (12 bytes), matching `btf-rs::cbtf::btf_array::from_reader`.
    /// `type_id` is the element type, `index_type_id` is the
    /// index type (typically `u32`), `nelems` is the array length.
    Array {
        type_id: u32,
        index_type_id: u32,
        nelems: u32,
    },
    Struct {
        name_off: u32,
        size: u32,
        members: Vec<SynMember>,
    },
    /// `BTF_KIND_UNION` — same wire layout as Struct (members are
    /// `btf_member` records). `btf-rs` aliases `Union = Struct`,
    /// so production code paths walk both via the same
    /// `Type::Struct(s) | Type::Union(s)` arm.
    Union {
        name_off: u32,
        size: u32,
        members: Vec<SynMember>,
    },
    /// `BTF_KIND_STRUCT` with kind_flag=1 — member `offset` u32
    /// packs `bit_offset` in low 24 bits and `bitfield_size` in
    /// upper 8 bits. Real C structs that contain ANY bitfield
    /// member have kind_flag=1 even for non-bitfield members in
    /// the same struct (per linux uapi `btf.h`).
    StructBitfields {
        name_off: u32,
        size: u32,
        members: Vec<SynMemberBits>,
    },
    /// `BTF_KIND_FWD` — forward declaration. No payload after the
    /// `btf_type` header. `kind_flag` selects struct (0) vs union
    /// (1) per `btf-rs::Fwd::is_struct` / `is_union`. Used by
    /// tests that probe `member_size_bytes` for unsupported
    /// terminals via a struct member typed as Fwd.
    Fwd {
        name_off: u32,
        kind_flag: u32,
    },
    /// `BTF_KIND_TYPEDEF` — `typedef X T`. Same wire layout as
    /// `Ptr`: header followed by a `u32 type` referencing the
    /// underlying type id. `peel_modifiers` peels through it.
    Typedef {
        name_off: u32,
        type_id: u32,
    },
    /// `BTF_KIND_VOLATILE` — `volatile T`. Same wire layout as
    /// `Ptr`. `name_off` is 0 per the BTF spec.
    Volatile {
        type_id: u32,
    },
    /// `BTF_KIND_CONST` — `const T`. Same wire layout as `Ptr`.
    /// `name_off` is 0 per the BTF spec.
    Const {
        type_id: u32,
    },
    /// `BTF_KIND_FUNC`. `type_id` is the FuncProto id; `vlen`
    /// encodes BTF_FUNC_STATIC/GLOBAL/EXTERN (0/1/2).
    Func {
        name_off: u32,
        type_id: u32,
        linkage: u32,
    },
    /// `BTF_KIND_FUNC_PROTO`. `return_type_id` is the BTF id
    /// of the return type (0 = void); `params` enumerate the
    /// parameter list. `name_off` is always 0 per the BTF
    /// spec (FuncProto types are anonymous).
    FuncProto {
        return_type_id: u32,
        params: Vec<SynParam>,
    },
    /// `BTF_KIND_VAR` — global variable declaration. Wire
    /// layout: header + `u32 type` + `u32 linkage`. Used as
    /// the entry-pointed-to from a `BTF_KIND_DATASEC`
    /// `VarSecinfo`, since libbpf always emits Datasec
    /// entries pointing at a Var (the Var carries the
    /// variable's name and references its underlying C type).
    /// `linkage` mirrors `BTF_VAR_STATIC=0` /
    /// `BTF_VAR_GLOBAL_ALLOCATED=1` /
    /// `BTF_VAR_GLOBAL_EXTERN=2`.
    Var {
        name_off: u32,
        type_id: u32,
        linkage: u32,
    },
    /// `BTF_KIND_DATASEC` — a global section (`.bss`,
    /// `.data`, `.rodata`, `.data.<name>`). Wire layout:
    /// header + `u32 size` + per-VarSecinfo records of
    /// `{u32 type; u32 offset; u32 size}`. Each VarSecinfo
    /// references a `BTF_KIND_VAR` whose underlying type is
    /// the global's C type.
    Datasec {
        name_off: u32,
        size: u32,
        entries: Vec<SynVarSecinfo>,
    },
}

/// One entry in a synthetic `BTF_KIND_DATASEC`. Wire layout:
/// `{u32 type_id; u32 offset; u32 size}` per VarSecinfo. The
/// `type_id` references a `BTF_KIND_VAR` whose underlying
/// type is the global's C type.
#[derive(Clone, Copy)]
struct SynVarSecinfo {
    type_id: u32,
    /// Byte offset of the variable within the section.
    offset: u32,
    /// Byte size of the variable's storage (matches the
    /// underlying type's `type_size`).
    size: u32,
}

/// Build a minimal BTF byte blob for testing.
///
/// `strings` is the string section payload (must start with
/// `\0`). Type ids start at 1 and increase in `types` order.
fn build_btf(types: &[SynType], strings: &[u8]) -> Vec<u8> {
    let mut type_section = Vec::new();
    for ty in types {
        match ty {
            SynType::Int {
                name_off,
                size,
                encoding,
                offset,
                bits,
            } => {
                type_section.extend_from_slice(&name_off.to_le_bytes());
                let info = (BTF_KIND_INT << 24) & 0x1f00_0000;
                type_section.extend_from_slice(&info.to_le_bytes());
                type_section.extend_from_slice(&size.to_le_bytes());
                let int_data = (*encoding << 24) | ((*offset & 0xff) << 16) | (*bits & 0xff);
                type_section.extend_from_slice(&int_data.to_le_bytes());
            }
            SynType::Ptr { type_id } => {
                let name_off: u32 = 0;
                type_section.extend_from_slice(&name_off.to_le_bytes());
                let info = (BTF_KIND_PTR << 24) & 0x1f00_0000;
                type_section.extend_from_slice(&info.to_le_bytes());
                type_section.extend_from_slice(&type_id.to_le_bytes());
            }
            SynType::Array {
                type_id,
                index_type_id,
                nelems,
            } => {
                // Per linux uapi `btf.h` (`btf_array_check_meta`):
                // ARRAY's `name_off`, `vlen`, `kind_flag`, and
                // `size_type` are all 0; the trailing `btf_array`
                // record carries `type`, `index_type`, `nelems`.
                let name_off: u32 = 0;
                type_section.extend_from_slice(&name_off.to_le_bytes());
                let info = (BTF_KIND_ARRAY << 24) & 0x1f00_0000;
                type_section.extend_from_slice(&info.to_le_bytes());
                let size_type: u32 = 0;
                type_section.extend_from_slice(&size_type.to_le_bytes());
                // Trailing `btf_array` (12 bytes) — matches
                // `btf-rs::cbtf::btf_array::from_reader` field order.
                type_section.extend_from_slice(&type_id.to_le_bytes());
                type_section.extend_from_slice(&index_type_id.to_le_bytes());
                type_section.extend_from_slice(&nelems.to_le_bytes());
            }
            SynType::Struct {
                name_off,
                size,
                members,
            } => {
                type_section.extend_from_slice(&name_off.to_le_bytes());
                let vlen = members.len() as u32;
                let info = ((BTF_KIND_STRUCT << 24) & 0x1f00_0000) | (vlen & 0xffff);
                type_section.extend_from_slice(&info.to_le_bytes());
                type_section.extend_from_slice(&size.to_le_bytes());
                for m in members {
                    type_section.extend_from_slice(&m.name_off.to_le_bytes());
                    type_section.extend_from_slice(&m.type_id.to_le_bytes());
                    // Non-bitfield: bit_offset = byte * 8.
                    let bit_off = m.byte_offset * 8;
                    type_section.extend_from_slice(&bit_off.to_le_bytes());
                }
            }
            SynType::Union {
                name_off,
                size,
                members,
            } => {
                type_section.extend_from_slice(&name_off.to_le_bytes());
                let vlen = members.len() as u32;
                // Same wire encoding as Struct, only the kind id
                // differs. kind_flag=0 (regular union, members
                // carry plain bit_offset).
                let info = ((BTF_KIND_UNION << 24) & 0x1f00_0000) | (vlen & 0xffff);
                type_section.extend_from_slice(&info.to_le_bytes());
                type_section.extend_from_slice(&size.to_le_bytes());
                for m in members {
                    type_section.extend_from_slice(&m.name_off.to_le_bytes());
                    type_section.extend_from_slice(&m.type_id.to_le_bytes());
                    // Union members all sit at bit offset 0 in
                    // real C, but the wire format still carries a
                    // u32 offset. Allow tests to set arbitrary
                    // byte_offset values to exercise the
                    // struct_member_at lookup logic; production
                    // matches on byte position regardless of kind.
                    let bit_off = m.byte_offset * 8;
                    type_section.extend_from_slice(&bit_off.to_le_bytes());
                }
            }
            SynType::StructBitfields {
                name_off,
                size,
                members,
            } => {
                type_section.extend_from_slice(&name_off.to_le_bytes());
                let vlen = members.len() as u32;
                // kind_flag=1 (bit 31 set): member offset packs
                // (bitfield_size << 24) | (bit_offset & 0xffffff).
                let info =
                    (((BTF_KIND_STRUCT << 24) & 0x1f00_0000) | (vlen & 0xffff)) | KIND_FLAG_BIT;
                type_section.extend_from_slice(&info.to_le_bytes());
                type_section.extend_from_slice(&size.to_le_bytes());
                for m in members {
                    type_section.extend_from_slice(&m.name_off.to_le_bytes());
                    type_section.extend_from_slice(&m.type_id.to_le_bytes());
                    let packed =
                        ((m.bitfield_size_bits & 0xff) << 24) | (m.bit_offset & 0x00ff_ffff);
                    type_section.extend_from_slice(&packed.to_le_bytes());
                }
            }
            SynType::Fwd {
                name_off,
                kind_flag,
            } => {
                type_section.extend_from_slice(&name_off.to_le_bytes());
                // BTF_KIND_FWD: vlen is unused (set to 0); the
                // kind_flag bit encodes struct (0) vs union (1).
                // size_type field is also unused per the kernel
                // wire format but is still 4 bytes long; emit 0.
                let info = ((BTF_KIND_FWD << 24) & 0x1f00_0000) | ((*kind_flag & 0x1) << 31);
                type_section.extend_from_slice(&info.to_le_bytes());
                type_section.extend_from_slice(&0u32.to_le_bytes());
            }
            SynType::Typedef { name_off, type_id } => {
                type_section.extend_from_slice(&name_off.to_le_bytes());
                let info = (BTF_KIND_TYPEDEF << 24) & 0x1f00_0000;
                type_section.extend_from_slice(&info.to_le_bytes());
                type_section.extend_from_slice(&type_id.to_le_bytes());
            }
            SynType::Volatile { type_id } => {
                let name_off: u32 = 0;
                type_section.extend_from_slice(&name_off.to_le_bytes());
                let info = (BTF_KIND_VOLATILE << 24) & 0x1f00_0000;
                type_section.extend_from_slice(&info.to_le_bytes());
                type_section.extend_from_slice(&type_id.to_le_bytes());
            }
            SynType::Const { type_id } => {
                let name_off: u32 = 0;
                type_section.extend_from_slice(&name_off.to_le_bytes());
                let info = (BTF_KIND_CONST << 24) & 0x1f00_0000;
                type_section.extend_from_slice(&info.to_le_bytes());
                type_section.extend_from_slice(&type_id.to_le_bytes());
            }
            SynType::Func {
                name_off,
                type_id,
                linkage,
            } => {
                type_section.extend_from_slice(&name_off.to_le_bytes());
                // BTF_KIND_FUNC encodes the linkage in vlen
                // (0=static, 1=global, 2=extern).
                let info = ((BTF_KIND_FUNC << 24) & 0x1f00_0000) | (*linkage & 0xffff);
                type_section.extend_from_slice(&info.to_le_bytes());
                type_section.extend_from_slice(&type_id.to_le_bytes());
            }
            SynType::FuncProto {
                return_type_id,
                params,
            } => {
                let name_off: u32 = 0;
                type_section.extend_from_slice(&name_off.to_le_bytes());
                let vlen = params.len() as u32;
                let info = ((BTF_KIND_FUNC_PROTO << 24) & 0x1f00_0000) | (vlen & 0xffff);
                type_section.extend_from_slice(&info.to_le_bytes());
                type_section.extend_from_slice(&return_type_id.to_le_bytes());
                for p in params {
                    type_section.extend_from_slice(&p.name_off.to_le_bytes());
                    type_section.extend_from_slice(&p.type_id.to_le_bytes());
                }
            }
            SynType::Var {
                name_off,
                type_id,
                linkage,
            } => {
                type_section.extend_from_slice(&name_off.to_le_bytes());
                // BTF_KIND_VAR = 14. Header followed by
                // `u32 type` + `u32 linkage`.
                let info = (BTF_KIND_VAR << 24) & 0x1f00_0000;
                type_section.extend_from_slice(&info.to_le_bytes());
                type_section.extend_from_slice(&type_id.to_le_bytes());
                type_section.extend_from_slice(&linkage.to_le_bytes());
            }
            SynType::Datasec {
                name_off,
                size,
                entries,
            } => {
                type_section.extend_from_slice(&name_off.to_le_bytes());
                let vlen = entries.len() as u32;
                // BTF_KIND_DATASEC = 15. Header followed by
                // `u32 size` + per-entry `{u32 type, u32
                // offset, u32 size}`.
                let info = ((BTF_KIND_DATASEC << 24) & 0x1f00_0000) | (vlen & 0xffff);
                type_section.extend_from_slice(&info.to_le_bytes());
                type_section.extend_from_slice(&size.to_le_bytes());
                for e in entries {
                    type_section.extend_from_slice(&e.type_id.to_le_bytes());
                    type_section.extend_from_slice(&e.offset.to_le_bytes());
                    type_section.extend_from_slice(&e.size.to_le_bytes());
                }
            }
        }
    }

    let type_len = type_section.len() as u32;
    let str_len = strings.len() as u32;

    let mut blob = Vec::new();
    // Header (24 bytes).
    blob.write_all(&BTF_MAGIC.to_le_bytes()).unwrap();
    blob.push(BTF_VERSION);
    blob.push(0); // flags
    blob.write_all(&BTF_HEADER_LEN.to_le_bytes()).unwrap();
    blob.write_all(&0u32.to_le_bytes()).unwrap(); // type_off
    blob.write_all(&type_len.to_le_bytes()).unwrap();
    blob.write_all(&type_len.to_le_bytes()).unwrap(); // str_off (= type_len)
    blob.write_all(&str_len.to_le_bytes()).unwrap();
    blob.extend_from_slice(&type_section);
    blob.extend_from_slice(strings);
    blob
}

// BTF int encoding flags: signed = 1, char = 2, bool = 4. The
// synthesizer uses 0 for plain unsigned.

/// Helper: build a BTF with `task_struct`-like source struct
/// `T` (id=2) and target struct `Q` (id=3). T has a u64 field
/// at byte offset `field_off` named `f`. Q has a u32 at byte
/// offset `target_off`. Returns the byte blob and the (T_id,
/// Q_id) pair.
fn btf_with_source_and_target(field_off: u32, target_off: u32) -> (Vec<u8>, u32, u32) {
    // Strings: null + names. Order matters since name_offs
    // index into this byte vector.
    let mut strings: Vec<u8> = vec![0];
    let n_int = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_q = push_name(&mut strings, "Q");
    let n_f = push_name(&mut strings, "f");
    let n_x = push_name(&mut strings, "x");

    let types = vec![
        // id 1: int u64 (size=8, bits=64).
        SynType::Int {
            name_off: n_int,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        // id 2: struct T { ... f at field_off ... } size = field_off + 8.
        SynType::Struct {
            name_off: n_t,
            size: field_off + 8,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 1,
                byte_offset: field_off,
            }],
        },
        // id 3: struct Q { u64 x at target_off }, size = target_off + 8.
        SynType::Struct {
            name_off: n_q,
            size: target_off + 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: target_off,
            }],
        },
    ];
    (build_btf(&types, &strings), 2, 3)
}

/// Small helper to emit a single [`BpfInsn`] with given fields.
/// Uses `BpfInsn::new` directly so dst/src register packing is
/// done by the constructor — no `let mut x = X::default(); x.f = …`
/// clippy footgun, no separate setter calls.
fn mk_insn(code: u8, dst: u8, src: u8, off: i16, imm: i32) -> BpfInsn {
    BpfInsn::new(code, dst, src, off, imm)
}

fn ldx(size: u8, dst: u8, src: u8, off: i16) -> BpfInsn {
    mk_insn(BPF_CLASS_LDX | size | BPF_MODE_MEM, dst, src, off, 0)
}

/// `*(size *)(r_dst + off) = r_src`. Plain memory store (BPF_MEM
/// mode), the spill / kptr-write encoding the analyzer cares
/// about. dst is the address-base register, src is the value.
fn stx(size: u8, dst: u8, src: u8, off: i16) -> BpfInsn {
    mk_insn(BPF_CLASS_STX | size | BPF_MODE_MEM, dst, src, off, 0)
}

fn mov_x(dst: u8, src: u8) -> BpfInsn {
    mk_insn(BPF_CLASS_ALU64 | BPF_OP_MOV | BPF_SRC_X, dst, src, 0, 0)
}

fn mov_k(dst: u8, imm: i32) -> BpfInsn {
    mk_insn(BPF_CLASS_ALU64 | BPF_OP_MOV, dst, 0, 0, imm)
}

/// Generic plain-helper `BPF_CALL` for tests that exercise the
/// R0..R5 clobber + spill/reload behaviour without engaging the
/// helper-return arm. `imm == 1` happens to coincide with
/// `BPF_FUNC_map_lookup_elem`, but the helper-return arm only
/// fires when R1 is a `RegState::DatasecPointer{".maps", ..}` at
/// the call site — none of the call sites that consume this
/// helper seed R1 that way, so R0 still ends up Unknown after the
/// clobber as those tests assert. Tests that need a different
/// helper id (e.g. to confirm the arm rejects non-allowlist ids)
/// build the call instruction inline via [`helper_call`] instead.
fn call() -> BpfInsn {
    mk_insn(BPF_CLASS_JMP | BPF_OP_CALL, 0, 0, 0, 1)
}

/// `BPF_CALL` with `src_reg == BPF_PSEUDO_KFUNC_CALL` and
/// `imm == kfunc_btf_id`. Models the relocated call form where
/// the imm carries the BTF id of a `BTF_KIND_FUNC`.
fn kfunc_call(kfunc_btf_id: u32) -> BpfInsn {
    mk_insn(
        BPF_CLASS_JMP | BPF_OP_CALL,
        0,
        BPF_PSEUDO_KFUNC_CALL,
        0,
        kfunc_btf_id as i32,
    )
}

fn exit() -> BpfInsn {
    mk_insn(BPF_CLASS_JMP | BPF_OP_EXIT, 0, 0, 0, 0)
}

/// `BPF_ADDR_SPACE_CAST` (kernel/bpf/verifier.c::check_alu_op):
/// `ALU64 | MOV | X` with `off=1, imm=1` is the as(1)→as(0)
/// cast — arena→kernel. `imm=1<<16` is the as(0)→as(1) cast in
/// the other direction. Tests use the arena→kernel form to
/// surface arena_confirmed evidence for shape-inference findings
/// (F1 mitigation).
fn addr_space_cast(dst: u8, src: u8, imm: i32) -> BpfInsn {
    mk_insn(BPF_CLASS_ALU64 | BPF_OP_MOV | BPF_SRC_X, dst, src, 1, imm)
}

// ----- Tests --------------------------------------------------

#[test]
fn empty_insns_yields_empty_map() {
    let (blob, _t, _q) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let map = analyze_casts(&[], &btf, &[], &[], &[], &[]);
    assert!(map.is_empty());
}

#[test]
fn no_initial_seed_yields_empty_map() {
    // Without seeding any register as a struct pointer, the
    // analyzer cannot identify the source type of an LDX.
    let (blob, _t, _q) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![ldx(BPF_SIZE_DW, 2, 1, 8), ldx(BPF_SIZE_DW, 3, 2, 0), exit()];
    let map = analyze_casts(&insns, &btf, &[], &[], &[], &[]);
    assert!(map.is_empty());
}

#[test]
fn simple_cast_recovers_target() {
    // r1 -> *(T *).
    // r2 = *(u64 *)(r1 + 8)   -- "load u64 at T.f"
    // r4 = bpf_addr_space_cast(r2, 0, 1)  -- arena_confirmed evidence (F1)
    // r3 = *(u64 *)(r4 + 0)   -- "use loaded value as Q*"
    //
    // The arena_space_cast on the LoadedU64Field register is the
    // F1 mitigation prerequisite: shape inference alone is not
    // enough evidence to emit a finding. The `bpf_addr_space_cast`
    // tags `(t_id, 8)` as arena-confirmed, after which the
    // shape-inference finding can fire when exactly one struct
    // matches the access pattern.
    let (blob, t_id, q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(4, 2, 1),
        ldx(BPF_SIZE_DW, 3, 4, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "got: {map:?}"
    );
}

/// F1 mitigation: shape-inference candidates without direct
/// arena evidence (no `BPF_ADDR_SPACE_CAST` AND no STX-flow
/// allocator-return tag) must drop, even when the (offset, size)
/// access pattern uniquely matches one BTF candidate. Pin the
/// drop-without-evidence behaviour against a regression that
/// would re-enable shape-inference-only emits, which the F1
/// hostile-input mitigation explicitly forbids: a 33-bit-shaped
/// counter on aarch64 falls inside the 4 GiB arena window and
/// would render as a chased pointer if the F1 gate weren't here.
///
/// Same instruction shape as `simple_cast_recovers_target` minus
/// the `BPF_ADDR_SPACE_CAST`. The companion proof — re-running
/// with the addr_space_cast added DOES emit — anchors that the
/// drop is the F1 gate, not a separate analysis defect that
/// would also have rejected the cast-augmented sequence.
#[test]
fn shape_inference_alone_drops_without_arena_confirmed() {
    let (blob, t_id, q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();

    // (a) WITHOUT addr_space_cast: shape inference recognizes
    // the (offset=0, size=8) access against Q's layout, but the
    // F1 gate at `finalize`'s arena loop demands direct evidence
    // (`arena_confirmed` OR `arena_stx_findings`). Neither is
    // populated, so the slot drops and the map stays empty.
    let insns_no_evidence = vec![ldx(BPF_SIZE_DW, 2, 1, 8), ldx(BPF_SIZE_DW, 3, 2, 0), exit()];
    let map_no_evidence = analyze_casts(
        &insns_no_evidence,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map_no_evidence.is_empty(),
        "shape inference without `arena_confirmed` / `arena_stx_findings` \
             must drop per the F1 mitigation: {map_no_evidence:?}"
    );

    // (b) WITH addr_space_cast on the LoadedU64Field source: the
    // cast populates `arena_confirmed` for (T, 8); the same
    // (offset=0, size=8) access is now matched against Q with
    // direct evidence, so the finding emits. Establishes that
    // (a)'s empty result is attributable specifically to the F1
    // gate — without this companion the drop could be explained
    // by an unrelated analysis defect (e.g. shape inference itself
    // failing to match Q's layout for some other reason).
    let insns_with_evidence = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(4, 2, 1),
        ldx(BPF_SIZE_DW, 3, 4, 0),
        exit(),
    ];
    let map_with_evidence = analyze_casts(
        &insns_with_evidence,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map_with_evidence.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "with addr_space_cast evidence the same shape MUST emit, \
             proving (a)'s empty result is the F1 gate firing: \
             {map_with_evidence:?}"
    );
}

/// F1 mitigation, multi-offset disambiguation form: a program
/// whose access pattern uniquely intersects to one candidate
/// (`Q { u64 @ 0; u32 @ 8 }`) but lacks ANY direct arena
/// evidence — neither a `BPF_ADDR_SPACE_CAST` nor an STX-flow
/// allocator-return tag — must drop. Pin the gate against
/// hostile-aarch64 regressions where a 33-bit-shaped counter
/// would fall inside the 4 GiB arena window at chase time and
/// render as a chased pointer if shape inference alone were
/// allowed to emit.
///
/// Distinct from `shape_inference_alone_drops_without_arena_confirmed`:
/// that test uses a single-access (size=8 @ 0) shape and pairs
/// the empty-without-evidence with a with-evidence companion.
/// This test exercises the multi-access intersection path —
/// `(offset=0, size=8)` AND `(offset=8, size=4)` together pin
/// the candidate set to exactly Q via shape inference, so the
/// drop guards the gate against any future rewrite that
/// preserves single-offset rejection but allows multi-offset
/// shapes to slip through.
#[test]
fn f1_mitigation_rejects_shape_inference_without_evidence() {
    // BTF: u64(1), u32(2), T(3, u64@8), Q(4, u64@0+u32@8). Q is
    // the ONLY struct in the BTF whose layout satisfies both
    // (offset=0, size=8) and (offset=8, size=4), so shape
    // inference would resolve to Q if the F1 gate weren't here.
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_u32 = push_name(&mut strings, "u32");
    let n_t = push_name(&mut strings, "T");
    let n_q = push_name(&mut strings, "Q");
    let n_f = push_name(&mut strings, "f");
    let n_a = push_name(&mut strings, "a");
    let n_b = push_name(&mut strings, "b");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Int {
            name_off: n_u32,
            size: 4,
            encoding: 0,
            offset: 0,
            bits: 32,
        },
        SynType::Struct {
            name_off: n_t,
            size: 16,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        SynType::Struct {
            name_off: n_q,
            size: 12,
            members: vec![
                SynMember {
                    name_off: n_a,
                    type_id: 1,
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_b,
                    type_id: 2,
                    byte_offset: 8,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 3;
    // Sequence: r2 = T.f, r3 = *(u64*)(r2 + 0), r4 = *(u32*)(r2 + 8).
    // Pattern entries: {(0, 8), (8, 4)}; intersection in
    // `build_layout_index` resolves to {Q} uniquely. NO
    // addr_space_cast, NO pseudo_call+SubprogReturn — neither
    // `arena_confirmed` nor `arena_stx_findings` populated for
    // (T, 8). The F1 gate at the head of the arena-emit loop
    // drops the slot.
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        ldx(BPF_SIZE_W, 4, 2, 8),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "multi-offset shape inference with NO direct arena evidence \
             (no addr_space_cast, no STX-flow tag) must drop per F1 \
             mitigation: {map:?}"
    );
}

#[test]
fn ambiguous_targets_drop_silently() {
    // Build BTF with two structs having a u64 at offset 0
    // (both Q1 and Q2 match the access pattern). Cast must NOT
    // be recorded because false positives are unacceptable.
    let mut strings: Vec<u8> = vec![0];
    let n_int = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_q1 = push_name(&mut strings, "Q1");
    let n_q2 = push_name(&mut strings, "Q2");
    let n_f = push_name(&mut strings, "f");
    let n_x = push_name(&mut strings, "x");
    let types = vec![
        SynType::Int {
            name_off: n_int,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 16,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        SynType::Struct {
            name_off: n_q1,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Struct {
            name_off: n_q2,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![ldx(BPF_SIZE_DW, 2, 1, 8), ldx(BPF_SIZE_DW, 3, 2, 0), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: 2,
        }],
        &[],
        &[],
        &[],
    );
    assert!(map.is_empty(), "ambiguous candidates must drop: {map:?}");
}

#[test]
fn multi_offset_disambiguates_target() {
    // Two Q-shaped structs differ by their second offset:
    //   Q1: { u64 @0; u64 @8 }
    //   Q2: { u64 @0; u32 @8 }
    // When the BPF program reads both Q->@0 (u64) and
    // Q->@8 (u64), only Q1 fits. The intersection-based
    // matcher must converge to Q1.
    let mut strings: Vec<u8> = vec![0];
    let n_u32 = push_name(&mut strings, "u32");
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_q1 = push_name(&mut strings, "Q1");
    let n_q2 = push_name(&mut strings, "Q2");
    let n_f = push_name(&mut strings, "f");
    let n_a = push_name(&mut strings, "a");
    let n_b = push_name(&mut strings, "b");
    let types = vec![
        SynType::Int {
            name_off: n_u32,
            size: 4,
            encoding: 0,
            offset: 0,
            bits: 32,
        },
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 16,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 2,
                byte_offset: 8,
            }],
        },
        SynType::Struct {
            name_off: n_q1,
            size: 16,
            members: vec![
                SynMember {
                    name_off: n_a,
                    type_id: 2,
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_b,
                    type_id: 2,
                    byte_offset: 8,
                },
            ],
        },
        SynType::Struct {
            name_off: n_q2,
            size: 16,
            members: vec![
                SynMember {
                    name_off: n_a,
                    type_id: 2,
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_b,
                    type_id: 1,
                    byte_offset: 8,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 3;
    let q1_id = 4;
    // Sequence: load r1->T.f (offset 8) into r2; cast r2 to
    // arena_confirmed (F1 mitigation prerequisite); then deref
    // the cast result at offset 0 (8 bytes) and offset 8 (8 bytes).
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        ldx(BPF_SIZE_DW, 4, 2, 8),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q1_id,
            addr_space: AddrSpace::Arena,
        }),
        "map: {map:?}"
    );
}

#[test]
fn multiple_distinct_casts_recorded() {
    // T has TWO u64 fields, each loaded and dereferenced as a
    // distinct target struct. Q1 has u64@8 only (no @0). Q2
    // has u64@0 + u32@8. The two cast access patterns each
    // narrow to a single candidate.
    let mut strings: Vec<u8> = vec![0];
    let n_u32 = push_name(&mut strings, "u32");
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_q1 = push_name(&mut strings, "Q1");
    let n_q2 = push_name(&mut strings, "Q2");
    let n_f1 = push_name(&mut strings, "f1");
    let n_f2 = push_name(&mut strings, "f2");
    let n_a = push_name(&mut strings, "a");
    let n_b = push_name(&mut strings, "b");
    let types = vec![
        SynType::Int {
            name_off: n_u32,
            size: 4,
            encoding: 0,
            offset: 0,
            bits: 32,
        },
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 24,
            members: vec![
                SynMember {
                    name_off: n_f1,
                    type_id: 2,
                    byte_offset: 8,
                },
                SynMember {
                    name_off: n_f2,
                    type_id: 2,
                    byte_offset: 16,
                },
            ],
        },
        SynType::Struct {
            name_off: n_q1,
            size: 16,
            members: vec![SynMember {
                name_off: n_a,
                type_id: 2,
                byte_offset: 8,
            }],
        },
        SynType::Struct {
            name_off: n_q2,
            size: 12,
            members: vec![
                SynMember {
                    name_off: n_a,
                    type_id: 2,
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_b,
                    type_id: 1,
                    byte_offset: 8,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    // Type ids per `types` order: u32=1, u64=2, T=3, Q1=4, Q2=5.
    let t_id = 3;
    let q1_id = 4;
    let q2_id = 5;

    // Cast 1: T.f1 -> *(Q1*). Read at offset 8 (8 bytes) only;
    // Q1 matches, Q2 has u32@8 (4 bytes) so does not match.
    // Cast 2: T.f2 -> *(Q2*). Read at offset 0 (8 bytes) and
    // offset 8 (4 bytes). Q1 lacks @0 → only Q2 matches.
    // Each LoadedU64Field gets an addr_space_cast applied to it
    // (F1 mitigation prerequisite for shape-inference findings).
    let insns = vec![
        // r2 = *(u64 *)(r1 + 8)  -- T.f1 → r2
        ldx(BPF_SIZE_DW, 2, 1, 8),
        // r2 = arena_cast(r2)    -- arena_confirmed for (T, 8)
        addr_space_cast(2, 2, 1),
        // r3 = *(u64 *)(r2 + 8)  -- (T.f1 → Q1).a (offset 8, size 8)
        ldx(BPF_SIZE_DW, 3, 2, 8),
        // Reset r2's loaded-state by overwriting via mov_k.
        mov_k(2, 0),
        // r2 = *(u64 *)(r1 + 16) -- T.f2 → r2
        ldx(BPF_SIZE_DW, 2, 1, 16),
        // r2 = arena_cast(r2)    -- arena_confirmed for (T, 16)
        addr_space_cast(2, 2, 1),
        // r4 = *(u64 *)(r2 + 0)  -- (T.f2 → Q2).a (offset 0, size 8)
        ldx(BPF_SIZE_DW, 4, 2, 0),
        // r5 = *(u32 *)(r2 + 8)  -- (T.f2 → Q2).b (offset 8, size 4)
        ldx(BPF_SIZE_W, 5, 2, 8),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q1_id,
            addr_space: AddrSpace::Arena,
        }),
        "f1: {map:?}"
    );
    assert_eq!(
        map.get(&(t_id, 16)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q2_id,
            addr_space: AddrSpace::Arena,
        }),
        "f2: {map:?}"
    );
}

#[test]
fn register_reuse_after_call_clears_state() {
    // Load T.f into r2, then BPF_CALL clobbers r0..r5. The
    // dereference of the post-call r2 must NOT be attributed
    // to the pre-call source.
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8), // r2 = T.f
        call(),                    // clobbers r0..r5
        ldx(BPF_SIZE_DW, 3, 2, 0), // r2 is Unknown now
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "post-call r2 must not retain T.f source: {map:?}"
    );
}

#[test]
fn nondw_load_does_not_track_u64_field() {
    // r2 = *(u32 *)(r1 + 8)  -- not a 64-bit load, cannot carry
    // a pointer. Subsequent deref must not be attributed.
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![ldx(BPF_SIZE_W, 2, 1, 8), ldx(BPF_SIZE_DW, 3, 2, 0), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(map.is_empty(), "32-bit load must not seed cast: {map:?}");
}

#[test]
fn ptr_field_tracked_as_typed_pointer_not_cast() {
    // T.field is declared as `Q *` in BTF (already typed). The
    // analyzer follows the chain to mark the loaded register
    // as a Q*, but does NOT record a cast (renderer already
    // chases declared Ptr fields).
    let mut strings: Vec<u8> = vec![0];
    let n_int = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_q = push_name(&mut strings, "Q");
    let n_f = push_name(&mut strings, "f");
    let n_x = push_name(&mut strings, "x");
    let types = vec![
        // id 1: u64
        SynType::Int {
            name_off: n_int,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        // id 2: struct Q { u64 x @0 }
        SynType::Struct {
            name_off: n_q,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        // id 3: Q* (pointer to id=2)
        SynType::Ptr { type_id: 2 },
        // id 4: struct T { Q* f @8 }
        SynType::Struct {
            name_off: n_t,
            size: 16,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 3,
                byte_offset: 8,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 4;
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8), // r2 = T.f -- typed Q* per BTF
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "typed Ptr field must not be recorded as cast: {map:?}"
    );
}

#[test]
fn null_check_fall_through_preserves_state() {
    // if r2 <COND> 0 goto SKIP; deref r2; SKIP: exit.
    // The deref happens at the FALL-THROUGH after the
    // conditional jump, so the state survives. The analyzer
    // should still record the cast across every supported
    // conditional-jump op-code: per linux uapi `bpf_common.h`
    // and `bpf.h` the JMP class accepts JEQ=0x10, JGT=0x20,
    // JGE=0x30, JNE=0x50, JSGT=0x60, JSGE=0x70, JLT=0xa0,
    // JLE=0xb0, JSLT=0xc0, JSLE=0xd0 (JSET=0x40 also branches
    // but takes a bitmask not a comparison; covered too). Each
    // pairs with BPF_SRC_K (0x00) for an immediate operand; the
    // K and X variants share the same off-relative branch
    // encoding so testing K covers both as far as
    // `jump_targets()` is concerned. JMP32 class mirrors the
    // op codes; covered with BPF_CLASS_JMP32 | BPF_JEQ to verify
    // class-bit independence. None of these touch register
    // state in `step()` (only BPF_OP_CALL clears registers per
    // line ~726), so every variant must preserve the
    // pre-jump LoadedU64Field on the fall-through path.
    let (blob, t_id, q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    // BPF_SRC_K is 0; OR with BPF_SRC_X (0x08) for the X-form
    // smoke test on JEQ to confirm src-kind has no effect on
    // jump-target detection or fall-through state preservation.
    let variants: &[(u8, &str)] = &[
        (BPF_CLASS_JMP | 0x10, "JEQ_K"),
        (BPF_CLASS_JMP | 0x10 | BPF_SRC_X, "JEQ_X"),
        (BPF_CLASS_JMP | 0x20, "JGT_K"),
        (BPF_CLASS_JMP | 0x30, "JGE_K"),
        (BPF_CLASS_JMP | 0x40, "JSET_K"),
        (BPF_CLASS_JMP | 0x50, "JNE_K"),
        (BPF_CLASS_JMP | 0x60, "JSGT_K"),
        (BPF_CLASS_JMP | 0x70, "JSGE_K"),
        (BPF_CLASS_JMP | 0xa0, "JLT_K"),
        (BPF_CLASS_JMP | 0xb0, "JLE_K"),
        (BPF_CLASS_JMP | 0xc0, "JSLT_K"),
        (BPF_CLASS_JMP | 0xd0, "JSLE_K"),
        (BPF_CLASS_JMP32 | 0x10, "JEQ32_K"),
    ];
    for (code, label) in variants {
        // pc 0: r2 = T.f
        // pc 1: if r2 <COND> 0 goto +1 (jump to pc=3, skip deref)
        // pc 2: r3 = *r2  (fall-through; r2 still LoadedU64Field)
        // pc 3: exit.
        // BPF_ADDR_SPACE_CAST adds arena_confirmed evidence
        // (F1 mitigation prerequisite). Apply BEFORE the
        // conditional jump so the cast lands on the source
        // u64 value, not the (already-typed) cast result.
        let jcc = mk_insn(*code, 2, 0, 1, 0);
        let insns = vec![
            ldx(BPF_SIZE_DW, 2, 1, 8),
            addr_space_cast(2, 2, 1),
            jcc,
            ldx(BPF_SIZE_DW, 3, 2, 0),
            exit(),
        ];
        let map = analyze_casts(
            &insns,
            &btf,
            &[InitialReg {
                reg: 1,
                struct_type_id: t_id,
            }],
            &[],
            &[],
            &[],
        );
        assert_eq!(
            map.len(),
            1,
            "{label}: exactly one cast expected on fall-through, got: {map:?}"
        );
        assert_eq!(
            map.get(&(t_id, 8)),
            Some(&CastHit {
                alloc_size: None,
                target_type_id: q_id,
                addr_space: AddrSpace::Arena,
            }),
            "{label}: fall-through deref must record: {map:?}"
        );
    }
}

#[test]
fn deref_at_jump_target_is_dropped() {
    // if r2 != 0 goto USE; ... USE: deref r2.
    // The deref is at the branch target, where state is reset
    // by the conservative join handler. False negative is
    // acceptable.
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    // pc 0: r2 = T.f
    // pc 1: if r2 != 0 goto +1 (= pc 3, the deref)
    // pc 2: exit (skipped on the taken branch)
    // pc 3: r3 = *r2  -- STATE WAS RESET at pc 3 (target).
    // pc 4: exit.
    let jne = mk_insn(BPF_CLASS_JMP | 0x50, 2, 0, 1, 0); // BPF_JNE_K = 0x50
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        jne,
        exit(),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(map.is_empty(), "deref at branch target must drop: {map:?}");
}

#[test]
fn mov_x_propagates_loaded_state() {
    // r2 = T.f; r2 = arena_cast(r2); r4 = r2; deref r4 at offset 0.
    // The MOV r4, r2 propagates LoadedU64Field after the
    // arena_confirmed evidence is recorded (F1 mitigation).
    let (blob, t_id, q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        mov_x(4, 2),
        ldx(BPF_SIZE_DW, 3, 4, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "MOV must propagate: {map:?}"
    );
}

#[test]
fn ld_imm64_skips_second_slot() {
    // BPF_LD_IMM64 is two slots; the second slot's `code` is 0.
    // A bare 0-code insn must not be misinterpreted as anything
    // active. After the two-slot insn, normal flow continues.
    let (blob, t_id, q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let ld_imm64_lo = mk_insn(BPF_CLASS_LD | BPF_SIZE_DW | BPF_MODE_IMM, 6, 0, 0, 0);
    let ld_imm64_hi = mk_insn(0, 0, 0, 0, 0);
    let insns = vec![
        ld_imm64_lo,
        ld_imm64_hi,
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "LD_IMM64 second slot must skip: {map:?}"
    );
}

#[test]
fn r10_seed_rejected() {
    // Seeding the frame pointer is silently dropped — even
    // when the BTF type id is valid. Nothing tracks r10.
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 10, 8),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 10,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(map.is_empty(), "r10 seed must be ignored: {map:?}");
}

#[test]
fn nonu64_field_at_source_offset_not_tracked() {
    // T has a u32 at offset 8 (not u64). Loading from there
    // and treating as a pointer is meaningless — the analyzer
    // must not seed LoadedU64Field.
    let mut strings: Vec<u8> = vec![0];
    let n_u32 = push_name(&mut strings, "u32");
    let n_t = push_name(&mut strings, "T");
    let n_f = push_name(&mut strings, "f");
    let types = vec![
        SynType::Int {
            name_off: n_u32,
            size: 4,
            encoding: 0,
            offset: 0,
            bits: 32,
        },
        SynType::Struct {
            name_off: n_t,
            size: 12,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 1,
                byte_offset: 8,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let insns = vec![ldx(BPF_SIZE_DW, 2, 1, 8), ldx(BPF_SIZE_DW, 3, 2, 0), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "u32-typed field must not seed cast: {map:?}"
    );
}

// ----- Kptr detection helpers ---------------------------------
//
// Kptr tests share a BTF shape: a "task_struct"-like target T,
// a parent struct P with a `u64 slot @ off` field, and the
// appropriate FuncProto / Func types when a function-entry
// seeding test calls them out. The helper keeps each test
// focused on the instruction sequence under examination.

/// Build a BTF blob with:
/// - id 1: u64
/// - id 2: struct T { u64 x @ 0 }   ("task_struct" stand-in)
/// - id 3: T*  (pointer to id=2)
/// - id 4: struct P { u64 slot @ slot_off }
///
/// Returns (blob, T_id, P_id, T_ptr_id). Tests that need a
/// FuncProto add it on top of this blob.
fn btf_kptr_base(slot_off: u32) -> (Vec<u8>, u32, u32, u32) {
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_p = push_name(&mut strings, "P");
    let n_x = push_name(&mut strings, "x");
    let n_slot = push_name(&mut strings, "slot");
    let types = vec![
        // id 1: u64
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        // id 2: struct T { u64 x @ 0 }
        SynType::Struct {
            name_off: n_t,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        // id 3: T*
        SynType::Ptr { type_id: 2 },
        // id 4: struct P { u64 slot @ slot_off }
        SynType::Struct {
            name_off: n_p,
            size: slot_off + 8,
            members: vec![SynMember {
                name_off: n_slot,
                type_id: 1,
                byte_offset: slot_off,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    (blob, 2, 4, 3)
}

#[test]
fn kptr_from_function_param_stored_to_u64_field() {
    // R1 starts as T* (param[0]).
    // R6 = R1 (preserve across the rest).
    // R2 = some P* (the parent struct holding the kptr slot).
    //   We don't have a separate P param so seed R2 directly.
    // *(u64 *)(R2 + slot_off) = R6
    //   - R2 is Pointer{P}, R6 is Pointer{T}, field is u64 ->
    //     map records (P, slot_off) -> (T, AddrSpace::Kernel).
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![mov_x(6, 1), stx(BPF_SIZE_DW, 2, 6, slot_off as i16), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 2,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(p_id, slot_off)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "kptr STX must record kernel-space cast: {map:?}"
    );
}

#[test]
fn kptr_through_stack_spill() {
    // R1 starts as T*; spill to [r10-8]; reload into R3; store
    // R3 into the parent slot. Tests that stack spill / reload
    // preserves the typed-pointer state.
    //
    //   *(u64 *)(r10 - 8) = R1     ; spill T*
    //   R3 = *(u64 *)(r10 - 8)     ; reload as T*
    //   *(u64 *)(R4 + slot_off) = R3
    let slot_off: u32 = 24;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![
        stx(BPF_SIZE_DW, 10, 1, -8), // spill R1
        ldx(BPF_SIZE_DW, 3, 10, -8), // reload to R3
        stx(BPF_SIZE_DW, 4, 3, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 4,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(p_id, slot_off)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "stack spill must preserve typed pointer: {map:?}"
    );
}

#[test]
fn kptr_from_kfunc_return() {
    // BTF layout reused across this test:
    //   id 1: u64
    //   id 2: struct T { u64 x @ 0 }
    //   id 3: T*
    //   id 4: struct P { u64 slot @ 16 }
    //   id 5: FuncProto returning T*  (return_type_id = 3)
    //   id 6: Func("bpf_task_acquire") -> id 5
    //
    // Sequence:
    //   call kfunc id=6
    //   *(u64 *)(R6 + 16) = R0   ; R6 is P*
    let slot_off: u32 = 16;
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_p = push_name(&mut strings, "P");
    let n_x = push_name(&mut strings, "x");
    let n_slot = push_name(&mut strings, "slot");
    let n_kfunc = push_name(&mut strings, "bpf_task_acquire");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Ptr { type_id: 2 },
        SynType::Struct {
            name_off: n_p,
            size: slot_off + 8,
            members: vec![SynMember {
                name_off: n_slot,
                type_id: 1,
                byte_offset: slot_off,
            }],
        },
        // id 5: FuncProto -> T*
        SynType::FuncProto {
            return_type_id: 3,
            params: vec![],
        },
        // id 6: Func bpf_task_acquire (linkage = global)
        SynType::Func {
            name_off: n_kfunc,
            type_id: 5,
            linkage: 1,
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let p_id = 4;
    let kfunc_id = 6;
    let insns = vec![
        kfunc_call(kfunc_id),
        stx(BPF_SIZE_DW, 6, 0, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: p_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(p_id, slot_off)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "kfunc-returned T* stored to P.slot must record: {map:?}"
    );
}

#[test]
fn kptr_clobbered_by_call() {
    // R1 starts as T*. A non-kfunc BPF_CALL clobbers R0..R5.
    // The post-call STX of R1 must NOT record a kptr — R1 is
    // Unknown after the helper call.
    //
    //   call helper        ; clobbers R0..R5
    //   *(u64 *)(R6 + 16) = R1   ; R1 was clobbered
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![call(), stx(BPF_SIZE_DW, 6, 1, slot_off as i16), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "post-call clobbered R1 must not record kptr: {map:?}"
    );
}

#[test]
fn mixed_arena_and_kptr_in_one_program() {
    // Single BTF, single instruction sequence: trigger BOTH
    // detection paths.
    //
    // BTF:
    //   id 1: u64
    //   id 2: struct T { u64 x @ 0 }     (kernel kptr target)
    //   id 3: T*
    //   id 4: struct A { u64 a0 @ 0; u64 a1 @ 8 }  (arena target)
    //   id 5: struct M {                ; map value
    //           u64 arena_ptr @ 0;     ; carries A*
    //           u64 kptr      @ 16;    ; carries T*
    //         }
    //
    // Instructions:
    //   r1 := M*        (seed via InitialReg)
    //   r6 := T*        (seed via InitialReg, separate value)
    //   r2 = *(u64 *)(r1 + 0)    ; load M.arena_ptr -> r2 = LoadedU64Field
    //   r3 = *(u64 *)(r2 + 0)    ; deref @0 (u64) -> records access
    //   r4 = *(u64 *)(r2 + 8)    ; deref @8 (u64) -> records access
    //                            ;   intersection -> A (unique match)
    //   *(u64 *)(r1 + 16) = r6   ; STX of T* into M.kptr -> Kernel cast
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_a = push_name(&mut strings, "A");
    let n_m = push_name(&mut strings, "M");
    let n_x = push_name(&mut strings, "x");
    let n_a0 = push_name(&mut strings, "a0");
    let n_a1 = push_name(&mut strings, "a1");
    let n_arena_ptr = push_name(&mut strings, "arena_ptr");
    let n_kptr = push_name(&mut strings, "kptr");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Ptr { type_id: 2 },
        SynType::Struct {
            name_off: n_a,
            size: 16,
            members: vec![
                SynMember {
                    name_off: n_a0,
                    type_id: 1,
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_a1,
                    type_id: 1,
                    byte_offset: 8,
                },
            ],
        },
        SynType::Struct {
            name_off: n_m,
            size: 24,
            members: vec![
                SynMember {
                    name_off: n_arena_ptr,
                    type_id: 1,
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_kptr,
                    type_id: 1,
                    byte_offset: 16,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let a_id = 4;
    let m_id = 5;
    let insns = vec![
        // Arena LDX path with arena_confirmed evidence (F1).
        ldx(BPF_SIZE_DW, 2, 1, 0),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        ldx(BPF_SIZE_DW, 4, 2, 8),
        // Kernel STX path.
        stx(BPF_SIZE_DW, 1, 6, 16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: m_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: t_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(m_id, 0)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: a_id,
            addr_space: AddrSpace::Arena,
        }),
        "arena cast missing: {map:?}"
    );
    assert_eq!(
        map.get(&(m_id, 16)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "kernel kptr missing: {map:?}"
    );
}

#[test]
fn func_entry_seeding_from_btf() {
    // FuncProto with two parameters: param 0 = T* (typed
    // source), param 1 = P* (parent base). FuncEntry seeds
    // R1 = Pointer{T} and R2 = Pointer{P}. R3..R5 must remain
    // Unknown — the FuncProto only describes two parameters,
    // and `seed_from_func_proto()` walks `proto.parameters`
    // (not R3..R5 unconditionally). InitialReg state set
    // before the run does not survive into a function entry
    // at PC 0.
    //
    // The strengthened test verifies BOTH halves:
    //   1. R1 and R2 are typed → STX through R2 records
    //      (P, slot1) -> T at the slot dedicated to the seeded
    //      param.
    //   2. R3, R4, R5 stay Unknown → STX through each into a
    //      distinct u64 slot in P records nothing. If
    //      `seed_from_func_proto()` accidentally typed R3..R5
    //      from leftover state or over-walked the parameter
    //      list, those stores would record (P, slotN) -> T
    //      and the count assertion would fire.
    let slot1: u32 = 16; // store R1 -> P (typed, must record)
    let slot3: u32 = 24; // store R3 -> P (must NOT record)
    let slot4: u32 = 32; // store R4 -> P (must NOT record)
    let slot5: u32 = 40; // store R5 -> P (must NOT record)
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_p = push_name(&mut strings, "P");
    let n_x = push_name(&mut strings, "x");
    let n_s1 = push_name(&mut strings, "s1");
    let n_s3 = push_name(&mut strings, "s3");
    let n_s4 = push_name(&mut strings, "s4");
    let n_s5 = push_name(&mut strings, "s5");
    let n_arg_t = push_name(&mut strings, "task");
    let n_arg_p = push_name(&mut strings, "parent");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Ptr { type_id: 2 }, // id 3: T*
        SynType::Struct {
            name_off: n_p,
            size: slot5 + 8,
            members: vec![
                SynMember {
                    name_off: n_s1,
                    type_id: 1,
                    byte_offset: slot1,
                },
                SynMember {
                    name_off: n_s3,
                    type_id: 1,
                    byte_offset: slot3,
                },
                SynMember {
                    name_off: n_s4,
                    type_id: 1,
                    byte_offset: slot4,
                },
                SynMember {
                    name_off: n_s5,
                    type_id: 1,
                    byte_offset: slot5,
                },
            ],
        },
        SynType::Ptr { type_id: 4 }, // id 5: P*
        // id 6: FuncProto(T*, P*) -> void. Only two params, so
        // FuncEntry only seeds R1 and R2 — R3, R4, R5 must
        // stay Unknown.
        SynType::FuncProto {
            return_type_id: 0,
            params: vec![
                SynParam {
                    name_off: n_arg_t,
                    type_id: 3,
                },
                SynParam {
                    name_off: n_arg_p,
                    type_id: 5,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let p_id = 4;
    let proto_id = 6;
    // STX *(R2 + slot1) = R1   ; R1=T, R2=P → records (P, slot1) -> T
    // STX *(R2 + slot3) = R3   ; R3=Unknown → no record
    // STX *(R2 + slot4) = R4   ; R4=Unknown → no record
    // STX *(R2 + slot5) = R5   ; R5=Unknown → no record
    let insns = vec![
        stx(BPF_SIZE_DW, 2, 1, slot1 as i16),
        stx(BPF_SIZE_DW, 2, 3, slot3 as i16),
        stx(BPF_SIZE_DW, 2, 4, slot4 as i16),
        stx(BPF_SIZE_DW, 2, 5, slot5 as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[],
        &[FuncEntry {
            insn_offset: 0,
            func_proto_id: proto_id,
        }],
        &[],
        &[],
    );
    assert_eq!(
        map.len(),
        1,
        "FuncEntry must seed only R1 and R2; R3..R5 stay Unknown so \
             only the R1->slot1 STX records: {map:?}"
    );
    assert_eq!(
        map.get(&(p_id, slot1)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "FuncEntry param seeding must populate R1 and R2: {map:?}"
    );
    // Adversary check: the failure modes we are guarding against
    // would emit (P, slot3/4/5) -> T. Assert each absent.
    assert!(
        !map.contains_key(&(p_id, slot3)),
        "R3 must remain Unknown post-FuncEntry: {map:?}"
    );
    assert!(
        !map.contains_key(&(p_id, slot4)),
        "R4 must remain Unknown post-FuncEntry: {map:?}"
    );
    assert!(
        !map.contains_key(&(p_id, slot5)),
        "R5 must remain Unknown post-FuncEntry: {map:?}"
    );
}

// ----- BPF_ADDR_SPACE_CAST tests ------------------------------

/// `BPF_ADDR_SPACE_CAST` arena -> kernel (`imm == 1`) on a
/// `LoadedU64Field` source populates `arena_confirmed` but does
/// NOT produce a standalone map entry when no subsequent deref
/// refines the target via shape inference. Without a resolved
/// target type, the renderer cannot chase — emitting a
/// placeholder would produce worse output than the raw u64
/// fallback. The cast evidence participates only in conflict
/// detection (preventing a kptr finding from claiming the slot).
///
/// The "no emit alone" fact must be distinguished from the failure
/// mode where the cast is silently ignored — both produce an
/// empty map. The test runs three analyses to nail down which
/// branch is exercised:
///   1. cast alone           → empty (arena_confirmed populated,
///      but no deref pattern).
///   2. cast + same-slot STX → empty (arena_confirmed conflicts
///      with kptr_findings, both drop).
///   3. same-slot STX alone  → kptr finding emits.
///
/// (1) + (2) - (3) prove arena_confirmed was populated by the
/// cast: if it were not, (2) would emit the kptr finding just as
/// (3) does, contradicting the empty result.
#[test]
fn addr_space_cast_arena_alone_does_not_emit() {
    let (blob, t_id, q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();

    // (1) cast alone — current behavior. arena_confirmed must
    // be populated for (T, 8) but no map entry emitted.
    // r3 = *(u64 *)(r1 + 8)         ; r3 = LoadedU64Field{T, 8}
    // r4 = (cast as(1) -> as(0)) r3 ; arena_confirmed += (T, 8)
    let cast = mk_insn(BPF_CLASS_ALU64 | BPF_OP_MOV | BPF_SRC_X, 4, 3, 1, 1);
    let insns_cast_only = vec![ldx(BPF_SIZE_DW, 3, 1, 8), cast, exit()];
    let map_cast_only = analyze_casts(
        &insns_cast_only,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map_cast_only.is_empty(),
        "arena_confirmed alone (no deref pattern) must not emit: {map_cast_only:?}"
    );

    // (2) cast + STX of Pointer{Q} into the same slot. If
    // arena_confirmed for (T, 8) was populated by the cast,
    // the conflict-detection chain in `finalize()` drops both
    // observations and the map stays empty. If the cast did
    // NOT populate arena_confirmed, no conflict and the kptr
    // finding (T, 8) -> Q emits.
    // r3 = *(u64 *)(r1 + 8)            ; LoadedU64Field source
    // r4 = (cast as(1) -> as(0)) r3    ; arena_confirmed += (T, 8)
    // *(u64 *)(r1 + 8) = r5            ; kptr_findings += (T, 8) -> Q
    let insns_cast_plus_kptr = vec![
        ldx(BPF_SIZE_DW, 3, 1, 8),
        cast,
        stx(BPF_SIZE_DW, 1, 5, 8),
        exit(),
    ];
    let map_cast_plus_kptr = analyze_casts(
        &insns_cast_plus_kptr,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 5,
                struct_type_id: q_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map_cast_plus_kptr.is_empty(),
        "cast + same-slot STX must conflict-drop both observations \
             (proves arena_confirmed was populated): {map_cast_plus_kptr:?}"
    );

    // (3) STX alone — no cast, so arena_confirmed stays empty
    // and the kptr finding emits. Establishes the baseline
    // "STX would have recorded" so that (2)'s empty result is
    // attributable to the conflict, not to a non-functional
    // STX path.
    let insns_kptr_only = vec![stx(BPF_SIZE_DW, 1, 5, 8), exit()];
    let map_kptr_only = analyze_casts(
        &insns_kptr_only,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 5,
                struct_type_id: q_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map_kptr_only.len(),
        1,
        "STX-only baseline must record exactly one kptr finding: {map_kptr_only:?}"
    );
    assert_eq!(
        map_kptr_only.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Kernel,
        }),
        "STX-only baseline records (T, 8) -> (Q, Kernel): {map_kptr_only:?}"
    );
}

/// `BPF_ADDR_SPACE_CAST` kernel -> arena (`imm == 0x10000`) drops
/// the destination register state. Per kernel `verifier.c
/// check_alu_op` the result is a 32-bit arena address, not a
/// kernel pointer the analyzer can track. A subsequent LDX
/// through the cast result must NOT record any access pattern,
/// so no entry appears in the output map. Production line
/// (`set_reg(dst, Unknown)` under the kernel->arena branch)
/// touches ONLY dst — src must retain its prior `LoadedU64Field`
/// state, otherwise an unrelated deref through src would also
/// stop recording, masking real cast evidence.
#[test]
fn addr_space_cast_kernel_to_arena_drops_dst() {
    let (blob, t_id, q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    // r3 = *(u64 *)(r1 + 8)            ; r3 = LoadedU64Field{T, 8}
    // r4 = (cast as(0) -> as(1)) r3    ; r4 = Unknown specifically
    // r5 = *(u64 *)(r4 + 0)            ; r4 Unknown -> no record
    // r6 = *(u64 *)(r3 + 0)            ; r3 retained -> records
    // The trailing deref through r3 distinguishes
    // "dst Unknown, src preserved" (correct) from "both
    // clobbered" (regression where the cast spilled into src).
    let cast = mk_insn(BPF_CLASS_ALU64 | BPF_OP_MOV | BPF_SRC_X, 4, 3, 1, 0x10000);
    // F1 mitigation: include an arena→kernel cast on r3 to
    // populate `arena_confirmed` for `(T, 8)`. Without it,
    // shape inference alone would not emit the finding. The
    // cast targets a fresh register so r3 retains its
    // `LoadedU64Field` state for the trailing deref.
    let arena_confirm = addr_space_cast(7, 3, 1);
    let insns = vec![
        ldx(BPF_SIZE_DW, 3, 1, 8),
        arena_confirm,
        cast,
        ldx(BPF_SIZE_DW, 5, 4, 0),
        ldx(BPF_SIZE_DW, 6, 3, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    // The deref through r3 unique-resolves to Q (the only
    // BTF struct with a u64 at offset 0). If r3 had been
    // clobbered, the access pattern would never have been
    // recorded and the map would be empty.
    assert_eq!(
        map.len(),
        1,
        "exactly one cast (via preserved r3) expected: {map:?}"
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "cast preserves src LoadedU64Field; dst-only invalidation: {map:?}"
    );
    // Verify the dst-derived deref produced no entry under
    // any other (source, offset) key — only the (T, 8) ->
    // (Q, Arena) finding from r3 is allowed.
    assert!(
        !map.keys().any(|k| *k != (t_id, 8)),
        "no record may originate from r4 (cast-clobbered dst): {map:?}"
    );
}

/// Sign-extending MOV (`off in {8, 16, 32}`) destroys the typed-
/// pointer property — a sign-extended s8/s16/s32 cannot survive
/// as a 64-bit pointer. Production drops dst to Unknown; a
/// subsequent deref through the resulting register must not
/// record any cast.
#[test]
fn sign_extend_mov_drops_state() {
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    // r3 = *(u64 *)(r1 + 8)         ; r3 = LoadedU64Field{T, 8}
    // r4 = (s32) r3                  ; off=8 sign-extend -> Unknown
    // r5 = *(u64 *)(r4 + 0)         ; r4 Unknown -> no record
    let sxt = mk_insn(BPF_CLASS_ALU64 | BPF_OP_MOV | BPF_SRC_X, 4, 3, 8, 0);
    let insns = vec![
        ldx(BPF_SIZE_DW, 3, 1, 8),
        sxt,
        ldx(BPF_SIZE_DW, 5, 4, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "sign-extend MOV must drop typed state: {map:?}"
    );
}

// ----- BPF_ATOMIC tests ---------------------------------------

/// Helper: build a `BPF_STX | BPF_DW | BPF_ATOMIC` instruction
/// with the given atomic-op `imm`. Encoding per kernel uapi
/// `bpf.h`: `code = STX | DW | ATOMIC = 0x03 | 0x18 | 0xc0 = 0xdb`.
fn atomic_stx(dst: u8, src: u8, off: i16, imm: i32) -> BpfInsn {
    mk_insn(
        BPF_CLASS_STX | BPF_SIZE_DW | BPF_MODE_ATOMIC,
        dst,
        src,
        off,
        imm,
    )
}

/// `BPF_XCHG` (`imm == 0xe0 | BPF_FETCH = 0xe1`) overwrites the
/// source register with the prior memory value per kernel uapi
/// `bpf.h`. The analyzer cannot type the prior memory contents,
/// so the source register's typed state is clobbered. A
/// subsequent plain STX of that register into a `u64` slot must
/// NOT produce a kptr finding.
#[test]
fn atomic_xchg_clobbers_src() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // R1 = Pointer{T}; XCHG src=R1 to [R2+0] -> R1 = Unknown.
    // Then STX R1 into P.slot must NOT record because R1 is
    // Unknown post-xchg.
    let insns = vec![
        atomic_stx(2, 1, 0, 0xe0 | BPF_FETCH),
        stx(BPF_SIZE_DW, 6, 1, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "XCHG must clobber src R1 typed state: {map:?}"
    );
}

/// `BPF_CMPXCHG` (`imm == 0xf0 | BPF_FETCH = 0xf1`) overwrites R0
/// with the prior memory value per kernel uapi `bpf.h`,
/// regardless of whether the compare-and-write succeeded. R0's
/// typed state must be clobbered. A subsequent STX of R0 into a
/// `u64` slot must NOT produce a kptr finding.
#[test]
fn atomic_cmpxchg_clobbers_r0() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // Seed R0 = Pointer{T} (analyzer accepts InitialReg.reg in
    // 0..=9). CMPXCHG dst=2, src=1 with imm=0xf1 clobbers R0.
    // Subsequent STX of R0 into P.slot must NOT record.
    let insns = vec![
        atomic_stx(2, 1, 0, 0xf0 | BPF_FETCH),
        stx(BPF_SIZE_DW, 6, 0, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 0,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "CMPXCHG must clobber R0 typed state: {map:?}"
    );
}

/// Non-fetch atomic ops (plain `BPF_ADD`/`AND`/`OR`/`XOR` without
/// the `BPF_FETCH` bit) read-modify-write memory but do not
/// overwrite any register. Source register typed state must
/// survive intact, so a subsequent STX of the source into a
/// `u64` slot still records the kptr finding. Per linux uapi
/// `bpf_common.h`: BPF_ADD=0x00, BPF_OR=0x40, BPF_AND=0x50,
/// BPF_XOR=0xa0. All four flavours must round-trip the source
/// register's `Pointer{T}` state.
#[test]
fn atomic_non_fetch_preserves_regs() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // Iterate every non-fetch atomic op to defend against the
    // failure mode where the analyzer accidentally clobbers
    // `src` for some imm encodings but not others (e.g. a future
    // refactor that special-cases BPF_ADD only). All four ops
    // share the kernel verifier's RMW semantics: mutate memory,
    // no register output. Encoding is the bare top nibble — adding
    // BPF_FETCH (0x01) shifts to the clobbering branch tested by
    // `atomic_xchg_clobbers_src`.
    const BPF_ATOMIC_ADD: i32 = 0x00;
    const BPF_ATOMIC_OR: i32 = 0x40;
    const BPF_ATOMIC_AND: i32 = 0x50;
    const BPF_ATOMIC_XOR: i32 = 0xa0;
    for imm in [
        BPF_ATOMIC_ADD,
        BPF_ATOMIC_OR,
        BPF_ATOMIC_AND,
        BPF_ATOMIC_XOR,
    ] {
        let insns = vec![
            atomic_stx(2, 1, 0, imm),
            stx(BPF_SIZE_DW, 6, 1, slot_off as i16),
            exit(),
        ];
        let map = analyze_casts(
            &insns,
            &btf,
            &[
                InitialReg {
                    reg: 1,
                    struct_type_id: t_id,
                },
                InitialReg {
                    reg: 6,
                    struct_type_id: p_id,
                },
            ],
            &[],
            &[],
            &[],
        );
        assert_eq!(
            map.len(),
            1,
            "imm=0x{imm:02x}: exactly one kptr finding expected, got: {map:?}"
        );
        assert_eq!(
            map.get(&(p_id, slot_off)),
            Some(&CastHit {
                alloc_size: None,
                target_type_id: t_id,
                addr_space: AddrSpace::Kernel,
            }),
            "imm=0x{imm:02x}: non-fetch ATOMIC must preserve src register: {map:?}"
        );
    }
}

/// An `ATOMIC` op targeting `[r10 + neg_off]` mutates a stack
/// slot the analyzer was tracking from a prior spill. The slot's
/// saved value is overwritten by the atomic operation, so a
/// subsequent reload through `r10` must NOT resurrect the
/// pre-atomic typed-pointer state.
#[test]
fn atomic_on_stack_invalidates_slot() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // *(u64 *)(r10 - 8) = R1   ; spill Pointer{T} -> stack[-8]
    // ATOMIC XCHG [r10 - 8] = R2   ; mutates the stack slot
    // R3 = *(u64 *)(r10 - 8)   ; reload must yield Unknown
    // *(u64 *)(R6 + slot_off) = R3 ; R3 Unknown -> no record
    let insns = vec![
        stx(BPF_SIZE_DW, 10, 1, -8),
        atomic_stx(10, 2, -8, 0xe0 | BPF_FETCH),
        ldx(BPF_SIZE_DW, 3, 10, -8),
        stx(BPF_SIZE_DW, 6, 3, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "ATOMIC on stack slot must invalidate, reload yields Unknown: {map:?}"
    );
}

/// `BPF_LOAD_ACQ` (`imm == 0x100`) loads a memory value with
/// acquire-ordered semantics into `dst` per kernel
/// `include/linux/filter.h`. The analyzer cannot type a memory
/// value pulled out via this path, so `dst` is clobbered to
/// `Unknown`. A subsequent STX of `dst` into a `u64` slot must
/// NOT record a kptr finding even though `dst` held a typed
/// pointer prior to the load-acquire.
#[test]
fn atomic_load_acq_clobbers_dst() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // R1 = Pointer{T}; LOAD_ACQ targets dst=1, src=2 (address
    // base) -> R1 = Unknown. Then STX R1 into P.slot must NOT
    // record because R1 is Unknown post-load-acquire.
    let insns = vec![
        atomic_stx(1, 2, 0, BPF_LOAD_ACQ_IMM),
        stx(BPF_SIZE_DW, 6, 1, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "LOAD_ACQ must clobber dst R1 typed state: {map:?}"
    );
}

/// `BPF_STORE_REL` (`imm == 0x110`) stores `src` to memory with
/// release-ordered semantics per kernel
/// `include/linux/filter.h`. `dst` is the address-base register
/// and `src` is the value being stored — neither is overwritten.
/// Both registers' typed-pointer state must survive intact: a
/// subsequent plain STX of either typed pointer into another
/// `u64` slot still records the kptr finding.
#[test]
fn atomic_store_rel_preserves_src_and_dst() {
    // BTF: u64(1), T(2, u64@0), T*(3), P(4, u64@slot_off1, u64@slot_off2).
    // Two distinct slots so we can verify BOTH registers'
    // typed states by storing each into a separate slot.
    let slot_off1: u32 = 16;
    let slot_off2: u32 = 24;
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_p = push_name(&mut strings, "P");
    let n_x = push_name(&mut strings, "x");
    let n_slot1 = push_name(&mut strings, "slot1");
    let n_slot2 = push_name(&mut strings, "slot2");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Ptr { type_id: 2 },
        SynType::Struct {
            name_off: n_p,
            size: slot_off2 + 8,
            members: vec![
                SynMember {
                    name_off: n_slot1,
                    type_id: 1,
                    byte_offset: slot_off1,
                },
                SynMember {
                    name_off: n_slot2,
                    type_id: 1,
                    byte_offset: slot_off2,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let p_id = 4;
    // R1 = Pointer{T}, R2 = Pointer{T}, R6 = Pointer{P}.
    // STORE_REL dst=R7 src=R1: address-base R7, value R1.
    //   R1 must remain Pointer{T}; R7 is uninvolved here.
    // STX *(R6 + slot1) = R1: records (P, slot1) -> T.
    // STX *(R6 + slot2) = R2: records (P, slot2) -> T.
    // If STORE_REL had clobbered R1, the first kptr write
    // would have dropped — but R2 (the unused-by-STORE_REL
    // typed pointer) would still record, giving a partial map.
    // The two-slot assertion discriminates: both slots present
    // proves STORE_REL left R1 alone; only-slot2 present would
    // catch a regression that clobbers R1 specifically.
    let insns = vec![
        atomic_stx(7, 1, 0, BPF_STORE_REL_IMM),
        stx(BPF_SIZE_DW, 6, 1, slot_off1 as i16),
        stx(BPF_SIZE_DW, 6, 2, slot_off2 as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 2,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(p_id, slot_off1)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "STORE_REL must preserve src R1 typed state (slot1 missing): {map:?}"
    );
    assert_eq!(
        map.get(&(p_id, slot_off2)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "STORE_REL must not affect uninvolved R2 (slot2 missing): {map:?}"
    );
}

/// `BPF_STORE_REL` through `r10` writes the stack slot at
/// `[r10 + off]`. Even though STORE_REL has no per-register
/// clobber effect, the stack-slot invalidation arm at the head
/// of `handle_atomic` runs unconditionally for every atomic
/// flavor when `dst == r10`. A prior spill of a typed pointer
/// into the slot is overwritten by the release store, so a
/// subsequent reload through `r10` must NOT resurrect the
/// pre-store-release typed-pointer state.
#[test]
fn atomic_store_rel_invalidates_stack_slot() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // *(u64 *)(r10 - 8) = R1     ; spill Pointer{T} -> stack[-8]
    // STORE_REL [r10 - 8] = R2   ; release-store overwrites slot
    // R3 = *(u64 *)(r10 - 8)     ; reload must yield Unknown
    // *(u64 *)(R6 + slot_off) = R3 ; R3 Unknown -> no record
    let insns = vec![
        stx(BPF_SIZE_DW, 10, 1, -8),
        atomic_stx(10, 2, -8, BPF_STORE_REL_IMM),
        ldx(BPF_SIZE_DW, 3, 10, -8),
        stx(BPF_SIZE_DW, 6, 3, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "STORE_REL through r10 must invalidate slot, reload Unknown: {map:?}"
    );
}

/// `BPF_ADD | BPF_FETCH` (`imm == 0x01`) is an atomic
/// fetch-and-add: src receives the prior memory value, memory
/// receives `memory + src`. Per kernel uapi `bpf.h` and the
/// `has_fetch` arm in `handle_atomic`, src's typed-pointer state
/// is dropped to `Unknown`. A subsequent STX of src into a `u64`
/// slot must NOT record a kptr finding.
#[test]
fn atomic_add_fetch_clobbers_src() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // R1 = Pointer{T}; ADD|FETCH src=R1 to [R2+0] -> R1 = Unknown.
    // Then STX R1 into P.slot must NOT record because R1 is
    // Unknown post-fetch-add. BPF_ADD = 0x00 (linux uapi
    // bpf_common.h) | BPF_FETCH = 0x01.
    let insns = vec![
        atomic_stx(2, 1, 0, BPF_FETCH),
        stx(BPF_SIZE_DW, 6, 1, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "ADD|FETCH must clobber src R1 typed state: {map:?}"
    );
}

/// `BPF_AND | BPF_FETCH` (`imm == 0x51`) is an atomic
/// fetch-and-and: src receives the prior memory value. The
/// `has_fetch` arm in `handle_atomic` drops src to `Unknown`.
/// A subsequent STX of src into a `u64` slot must NOT record.
#[test]
fn atomic_and_fetch_clobbers_src() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // BPF_AND = 0x50 (linux uapi bpf_common.h) | BPF_FETCH = 0x51.
    let insns = vec![
        atomic_stx(2, 1, 0, 0x50 | BPF_FETCH),
        stx(BPF_SIZE_DW, 6, 1, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "AND|FETCH must clobber src R1 typed state: {map:?}"
    );
}

/// `BPF_OR | BPF_FETCH` (`imm == 0x41`) is an atomic
/// fetch-and-or: src receives the prior memory value. The
/// `has_fetch` arm in `handle_atomic` drops src to `Unknown`.
/// A subsequent STX of src into a `u64` slot must NOT record.
#[test]
fn atomic_or_fetch_clobbers_src() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // BPF_OR = 0x40 (linux uapi bpf_common.h) | BPF_FETCH = 0x41.
    let insns = vec![
        atomic_stx(2, 1, 0, 0x40 | BPF_FETCH),
        stx(BPF_SIZE_DW, 6, 1, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "OR|FETCH must clobber src R1 typed state: {map:?}"
    );
}

/// `BPF_XOR | BPF_FETCH` (`imm == 0xa1`) is an atomic
/// fetch-and-xor: src receives the prior memory value. The
/// `has_fetch` arm in `handle_atomic` drops src to `Unknown`.
/// A subsequent STX of src into a `u64` slot must NOT record.
#[test]
fn atomic_xor_fetch_clobbers_src() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // BPF_XOR = 0xa0 (linux uapi bpf_common.h) | BPF_FETCH = 0xa1.
    let insns = vec![
        atomic_stx(2, 1, 0, 0xa0 | BPF_FETCH),
        stx(BPF_SIZE_DW, 6, 1, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "XOR|FETCH must clobber src R1 typed state: {map:?}"
    );
}

/// `BPF_ATOMIC` with `BPF_W` (4-byte) size targeting `[r10+off]`
/// must invalidate the stack slot the same way a DW atomic does.
/// Per `handle_atomic`, the stack-invalidation arm runs
/// unconditionally on `dst == r10` regardless of the size bits
/// in the opcode — a 4-byte atomic write into a slot that
/// formerly held a 64-bit typed pointer truncates the slot's
/// content. A subsequent DW reload must NOT resurrect the
/// pre-atomic typed-pointer state.
#[test]
fn atomic_w_size_invalidates_stack_slot() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // *(u64 *)(r10 - 8) = R1                 ; spill Pointer{T} -> stack[-8]
    // ATOMIC<W> XCHG [r10 - 8] = R2          ; W-size atomic on slot
    // R3 = *(u64 *)(r10 - 8)                 ; reload must yield Unknown
    // *(u64 *)(R6 + slot_off) = R3           ; R3 Unknown -> no record
    //
    // Constructed with `mk_insn` directly because the `atomic_stx`
    // helper hard-codes `BPF_SIZE_DW`. Code = STX | W | ATOMIC.
    let atomic_w = mk_insn(
        BPF_CLASS_STX | BPF_SIZE_W | BPF_MODE_ATOMIC,
        10,
        2,
        -8,
        0xe0 | BPF_FETCH,
    );
    let insns = vec![
        stx(BPF_SIZE_DW, 10, 1, -8),
        atomic_w,
        ldx(BPF_SIZE_DW, 3, 10, -8),
        stx(BPF_SIZE_DW, 6, 3, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "W-size ATOMIC on stack slot must invalidate, reload Unknown: {map:?}"
    );
}

/// `BPF_CMPXCHG` (`imm == 0xf1`) overwrites BOTH `R0` (with the
/// prior memory value) AND `src` (because `BPF_FETCH` is set,
/// the second-stage `has_fetch` arm in `handle_atomic` runs in
/// addition to the CMPXCHG-specific R0 clobber). The existing
/// `atomic_cmpxchg_clobbers_r0` test guards the R0 path; this
/// test guards the src path. Per kernel uapi `bpf.h` and the
/// final fall-through `if has_fetch` arm in `handle_atomic`,
/// src's typed-pointer state is dropped to `Unknown` regardless
/// of which atomic-op top nibble was used. A subsequent STX of
/// src into a `u64` slot must NOT record a kptr finding.
#[test]
fn atomic_cmpxchg_clobbers_src() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // R1 = Pointer{T}; CMPXCHG dst=R2, src=R1 with imm=0xf1.
    // R0 (the cmpxchg "expected" register, not seeded here) is
    // clobbered to Unknown by the CMPXCHG-specific arm; R1 is
    // clobbered to Unknown by the final has_fetch arm. STX R1
    // into P.slot must NOT record.
    let insns = vec![
        atomic_stx(2, 1, 0, 0xf0 | BPF_FETCH),
        stx(BPF_SIZE_DW, 6, 1, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "CMPXCHG must clobber src R1 typed state via has_fetch arm: {map:?}"
    );
}

// ----- Stack tests --------------------------------------------

/// A second spill to the same stack slot overwrites the prior
/// saved state. Reload restores the latest typed pointer, not
/// the original one. Production line `self.stack_slots.insert`
/// replaces by key.
#[test]
fn stack_spill_overwrite_uses_latest() {
    // BTF: u64(1), T1(2, u64@0), T2(3, u64@0), P(4, u64@slot_off).
    // T1 and T2 are distinguishable by id; the test seeds R1=T1,
    // R2=T2, then spills T2 last so reload should yield T2.
    let slot_off: u32 = 16;
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t1 = push_name(&mut strings, "T1");
    let n_t2 = push_name(&mut strings, "T2");
    let n_p = push_name(&mut strings, "P");
    let n_x = push_name(&mut strings, "x");
    let n_slot = push_name(&mut strings, "slot");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t1,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Struct {
            name_off: n_t2,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Struct {
            name_off: n_p,
            size: slot_off + 8,
            members: vec![SynMember {
                name_off: n_slot,
                type_id: 1,
                byte_offset: slot_off,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t1_id = 2;
    let t2_id = 3;
    let p_id = 4;
    // Spill R1 (T1*) to [r10-8]
    // Spill R2 (T2*) to [r10-8] -- overwrite
    // Reload to R3 (must be T2*)
    // Store R3 into P.slot
    let insns = vec![
        stx(BPF_SIZE_DW, 10, 1, -8),
        stx(BPF_SIZE_DW, 10, 2, -8),
        ldx(BPF_SIZE_DW, 3, 10, -8),
        stx(BPF_SIZE_DW, 6, 3, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t1_id,
            },
            InitialReg {
                reg: 2,
                struct_type_id: t2_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(p_id, slot_off)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t2_id,
            addr_space: AddrSpace::Kernel,
        }),
        "second spill to same slot must win: {map:?}"
    );
}

/// `BPF_CALL` clobbers `r0..r5` per the BPF ABI but does NOT
/// invalidate stack slots. A typed pointer parked in `[r10-N]`
/// before a helper call must reload as the same typed pointer
/// after the call returns.
#[test]
fn stack_spill_survives_helper_call() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // Spill R1 (T*) to [r10-8]
    // CALL helper (clobbers R0..R5, R6 untouched)
    // Reload from [r10-8] to R3 (must restore T*)
    // Store R3 into P.slot
    let insns = vec![
        stx(BPF_SIZE_DW, 10, 1, -8),
        call(),
        ldx(BPF_SIZE_DW, 3, 10, -8),
        stx(BPF_SIZE_DW, 6, 3, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(p_id, slot_off)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "stack-spilled pointer must survive helper call: {map:?}"
    );
}

/// A sub-DW (4-byte W) store through `r10` to a slot previously
/// holding a typed pointer truncates the stored value. Per
/// `handle_stx`, the slot is removed so a later DW reload
/// returns Unknown rather than resurrecting the stale typed
/// state.
#[test]
fn sub_dw_spill_invalidates() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // *(u64 *)(r10 - 8) = R1   ; spill T* to slot
    // *(u32 *)(r10 - 8) = R1   ; sub-DW store, slot removed
    // R3 = *(u64 *)(r10 - 8)   ; reload must yield Unknown
    // *(u64 *)(R6 + slot_off) = R3 ; no record
    let insns = vec![
        stx(BPF_SIZE_DW, 10, 1, -8),
        stx(BPF_SIZE_W, 10, 1, -8),
        ldx(BPF_SIZE_DW, 3, 10, -8),
        stx(BPF_SIZE_DW, 6, 3, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "sub-DW store must invalidate slot, reload Unknown: {map:?}"
    );
}

/// `BPF_ST` (immediate store, `code = BPF_ST | BPF_MEM | BPF_DW
/// = 0x7A`) writes a constant immediate to memory through `r10`.
/// The constant is never a typed pointer, but the store overlays
/// any prior typed value the analyzer was tracking in the
/// stack slot. Per the `BPF_CLASS_ST` arm in `step()`, the
/// stack slot is removed when `dst == r10 && mode == BPF_MEM`
/// so a subsequent reload through `r10` must NOT resurrect the
/// pre-immediate-store typed-pointer state.
#[test]
fn st_imm_invalidates_stack_slot() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // *(u64 *)(r10 - 8) = R1     ; spill Pointer{T} -> stack[-8]
    // *(u64 *)(r10 - 8) = imm 0  ; ST overwrites slot with constant
    // R3 = *(u64 *)(r10 - 8)     ; reload must yield Unknown
    // *(u64 *)(R6 + slot_off) = R3 ; R3 Unknown -> no record
    //
    // Constructed with `mk_insn` directly — there is no
    // helper for BPF_ST class instructions. Code per linux
    // uapi `bpf_common.h` and `bpf.h`: BPF_ST | BPF_MEM | BPF_DW
    // = 0x02 | 0x60 | 0x18 = 0x7A. dst=r10 (frame pointer),
    // src is unused (encoded as 0), off=-8 (slot key matching
    // the prior spill), imm=0 (constant value, irrelevant —
    // any constant overwrites the typed slot the same way).
    let st_imm_dw = mk_insn(BPF_CLASS_ST | BPF_MODE_MEM | BPF_SIZE_DW, 10, 0, -8, 0);
    let insns = vec![
        stx(BPF_SIZE_DW, 10, 1, -8),
        st_imm_dw,
        ldx(BPF_SIZE_DW, 3, 10, -8),
        stx(BPF_SIZE_DW, 6, 3, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "BPF_ST imm to stack slot must invalidate, reload Unknown: {map:?}"
    );
}

// ----- Conflict tests -----------------------------------------

/// A single `(struct, offset)` slot observed by BOTH the arena
/// LDX path (loaded then dereferenced) AND the kernel STX path
/// (typed `Pointer{T}` stored) is ambiguous. The same byte cannot
/// simultaneously hold an arena VA and a kernel VA. Per
/// `finalize`, both observations drop and the slot does not
/// appear in the output map.
#[test]
fn arena_and_kptr_same_field_drops_both() {
    // BTF: u64(1), T(2, u64@0), T*(3), P(4, u64@8).
    // T is the unique candidate for shape pattern (offset=0, size=8).
    // Arena: load P.u64@8 -> r2, deref r2+0 -> patterns[(P,8)]={(0,8)}.
    // Kptr: STX *(P+8) = R6 (Pointer{T}) -> kptr_findings[(P,8)] = T.
    // Conflict on (P, 8) drops both.
    let slot_off: u32 = 8;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // Arena LDX path: r2 = *(u64*)(r1+8); r3 = *(u64*)(r2+0).
    // Kernel STX path: *(u64*)(r1+8) = r6.
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, slot_off as i16),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        stx(BPF_SIZE_DW, 1, 6, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: p_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: t_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "arena+kptr conflict on same slot must drop both: {map:?}"
    );
}

/// Two STX writes to the same `(struct, offset)` slot with
/// different target struct ids collapse the kptr finding to
/// `KptrEntry::Conflicting`. `finalize` skips conflicting
/// entries, so the slot does not appear in the output map.
///
/// Bare `map.is_empty()` cannot distinguish "Conflicting state
/// was reached" from "the analyzer never recorded either STX".
/// Both yield empty maps. The strengthened test runs THREE
/// analyses to triangulate the production path:
///   (a) baseline single-STX of T1: must record (P, slot) -> T1.
///       Establishes that the STX path is functional and that
///       T1 is recoverable from R1.
///   (b) STX T1 then STX T2: must drop (collapse to Conflicting).
///       Same as the original test.
///   (c) STX T1, STX T2, STX T1 again: must STILL drop. Once a
///       slot transitions to Conflicting, every subsequent STX
///       (even of the original target) preserves Conflicting per
///       the `Some(_)` arm of the match in `handle_stx()` —
///       proves the slot did NOT revert to `Single(T1)` after
///       the third store. If the analyzer instead overwrote
///       Conflicting back to Single on a same-target restore,
///       (c) would emit (P, slot) -> T1 like (a) does.
#[test]
fn kptr_conflict_two_targets_drops() {
    // BTF: u64(1), T1(2, u64@0), T2(3, u64@0), P(4, u64@slot_off).
    // Seed R1=Pointer{T1}, R2=Pointer{T2}, R6=Pointer{P}.
    let slot_off: u32 = 16;
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t1 = push_name(&mut strings, "T1");
    let n_t2 = push_name(&mut strings, "T2");
    let n_p = push_name(&mut strings, "P");
    let n_x = push_name(&mut strings, "x");
    let n_slot = push_name(&mut strings, "slot");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t1,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Struct {
            name_off: n_t2,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Struct {
            name_off: n_p,
            size: slot_off + 8,
            members: vec![SynMember {
                name_off: n_slot,
                type_id: 1,
                byte_offset: slot_off,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t1_id = 2;
    let t2_id = 3;
    let p_id = 4;
    let seeds = [
        InitialReg {
            reg: 1,
            struct_type_id: t1_id,
        },
        InitialReg {
            reg: 2,
            struct_type_id: t2_id,
        },
        InitialReg {
            reg: 6,
            struct_type_id: p_id,
        },
    ];

    // (a) Baseline: single STX of T1 records (P, slot) -> T1.
    // Without this anchor, the empty map from (b)/(c) below
    // could be explained by a non-functional STX path rather
    // than the Conflicting transition.
    let insns_single = vec![stx(BPF_SIZE_DW, 6, 1, slot_off as i16), exit()];
    let map_single = analyze_casts(&insns_single, &btf, &seeds, &[], &[], &[]);
    assert_eq!(
        map_single.len(),
        1,
        "(a) single STX must record exactly one finding: {map_single:?}"
    );
    assert_eq!(
        map_single.get(&(p_id, slot_off)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t1_id,
            addr_space: AddrSpace::Kernel,
        }),
        "(a) baseline records (P, slot) -> (T1, Kernel): {map_single:?}"
    );

    // (b) Two distinct targets — collapses to Conflicting and
    // finalize drops. Same shape as the historical test.
    let insns_conflict = vec![
        stx(BPF_SIZE_DW, 6, 1, slot_off as i16),
        stx(BPF_SIZE_DW, 6, 2, slot_off as i16),
        exit(),
    ];
    let map_conflict = analyze_casts(&insns_conflict, &btf, &seeds, &[], &[], &[]);
    assert!(
        map_conflict.is_empty(),
        "(b) two distinct kptr targets on same slot must collapse to \
             Conflicting and drop: {map_conflict:?}"
    );

    // (c) Append a third STX of T1. If the slot is Conflicting,
    // the `Some(_)` arm preserves Conflicting (no revert to
    // Single). If the production code instead reset to
    // Single(T1) on a same-target restore, the map would
    // emit (P, slot) -> T1 like (a) does. Empty map confirms
    // Conflicting was reached and is sticky.
    let insns_three = vec![
        stx(BPF_SIZE_DW, 6, 1, slot_off as i16),
        stx(BPF_SIZE_DW, 6, 2, slot_off as i16),
        stx(BPF_SIZE_DW, 6, 1, slot_off as i16),
        exit(),
    ];
    let map_three = analyze_casts(&insns_three, &btf, &seeds, &[], &[], &[]);
    assert!(
        map_three.is_empty(),
        "(c) Conflicting state must be sticky across same-target \
             restore — third STX of T1 must not resurrect: {map_three:?}"
    );
}

// ----- OOB tests ----------------------------------------------

/// A malformed `BpfInsn` with `dst >= 11` (out of the 0..=10
/// valid register range) must NOT panic. The bounds check at
/// the top of `step()` and `handle_*` rejects early. The
/// analyzer treats the instruction as a no-op; output map is
/// empty.
#[test]
fn oob_dst_reg_does_not_panic() {
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    // LDX with dst=11 (invalid). Construct via BpfInsn::new
    // which masks to 4 bits (11 & 0x0f == 11). No panic; map empty.
    let bad = BpfInsn::new(BPF_CLASS_LDX | BPF_SIZE_DW | BPF_MODE_MEM, 11, 1, 8, 0);
    let insns = vec![bad, exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(map.is_empty(), "OOB dst must not panic, map empty: {map:?}");
}

/// A malformed `BpfInsn` with `src == 15` (out of the 0..=10
/// valid register range) must NOT panic. `BpfInsn::new` packs
/// 15 into the 4-bit src field; `src_reg()` decodes back to 15.
/// The bounds check rejects early; output map is empty.
#[test]
fn oob_src_reg_does_not_panic() {
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    // LDX with src=15 (invalid). No panic; map empty.
    let bad = BpfInsn::new(BPF_CLASS_LDX | BPF_SIZE_DW | BPF_MODE_MEM, 2, 15, 8, 0);
    let insns = vec![bad, exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(map.is_empty(), "OOB src must not panic, map empty: {map:?}");
}

// ----- Other tests --------------------------------------------

/// Storing a `Pointer{P}` into a `u64` field of struct `P`
/// itself is rejected: `parent == target` is almost always a
/// structural error from ambiguous pointer aliasing in the
/// analyzer, not a real kptr write. Production line
/// `if parent_struct_id == target_struct_id { return; }`
/// drops the finding; output map is empty.
#[test]
fn self_store_rejected() {
    // BTF: u64(1), P(2, u64@slot_off). No separate target type.
    let slot_off: u32 = 8;
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_p = push_name(&mut strings, "P");
    let n_slot = push_name(&mut strings, "slot");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_p,
            size: slot_off + 8,
            members: vec![SynMember {
                name_off: n_slot,
                type_id: 1,
                byte_offset: slot_off,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let p_id = 2;
    // R1 = Pointer{P}. STX *(R1 + slot_off) = R1. Self-store.
    let insns = vec![stx(BPF_SIZE_DW, 1, 1, slot_off as i16), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: p_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(map.is_empty(), "self-store must be rejected: {map:?}");
}

/// A FuncProto with a variadic sentinel parameter (`name_off=0
/// AND type_id=0` per `Parameter::is_variadic`) must terminate
/// the parameter scan: no parameter slot past the sentinel
/// reseeds a register. With params `[T*, P*, variadic]` the
/// non-variadic prefix seeds R1 = Pointer{T} and R2 = Pointer{P};
/// the variadic sentinel terminates the scan so R3 stays Unknown
/// even though a real BTF parameter slot follows. A subsequent
/// STX through R3 must not record a kptr finding.
#[test]
fn variadic_param_breaks_seeding() {
    // BTF: u64(1), T(2, u64@0), T*(3), P(4, u64@slot_off1, u64@slot_off2),
    //      P*(5), FuncProto(6, params=[T*, P*, variadic, T*]).
    let slot_off1: u32 = 16;
    let slot_off2: u32 = 24;
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_p = push_name(&mut strings, "P");
    let n_x = push_name(&mut strings, "x");
    let n_slot1 = push_name(&mut strings, "slot1");
    let n_slot2 = push_name(&mut strings, "slot2");
    let n_arg_t = push_name(&mut strings, "task");
    let n_arg_p = push_name(&mut strings, "parent");
    let n_arg_after = push_name(&mut strings, "after_variadic");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Ptr { type_id: 2 }, // id 3: T*
        SynType::Struct {
            name_off: n_p,
            size: slot_off2 + 8,
            members: vec![
                SynMember {
                    name_off: n_slot1,
                    type_id: 1,
                    byte_offset: slot_off1,
                },
                SynMember {
                    name_off: n_slot2,
                    type_id: 1,
                    byte_offset: slot_off2,
                },
            ],
        },
        SynType::Ptr { type_id: 4 }, // id 5: P*
        // FuncProto with [T*, P*, variadic, T*]. The trailing
        // T* slot is BTF-reachable but unreachable in the BPF
        // calling convention because the variadic sentinel
        // terminates the scan; the analyzer must NOT seed R4
        // from it.
        SynType::FuncProto {
            return_type_id: 0,
            params: vec![
                SynParam {
                    name_off: n_arg_t,
                    type_id: 3,
                },
                SynParam {
                    name_off: n_arg_p,
                    type_id: 5,
                },
                SynParam {
                    name_off: 0,
                    type_id: 0,
                },
                SynParam {
                    name_off: n_arg_after,
                    type_id: 3,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let p_id = 4;
    let proto_id = 6;
    // FuncEntry seeds R1 = Pointer{T} (param 0), R2 = Pointer{P}
    // (param 1). R3 stays Unknown because the variadic sentinel
    // terminates the scan before param 3.
    // STX *(R2 + slot1) = R1 records (P, slot1) -> T.
    // STX *(R2 + slot2) = R3 must NOT record (R3 Unknown).
    let insns = vec![
        stx(BPF_SIZE_DW, 2, 1, slot_off1 as i16),
        stx(BPF_SIZE_DW, 2, 3, slot_off2 as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[],
        &[FuncEntry {
            insn_offset: 0,
            func_proto_id: proto_id,
        }],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(p_id, slot_off1)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "non-variadic params must seed R1 and R2: {map:?}"
    );
    assert!(
        !map.contains_key(&(p_id, slot_off2)),
        "variadic sentinel must terminate scan, R3 must stay Unknown: {map:?}"
    );
}

/// `FuncEntry` clears ALL registers (R0..R10) and the stack before
/// seeding R1..R5 from the FuncProto. A typed pointer parked in
/// any register by `InitialReg` is dropped at the entry PC —
/// including callee-saved R6..R9 (the linear walk has no real
/// caller, so preserving them would leak stale state).
#[test]
fn func_entry_clears_all_regs() {
    // BTF: u64(1), T(2, u64@0), T*(3), P(4, u64@slot_off),
    //      FuncProto(5, params=[T*]).
    let slot_off: u32 = 16;
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_p = push_name(&mut strings, "P");
    let n_x = push_name(&mut strings, "x");
    let n_slot = push_name(&mut strings, "slot");
    let n_arg = push_name(&mut strings, "arg");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Ptr { type_id: 2 },
        SynType::Struct {
            name_off: n_p,
            size: slot_off + 8,
            members: vec![SynMember {
                name_off: n_slot,
                type_id: 1,
                byte_offset: slot_off,
            }],
        },
        // FuncProto(T*) -> void.
        SynType::FuncProto {
            return_type_id: 0,
            params: vec![SynParam {
                name_off: n_arg,
                type_id: 3,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let p_id = 4;
    let proto_id = 5;
    // Seed R3 = Pointer{T} and R6 = Pointer{P} via InitialReg.
    // FuncEntry at PC 0 clears ALL registers (R0..R10), then
    // seeds R1 from param 0. Both R3 and R6 are now Unknown.
    // STX *(R6 + slot) = R3 must NOT record (both cleared).
    let insns = vec![stx(BPF_SIZE_DW, 6, 3, slot_off as i16), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 3,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[FuncEntry {
            insn_offset: 0,
            func_proto_id: proto_id,
        }],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "FuncEntry pre-clear must drop R3 typed state: {map:?}"
    );
}

/// `BPF_PROBE_MEM` (`mode = 0x20`) is a post-verifier marker
/// per linux `include/linux/filter.h` and never appears in
/// pre-verification bytecode. Production treats any LDX with
/// `mode != BPF_MODE_MEM` as Unknown; a subsequent deref
/// through the resulting register records nothing.
#[test]
fn probe_mem_load_treated_as_unknown() {
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    // PROBE_MEM mode = 0x20. code = LDX | DW | PROBE_MEM = 0x39.
    // dst=2, src=1, off=8 mimics the arena LDX shape but the
    // mode bits divert to the Unknown branch.
    const BPF_MODE_PROBE_MEM: u8 = 0x20;
    let probe_load = mk_insn(BPF_CLASS_LDX | BPF_SIZE_DW | BPF_MODE_PROBE_MEM, 2, 1, 8, 0);
    let insns = vec![probe_load, ldx(BPF_SIZE_DW, 3, 2, 0), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "BPF_PROBE_MEM load must mark dst Unknown: {map:?}"
    );
}

// ----- Finalize edge cases ------------------------------------

/// `BPF_ADDR_SPACE_CAST` arena->kernel populates `arena_confirmed`
/// even when the originating LDX never produces a downstream
/// dereference, so `patterns[(T,8)]` carries an EMPTY access set.
/// If the same `(T, off)` slot is also the parent of a STX-source
/// kptr write, `finalize` must treat the slot as conflicting and
/// drop BOTH observations: the kptr loop skips the conflicted key
/// and the arena loop skips the empty-access entry independently.
/// Without the `arena_confirmed`-side participation in the
/// conflict set the kptr finding would emit even though the cast
/// instruction proves the slot holds an arena address.
#[test]
fn finalize_arena_confirmed_conflicts_with_kptr() {
    // BTF: u64(1), T(2, u64@8), T*(3), Q(4, u64@0). T also acts
    // as the parent for the kptr STX (the slot at T+8). Q is the
    // distinct value type to keep the self-store rejection from
    // firing.
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_q = push_name(&mut strings, "Q");
    let n_f = push_name(&mut strings, "f");
    let n_x = push_name(&mut strings, "x");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 16,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        SynType::Ptr { type_id: 2 },
        SynType::Struct {
            name_off: n_q,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let q_id = 4;
    // r2 = *(u64*)(r1 + 8)        ; r2 = LoadedU64Field{T, 8},
    //                               patterns[(T,8)] = {} (no deref)
    // r4 = (cast as(1)->as(0)) r2 ; arena_confirmed += (T, 8)
    // *(u64*)(r1 + 8) = r3        ; r1 still Pointer{T},
    //                               r3 = Pointer{Q} ->
    //                               kptr_findings[(T,8)] = Single(Q)
    let cast = mk_insn(BPF_CLASS_ALU64 | BPF_OP_MOV | BPF_SRC_X, 4, 2, 1, 1);
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        cast,
        stx(BPF_SIZE_DW, 1, 3, 8),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 3,
                struct_type_id: q_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        !map.contains_key(&(t_id, 8)),
        "arena_confirmed + kptr conflict on (T, 8) must drop both: {map:?}"
    );
    assert!(map.is_empty(), "no other entries expected: {map:?}");
}

/// Loading a u64 field without dereferencing through it leaves
/// `patterns[(T, off)]` populated but with an EMPTY access set.
/// `finalize`'s arena loop short-circuits via
/// `if accesses.is_empty() { continue }` and emits nothing. The
/// slot stays absent from the output map even though the source
/// register held a `LoadedU64Field` state at one point.
#[test]
fn finalize_empty_access_set_does_not_emit() {
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    // r2 = *(u64 *)(r1 + 8)  -- patterns[(T,8)] = {} (loaded only)
    // exit                    -- never dereferenced
    let insns = vec![ldx(BPF_SIZE_DW, 2, 1, 8), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        !map.contains_key(&(t_id, 8)),
        "empty access set must not emit: {map:?}"
    );
    assert!(map.is_empty(), "no other entries expected: {map:?}");
}

/// The candidate-search intersection drops the source struct
/// itself even when its layout matches every observed
/// `(offset, size)` access. When the original candidate set is
/// `{source, X}` (source plus exactly one foreign struct that also
/// matches), `finalize` rejects the entire entry rather than
/// emitting `X`: an `{source, X}` set means the true target could
/// have been the source AND its access pattern happens to match
/// X by coincidence. Picking X would be a false positive.
#[test]
fn finalize_source_in_candidates_with_others_emits_other() {
    // BTF: u64(1), T(2, u64@0 + u64@8 -- same shape T matches its
    // own access pattern), Q(3, u64@0 + u64@8). Loading T.f at
    // offset 0 then dereferencing through it at offsets 0 and 8
    // gives candidates {T, Q} -- both have u64s at those offsets.
    // Production must drop because the source T is in the set
    // alongside Q.
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_q = push_name(&mut strings, "Q");
    let n_a = push_name(&mut strings, "a");
    let n_b = push_name(&mut strings, "b");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 16,
            members: vec![
                SynMember {
                    name_off: n_a,
                    type_id: 1,
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_b,
                    type_id: 1,
                    byte_offset: 8,
                },
            ],
        },
        SynType::Struct {
            name_off: n_q,
            size: 16,
            members: vec![
                SynMember {
                    name_off: n_a,
                    type_id: 1,
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_b,
                    type_id: 1,
                    byte_offset: 8,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    // Sequence: r2 = *(u64*)(r1 + 0); r3 = *(u64*)(r2 + 0);
    // r4 = *(u64*)(r2 + 8). Candidates for (offset=0, size=8) and
    // (offset=8, size=8) intersect to {T, Q}. Source T is removed
    // from candidates; Q remains as the sole non-source candidate
    // and is emitted.
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 0),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        ldx(BPF_SIZE_DW, 4, 2, 8),
        exit(),
    ];
    let q_id = 3;
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 0)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "source removed, sole non-source candidate Q emitted: {map:?}"
    );
}

/// When the only candidate matching the access pattern is the
/// source struct itself, `finalize` removes it via
/// `had_source = candidates.remove(source)` and the resulting set
/// is empty -- nothing emits. This guards against self-typed
/// casts (`source.f` -> `source*`) where a self-referential layout
/// would silently win the intersection without disambiguating
/// evidence.
#[test]
fn finalize_only_source_candidate_drops() {
    // BTF: u64(1), T(2, u64@8). T is the only struct in the BTF;
    // its layout matches the access pattern (offset=8, size=8).
    // After remove(source) the candidate set is empty -> skip emit.
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_f = push_name(&mut strings, "f");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        // T has u64@8 only; (offset=8, size=8) matches T.
        SynType::Struct {
            name_off: n_t,
            size: 16,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 1,
                byte_offset: 8,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    // Sequence: r2 = *(u64*)(r1 + 8); r3 = *(u64*)(r2 + 8).
    // Pattern recorded: source=(T,8), access=(8,8). Layout maps
    // (8,8) -> {T}. After remove(source), candidates empty ->
    // skip emit.
    let insns = vec![ldx(BPF_SIZE_DW, 2, 1, 8), ldx(BPF_SIZE_DW, 3, 2, 8), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "candidate set containing only the source must drop: {map:?}"
    );
}

/// The candidate-search loop walks BTF ids `1..=max_id` where
/// `max_id = max_seen_type_id + CANDIDATE_SEARCH_SLACK` capped at
/// `MAX_BTF_ID_PROBE`. When the source struct id is small (e.g.
/// 2), `max_seen_type_id` picks up the source id (via
/// `note_type_id`) and the slack carries the search several
/// thousand ids further. A target struct that lives WELL beyond
/// the source id but well inside the slack window must still be
/// found. This guards against a regression that would shrink the
/// loop bound to `max_seen_type_id` itself, AND verifies that the
/// `MAX_BTF_ID_PROBE` cap leaves room for the slack on small
/// max_seen values.
#[test]
fn finalize_max_seen_type_id_slack_finds_distant_candidate() {
    // BTF: many filler Ptr types between T and Q so that Q's id
    // is far above max_seen_type_id (which the analyzer sets to
    // T's id when seeding R1). The slack (CANDIDATE_SEARCH_SLACK
    // = 65_536) more than covers any practical BTF id space, so
    // Q at id 203 must be found even though only T (id 2) is
    // touched during the forward pass. The MAX_BTF_ID_PROBE cap
    // (100_000) is far above id 203, so this also exercises the
    // .min() arm without truncating the search.
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_q = push_name(&mut strings, "Q");
    let n_f = push_name(&mut strings, "f");
    let n_x = push_name(&mut strings, "x");
    // Build: id 1 = u64, id 2 = T (struct with u64@8), then 200
    // filler Ptr-to-u64 types (ids 3..=202), then id 203 = Q
    // (struct with u64@0). max_seen ends up at 2 (T), slack pushes
    // search through id 65_538, so id 203 is well within range.
    let mut types: Vec<SynType> = Vec::new();
    types.push(SynType::Int {
        name_off: n_u64,
        size: 8,
        encoding: 0,
        offset: 0,
        bits: 64,
    });
    types.push(SynType::Struct {
        name_off: n_t,
        size: 16,
        members: vec![SynMember {
            name_off: n_f,
            type_id: 1,
            byte_offset: 8,
        }],
    });
    for _ in 0..200 {
        types.push(SynType::Ptr { type_id: 1 });
    }
    types.push(SynType::Struct {
        name_off: n_q,
        size: 8,
        members: vec![SynMember {
            name_off: n_x,
            type_id: 1,
            byte_offset: 0,
        }],
    });
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let q_id = 203;
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "slack must carry search well past max_seen, capped within \
             MAX_BTF_ID_PROBE: {map:?}"
    );
}

// ----- BTF type edge cases ------------------------------------

/// `struct_member_at` skips bitfield members (members with
/// `bitfield_size > 0`) even when their byte offset matches the
/// query. A LDX through a `Pointer{T}` register at the bitfield's
/// byte offset must NOT seed a `LoadedU64Field` state, so no
/// pattern accumulates and no cast emits.
#[test]
fn struct_member_at_skips_bitfield_at_target_offset() {
    // BTF: u64(1), T(kind_flag=1) with a u64 bitfield at byte
    // offset 8 (bitfield_size = 32 bits). The byte offset matches
    // the LDX target but the bitfield_size > 0 makes
    // struct_member_at return None.
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_f = push_name(&mut strings, "f");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::StructBitfields {
            name_off: n_t,
            size: 16,
            members: vec![SynMemberBits {
                name_off: n_f,
                type_id: 1,
                bit_offset: 8 * 8,      // byte offset 8
                bitfield_size_bits: 32, // bitfield -> skip
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    // r2 = *(u64*)(r1 + 8): handle_ldx queries struct_member_at(T, 8).
    // The bitfield at 8 is skipped; struct_member_at returns None;
    // r2 becomes Unknown; no LoadedU64Field; no pattern recorded.
    // r3 = *(u64*)(r2 + 0) on Unknown source records nothing.
    let insns = vec![ldx(BPF_SIZE_DW, 2, 1, 8), ldx(BPF_SIZE_DW, 3, 2, 0), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "bitfield at target offset must not seed cast: {map:?}"
    );
}

/// `struct_member_at` skips members whose bit offset is not a
/// multiple of 8 (`bit_off % 8 != 0`) -- bit-position members
/// inside a kind_flag=1 struct that happen to lie between byte
/// boundaries cannot serve as a u64 LDX source. Even though the
/// byte derived from the bit position would round to the LDX
/// target offset, the alignment guard rejects.
#[test]
fn struct_member_at_skips_non_byte_aligned_member() {
    // T (kind_flag=1) with a u64 member at bit_offset = 65 (NOT
    // a multiple of 8; integer-divided by 8 gives byte 8). The
    // alignment guard rejects regardless of bitfield_size_bits.
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_f = push_name(&mut strings, "f");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::StructBitfields {
            name_off: n_t,
            size: 24,
            members: vec![SynMemberBits {
                name_off: n_f,
                type_id: 1,
                bit_offset: 65,        // NOT a multiple of 8
                bitfield_size_bits: 0, // not a bitfield
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    // r2 = *(u64*)(r1 + 8): struct_member_at scans T's members,
    // sees bit_offset 65 % 8 = 1, skips. r2 stays Unknown.
    let insns = vec![ldx(BPF_SIZE_DW, 2, 1, 8), ldx(BPF_SIZE_DW, 3, 2, 0), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "non-byte-aligned member must not seed cast: {map:?}"
    );
}

/// `member_size_bytes` returns `None` for terminal types whose
/// size is not resolvable from BTF alone (Func, FuncProto, Void,
/// Fwd, Var, Datasec). The `build_layout_index` loop must handle
/// `None` by skipping the member rather than panicking. Stress
/// the path by constructing a candidate struct whose members
/// include one each of Fwd, Func, and Void; the matcher must not
/// include those member positions in the (offset, size) layout
/// map. Without this guard the matcher would either crash on the
/// `expect`-style unwrap or emit a candidate the renderer cannot
/// chase.
#[test]
fn member_size_bytes_unsupported_terminals_skipped() {
    // BTF:
    //   id 1: u64
    //   id 2: T   { u64 f @ 8 }       -- source struct
    //   id 3: Fwd struct (kind_flag=0)
    //   id 4: FuncProto returning void, no params
    //   id 5: Func -> id 4
    //   id 6: U  { fwd_ref @ 0; func_ref @ 8; void_ref @ 16; u64 v @ 24 }
    //
    //   The members typed as Fwd / Func / Void all return None
    //   from member_size_bytes, so layout_index for U skips them.
    //   The single u64 at offset 24 makes U a candidate at
    //   (offset=24, size=8) ONLY. The LDX pattern accesses
    //   offset=24 (size 8); intersection -> {U}.
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_u = push_name(&mut strings, "U");
    let n_fwd_target = push_name(&mut strings, "fwd_struct");
    let n_func = push_name(&mut strings, "fn");
    let n_fwd_ref = push_name(&mut strings, "fwd_ref");
    let n_func_ref = push_name(&mut strings, "func_ref");
    let n_void_ref = push_name(&mut strings, "void_ref");
    let n_v = push_name(&mut strings, "v");
    let n_f = push_name(&mut strings, "f");
    let types = vec![
        // id 1: u64
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        // id 2: source T { u64 f @ 8 }
        SynType::Struct {
            name_off: n_t,
            size: 16,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        // id 3: Fwd (struct).
        SynType::Fwd {
            name_off: n_fwd_target,
            kind_flag: 0,
        },
        // id 4: FuncProto -> void, no params.
        SynType::FuncProto {
            return_type_id: 0,
            params: vec![],
        },
        // id 5: Func -> id 4.
        SynType::Func {
            name_off: n_func,
            type_id: 4,
            linkage: 1,
        },
        // id 6: U with members of unsupported sizes plus one
        // sized u64 member. Production must skip the unsupported
        // ones and include only (offset=24, size=8).
        SynType::Struct {
            name_off: n_u,
            size: 32,
            members: vec![
                SynMember {
                    name_off: n_fwd_ref,
                    type_id: 3, // Fwd -> None size
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_func_ref,
                    type_id: 5, // Func -> None size
                    byte_offset: 8,
                },
                SynMember {
                    name_off: n_void_ref,
                    type_id: 0, // Void -> None size
                    byte_offset: 16,
                },
                SynMember {
                    name_off: n_v,
                    type_id: 1, // u64 -> Some(8)
                    byte_offset: 24,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let u_id = 6;
    // r2 = *(u64*)(r1 + 8); cast r2 (F1 evidence); r3 =
    // *(u64*)(r2 + 24). The pattern (offset=24, size=8) must
    // intersect to {U} only -- Fwd / Func / Void members at
    // offsets 0/8/16 are skipped during layout indexing.
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 24),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: u_id,
            addr_space: AddrSpace::Arena,
        }),
        "unsupported terminals must be skipped without crashing: {map:?}"
    );
}

/// `build_layout_index` skips bitfield members (those with
/// `bitfield_size > 0`). A struct whose only u64 sits as a
/// bitfield does NOT register in the (offset, size) layout map,
/// so it cannot be a candidate even when the access pattern
/// "would" match its byte position. The matcher converges on the
/// struct that has a NON-bitfield member at the queried position.
#[test]
fn build_layout_index_skips_bitfields_in_candidates() {
    // BTF: u64(1), T(2, u64@8) source. Q1(3, kind_flag=1) with a
    // u64 BITFIELD at byte 0 (size 32 bits) -- must NOT register
    // as a candidate. Q2(4) with a u64 NON-bitfield at byte 0 --
    // sole candidate. Pattern (offset=0, size=8) -> {Q2} only.
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_q1 = push_name(&mut strings, "Q1");
    let n_q2 = push_name(&mut strings, "Q2");
    let n_f = push_name(&mut strings, "f");
    let n_a = push_name(&mut strings, "a");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        // T has u64@8 source field.
        SynType::Struct {
            name_off: n_t,
            size: 16,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        // Q1 (kind_flag=1) with bitfield u64 at byte 0
        // (bitfield_size = 32 bits). Production must skip during
        // layout indexing because bitfield_size > 0.
        SynType::StructBitfields {
            name_off: n_q1,
            size: 8,
            members: vec![SynMemberBits {
                name_off: n_a,
                type_id: 1,
                bit_offset: 0,
                bitfield_size_bits: 32,
            }],
        },
        // Q2 with a normal u64 at byte 0 -- included in layout.
        SynType::Struct {
            name_off: n_q2,
            size: 8,
            members: vec![SynMember {
                name_off: n_a,
                type_id: 1,
                byte_offset: 0,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let q2_id = 4;
    // Sequence: r2 = *(u64*)(r1 + 8); cast r2 (F1 evidence);
    // r3 = *(u64*)(r2 + 0).
    // Pattern (0, 8): layout includes Q2 only (Q1's bitfield
    // skipped). Map records (T, 8) -> (Q2, Arena).
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q2_id,
            addr_space: AddrSpace::Arena,
        }),
        "bitfield candidate must be skipped: {map:?}"
    );
}

/// `BTF_KIND_UNION` participates in `build_layout_index` and
/// `struct_member_at` identically to `BTF_KIND_STRUCT` -- `btf-rs`
/// aliases `Union = Struct`, and production matches both via
/// `Type::Struct(s) | Type::Union(s)`. Verify a kptr STX through
/// a parent typed as a union records correctly, AND a candidate
/// search resolves to a union when its layout uniquely matches.
#[test]
fn union_works_like_struct_for_layout_and_member_lookup() {
    // BTF:
    //   id 1: u64
    //   id 2: T (struct, kptr target) { u64 x @ 0 }
    //   id 3: T*
    //   id 4: P (UNION) { u64 slot @ 16 }
    //   id 5: SourceU (struct) { u64 f @ 8 }
    //   id 6: TargetU (UNION) { u64 a @ 0 } -- candidate target
    //
    // Two checks in one test:
    //   (a) STX through a Pointer{P=union} into P.slot at offset
    //       16 records (P, 16) -> T (Kernel).
    //   (b) LDX through a SourceU producing LoadedU64Field then
    //       deref at offset 0 (size 8) finds TargetU (the only
    //       struct/union with u64@0 in this BTF after dropping
    //       SourceU which has u64@8 not u64@0).
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_p = push_name(&mut strings, "P");
    let n_su = push_name(&mut strings, "SourceU");
    let n_tu = push_name(&mut strings, "TargetU");
    let n_x = push_name(&mut strings, "x");
    let n_slot = push_name(&mut strings, "slot");
    let n_f = push_name(&mut strings, "f");
    let n_a = push_name(&mut strings, "a");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        // T has its u64 at offset 8 (NOT 0) so layout(0, 8) is
        // uniquely satisfied by TargetU below — production must
        // converge on TargetU only when intersecting candidates.
        SynType::Struct {
            name_off: n_t,
            size: 16,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        SynType::Ptr { type_id: 2 }, // id 3: T*
        // id 4: P as a UNION with a u64 slot at byte 16.
        SynType::Union {
            name_off: n_p,
            size: 24,
            members: vec![SynMember {
                name_off: n_slot,
                type_id: 1,
                byte_offset: 16,
            }],
        },
        // id 5: SourceU as a struct with u64 source field at
        // offset 8.
        SynType::Struct {
            name_off: n_su,
            size: 16,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        // id 6: TargetU as a UNION with u64 a at offset 0. Sole
        // candidate for the (0, 8) access pattern (after dropping
        // the source struct SourceU which has u64@8 not u64@0).
        // Ensures the layout index walks Union the same as Struct.
        SynType::Union {
            name_off: n_tu,
            size: 8,
            members: vec![SynMember {
                name_off: n_a,
                type_id: 1,
                byte_offset: 0,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let p_id = 4;
    let source_u_id = 5;
    let target_u_id = 6;
    // Block 1: kptr through union parent.
    //   r1 = Pointer{P=union}; r6 = Pointer{T}.
    //   *(u64*)(r1 + 16) = r6  -> kptr_findings[(P,16)] = T.
    // Block 2: arena LDX through union target.
    //   r2 = Pointer{SourceU}; r3 = *(u64*)(r2 + 8); r4 = *(u64*)(r3 + 0).
    //   Pattern (0, 8) -> {TargetU}; (SourceU, 8) -> (TargetU, Arena).
    // Add arena_confirmed evidence (F1) on r3 between the load
    // of SourceU.f and the deref through it.
    let insns = vec![
        stx(BPF_SIZE_DW, 1, 6, 16),
        ldx(BPF_SIZE_DW, 3, 2, 8),
        addr_space_cast(3, 3, 1),
        ldx(BPF_SIZE_DW, 4, 3, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: p_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 2,
                struct_type_id: source_u_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(p_id, 16)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "kptr through union parent must record: {map:?}"
    );
    assert_eq!(
        map.get(&(source_u_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: target_u_id,
            addr_space: AddrSpace::Arena,
        }),
        "union target must be a layout candidate: {map:?}"
    );
}

/// `build_layout_index`'s walk advances type ids `1..=max_id`
/// using `consecutive_fail` to short-circuit pathological /
/// synthesized BTFs. After 256 consecutive failed
/// `resolve_type_by_id` calls the loop breaks. To exercise this
/// path the test relies on the fact that `max_seen_type_id +
/// CANDIDATE_SEARCH_SLACK` (= 65538 here) is far above the
/// legitimate ids in the BTF, so the walk WOULD iterate ~65k
/// failed lookups without the cap; the consecutive fail cap of
/// 256 short-circuits early. Verify that:
///   - the matcher still finds the legitimate candidate (loop
///     visits valid ids before the cap kicks in),
///   - the matcher does not panic when many failed ids accumulate.
#[test]
fn build_layout_index_consecutive_fail_cap_short_circuits() {
    // BTF: u64(1), T(2, u64@8 source), Q(3, u64@0 unique target).
    // Type ids 4..=65538 would all fail -- production stops after
    // 256 consecutive fails. The legitimate candidate at id 3 is
    // found before the cap activates, so the cast still emits.
    let (blob, t_id, q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    // Even though ids 4..=65538 (max_seen=2 + slack=65536) all
    // resolve to errors, the consecutive_fail cap (256) stops the
    // loop early without panic, and Q(3) is recorded normally.
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "valid candidate must be found before fail cap; sparse \
             BTF must not panic: {map:?}"
    );
}

/// Non-bitfield members (`bitfield_size_bits = 0`) inside a
/// `kind_flag=1` struct ARE included in `build_layout_index`. The
/// production guard
/// `matches!(m.bitfield_size(), Some(s) if s > 0)` only matches
/// when the size is strictly positive. With kind_flag=1 every
/// member exposes `bitfield_size = Some(0)` for non-bitfield
/// members; production must NOT skip them.
#[test]
fn kind_flag_struct_includes_non_bitfield_members() {
    // BTF:
    //   id 1: u64
    //   id 2: T (kind_flag=0) { u64 src @ 8 }   -- source struct
    //   id 3: Q (kind_flag=1) { u64 a @ 0,
    //                            bf u64 b @ 64 (bitfield 32) }
    // Q has a non-bitfield u64 at byte 0. Production must include
    // it in layout (kind_flag=1, but bitfield_size=Some(0) since
    // bitfield_size_bits=0). The bitfield member at byte 8 is
    // skipped (bitfield_size_bits=32 > 0). Pattern (0, 8) -> {Q}.
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_q = push_name(&mut strings, "Q");
    let n_src = push_name(&mut strings, "src");
    let n_a = push_name(&mut strings, "a");
    let n_b = push_name(&mut strings, "b");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 16,
            members: vec![SynMember {
                name_off: n_src,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        // Q (kind_flag=1) has a non-bitfield u64 at byte 0 AND a
        // bitfield u64 at byte 8 (32-bit field). The non-bitfield
        // member must remain in layout despite kind_flag=1.
        SynType::StructBitfields {
            name_off: n_q,
            size: 16,
            members: vec![
                SynMemberBits {
                    name_off: n_a,
                    type_id: 1,
                    bit_offset: 0,
                    bitfield_size_bits: 0,
                },
                SynMemberBits {
                    name_off: n_b,
                    type_id: 1,
                    bit_offset: 64,
                    bitfield_size_bits: 32,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let q_id = 3;
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "non-bitfield member of kind_flag=1 struct must be a \
             layout candidate: {map:?}"
    );
}

// ----- Stack edge cases ---------------------------------------

/// `handle_stx`'s r10 spill guard treats a store with `off >= 0`
/// as out-of-spec for BPF (the stack grows DOWN; slots live at
/// negative offsets). The guard removes any prior slot at that
/// offset rather than saving state. Symmetrically, `handle_ldx`'s
/// r10 reload guard rejects loads with `off >= 0` and produces
/// Unknown. Verify the STX path's invalidation: a write with
/// `off >= 0` through r10 must remove any previously saved slot
/// state at that offset so a later DW reload returns Unknown.
#[test]
fn stack_off_non_negative_through_r10_invalidates() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // *(u64 *)(r10 + 0) = R1   ; off >= 0 spill: dropped, no
    //                            ; state saved at slot 0
    // R3 = *(u64 *)(r10 + 0)   ; off >= 0 reload: returns Unknown
    // *(u64 *)(R6 + slot_off) = R3
    //                          ; R3 Unknown -> no kptr finding
    let insns = vec![
        stx(BPF_SIZE_DW, 10, 1, 0),
        ldx(BPF_SIZE_DW, 3, 10, 0),
        stx(BPF_SIZE_DW, 6, 3, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "non-negative r10 store must not save state, reload \
             returns Unknown: {map:?}"
    );
}

/// `field_byte_offset` returns `None` for negative offsets when
/// the base register is NOT r10 (stack-relative loads are handled
/// separately via the r10 fast path). On a struct-pointer base,
/// a negative `off` is undefined behavior -- kernel struct fields
/// have non-negative byte offsets relative to the struct base.
/// Production drops dst to Unknown via
/// `field_byte_offset(off) -> None` and the LDX records nothing.
#[test]
fn negative_off_in_non_r10_context_drops() {
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    // r2 = *(u64 *)(r1 - 8): r1 is Pointer{T}, NOT r10. Negative
    // off goes to the Pointer arm of handle_ldx and produces
    // None in field_byte_offset, dropping dst to Unknown. No
    // pattern recorded.
    // r3 = *(u64 *)(r2 + 0): r2 Unknown -> no record.
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, -8),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "negative offset through Pointer{{T}} must drop, no \
             pattern recorded: {map:?}"
    );
}

/// Two consecutive STX-through-r10 spills with the SAME source
/// register state (Pointer{T}) overwrite the slot with a value
/// indistinguishable from the prior contents. Production stores
/// the second spill via `self.stack_slots.insert(off, regs[src])`
/// which replaces by key but does not collapse to Conflicting.
/// A later reload restores the same Pointer{T}; a subsequent STX
/// of the reloaded register into a parent slot must record the
/// kptr finding as `Single(T)` -- NOT `Conflicting`.
#[test]
fn stack_spill_same_target_stays_single() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // *(u64 *)(r10 - 8) = R1   ; spill Pointer{T} (slot=Pointer{T})
    // *(u64 *)(r10 - 8) = R1   ; spill Pointer{T} again -- same
    //                            ; target type, slot replaced
    //                            ; with same value, NOT Conflicting
    // R3 = *(u64 *)(r10 - 8)   ; reload as Pointer{T}
    // *(u64 *)(R6 + slot_off) = R3
    //                          ; records (P, slot_off) -> T
    let insns = vec![
        stx(BPF_SIZE_DW, 10, 1, -8),
        stx(BPF_SIZE_DW, 10, 1, -8),
        ldx(BPF_SIZE_DW, 3, 10, -8),
        stx(BPF_SIZE_DW, 6, 3, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(p_id, slot_off)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "spill of identical Pointer{{T}} must reload as Pointer{{T}}, \
             kptr stays Single: {map:?}"
    );
}

// ----- kfunc edge cases ---------------------------------------

/// `handle_kfunc_call` walks the FuncProto's return type through
/// `bpf_map::resolve_to_struct_id`. A return type that resolves
/// to a non-struct pointer (e.g. `int *`, `void *`) yields `None`
/// from the resolver, so R0 stays Unknown. A subsequent STX of
/// R0 into a u64 slot must NOT record a kptr finding.
#[test]
fn kfunc_call_returning_int_ptr_leaves_r0_unknown() {
    let slot_off: u32 = 16;
    // BTF:
    //   id 1: u64
    //   id 2: P (struct with u64 slot @ slot_off) -- kptr parent
    //         seed type for the post-call STX
    //   id 3: int* (Ptr -> u64). Pointee peels to Type::Int, so
    //         resolve_to_struct_id returns None.
    //   id 4: FuncProto returning id 3 (int*)
    //   id 5: Func -> id 4
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_p = push_name(&mut strings, "P");
    let n_slot = push_name(&mut strings, "slot");
    let n_kfunc = push_name(&mut strings, "bpf_returns_int_ptr");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_p,
            size: slot_off + 8,
            members: vec![SynMember {
                name_off: n_slot,
                type_id: 1,
                byte_offset: slot_off,
            }],
        },
        SynType::Ptr { type_id: 1 }, // id 3: u64*
        SynType::FuncProto {
            return_type_id: 3,
            params: vec![],
        },
        SynType::Func {
            name_off: n_kfunc,
            type_id: 4,
            linkage: 1,
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let p_id = 2;
    let kfunc_id = 5;
    // call kfunc returning int*; *(P + slot) = R0. R0 must be
    // Unknown (the return type's pointee resolves to Int, not
    // Struct, so resolve_to_struct_id returns None).
    let insns = vec![
        kfunc_call(kfunc_id),
        stx(BPF_SIZE_DW, 6, 0, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: p_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "kfunc returning int* must leave R0 Unknown: {map:?}"
    );
}

/// `handle_kfunc_call` short-circuits when the FuncProto's
/// `return_type_id == 0` (void return). R0 stays Unknown after
/// the standard r0..r5 clobber. A subsequent STX of R0 into a
/// u64 slot must NOT record a kptr finding.
#[test]
fn kfunc_call_void_return_leaves_r0_unknown() {
    let slot_off: u32 = 16;
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_p = push_name(&mut strings, "P");
    let n_slot = push_name(&mut strings, "slot");
    let n_kfunc = push_name(&mut strings, "bpf_void_return");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_p,
            size: slot_off + 8,
            members: vec![SynMember {
                name_off: n_slot,
                type_id: 1,
                byte_offset: slot_off,
            }],
        },
        // id 3: FuncProto -> void (return_type_id = 0).
        SynType::FuncProto {
            return_type_id: 0,
            params: vec![],
        },
        // id 4: Func -> id 3.
        SynType::Func {
            name_off: n_kfunc,
            type_id: 3,
            linkage: 1,
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let p_id = 2;
    let kfunc_id = 4;
    let insns = vec![
        kfunc_call(kfunc_id),
        stx(BPF_SIZE_DW, 6, 0, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: p_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "kfunc with void return must leave R0 Unknown: {map:?}"
    );
}

/// `handle_kfunc_call`'s `imm` may resolve directly to a
/// `Type::FuncProto` (no `Type::Func` wrapper). Production peels
/// `Type::Func -> Type::FuncProto` when needed but also accepts a
/// FuncProto id directly. A kfunc call with `imm` == FuncProto id
/// must seed R0 from the proto's return type just as it would
/// from a Func wrapper.
#[test]
fn kfunc_call_with_funcproto_id_directly() {
    let slot_off: u32 = 16;
    // BTF:
    //   id 1: u64
    //   id 2: T (kptr target struct) { u64 x @ 0 }
    //   id 3: T*
    //   id 4: P (struct holding the kptr slot)
    //   id 5: FuncProto -> T*  (no Func wrapper)
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_p = push_name(&mut strings, "P");
    let n_x = push_name(&mut strings, "x");
    let n_slot = push_name(&mut strings, "slot");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Ptr { type_id: 2 }, // id 3: T*
        SynType::Struct {
            name_off: n_p,
            size: slot_off + 8,
            members: vec![SynMember {
                name_off: n_slot,
                type_id: 1,
                byte_offset: slot_off,
            }],
        },
        // id 5: FuncProto returning T* -- pass id=5 directly to
        // kfunc_call's imm so the resolver hits the Type::FuncProto
        // arm, not Type::Func -> peel.
        SynType::FuncProto {
            return_type_id: 3,
            params: vec![],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let p_id = 4;
    let proto_id = 5;
    // kfunc call with imm = proto_id (id 5 = FuncProto). R0 must
    // be set to Pointer{T} via the FuncProto-direct path.
    let insns = vec![
        kfunc_call(proto_id),
        stx(BPF_SIZE_DW, 6, 0, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: p_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(p_id, slot_off)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "kfunc with direct FuncProto id must seed R0 from return \
             type: {map:?}"
    );
}

// ----- Register protection tests ------------------------------
//
// R10 is the read-only frame pointer per the BPF ABI; the
// analyzer enforces the invariant that `regs[10]` is always
// Unknown by guarding MOV and LDX early. Out-of-range register
// indices (11..=15) can appear in a malformed instruction stream
// because BpfInsn packs each field into 4 bits; the bounds check
// at the top of step() and each handle_* routine rejects without
// panicking.

/// MOV with `dst == r10` is rejected by the production guard in
/// the ALU64-MOV-X arm (`if dst == BPF_REG_R10 { return; }`).
/// Verifying r10's state directly is impossible because the
/// stack-spill / reload path keys on the register index, not on
/// `regs[10]`'s `RegState`. The probe instead routes through a
/// second MOV: `MOV r3, r10` copies `regs[10]` into `regs[3]`,
/// then a deref chain through r3 records a cast iff `regs[10]`
/// was typed. With the rejection working, `regs[10]` stays
/// Unknown, so r3 stays Unknown, and the deref chain produces no
/// record.
#[test]
fn mov_to_r10_rejected_keeps_r10_unknown() {
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    // r2 = *(u64 *)(r1 + 8)   -- r2 = LoadedU64Field{T, 8}
    // r10 = r2                -- REJECTED, r10 stays Unknown
    // r3 = r10                -- r3 = regs[10] = Unknown
    // r4 = *(u64 *)(r3 + 0)   -- r3 Unknown, no record
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        mov_x(10, 2),
        mov_x(3, 10),
        ldx(BPF_SIZE_DW, 4, 3, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "MOV r10, r2 must be rejected so r10 stays Unknown: {map:?}"
    );
}

/// LDX with `dst == r10` is rejected by the production guard
/// (`if dst == BPF_REG_R10 { return; }` in `handle_ldx`). The
/// same routing trick as `mov_to_r10_rejected_keeps_r10_unknown`
/// observes the rejection: a successful LDX into r10 would have
/// seeded `regs[10] = LoadedU64Field`, and a follow-up
/// `MOV r3, r10; LDX r4, [r3+0]` chain would record a cast.
/// With the guard active, r10 stays Unknown and the chain
/// produces nothing.
#[test]
fn ldx_into_r10_rejected_keeps_r10_unknown() {
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    // r10 = *(u64 *)(r1 + 8)  -- REJECTED, r10 stays Unknown
    // r3 = r10                -- r3 = regs[10] = Unknown
    // r4 = *(u64 *)(r3 + 0)   -- r3 Unknown, no record
    let insns = vec![
        ldx(BPF_SIZE_DW, 10, 1, 8),
        mov_x(3, 10),
        ldx(BPF_SIZE_DW, 4, 3, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "LDX r10, [r1+8] must be rejected so r10 stays Unknown: {map:?}"
    );
}

/// `BPF_STX | BPF_DW | BPF_MEM` with both `dst` and `src` out of
/// the 0..=10 valid register range (encoded as 15) must NOT panic.
/// `BpfInsn::new` masks each register field to 4 bits, so 15
/// round-trips through `dst_reg()` / `src_reg()` as 15. The bounds
/// check at the top of `step()` (and the redundant guard in
/// `handle_stx`) reject before any array indexing.
#[test]
fn oob_stx_reg_does_not_panic() {
    let (blob, _t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let bad = BpfInsn::new(BPF_CLASS_STX | BPF_SIZE_DW | BPF_MODE_MEM, 15, 15, 0, 0);
    let insns = vec![bad, exit()];
    let map = analyze_casts(&insns, &btf, &[], &[], &[], &[]);
    assert!(
        map.is_empty(),
        "OOB STX (dst=15, src=15) must not panic: {map:?}"
    );
}

/// `BPF_ALU64 | BPF_OP_MOV | BPF_SRC_X` with `dst == 15` (out of
/// range) must NOT panic. The bounds check at the top of `step()`
/// rejects before the MOV branch executes.
#[test]
fn oob_mov_reg_does_not_panic() {
    let (blob, _t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let bad = BpfInsn::new(BPF_CLASS_ALU64 | BPF_OP_MOV | BPF_SRC_X, 15, 0, 0, 0);
    let insns = vec![bad, exit()];
    let map = analyze_casts(&insns, &btf, &[], &[], &[], &[]);
    assert!(map.is_empty(), "OOB MOV (dst=15) must not panic: {map:?}");
}

/// `BPF_STX | BPF_DW | BPF_ATOMIC` with `dst` and `src` out of
/// range (15) must NOT panic. The bounds check at the top of
/// `step()` rejects before dispatch into `handle_atomic`; the
/// redundant guard at the top of `handle_atomic` is a defense-in-
/// depth backstop.
#[test]
fn oob_atomic_reg_does_not_panic() {
    let (blob, _t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let bad = BpfInsn::new(
        BPF_CLASS_STX | BPF_SIZE_DW | BPF_MODE_ATOMIC,
        15,
        15,
        0,
        BPF_FETCH | 0xe0,
    );
    let insns = vec![bad, exit()];
    let map = analyze_casts(&insns, &btf, &[], &[], &[], &[]);
    assert!(
        map.is_empty(),
        "OOB ATOMIC (dst=15, src=15) must not panic: {map:?}"
    );
}

/// `MOV dst, src` where the source register is `Unknown`
/// overwrites the destination's typed state with `Unknown`.
/// Production unconditionally copies `regs[src]` into `regs[dst]`,
/// so a previously-typed dst loses its `Pointer{T}` /
/// `LoadedU64Field` state when an Unknown source is moved in. A
/// subsequent deref through dst must NOT record a cast.
#[test]
fn mov_x_unknown_source_overwrites_typed_dst() {
    // Seed r2 with a load chain so it carries LoadedU64Field{T, 8}.
    // Then MOV r2 = r3, where r3 stays Unknown. r2 becomes Unknown.
    // The follow-up deref chain through r2 must produce no record.
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![
        // r2 = *(u64*)(r1+8)  -- r2 = LoadedU64Field{T, 8}
        ldx(BPF_SIZE_DW, 2, 1, 8),
        // r2 = r3            -- r3 Unknown -> r2 becomes Unknown
        mov_x(2, 3),
        // r4 = *(u64*)(r2+0) -- r2 Unknown, no record
        ldx(BPF_SIZE_DW, 4, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "MOV with Unknown source must overwrite typed dst: {map:?}"
    );
}

/// Self-copy `MOV r2, r2` preserves the register's state because
/// production reads and writes `regs[2]` with no intermediate
/// transformation. A typed register that self-copies continues
/// to carry its typed state into subsequent operations.
#[test]
fn mov_x_self_copy_preserves_state() {
    let (blob, t_id, q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![
        // r2 = *(u64*)(r1+8)  -- r2 = LoadedU64Field{T, 8}
        ldx(BPF_SIZE_DW, 2, 1, 8),
        // r2 = arena_cast(r2) -- arena_confirmed evidence (F1)
        addr_space_cast(2, 2, 1),
        // r2 = r2             -- self-copy, r2 stays LoadedU64Field
        mov_x(2, 2),
        // r3 = *(u64*)(r2+0)  -- records access, resolves to Q
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "MOV self-copy must preserve LoadedU64Field state: {map:?}"
    );
}

/// 32-bit MOV (`BPF_CLASS_ALU | BPF_OP_MOV | BPF_SRC_X`) destroys
/// typed-pointer state in the destination register because a
/// 32-bit move truncates the upper 32 bits of any 64-bit pointer.
/// Production routes 32-bit MOV to `set_reg(dst, Unknown)`
/// regardless of source state. A subsequent deref through the
/// destination must record nothing.
#[test]
fn mov32_destroys_typed_state() {
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    // Build a 32-bit MOV: ALU (not ALU64) | MOV | SRC_X.
    let mov32 = mk_insn(BPF_CLASS_ALU | BPF_OP_MOV | BPF_SRC_X, 4, 2, 0, 0);
    let insns = vec![
        // r2 = *(u64*)(r1+8)  -- r2 = LoadedU64Field{T, 8}
        ldx(BPF_SIZE_DW, 2, 1, 8),
        // r4 = (u32) r2       -- 32-bit MOV truncates -> r4 = Unknown
        mov32,
        // r5 = *(u64*)(r4+0)  -- r4 Unknown, no record
        ldx(BPF_SIZE_DW, 5, 4, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(map.is_empty(), "32-bit MOV must drop typed state: {map:?}");
}

// ----- ALU op tests -------------------------------------------
//
// All non-MOV ALU ops (ADD, SUB, AND, OR, LSH, etc.) and
// immediate-source MOV (`BPF_OP_MOV | BPF_SRC_K`) destroy the
// typed-pointer property of the destination register. Production
// handles every such case via the catch-all in the ALU dispatch:
// drop dst to Unknown.
//
// Tests verify destruction by setting up a Pointer{T} register
// that would normally produce a kptr finding when stored into a
// P struct's u64 slot, then applying the ALU op, then performing
// the STX. With the destruction working, the STX records nothing.

/// `BPF_ALU64 | BPF_ADD | BPF_SRC_X` with a typed pointer in dst
/// destroys the pointer state. Pointer + integer is no longer a
/// pointer to the same struct (it's a derived address), so the
/// kptr finding must drop.
#[test]
fn alu64_add_x_destroys_typed_pointer() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // ALU64 ADD X: code = BPF_CLASS_ALU64 | BPF_ADD | BPF_SRC_X.
    // BPF_ADD = 0x00, so code = 0x07 | 0x00 | 0x08 = 0x0f.
    let add_x = mk_insn(
        BPF_CLASS_ALU64 | (bs::BPF_ADD as u8) | BPF_SRC_X,
        1,
        3,
        0,
        0,
    );
    // r1 starts Pointer{T}. ADD r1, r3 -> r1 Unknown.
    // STX *(r6+slot_off) = r1 -> no record.
    let insns = vec![add_x, stx(BPF_SIZE_DW, 6, 1, slot_off as i16), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "ALU64 ADD X must destroy typed pointer: {map:?}"
    );
}

/// `BPF_ALU64 | BPF_SUB | BPF_SRC_X` destroys the typed pointer
/// state of the destination register. Same shape as ADD: any
/// arithmetic on a pointer produces an integer, not a typed
/// pointer.
#[test]
fn alu64_sub_x_destroys_typed_pointer() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    let sub_x = mk_insn(
        BPF_CLASS_ALU64 | (bs::BPF_SUB as u8) | BPF_SRC_X,
        1,
        3,
        0,
        0,
    );
    let insns = vec![sub_x, stx(BPF_SIZE_DW, 6, 1, slot_off as i16), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "ALU64 SUB X must destroy typed pointer: {map:?}"
    );
}

/// `BPF_ALU64 | BPF_AND | BPF_SRC_X` destroys the typed pointer
/// state of the destination register. Bitwise AND on a pointer
/// produces a masked integer, not a typed pointer.
#[test]
fn alu64_and_x_destroys_typed_pointer() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    let and_x = mk_insn(
        BPF_CLASS_ALU64 | (bs::BPF_AND as u8) | BPF_SRC_X,
        1,
        3,
        0,
        0,
    );
    let insns = vec![and_x, stx(BPF_SIZE_DW, 6, 1, slot_off as i16), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "ALU64 AND X must destroy typed pointer: {map:?}"
    );
}

/// `BPF_ALU64 | BPF_ADD | BPF_SRC_K` (immediate ADD) destroys
/// typed-pointer state in the destination register. Same code
/// path as ADD with register source -- production drops dst to
/// Unknown for any non-MOV-X-ALU64 op.
#[test]
fn alu64_add_k_destroys_typed_pointer() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // ALU64 ADD K: BPF_SRC_K is 0, so source field is unused.
    // imm carries the constant.
    let add_k = mk_insn(BPF_CLASS_ALU64 | (bs::BPF_ADD as u8), 1, 0, 0, 8);
    let insns = vec![add_k, stx(BPF_SIZE_DW, 6, 1, slot_off as i16), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "ALU64 ADD K must destroy typed pointer: {map:?}"
    );
}

/// Immediate MOV (`mov_k`, `BPF_OP_MOV | BPF_SRC_K`) destroys the
/// destination register's typed-pointer state. The catch-all in
/// the ALU dispatch handles this case because the `BPF_OP_MOV +
/// BPF_SRC_X` short-circuit only matches the register source
/// variant; the immediate variant lands in the destruction branch.
#[test]
fn mov_k_destroys_typed_pointer() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // mov_k r1, 42 -> r1 Unknown.
    // STX *(r6+slot_off) = r1 -> no record.
    let insns = vec![
        mov_k(1, 42),
        stx(BPF_SIZE_DW, 6, 1, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(map.is_empty(), "mov_k must destroy typed pointer: {map:?}");
}

// ----- Additional BPF_ADDR_SPACE_CAST tests -------------------

/// `BPF_ADDR_SPACE_CAST` with a reserved imm value (`imm == 2`,
/// neither `1` nor `0x10000`) drops the destination register to
/// Unknown. The verifier in `kernel/bpf/verifier.c check_alu_op`
/// rejects programs that use any other imm for
/// `BPF_ADDR_SPACE_CAST`, so seeing it in pre-verification
/// bytecode is malformed; treating dst as Unknown is the
/// conservative direction.
#[test]
fn addr_space_cast_unknown_imm_drops_dst() {
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    // r3 = *(u64*)(r1+8)             -- r3 = LoadedU64Field{T, 8}
    // r4 = (cast imm=2) r3            -- imm=2 is reserved, r4 Unknown
    // r5 = *(u64*)(r4+0)              -- no record
    let cast = mk_insn(BPF_CLASS_ALU64 | BPF_OP_MOV | BPF_SRC_X, 4, 3, 1, 2);
    let insns = vec![
        ldx(BPF_SIZE_DW, 3, 1, 8),
        cast,
        ldx(BPF_SIZE_DW, 5, 4, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "BPF_ADDR_SPACE_CAST with reserved imm must drop dst: {map:?}"
    );
}

/// `BPF_ADDR_SPACE_CAST` arena -> kernel (`imm == 1`) on a
/// `Pointer{T}` source (rather than a `LoadedU64Field`) propagates
/// the typed pointer state into the destination register.
/// Production unconditionally copies `regs[src]` into `regs[dst]`;
/// the LoadedU64Field-only branch merely populates
/// `arena_confirmed` as a side effect when the source matches
/// that variant. Since Pointer{T} sources skip the
/// `arena_confirmed` insertion, no false-positive arena evidence
/// is recorded, and the typed pointer survives the cast for use
/// as a kptr value in a subsequent STX.
#[test]
fn addr_space_cast_arena_imm1_on_pointer_propagates() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // r4 = (cast imm=1) r3   -- r3 = Pointer{T}, r4 = Pointer{T}
    // STX *(r6+slot_off) = r4 -- records (P, slot_off) -> T kptr finding
    let cast = mk_insn(BPF_CLASS_ALU64 | BPF_OP_MOV | BPF_SRC_X, 4, 3, 1, 1);
    let insns = vec![cast, stx(BPF_SIZE_DW, 6, 4, slot_off as i16), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 3,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(p_id, slot_off)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "ADDR_SPACE_CAST imm=1 on Pointer{{T}} must propagate state: {map:?}"
    );
}

/// `BPF_ADDR_SPACE_CAST` kernel -> arena (`imm == 0x10000`) on a
/// `Pointer{T}` source drops the destination to Unknown, even
/// though the source carries a typed kernel pointer. Production
/// routes any imm other than `1` (including `0x10000`) through
/// the else branch, which clears dst regardless of source state.
/// A subsequent kptr STX through the destination must NOT record.
///
/// Sibling test `addr_space_cast_kernel_to_arena_drops_dst`
/// covers the `LoadedU64Field` source case; this test verifies
/// that `Pointer{T}` survives `addr_space_cast(imm=0x10000)` so
/// subsequent field loads through the cast destination produce
/// `LoadedU64Field` entries (needed for cross-subprog arena
/// pointer detection where a callee casts a forwarded Pointer
/// parameter).
#[test]
fn addr_space_cast_kernel_arena_preserves_pointer_source() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // r4 = (cast imm=0x10000) r3   -- r3 = Pointer{T}, r4 = Pointer{T}
    // STX *(r6+slot_off) = r4      -- r4 Pointer{T}, kptr record
    let cast = mk_insn(BPF_CLASS_ALU64 | BPF_OP_MOV | BPF_SRC_X, 4, 3, 1, 0x10000);
    let insns = vec![cast, stx(BPF_SIZE_DW, 6, 4, slot_off as i16), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 3,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.len(),
        1,
        "Pointer through addr_space_cast should produce a kptr CastHit: {map:?}"
    );
}

// ----- Misc tests ---------------------------------------------

/// `BPF_LD | BPF_W | BPF_ABS` (`code == 0x20`) is the legacy
/// packet-data load mode kept for socket filters; it loads from
/// packet data into r0. Production sets r0 to Unknown for any LD
/// mode that is not the LD_IMM64 two-slot form. A previously-
/// typed r0 must lose its typed state, so a follow-up kptr STX
/// through r0 produces no record.
#[test]
fn bpf_ld_abs_clears_r0() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // BPF_LD | BPF_W | BPF_ABS = 0x00 | 0x00 | 0x20 = 0x20.
    let ld_abs = mk_insn(BPF_CLASS_LD | BPF_SIZE_W | (bs::BPF_ABS as u8), 0, 0, 0, 0);
    // r0 starts Pointer{T}. After BPF_LD_ABS, r0 is Unknown.
    // STX *(r6+slot_off) = r0 -> no record.
    let insns = vec![ld_abs, stx(BPF_SIZE_DW, 6, 0, slot_off as i16), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 0,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "BPF_LD_ABS must clear r0 typed state: {map:?}"
    );
}

/// `BPF_LD | BPF_W | BPF_IND` (`code == 0x40`) is the indirect
/// packet-data load mode for socket filters; it loads from
/// `packet[src + imm]` into r0. Production treats it the same way
/// as `BPF_LD_ABS`: r0 becomes Unknown. A previously-typed r0
/// must lose its state.
#[test]
fn bpf_ld_ind_clears_r0() {
    let slot_off: u32 = 16;
    let (blob, t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    // BPF_LD | BPF_W | BPF_IND = 0x00 | 0x00 | 0x40 = 0x40.
    let ld_ind = mk_insn(BPF_CLASS_LD | BPF_SIZE_W | (bs::BPF_IND as u8), 0, 0, 0, 0);
    let insns = vec![ld_ind, stx(BPF_SIZE_DW, 6, 0, slot_off as i16), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 0,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 6,
                struct_type_id: p_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "BPF_LD_IND must clear r0 typed state: {map:?}"
    );
}

/// A program consisting of a single `EXIT` instruction must not
/// panic and must produce an empty `CastMap`. EXIT is in
/// `BPF_CLASS_JMP` with `op == BPF_OP_EXIT`, which production
/// explicitly leaves unmodified. The empty instruction-stream
/// behavior is the baseline; this test guards against regressions
/// where a "no recognizable ops" program produces phantom output.
#[test]
fn single_exit_does_not_panic() {
    let (blob, _t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![exit()];
    let map = analyze_casts(&insns, &btf, &[], &[], &[], &[]);
    assert!(map.is_empty(), "single EXIT must yield empty map: {map:?}");
}

/// A program of only jump / branch instructions (no LDX, STX, MOV,
/// or call) carries no data flow that the analyzer could track.
/// Production processes each insn through `step()` but the JMP
/// arm only mutates state on CALL -- branches and EXIT are no-ops
/// for state. The forward walk completes without panicking; the
/// output map is empty even though every PC is processed.
#[test]
fn jumps_only_program_does_not_panic() {
    let (blob, _t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    // BPF_JEQ_K = 0x10. Construct a sequence of conditional and
    // unconditional jumps that branch within bounds.
    // pc 0: if r1 == 0 goto +1 (target = pc 2)
    // pc 1: ja +1               (target = pc 3)
    // pc 2: ja -2               (target = pc 1)
    // pc 3: exit
    let jeq = mk_insn(BPF_CLASS_JMP | 0x10, 1, 0, 1, 0);
    let ja_plus = mk_insn(BPF_CLASS_JMP, 0, 0, 1, 0);
    let ja_minus = mk_insn(BPF_CLASS_JMP, 0, 0, -2, 0);
    let insns = vec![jeq, ja_plus, ja_minus, exit()];
    let map = analyze_casts(&insns, &btf, &[], &[], &[], &[]);
    assert!(
        map.is_empty(),
        "all-jumps program must yield empty map: {map:?}"
    );
}

// ----- BSS / Datasec kptr detection ---------------------------
//
// These tests exercise the `BPF_PSEUDO_MAP_VALUE` path in the
// `BPF_LD_IMM64` arm. The tests build a synthetic BTF with a
// `BTF_KIND_DATASEC` over a `BTF_KIND_VAR` whose underlying
// type is a plain u64 — the BSS layout libbpf generates for
// `__u64 my_kptr;`. The `DatasecPointer` annotation passed to
// `analyze_casts` mirrors what the host-side cast loader
// emits after walking `.rel.text` against the program's
// datasec sections.

/// Helper: emit `BPF_LD_IMM64 dst, imm` as the two-instruction
/// pseudo. The second slot's `code` is 0 per linux uapi
/// `bpf.h`. The analyzer's `skip_next` flag swallows the
/// second slot.
fn ld_imm64(dst: u8, imm: i32) -> [BpfInsn; 2] {
    let lo = mk_insn(BPF_CLASS_LD | BPF_SIZE_DW | BPF_MODE_IMM, dst, 0, 0, imm);
    let hi = mk_insn(0, 0, 0, 0, 0);
    [lo, hi]
}

/// Build a synthetic BTF that declares a `BTF_KIND_DATASEC`
/// (`.bss`) containing a single u64 global variable
/// (`my_kptr`) at offset 0. Returns `(blob, datasec_id,
/// kptr_target_id, var_byte_offset, kfunc_btf_id)` where
/// `kptr_target_id` is a separate struct
/// (`task_struct`-stand-in) that the STX path stores INTO
/// the u64 slot.
///
/// Layout (BTF type ids assigned in order):
/// - id 1: int u64 (size=8, bits=64)
/// - id 2: struct task_struct { u64 x @ 0 }   -- kptr target
/// - id 3: T*
/// - id 4: BTF_KIND_VAR(name="my_kptr", type=1, linkage=GLOBAL)
/// - id 5: BTF_KIND_DATASEC(name=".bss", size=8, entries=[
///   {type=4, offset=0, size=8}])
/// - id 6: FuncProto returning T*
/// - id 7: Func("bpf_task_acquire") -> id 6
fn btf_bss_with_kptr() -> (Vec<u8>, u32, u32, u32, u32) {
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "task_struct");
    let n_x = push_name(&mut strings, "x");
    let n_kptr = push_name(&mut strings, "my_kptr");
    let n_bss = push_name(&mut strings, ".bss");
    let n_kfunc = push_name(&mut strings, "bpf_task_acquire");
    let types = vec![
        // id 1: u64
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        // id 2: struct task_struct { u64 x @ 0 }
        SynType::Struct {
            name_off: n_t,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        // id 3: T*
        SynType::Ptr { type_id: 2 },
        // id 4: Var("my_kptr", type=u64=1, linkage=GLOBAL)
        SynType::Var {
            name_off: n_kptr,
            type_id: 1,
            linkage: 1,
        },
        // id 5: Datasec(".bss") containing my_kptr at offset 0
        SynType::Datasec {
            name_off: n_bss,
            size: 8,
            entries: vec![SynVarSecinfo {
                type_id: 4,
                offset: 0,
                size: 8,
            }],
        },
        // id 6: FuncProto -> T*
        SynType::FuncProto {
            return_type_id: 3,
            params: vec![],
        },
        // id 7: Func bpf_task_acquire (linkage = global)
        SynType::Func {
            name_off: n_kfunc,
            type_id: 6,
            linkage: 1,
        },
    ];
    let blob = build_btf(&types, &strings);
    (blob, 5, 2, 0, 7)
}

/// `BPF_LD_IMM64` with a `DatasecPointer` annotation must type
/// the destination register as a typed pointer into the
/// datasec. The follow-up STX through that register records a
/// kptr finding keyed on `(datasec_id, var_byte_offset)`.
///
/// Sequence (mirrors clang's `my_kptr = bpf_task_acquire(...)`
/// codegen):
///   call kfunc bpf_task_acquire   ; r0 = T*
///   r1 = LD_IMM64(.bss, 0)        ; r1 = DatasecPointer{bss, 0}
///   *(u64 *)(r1 + 0) = r0         ; STX r0 into .bss[my_kptr]
///
/// Expected: CastMap entry
/// `(datasec_id, 0) -> (T, AddrSpace::Kernel)`.
#[test]
fn bss_kptr_records_kernel_cast() {
    let (blob, datasec_id, t_id, var_off, kfunc_id) = btf_bss_with_kptr();
    let btf = Btf::from_bytes(&blob).unwrap();
    let [ld_lo, ld_hi] = ld_imm64(1, var_off as i32);
    let stx_kptr = stx(BPF_SIZE_DW, 1, 0, 0);
    let insns = vec![kfunc_call(kfunc_id), ld_lo, ld_hi, stx_kptr, exit()];
    // PC numbering: 0=call, 1=ld_lo, 2=ld_hi (skipped via
    // skip_next), 3=stx, 4=exit. The DatasecPointer marks PC=1
    // (the BPF_LD_IMM64 lo slot) as targeting the .bss
    // datasec at the my_kptr offset.
    let datasec_pointers = vec![DatasecPointer {
        insn_offset: 1,
        datasec_type_id: datasec_id,
        base_offset: var_off,
    }];
    let map = analyze_casts(&insns, &btf, &[], &[], &datasec_pointers, &[]);
    assert_eq!(
        map.get(&(datasec_id, var_off)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "kfunc-returned T* stored into .bss[my_kptr] must record \
             (datasec_id, 0) -> (T, Kernel): {map:?}"
    );
}

/// `BPF_LD_IMM64` WITHOUT a `DatasecPointer` annotation leaves
/// the destination register as `Unknown`, so a follow-up STX
/// through it cannot record a kptr finding. This guards
/// against a regression where the analyzer accidentally types
/// the LD_IMM64 destination as the global variable's
/// underlying integer type just from the BTF.
#[test]
fn ld_imm64_without_annotation_no_record() {
    let (blob, _datasec_id, _t_id, var_off, kfunc_id) = btf_bss_with_kptr();
    let btf = Btf::from_bytes(&blob).unwrap();
    let [ld_lo, ld_hi] = ld_imm64(1, var_off as i32);
    let stx_kptr = stx(BPF_SIZE_DW, 1, 0, 0);
    let insns = vec![kfunc_call(kfunc_id), ld_lo, ld_hi, stx_kptr, exit()];
    // Empty datasec_pointers — analyzer has no way to recover
    // the parent datasec id, so the LD_IMM64 destination
    // stays Unknown.
    let map = analyze_casts(&insns, &btf, &[], &[], &[], &[]);
    assert!(
        map.is_empty(),
        "LD_IMM64 without DatasecPointer annotation must not record \
             a kptr finding: {map:?}"
    );
}

/// `BPF_LD_IMM64` with a `DatasecPointer` annotation but the
/// follow-up STX uses an untyped value register (literal
/// constant via mov_k) records nothing. The kptr path
/// requires both base AND value registers to be typed.
#[test]
fn bss_stx_with_untyped_value_no_record() {
    let (blob, datasec_id, _t_id, var_off, _kfunc_id) = btf_bss_with_kptr();
    let btf = Btf::from_bytes(&blob).unwrap();
    let [ld_lo, ld_hi] = ld_imm64(1, var_off as i32);
    // r0 = literal 0 (mov_k clobbers any prior typed state)
    // *(u64 *)(r1 + 0) = r0      ; r0 Unknown -> no record
    let mov_zero = mov_k(0, 0);
    let stx_kptr = stx(BPF_SIZE_DW, 1, 0, 0);
    let insns = vec![ld_lo, ld_hi, mov_zero, stx_kptr, exit()];
    let datasec_pointers = vec![DatasecPointer {
        insn_offset: 0,
        datasec_type_id: datasec_id,
        base_offset: var_off,
    }];
    let map = analyze_casts(&insns, &btf, &[], &[], &datasec_pointers, &[]);
    assert!(
        map.is_empty(),
        "STX with untyped value register must not record kptr: {map:?}"
    );
}

/// Multi-variable BSS layout: a single datasec contains TWO
/// u64 globals at distinct offsets. The analyzer must key
/// each kptr finding on the right `(datasec_id, var_offset)`
/// pair without conflating them.
#[test]
fn bss_multi_variable_layout() {
    // BTF: u64(1), T(2, u64@0), T*(3), Var "kptr_a"(4),
    // Var "kptr_b"(5), Datasec(6, [(4,0,8), (5,16,8)]),
    // FuncProto(7), Func(8).
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "task_struct");
    let n_x = push_name(&mut strings, "x");
    let n_a = push_name(&mut strings, "kptr_a");
    let n_b = push_name(&mut strings, "kptr_b");
    let n_bss = push_name(&mut strings, ".bss");
    let n_kfunc = push_name(&mut strings, "bpf_task_acquire");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Ptr { type_id: 2 },
        SynType::Var {
            name_off: n_a,
            type_id: 1,
            linkage: 1,
        },
        SynType::Var {
            name_off: n_b,
            type_id: 1,
            linkage: 1,
        },
        SynType::Datasec {
            name_off: n_bss,
            size: 24,
            entries: vec![
                SynVarSecinfo {
                    type_id: 4,
                    offset: 0,
                    size: 8,
                },
                SynVarSecinfo {
                    type_id: 5,
                    offset: 16,
                    size: 8,
                },
            ],
        },
        SynType::FuncProto {
            return_type_id: 3,
            params: vec![],
        },
        SynType::Func {
            name_off: n_kfunc,
            type_id: 7,
            linkage: 1,
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let datasec_id = 6;
    let t_id = 2;
    let kfunc_id = 8;
    let [ld_a_lo, ld_a_hi] = ld_imm64(1, 0);
    let [ld_b_lo, ld_b_hi] = ld_imm64(2, 16);
    let insns = vec![
        kfunc_call(kfunc_id),
        ld_a_lo,
        ld_a_hi,
        stx(BPF_SIZE_DW, 1, 0, 0),
        kfunc_call(kfunc_id),
        ld_b_lo,
        ld_b_hi,
        stx(BPF_SIZE_DW, 2, 0, 0),
        exit(),
    ];
    // PC numbering: 0=call, 1=ld_a_lo, 2=ld_a_hi, 3=stx_a,
    // 4=call, 5=ld_b_lo, 6=ld_b_hi, 7=stx_b, 8=exit.
    let datasec_pointers = vec![
        DatasecPointer {
            insn_offset: 1,
            datasec_type_id: datasec_id,
            base_offset: 0,
        },
        DatasecPointer {
            insn_offset: 5,
            datasec_type_id: datasec_id,
            base_offset: 16,
        },
    ];
    let map = analyze_casts(&insns, &btf, &[], &[], &datasec_pointers, &[]);
    assert_eq!(
        map.get(&(datasec_id, 0)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "kptr_a at offset 0: {map:?}"
    );
    assert_eq!(
        map.get(&(datasec_id, 16)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "kptr_b at offset 16: {map:?}"
    );
}

/// `struct_member_at` on a Datasec parent finds the variable
/// whose byte range contains the queried offset. A query
/// inside a multi-byte variable's range returns the
/// variable's start offset, NOT the queried offset, in
/// `MemberAt::Datasec::var_byte_offset`. A query that lands
/// outside any variable's range returns None.
#[test]
fn struct_member_at_datasec_resolves_variables() {
    let (blob, datasec_id, _t_id, _var_off, _kfunc_id) = btf_bss_with_kptr();
    let btf = Btf::from_bytes(&blob).unwrap();
    // Exact-offset hit: my_kptr starts at byte 0.
    let m0 = struct_member_at(&btf, datasec_id, 0).expect("byte 0 must hit my_kptr");
    match m0 {
        MemberAt::Datasec {
            var_byte_offset, ..
        } => assert_eq!(var_byte_offset, 0),
        MemberAt::Struct { .. } => panic!("Datasec parent must yield Datasec match"),
    }
    // Mid-variable hit: byte 4 lands inside my_kptr's [0, 8)
    // range; should return the variable's start (0).
    let m4 = struct_member_at(&btf, datasec_id, 4).expect("byte 4 must hit my_kptr range");
    match m4 {
        MemberAt::Datasec {
            var_byte_offset, ..
        } => assert_eq!(var_byte_offset, 0),
        MemberAt::Struct { .. } => panic!("Datasec parent must yield Datasec match"),
    }
    // Out-of-range hit: byte 100 is past the section.
    assert!(
        struct_member_at(&btf, datasec_id, 100).is_none(),
        "byte 100 outside section must return None"
    );
}

/// End-to-end: a BSS u64 stores a kfunc-returned pointer
/// (mirrors `__u64 my_kptr; my_kptr = bpf_task_acquire(...)`
/// at the analyzer level). Produces exactly one CastMap entry
/// keyed on `(datasec_id, 0)` -> `(task_struct, Kernel)`.
#[test]
fn end_to_end_bss_global_stores_kfunc_pointer() {
    let (blob, datasec_id, t_id, var_off, kfunc_id) = btf_bss_with_kptr();
    let btf = Btf::from_bytes(&blob).unwrap();
    let [ld_lo, ld_hi] = ld_imm64(1, var_off as i32);
    let insns = vec![
        kfunc_call(kfunc_id),
        ld_lo,
        ld_hi,
        stx(BPF_SIZE_DW, 1, 0, 0),
        exit(),
    ];
    let datasec_pointers = vec![DatasecPointer {
        insn_offset: 1,
        datasec_type_id: datasec_id,
        base_offset: var_off,
    }];
    let map = analyze_casts(&insns, &btf, &[], &[], &datasec_pointers, &[]);
    assert_eq!(map.len(), 1, "exactly one finding expected: {map:?}");
    assert_eq!(
        map.get(&(datasec_id, var_off)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
    );
}

// ----- Edge case tests: kfunc imm=0 ---------------------------

/// `handle_kfunc_call` short-circuits on `imm <= 0`. Typically
/// `imm = -1` for an unrelocated kfunc placeholder; `imm = 0`
/// also hits the short-circuit. R0 stays Unknown after the
/// standard R0..R5 clobber.
#[test]
fn kfunc_call_imm_zero_leaves_r0_unknown() {
    let slot_off: u32 = 16;
    let (blob, _t_id, p_id, _t_ptr_id) = btf_kptr_base(slot_off);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![
        kfunc_call(0),
        stx(BPF_SIZE_DW, 6, 0, slot_off as i16),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: p_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "kfunc_call imm=0 must leave R0 Unknown: {map:?}"
    );
}

// ----- Edge case tests: jumps ---------------------------------

/// `BPF_JMP32 | BPF_JA` (gotol, op=0x00) uses `insn.imm` as the
/// 32-bit jump offset per `jump_targets`. The target PC is reset.
#[test]
fn jmp32_gotol_resets_state_at_target() {
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    // pc 0: r2 = T.f (LoadedU64Field).
    // pc 1: gotol +1 (JMP32|JA, imm=1). Target = pc 3.
    // pc 2: exit (skipped).
    // pc 3: r3 = *(u64 *)(r2 + 0) — state reset, no record.
    let gotol = mk_insn(BPF_CLASS_JMP32, 0, 0, 0, 1);
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        gotol,
        exit(),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(map.is_empty(), "JMP32|JA target must reset state: {map:?}");
}

/// Out-of-range jump targets (negative resolved address, or past
/// `insns.len()`) are silently dropped. State survives.
#[test]
fn out_of_range_jump_targets_dropped() {
    let (blob, t_id, q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let jeq_neg = mk_insn(BPF_CLASS_JMP | 0x10, 2, 0, -100, 0);
    let jeq_pos = mk_insn(BPF_CLASS_JMP | 0x10, 2, 0, 100, 0);
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        jeq_neg,
        jeq_pos,
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "out-of-range jumps must drop, state survives: {map:?}"
    );
}

/// All conditional jump opcodes register their targets per
/// `jump_targets`. JEQ, JGT, JGE, JSET, JNE, JSGT, JSGE, JLT,
/// JLE, JSLT, JSLE — each one's target PC must reset state.
#[test]
fn all_conditional_jumps_register_targets() {
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let ops: [u8; 11] = [
        0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0xa0, 0xb0, 0xc0, 0xd0,
    ];
    for op in ops {
        let cond = mk_insn(BPF_CLASS_JMP | op, 2, 0, 1, 0);
        let insns = vec![
            ldx(BPF_SIZE_DW, 2, 1, 8),
            cond,
            exit(),
            ldx(BPF_SIZE_DW, 3, 2, 0),
            exit(),
        ];
        let map = analyze_casts(
            &insns,
            &btf,
            &[InitialReg {
                reg: 1,
                struct_type_id: t_id,
            }],
            &[],
            &[],
            &[],
        );
        assert!(
            map.is_empty(),
            "JMP op 0x{op:02x} target must reset state: {map:?}"
        );
    }
}

// ----- Edge case tests: FuncEntry -----------------------------

/// Multiple `FuncEntry` entries at the same PC are processed in
/// order — last one wins. Each entry's `seed_from_func_proto`
/// clears all registers before seeding.
/// Two FuncProtos at PC 0:
///   A: ([T*, P*]) — seeds R1=T*, R2=P*.
///   B: ([P*, T*]) — seeds R1=P*, R2=T*.
/// With B processed second, R1=P* and R2=T*. Records (P, slot) -> T.
#[test]
fn func_entry_multiple_at_same_pc_last_wins() {
    let slot_off: u32 = 16;
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_p = push_name(&mut strings, "P");
    let n_x = push_name(&mut strings, "x");
    let n_slot = push_name(&mut strings, "slot");
    let n_arg_t = push_name(&mut strings, "arg_t");
    let n_arg_p = push_name(&mut strings, "arg_p");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Ptr { type_id: 2 },
        SynType::Struct {
            name_off: n_p,
            size: slot_off + 8,
            members: vec![SynMember {
                name_off: n_slot,
                type_id: 1,
                byte_offset: slot_off,
            }],
        },
        SynType::Ptr { type_id: 4 },
        SynType::FuncProto {
            return_type_id: 0,
            params: vec![
                SynParam {
                    name_off: n_arg_t,
                    type_id: 3,
                },
                SynParam {
                    name_off: n_arg_p,
                    type_id: 5,
                },
            ],
        },
        SynType::FuncProto {
            return_type_id: 0,
            params: vec![
                SynParam {
                    name_off: n_arg_p,
                    type_id: 5,
                },
                SynParam {
                    name_off: n_arg_t,
                    type_id: 3,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let p_id = 4;
    let proto_a = 6;
    let proto_b = 7;
    let insns = vec![stx(BPF_SIZE_DW, 1, 2, slot_off as i16), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[],
        &[
            FuncEntry {
                insn_offset: 0,
                func_proto_id: proto_a,
            },
            FuncEntry {
                insn_offset: 0,
                func_proto_id: proto_b,
            },
        ],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(p_id, slot_off)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "later FuncEntry at same PC must win: {map:?}"
    );
}

/// `FuncEntry` with `insn_offset` past `insns.len()` is silently
/// skipped — the loop never finds a matching PC.
#[test]
fn func_entry_past_insns_len_no_op() {
    let (blob, t_id, q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[FuncEntry {
            insn_offset: 999,
            func_proto_id: 1,
        }],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "FuncEntry past insns.len() must not affect run: {map:?}"
    );
}

/// `FuncEntry` at PC 0 with no params clears all registers, then
/// iterates an empty param list (no seeding). InitialReg state
/// is wiped.
#[test]
fn func_entry_pc0_no_params_clears_initial_regs() {
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_q = push_name(&mut strings, "Q");
    let n_f = push_name(&mut strings, "f");
    let n_x = push_name(&mut strings, "x");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 16,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        SynType::Struct {
            name_off: n_q,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::FuncProto {
            return_type_id: 0,
            params: vec![],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let proto_id = 4;
    let insns = vec![ldx(BPF_SIZE_DW, 2, 1, 8), ldx(BPF_SIZE_DW, 3, 2, 0), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[FuncEntry {
            insn_offset: 0,
            func_proto_id: proto_id,
        }],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "FuncEntry with empty params must clear all regs: {map:?}"
    );
}

/// `FuncEntry` with `func_proto_id == 0` (Void) hits the
/// `_ => return` arm — but only AFTER all registers are cleared.
#[test]
fn func_entry_proto_id_zero_clears_regs_no_seed() {
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![ldx(BPF_SIZE_DW, 2, 1, 8), ldx(BPF_SIZE_DW, 3, 2, 0), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[FuncEntry {
            insn_offset: 0,
            func_proto_id: 0,
        }],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "FuncEntry with proto_id=0 must clear regs and not seed: {map:?}"
    );
}

/// `FuncEntry` at PC > 0 reseeds at the matching PC mid-stream.
#[test]
fn func_entry_pc_gt_0_reseeds_mid_stream() {
    let slot_off: u32 = 16;
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_p = push_name(&mut strings, "P");
    let n_x = push_name(&mut strings, "x");
    let n_slot = push_name(&mut strings, "slot");
    let n_arg_t = push_name(&mut strings, "arg_t");
    let n_arg_p = push_name(&mut strings, "arg_p");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Ptr { type_id: 2 },
        SynType::Struct {
            name_off: n_p,
            size: slot_off + 8,
            members: vec![SynMember {
                name_off: n_slot,
                type_id: 1,
                byte_offset: slot_off,
            }],
        },
        SynType::Ptr { type_id: 4 },
        SynType::FuncProto {
            return_type_id: 0,
            params: vec![
                SynParam {
                    name_off: n_arg_t,
                    type_id: 3,
                },
                SynParam {
                    name_off: n_arg_p,
                    type_id: 5,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 2;
    let p_id = 4;
    let proto_id = 6;
    // pc 0: exit. pc 1: STX *(R2 + slot_off) = R1.
    // FuncEntry at PC 1 reseeds R1=T*, R2=P*. Records (P, slot) -> T.
    let insns = vec![exit(), stx(BPF_SIZE_DW, 2, 1, slot_off as i16), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[],
        &[FuncEntry {
            insn_offset: 1,
            func_proto_id: proto_id,
        }],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(p_id, slot_off)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: t_id,
            addr_space: AddrSpace::Kernel,
        }),
        "FuncEntry at PC>0 must reseed: {map:?}"
    );
}

// ----- Misc edge case tests -----------------------------------

/// The second slot of `BPF_LD_IMM64` is skipped per `skip_next`.
/// Even non-zero content must not be interpreted as instruction.
#[test]
fn ld_imm64_second_slot_with_non_zero_content_skipped() {
    let (blob, t_id, q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    // pc 0: LD_IMM64 first slot (with non-zero imm = 42).
    // pc 1: second slot — emit a fake "instruction" that LOOKS
    //       like an ALU64|MOV|X. It must be skipped.
    // pc 2: r2 = T.f
    // pc 3: r3 = *r2
    let ld_imm64_lo = mk_insn(BPF_CLASS_LD | BPF_SIZE_DW | BPF_MODE_IMM, 6, 0, 0, 42);
    let fake_mov = mk_insn(BPF_CLASS_ALU64 | BPF_OP_MOV | BPF_SRC_X, 4, 3, 0, 0);
    let insns = vec![
        ld_imm64_lo,
        fake_mov,
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "non-zero LD_IMM64 second slot must skip: {map:?}"
    );
}

/// `seed` iterates `initial_regs` in order; later seeds for the
/// same register overwrite earlier ones (last wins).
#[test]
fn initial_reg_duplicate_seeds_last_wins() {
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_s1 = push_name(&mut strings, "S1");
    let n_s2 = push_name(&mut strings, "S2");
    let n_q = push_name(&mut strings, "Q");
    let n_f = push_name(&mut strings, "f");
    let n_x = push_name(&mut strings, "x");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        // id 2: S1 { u64 f @ 8 }, size 16
        SynType::Struct {
            name_off: n_s1,
            size: 16,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        // id 3: S2 { u64 f @ 16 }, size 24
        SynType::Struct {
            name_off: n_s2,
            size: 24,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 1,
                byte_offset: 16,
            }],
        },
        // id 4: Q { u64 x @ 0 }, size 8
        SynType::Struct {
            name_off: n_q,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let s1_id = 2;
    let s2_id = 3;
    let q_id = 4;
    // Seed R1 first as S1, then as S2 — last wins, R1 = S2.
    // Sequence: r2 = *(u64*)(r1+16) = S2.f, cast (F1 evidence),
    // then r3 = *r2 at 0. Records (S2, 16) -> Q. If first seed
    // had won, S1 has no field at offset 16, so no record.
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 16),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: s1_id,
            },
            InitialReg {
                reg: 1,
                struct_type_id: s2_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(s2_id, 16)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "duplicate InitialReg seed must use last value: {map:?}"
    );
    assert!(
        !map.contains_key(&(s1_id, 16)),
        "first InitialReg seed must NOT take effect: {map:?}"
    );
}

/// `InitialReg` with `struct_type_id == 0` is silently dropped.
#[test]
fn initial_reg_struct_type_id_zero_dropped() {
    let (blob, _t, _q) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![ldx(BPF_SIZE_DW, 2, 1, 8), ldx(BPF_SIZE_DW, 3, 2, 0), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: 0,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "InitialReg with struct_type_id=0 must be dropped: {map:?}"
    );
}

// ----- Stress / boundary tests -------------------------------
//
// These tests target performance regressions (quadratic blowups
// over the BTF id walk, the patterns set, the layout index) and
// boundary panics (OOB indexing on max-stack, depth-limit chains
// through `peel_modifiers`, all-LD_IMM64 streams driving
// `skip_next` to the program end). Assertions verify exact
// `CastMap` contents — counting only would mask both spurious
// entries and missed entries.

/// 10,000-instruction program: stuffed with `r0 = 0` no-ops with
/// a single arena cast pattern buried near the middle. Verifies
/// the analyzer's forward-pass cost remains linear in instruction
/// count and that its register tracking does not lose the typed
/// state across thousands of unrelated instructions. Single-slot
/// `r0 = 0` only clobbers `r0`, so the seeded `r1 = T*` and the
/// loaded `r2 = LoadedU64Field{T, 8}` survive across the no-op
/// padding and the cast resolves uniquely to `Q`. Real `BPF_JA +0`
/// would add every PC to the jump-target set and reset register
/// state at every step.
#[test]
fn large_program_buried_cast_recorded() {
    let (blob, t_id, q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let mut insns: Vec<BpfInsn> = Vec::with_capacity(10_001);
    for _ in 0..4_999 {
        insns.push(mov_k(0, 0));
    }
    insns.push(ldx(BPF_SIZE_DW, 2, 1, 8));
    // F1 mitigation: arena_confirmed evidence on r2.
    insns.push(addr_space_cast(2, 2, 1));
    insns.push(ldx(BPF_SIZE_DW, 3, 2, 0));
    for _ in 0..4_997 {
        insns.push(mov_k(0, 0));
    }
    insns.push(exit());
    assert_eq!(insns.len(), 10_000);
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.len(),
        1,
        "exactly one cast in 10k-insn program: {map:?}"
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "buried cast must resolve: {map:?}"
    );
}

/// 100 distinct `FuncEntry` records at consecutive PCs, each
/// pointing at a distinct `FuncProto(T_i*, P*) -> void`. After
/// each entry's reseeding, the single instruction at that PC is
/// `STX *(R2 + slot_off_i) = R1`, recording `(P, slot_off_i) ->
/// (T_i, Kernel)`. Verifies that the analyzer applies every
/// `FuncEntry` (no off-by-one, no early-exit on the entry list
/// scan) and that 100 distinct kptr findings land in the output.
/// Sized below the `i16` byte-offset bound (100 * 8 = 800).
#[test]
fn many_func_entries_each_seeds() {
    const N: usize = 100;
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_p = push_name(&mut strings, "P");
    let n_arg_t = push_name(&mut strings, "task");
    let n_arg_p = push_name(&mut strings, "parent");
    let mut t_name_offs = Vec::with_capacity(N);
    for i in 0..N {
        t_name_offs.push(push_name(&mut strings, &format!("T{i}")));
    }
    let mut slot_name_offs = Vec::with_capacity(N);
    for i in 0..N {
        slot_name_offs.push(push_name(&mut strings, &format!("slot{i}")));
    }
    // Type id layout (1-indexed; id 0 is Void):
    //   1: u64; 2..=N+1: T_i (each with u64@0);
    //   N+2..=2N+1: T_i*; 2N+2: P (N u64 fields); 2N+3: P*;
    //   2N+4..=3N+3: N FuncProtos (T_i*, P*) -> void.
    let mut types: Vec<SynType> = Vec::new();
    types.push(SynType::Int {
        name_off: n_u64,
        size: 8,
        encoding: 0,
        offset: 0,
        bits: 64,
    });
    for &name_off in t_name_offs.iter().take(N) {
        types.push(SynType::Struct {
            name_off,
            size: 8,
            members: vec![SynMember {
                name_off: 0,
                type_id: 1,
                byte_offset: 0,
            }],
        });
    }
    for i in 0..N {
        types.push(SynType::Ptr {
            type_id: (2 + i) as u32,
        });
    }
    let p_size: u32 = 8 * (N as u32);
    let p_members: Vec<SynMember> = (0..N)
        .map(|i| SynMember {
            name_off: slot_name_offs[i],
            type_id: 1,
            byte_offset: 8 * i as u32,
        })
        .collect();
    types.push(SynType::Struct {
        name_off: n_p,
        size: p_size,
        members: p_members,
    });
    let p_id: u32 = 2 + 2 * N as u32;
    types.push(SynType::Ptr { type_id: p_id });
    let p_ptr_id: u32 = 2 * N as u32 + 3;
    for i in 0..N {
        types.push(SynType::FuncProto {
            return_type_id: 0,
            params: vec![
                SynParam {
                    name_off: n_arg_t,
                    type_id: (N as u32 + 2 + i as u32),
                },
                SynParam {
                    name_off: n_arg_p,
                    type_id: p_ptr_id,
                },
            ],
        });
    }
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let mut insns: Vec<BpfInsn> = Vec::with_capacity(N + 1);
    let mut func_entries: Vec<FuncEntry> = Vec::with_capacity(N);
    for i in 0..N {
        insns.push(stx(BPF_SIZE_DW, 2, 1, (8 * i) as i16));
        let proto_id: u32 = 2 * N as u32 + 4 + i as u32;
        func_entries.push(FuncEntry {
            insn_offset: i,
            func_proto_id: proto_id,
        });
    }
    insns.push(exit());
    let map = analyze_casts(&insns, &btf, &[], &func_entries, &[], &[]);
    assert_eq!(map.len(), N, "expected {N} kptr findings: {map:?}");
    for i in 0..N {
        let t_id = (2 + i) as u32;
        assert_eq!(
            map.get(&(p_id, 8 * i as u32)),
            Some(&CastHit {
                alloc_size: None,
                target_type_id: t_id,
                addr_space: AddrSpace::Kernel,
            }),
            "FuncEntry #{i} at PC {i} must record (P, {}) -> T{i}: {map:?}",
            8 * i as u32
        );
    }
}

/// 500 distinct struct types in the BTF; only one matches the
/// observed access pattern. Verifies that the matcher's
/// intersection over `build_layout_index` correctly narrows the
/// candidate set when nearly every other type matches a
/// disambiguating-but-not-target shape.
///
/// Layout: `Qtarget` has `(u64@40, u32@80)`. The other 499 each
/// carry only a single `u64@0` — they match neither `(40, 8)` nor
/// `(80, 4)`, so the intersection collapses to `Qtarget`. Source
/// `T` has a single u64@8; T's u64@0 is absent, avoiding the
/// "had_source && others remain" ambiguity drop.
#[test]
fn many_struct_types_unique_match_resolves() {
    const N_FILLER: usize = 499;
    let mut strings: Vec<u8> = vec![0];
    let n_u32 = push_name(&mut strings, "u32");
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_qtarget = push_name(&mut strings, "Qtarget");
    let n_filler_a = push_name(&mut strings, "a");
    let n_filler_b = push_name(&mut strings, "b");
    let n_f = push_name(&mut strings, "f");
    let mut filler_name_offs = Vec::with_capacity(N_FILLER);
    for i in 0..N_FILLER {
        filler_name_offs.push(push_name(&mut strings, &format!("Q{i}")));
    }
    let mut types: Vec<SynType> = vec![
        SynType::Int {
            name_off: n_u32,
            size: 4,
            encoding: 0,
            offset: 0,
            bits: 32,
        },
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 16,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 2,
                byte_offset: 8,
            }],
        },
        SynType::Struct {
            name_off: n_qtarget,
            size: 84,
            members: vec![
                SynMember {
                    name_off: n_filler_a,
                    type_id: 2,
                    byte_offset: 40,
                },
                SynMember {
                    name_off: n_filler_b,
                    type_id: 1,
                    byte_offset: 80,
                },
            ],
        },
    ];
    for &name_off in filler_name_offs.iter().take(N_FILLER) {
        types.push(SynType::Struct {
            name_off,
            size: 8,
            members: vec![SynMember {
                name_off: n_filler_a,
                type_id: 2,
                byte_offset: 0,
            }],
        });
    }
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id: u32 = 3;
    let qtarget_id: u32 = 4;
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 40),
        ldx(BPF_SIZE_W, 4, 2, 80),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.len(),
        1,
        "single unique cast across 500 candidates: {map:?}"
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: qtarget_id,
            addr_space: AddrSpace::Arena,
        }),
        "unique match must resolve to Qtarget: {map:?}"
    );
}

/// 30-level chain of cycling `Typedef -> Const -> Volatile`
/// modifiers wrapping a `u64` `Int`. `peel_modifiers` walks 30
/// peel iterations (well below the `MAX_MODIFIER_DEPTH = 32`
/// cap) before resolving the underlying type. The struct member
/// at `T.f` carries this deep chain as its declared type; the
/// analyzer's cast path must still recognize the field as a
/// plain `u64` and seed `LoadedU64Field` on the LDX. The
/// follow-up deref then records `(T, 8) -> (Q, Arena)`.
#[test]
fn deep_modifier_chain_resolves_to_u64() {
    const CHAIN_LEN: usize = 30;
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_q = push_name(&mut strings, "Q");
    let n_f = push_name(&mut strings, "f");
    let n_x = push_name(&mut strings, "x");
    let n_typedef = push_name(&mut strings, "alias_t");
    let mut types: Vec<SynType> = Vec::new();
    types.push(SynType::Int {
        name_off: n_u64,
        size: 8,
        encoding: 0,
        offset: 0,
        bits: 64,
    });
    for i in 0..CHAIN_LEN {
        let inner_id = 1 + i as u32;
        let kind = i % 3;
        let chain_node = match kind {
            0 => SynType::Typedef {
                name_off: n_typedef,
                type_id: inner_id,
            },
            1 => SynType::Const { type_id: inner_id },
            _ => SynType::Volatile { type_id: inner_id },
        };
        types.push(chain_node);
    }
    let chain_head_id: u32 = (CHAIN_LEN as u32) + 1;
    types.push(SynType::Struct {
        name_off: n_t,
        size: 16,
        members: vec![SynMember {
            name_off: n_f,
            type_id: chain_head_id,
            byte_offset: 8,
        }],
    });
    types.push(SynType::Struct {
        name_off: n_q,
        size: 8,
        members: vec![SynMember {
            name_off: n_x,
            type_id: 1,
            byte_offset: 0,
        }],
    });
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id: u32 = chain_head_id + 1;
    let q_id: u32 = chain_head_id + 2;
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "30-level modifier chain must peel to u64 and seed cast: {map:?}"
    );
}

/// All 64 stack slots filled with distinct typed pointers (each
/// produced by a kfunc-call return), then all reloaded and stored
/// into 64 distinct `(P, slot_off)` slots — yielding 64 kernel
/// kptr findings. Verifies that `stack_slots` (a `BTreeMap`)
/// handles a fully-loaded BPF stack frame (512 bytes at 8 bytes/slot)
/// with no slot lost or aliased on reload. Each kfunc returns a
/// different `T_i*` so the assertion validates that saved register
/// state per slot is preserved independently.
#[test]
fn maximum_stack_slots_all_recorded() {
    const N: usize = 64;
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_p = push_name(&mut strings, "P");
    let mut t_names = Vec::with_capacity(N);
    let mut slot_names = Vec::with_capacity(N);
    let mut kfunc_names = Vec::with_capacity(N);
    for i in 0..N {
        t_names.push(push_name(&mut strings, &format!("T{i}")));
        slot_names.push(push_name(&mut strings, &format!("slot{i}")));
        kfunc_names.push(push_name(&mut strings, &format!("kfunc_acquire_{i}")));
    }
    // Type id layout:
    //   1: u64; 2..=N+1: T_i; N+2..=2N+1: T_i*;
    //   2N+2: P (N u64 fields); 2N+3..=3N+2: FuncProtos returning T_i*;
    //   3N+3..=4N+2: Func entries.
    let mut types: Vec<SynType> = Vec::new();
    types.push(SynType::Int {
        name_off: n_u64,
        size: 8,
        encoding: 0,
        offset: 0,
        bits: 64,
    });
    for &name_off in t_names.iter().take(N) {
        types.push(SynType::Struct {
            name_off,
            size: 8,
            members: vec![SynMember {
                name_off: 0,
                type_id: 1,
                byte_offset: 0,
            }],
        });
    }
    for i in 0..N {
        types.push(SynType::Ptr {
            type_id: (2 + i) as u32,
        });
    }
    let p_members: Vec<SynMember> = (0..N)
        .map(|i| SynMember {
            name_off: slot_names[i],
            type_id: 1,
            byte_offset: 8 * i as u32,
        })
        .collect();
    types.push(SynType::Struct {
        name_off: n_p,
        size: 8 * N as u32,
        members: p_members,
    });
    for i in 0..N {
        types.push(SynType::FuncProto {
            return_type_id: (N as u32 + 2 + i as u32),
            params: vec![],
        });
    }
    for (i, &name_off) in kfunc_names.iter().enumerate().take(N) {
        types.push(SynType::Func {
            name_off,
            type_id: (2 * N as u32 + 3 + i as u32),
            linkage: 1,
        });
    }
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let p_id: u32 = 2 * N as u32 + 2;
    // r6 is seeded with Pointer{P} via InitialReg and is callee-
    // saved across kfunc CALL (per BPF ABI, R6..R9 are not clobbered).
    let mut insns: Vec<BpfInsn> = Vec::with_capacity(4 * N + 1);
    for i in 0..N {
        let func_id: u32 = 3 * N as u32 + 3 + i as u32;
        insns.push(kfunc_call(func_id));
        insns.push(stx(BPF_SIZE_DW, 10, 0, -((i as i16 + 1) * 8)));
    }
    for i in 0..N {
        insns.push(ldx(BPF_SIZE_DW, 3, 10, -((i as i16 + 1) * 8)));
        insns.push(stx(BPF_SIZE_DW, 6, 3, (8 * i) as i16));
    }
    insns.push(exit());
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: p_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(map.len(), N, "expected {N} kptr findings: {map:?}");
    for i in 0..N {
        let t_id: u32 = (2 + i) as u32;
        assert_eq!(
            map.get(&(p_id, 8 * i as u32)),
            Some(&CastHit {
                alloc_size: None,
                target_type_id: t_id,
                addr_space: AddrSpace::Kernel,
            }),
            "stack slot {i} (off={}) must record T{i}: {map:?}",
            -((i as i16 + 1) * 8)
        );
    }
}

/// Source struct `T` with 100 `u64` members; cast pattern triggers
/// at `f50` (offset 400) and `f99` (offset 792). Each load enters
/// `LoadedU64Field`, then a follow-up deref records a unique-shape
/// access against a single matching candidate (`Q50` for `f50`,
/// `Q99` for `f99`). The dereference offsets/sizes are chosen so
/// `T`'s u64-at-multiple-of-8 layout matches NEITHER pattern,
/// avoiding the ambiguity drop. Verifies the matcher scales when
/// the source struct has many fields.
#[test]
fn many_field_struct_records_two_distinct_casts() {
    const N: u32 = 100;
    let mut strings: Vec<u8> = vec![0];
    let n_u8 = push_name(&mut strings, "u8");
    let n_u32 = push_name(&mut strings, "u32");
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_q50 = push_name(&mut strings, "Q50");
    let n_q99 = push_name(&mut strings, "Q99");
    let n_x = push_name(&mut strings, "x");
    let mut t_field_names = Vec::with_capacity(N as usize);
    for i in 0..N {
        t_field_names.push(push_name(&mut strings, &format!("f{i}")));
    }
    let t_members: Vec<SynMember> = (0..N)
        .map(|i| SynMember {
            name_off: t_field_names[i as usize],
            type_id: 3,
            byte_offset: 8 * i,
        })
        .collect();
    // Type ids:
    //   1: u8, 2: u32, 3: u64;
    //   4: T (100 u64 fields at 0, 8, ..., 792);
    //   5: Q50 (single u32@4 — pattern (4, 4) matches only this);
    //   6: Q99 (single u8@5 — pattern (5, 1) matches only this).
    let types = vec![
        SynType::Int {
            name_off: n_u8,
            size: 1,
            encoding: 0,
            offset: 0,
            bits: 8,
        },
        SynType::Int {
            name_off: n_u32,
            size: 4,
            encoding: 0,
            offset: 0,
            bits: 32,
        },
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 8 * N,
            members: t_members,
        },
        SynType::Struct {
            name_off: n_q50,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 2,
                byte_offset: 4,
            }],
        },
        SynType::Struct {
            name_off: n_q99,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 5,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id: u32 = 4;
    let q50_id: u32 = 5;
    let q99_id: u32 = 6;
    // f50 at offset 400; f99 at offset 792.
    // Each LoadedU64Field gets an addr_space_cast applied for
    // F1 mitigation arena_confirmed evidence.
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 400),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_W, 3, 2, 4),
        ldx(BPF_SIZE_DW, 2, 1, 792),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_B, 4, 2, 5),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(map.len(), 2, "two distinct casts expected: {map:?}");
    assert_eq!(
        map.get(&(t_id, 400)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q50_id,
            addr_space: AddrSpace::Arena,
        }),
        "f50 at offset 400: {map:?}"
    );
    assert_eq!(
        map.get(&(t_id, 792)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q99_id,
            addr_space: AddrSpace::Arena,
        }),
        "f99 at offset 792: {map:?}"
    );
}

/// 20 distinct `(source_struct, field_offset)` cast patterns in a
/// single program. Source struct `T` has 20 `u64` fields at
/// offsets `0, 8, ..., 152`. Each `T.f_i` is loaded then
/// dereferenced at offset `(i+1)` size 1, matching exactly one of
/// 20 distinct `Q_i` target structs (each with a single `u8` at
/// the matching offset). Verifies that the analyzer's `patterns`
/// map and the matcher's per-pattern intersection scale to many
/// distinct cast emissions in one walk.
#[test]
fn many_cast_patterns_in_one_program() {
    const N: u32 = 20;
    let mut strings: Vec<u8> = vec![0];
    let n_u8 = push_name(&mut strings, "u8");
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_x = push_name(&mut strings, "x");
    let mut t_field_names = Vec::with_capacity(N as usize);
    let mut q_names = Vec::with_capacity(N as usize);
    for i in 0..N {
        t_field_names.push(push_name(&mut strings, &format!("f{i}")));
        q_names.push(push_name(&mut strings, &format!("Q{i}")));
    }
    // Type ids:
    //   1: u8, 2: u64; 3: T (N u64 fields);
    //   4..=3+N: Q_i, each with single u8@(i+1).
    let t_members: Vec<SynMember> = (0..N)
        .map(|i| SynMember {
            name_off: t_field_names[i as usize],
            type_id: 2,
            byte_offset: 8 * i,
        })
        .collect();
    let mut types: Vec<SynType> = vec![
        SynType::Int {
            name_off: n_u8,
            size: 1,
            encoding: 0,
            offset: 0,
            bits: 8,
        },
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 8 * N,
            members: t_members,
        },
    ];
    for i in 0..N {
        types.push(SynType::Struct {
            name_off: q_names[i as usize],
            size: i + 2, // u8@(i+1) requires size >= i+2
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: i + 1,
            }],
        });
    }
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id: u32 = 3;
    // Emit one (load + arena_cast + deref) triple per pattern for
    // F1 mitigation arena_confirmed evidence on each slot.
    let mut insns: Vec<BpfInsn> = Vec::with_capacity(3 * N as usize + 1);
    for i in 0..N {
        insns.push(ldx(BPF_SIZE_DW, 2, 1, (8 * i) as i16));
        insns.push(addr_space_cast(2, 2, 1));
        insns.push(ldx(BPF_SIZE_B, 3, 2, (i + 1) as i16));
    }
    insns.push(exit());
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(map.len(), N as usize, "expected {N} cast patterns: {map:?}");
    for i in 0..N {
        let q_id: u32 = 4 + i;
        assert_eq!(
            map.get(&(t_id, 8 * i)),
            Some(&CastHit {
                alloc_size: None,
                target_type_id: q_id,
                addr_space: AddrSpace::Arena,
            }),
            "pattern #{i} at (T, {}) must resolve to Q{i}: {map:?}",
            8 * i
        );
    }
}

/// BTF with no struct types at all (only a single `u64` Int).
/// `build_layout_index` walks the id space without finding any
/// struct/union; `finalize` emits no findings. Verifies the
/// analyzer does not panic on a degenerate BTF that contains no
/// aggregate types, and that the empty layout index correctly
/// produces an empty `CastMap` even when the instruction stream
/// contains LDX patterns. The seed of `r1 = struct_type_id 1` is
/// silently dropped by `resolve_to_struct_id` (id 1 is `u64`).
#[test]
fn empty_btf_no_panic() {
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let types = vec![SynType::Int {
        name_off: n_u64,
        size: 8,
        encoding: 0,
        offset: 0,
        bits: 64,
    }];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![ldx(BPF_SIZE_DW, 2, 1, 8), ldx(BPF_SIZE_DW, 3, 2, 0), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: 1,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "no struct types in BTF must produce empty CastMap: {map:?}"
    );
}

/// BTF containing only `Int` types and no structs. The seed
/// targets a non-struct id, so `resolve_to_struct_id` returns
/// `None` and the seed is dropped. The instruction stream's LDX
/// cannot type any register, the `patterns` map stays empty, and
/// `build_layout_index` finds no struct/union to index. Verifies
/// the analyzer handles a scalar-only BTF without panic.
#[test]
fn btf_only_ints_no_panic() {
    let mut strings: Vec<u8> = vec![0];
    let n_u8 = push_name(&mut strings, "u8");
    let n_u16 = push_name(&mut strings, "u16");
    let n_u32 = push_name(&mut strings, "u32");
    let n_u64 = push_name(&mut strings, "u64");
    let n_s32 = push_name(&mut strings, "s32");
    // BTF int encoding bit `BTF_INT_SIGNED` per linux uapi `btf.h`.
    const BTF_INT_SIGNED: u32 = 1;
    let types = vec![
        SynType::Int {
            name_off: n_u8,
            size: 1,
            encoding: 0,
            offset: 0,
            bits: 8,
        },
        SynType::Int {
            name_off: n_u16,
            size: 2,
            encoding: 0,
            offset: 0,
            bits: 16,
        },
        SynType::Int {
            name_off: n_u32,
            size: 4,
            encoding: 0,
            offset: 0,
            bits: 32,
        },
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Int {
            name_off: n_s32,
            size: 4,
            encoding: BTF_INT_SIGNED,
            offset: 0,
            bits: 32,
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    // Seed targets the u64 id — `resolve_to_struct_id` walks
    // Int as terminal and returns None. The seed silently drops.
    let insns = vec![ldx(BPF_SIZE_DW, 2, 1, 8), ldx(BPF_SIZE_DW, 3, 2, 0), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: 4,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "Int-only BTF must produce empty CastMap: {map:?}"
    );
}

// ----- STX-flow arena cast (allocator-return seed path) ------
//
// The STX-flow path detects allocator-return values stored into
// u64 slots: at a `BPF_PSEUDO_CALL` site flagged via
// [`SubprogReturn::insn_offset`], the analyzer seeds R0 to
// `RegState::ArenaU64FromAlloc` after the standard R0..=R5
// clobber. The next STX of R0 (or its propagation through MOV /
// stack spill) into a u64 field of a typed `Pointer{P}` parent
// records `(P, off)` as an Arena cast finding with
// `target_type_id == 0` (the renderer's resolve_arena_type
// bridge supplies the actual payload type at chase time).

/// Allocator-return → STX path: a `BPF_PSEUDO_CALL` flagged by
/// `SubprogReturn` seeds R0 to `ArenaU64FromAlloc`; the
/// subsequent `STX [R1+8] = R0` records `(M, 8)` as an Arena
/// finding with `target_type_id == 0`. The renderer's
/// `resolve_arena_type` bridge resolves the actual payload type
/// at chase time.
#[test]
fn stx_flow_alloc_return_records_arena_finding() {
    // BTF: u64(1), M(2, u64@8 — the `cgx_raw` slot).
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_m = push_name(&mut strings, "M");
    let n_cgx = push_name(&mut strings, "cgx_raw");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_m,
            size: 16,
            members: vec![SynMember {
                name_off: n_cgx,
                type_id: 1,
                byte_offset: 8,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let m_id = 2;
    // R6 is callee-saved per the BPF ABI — survives the
    // R0..=R5 clobber the call applies. Seed R6 = Pointer{M}
    // so the post-call STX through R6 still has a typed parent
    // base. R1 cannot be used as the parent (the call clobbers
    // it as an argument register), and the test specifically
    // wants the analyzer to record `(M, 8)` AFTER the call.
    //
    // Insn 0: BPF_PSEUDO_CALL — SubprogReturn seed at
    //         insn_offset=0 tags R0 as ArenaU64FromAlloc
    //         after the R0..=R5 clobber.
    // Insn 1: STX [R6 + 8] = R0 — records (M, 8) -> Arena
    //         via the STX-flow path.
    let pseudo_call = mk_insn(
        BPF_CLASS_JMP | BPF_OP_CALL,
        0,
        BPF_PSEUDO_CALL,
        0,
        0, // pc-relative offset to the subprog (irrelevant here)
    );
    let insns = vec![pseudo_call, stx(BPF_SIZE_DW, 6, 0, 8), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: m_id,
        }],
        &[],
        &[],
        &[SubprogReturn {
            alloc_size: None,
            insn_offset: 0,
        }],
    );
    assert_eq!(
        map.get(&(m_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: 0,
            addr_space: AddrSpace::Arena,
        }),
        "STX-flow alloc-return must record Arena finding with \
             target_type_id=0: {map:?}"
    );
}

/// Allocator-return seed propagates through `mov_x` so a register
/// rename before the STX still records the Arena finding.
#[test]
fn stx_flow_alloc_return_propagates_through_mov() {
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_m = push_name(&mut strings, "M");
    let n_cgx = push_name(&mut strings, "cgx_raw");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_m,
            size: 16,
            members: vec![SynMember {
                name_off: n_cgx,
                type_id: 1,
                byte_offset: 8,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let m_id = 2;
    let pseudo_call = mk_insn(BPF_CLASS_JMP | BPF_OP_CALL, 0, BPF_PSEUDO_CALL, 0, 0);
    // r7 = r0  (mov_x). r7 is callee-saved per the BPF ABI;
    // mov_x propagates ArenaU64FromAlloc from R0 to R7. R6 is
    // the parent base (callee-saved, seeded as `Pointer{M}`),
    // so the STX through [R6 + 8] = R7 records the Arena
    // finding. The post-call STX cannot use R1 as the parent —
    // the call clobbered R1 along with the rest of R0..=R5.
    let insns = vec![pseudo_call, mov_x(7, 0), stx(BPF_SIZE_DW, 6, 7, 8), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: m_id,
        }],
        &[],
        &[],
        &[SubprogReturn {
            alloc_size: None,
            insn_offset: 0,
        }],
    );
    assert_eq!(
        map.get(&(m_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: 0,
            addr_space: AddrSpace::Arena,
        }),
        "MOV must propagate ArenaU64FromAlloc through r7: {map:?}"
    );
}

/// Allocator-return seed propagates through stack spill / reload.
/// Mirrors the `register_stack_spill_round_trip` pattern: STX
/// through r10 saves the register state, LDX through r10
/// restores it.
#[test]
fn stx_flow_alloc_return_round_trips_through_stack() {
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_m = push_name(&mut strings, "M");
    let n_cgx = push_name(&mut strings, "cgx_raw");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_m,
            size: 16,
            members: vec![SynMember {
                name_off: n_cgx,
                type_id: 1,
                byte_offset: 8,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let m_id = 2;
    let pseudo_call = mk_insn(BPF_CLASS_JMP | BPF_OP_CALL, 0, BPF_PSEUDO_CALL, 0, 0);
    // *(u64 *)(r10 - 8) = r0   ; spill R0 (ArenaU64FromAlloc)
    // r7 = *(u64 *)(r10 - 8)   ; reload — R7 holds ArenaU64FromAlloc
    // *(u64 *)(R6 + 8) = R7    ; records (M, 8) -> Arena
    //
    // R6 is the parent base, seeded as `Pointer{M}`. Both R6
    // and R7 are callee-saved — they survive the R0..=R5
    // clobber the call applied at PC 0.
    let insns = vec![
        pseudo_call,
        stx(BPF_SIZE_DW, 10, 0, -8),
        ldx(BPF_SIZE_DW, 7, 10, -8),
        stx(BPF_SIZE_DW, 6, 7, 8),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: m_id,
        }],
        &[],
        &[],
        &[SubprogReturn {
            alloc_size: None,
            insn_offset: 0,
        }],
    );
    assert_eq!(
        map.get(&(m_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: 0,
            addr_space: AddrSpace::Arena,
        }),
        "Stack spill/reload must round-trip ArenaU64FromAlloc: {map:?}"
    );
}

/// Subsequent LDX from a previously-arena-tagged slot inherits
/// `ArenaU64FromAlloc` (alias-set tracking via the source field).
/// Storing the inherited tag into another u64 slot also records
/// the Arena finding.
#[test]
fn stx_flow_alias_tracking_propagates_via_ldx() {
    // M: { u64 src_slot @ 0; u64 dst_slot @ 8 }
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_m = push_name(&mut strings, "M");
    let n_src = push_name(&mut strings, "src_slot");
    let n_dst = push_name(&mut strings, "dst_slot");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_m,
            size: 16,
            members: vec![
                SynMember {
                    name_off: n_src,
                    type_id: 1,
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_dst,
                    type_id: 1,
                    byte_offset: 8,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let m_id = 2;
    let pseudo_call = mk_insn(BPF_CLASS_JMP | BPF_OP_CALL, 0, BPF_PSEUDO_CALL, 0, 0);
    // pc 0: pseudo_call -> R0 = ArenaU64FromAlloc { source: None }.
    // pc 1: stx [R6 + 0] = R0 -> records (M, 0) -> Arena.
    // pc 2: ldx R7, [R6 + 0]   -> R7 inherits ArenaU64FromAlloc
    //                              { source: Some((M, 0)) } via
    //                              alias-set tracking.
    // pc 3: stx [R6 + 8] = R7 -> records (M, 8) -> Arena.
    //
    // R6 is the parent base (callee-saved, seeded as
    // `Pointer{M}`); R7 is also callee-saved and survives
    // any future call clobber. R1 cannot be the parent here —
    // the call at PC 0 clobbered it.
    let insns = vec![
        pseudo_call,
        stx(BPF_SIZE_DW, 6, 0, 0),
        ldx(BPF_SIZE_DW, 7, 6, 0),
        stx(BPF_SIZE_DW, 6, 7, 8),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: m_id,
        }],
        &[],
        &[],
        &[SubprogReturn {
            alloc_size: None,
            insn_offset: 0,
        }],
    );
    assert_eq!(
        map.get(&(m_id, 0)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: 0,
            addr_space: AddrSpace::Arena,
        }),
        "first STX must record (M, 0) -> Arena: {map:?}"
    );
    assert_eq!(
        map.get(&(m_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: 0,
            addr_space: AddrSpace::Arena,
        }),
        "alias-tracked LDX from (M, 0) must propagate to (M, 8) STX: {map:?}"
    );
}

/// Conflict between arena STX and kernel kptr STX on the same
/// slot drops both observations from the output map. Mirrors the
/// existing arena/kptr conflict invariant for the new path.
#[test]
fn stx_flow_conflict_with_kptr_drops_both() {
    // BTF: u64(1), T(2, struct), T*(3), M(4, u64@0).
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_m = push_name(&mut strings, "M");
    let n_x = push_name(&mut strings, "x");
    let n_slot = push_name(&mut strings, "slot");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_t,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Ptr { type_id: 2 },
        SynType::Struct {
            name_off: n_m,
            size: 8,
            members: vec![SynMember {
                name_off: n_slot,
                type_id: 1,
                byte_offset: 0,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let m_id = 4;
    let t_id = 2;
    let pseudo_call = mk_insn(BPF_CLASS_JMP | BPF_OP_CALL, 0, BPF_PSEUDO_CALL, 0, 0);
    // R6 = M* (parent base, callee-saved → survives the call).
    // R7 = T* (kptr value source, also callee-saved → survives
    // the call). pc 0: pseudo_call → R0 = arena.
    // pc 1: stx [R6+0] = R0 → arena_stx_findings[(M,0)] = Pending.
    // pc 2: stx [R6+0] = R7 → kptr_findings[(M,0)] = Single(T).
    // Conflict: both observations on (M, 0) — drop both.
    let insns = vec![
        pseudo_call,
        stx(BPF_SIZE_DW, 6, 0, 0),
        stx(BPF_SIZE_DW, 6, 7, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 6,
                struct_type_id: m_id,
            },
            InitialReg {
                reg: 7,
                struct_type_id: t_id,
            },
        ],
        &[],
        &[],
        &[SubprogReturn {
            alloc_size: None,
            insn_offset: 0,
        }],
    );
    assert!(
        !map.contains_key(&(m_id, 0)),
        "arena/kptr conflict must drop the slot from output: {map:?}"
    );
}

/// Same slot triggers both detection paths in one program: the
/// shape-inference path's LDX accumulates into `patterns`, AND a
/// `pseudo_call` + STX-flow path inserts into `arena_stx_findings`.
/// The two evidence sources combine: STX-flow proves the slot
/// holds an arena pointer (gates emission past the F1 direct-
/// evidence requirement), and shape-inference resolves the
/// target struct from the observed dereference pattern. The
/// arena STX-flow loop in [`Analyzer::finalize`] runs the same
/// shape-inference intersection across `patterns[key]` as the
/// shape-inference loop does, so a slot with BOTH evidence
/// sources emits a `CastHit` whose `target_type_id` is the
/// uniquely-resolved struct id (when shape inference resolves)
/// — not the deferred-resolve sentinel.
///
/// Pre-fix: the LDX alias-tracking arm at
/// [`Analyzer::handle_ldx`] re-typed any LDX off a slot already
/// in `arena_stx_findings` to `RegState::ArenaU64FromAlloc`,
/// which suppressed downstream access recording (the arena arm
/// in `handle_ldx` drops dst without populating patterns) — so
/// even when struct shape uniquely identified the target,
/// `target_type_id` stayed 0. Post-fix the LDX always emits
/// `LoadedU64Field`, downstream LDXs through it record the
/// access pattern, and shape inference resolves the target the
/// renderer can chase against without consulting the
/// `MemReader::resolve_arena_type` bridge. The bridge stays in
/// place for slots whose access pattern doesn't uniquely
/// resolve.
///
/// Test fixture: struct Q has `u64@0` + `u64@8` (size 16), so
/// the access pattern at offsets 0 and 8 with size 8 uniquely
/// identifies Q. The assertion pins that target_type_id ==
/// Q's BTF id, NOT 0.
#[test]
fn stx_flow_resolves_target_via_shape_inference_under_alias_tracking() {
    // BTF: u64(1), P(2, u64@8 source), Q(3, u64@0+u64@8). Q is the
    // unique candidate matching both pattern accesses (offset=0,
    // size=8) and (offset=8, size=8). Both detection paths fire and
    // combine: STX-flow proves the slot holds an arena pointer and
    // gates emission, shape inference resolves the target struct
    // from the access pattern.
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_p = push_name(&mut strings, "P");
    let n_q = push_name(&mut strings, "Q");
    let n_f = push_name(&mut strings, "f");
    let n_a = push_name(&mut strings, "a");
    let n_b = push_name(&mut strings, "b");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_p,
            size: 16,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        SynType::Struct {
            name_off: n_q,
            size: 16,
            members: vec![
                SynMember {
                    name_off: n_a,
                    type_id: 1,
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_b,
                    type_id: 1,
                    byte_offset: 8,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let p_id = 2;
    let q_id = 3;
    let pseudo_call = mk_insn(BPF_CLASS_JMP | BPF_OP_CALL, 0, BPF_PSEUDO_CALL, 0, 0);
    // Phase 1 — shape-inference accesses for (P, 8). Both passes
    // record the same pattern: the LDX at PC 0 emits
    // `LoadedU64Field{P, 8}` regardless of whether
    // `arena_stx_findings` already contains the slot, and
    // downstream LDXs through that register record accesses
    // (0, 8) and (8, 8) into `patterns[(P, 8)]`. Q is the
    // unique candidate matching both accesses (it has u64@0
    // and u64@8, size 16), so finalize's intersection resolves
    // `target_type_id = q_id`.
    //   r2 = LDX[r1 + 8]   ; LoadedU64Field{P, 8}
    //   r3 = LDX[r2 + 0]   ; records access (0, 8)
    //   r4 = LDX[r2 + 8]   ; records access (8, 8)
    // Phase 2 — preserve r1 across the call clobber by stashing
    // it in r6 (callee-saved per BPF ABI, R0..R5 only clobbered):
    //   r6 = r1
    // Phase 3 — STX-flow tags the same slot:
    //   pseudo_call (PC 4)  ; SubprogReturn at PC=4 sets R0 to
    //                         RegState::ArenaU64FromAlloc after
    //                         the standard R0..=R5 clobber
    //   STX[r6 + 8] = r0    ; arena_stx_findings.insert((P, 8),
    //                         Pending)
    let insns = vec![
        // Phase 1: shape inference seeding.
        ldx(BPF_SIZE_DW, 2, 1, 8),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        ldx(BPF_SIZE_DW, 4, 2, 8),
        // Phase 2: preserve P* across the call.
        mov_x(6, 1),
        // Phase 3: STX-flow tag.
        pseudo_call,
        stx(BPF_SIZE_DW, 6, 0, 8),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: p_id,
        }],
        &[],
        &[],
        &[SubprogReturn {
            alloc_size: None,
            insn_offset: 4,
        }],
    );
    assert_eq!(
        map.get(&(p_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "STX-flow gates emission past F1; shape inference resolves \
             target_type_id from the recorded access pattern (Q is the \
             only struct of size 16 with u64@0 and u64@8): {map:?}"
    );
}

/// Long stream of `BPF_LD_IMM64` two-slot instructions back-to-
/// back, terminated by `exit`. Every `lo` slot sets `skip_next`,
/// and every `hi` slot is the upper-immediate placeholder that
/// the analyzer must not interpret. Verifies the
/// `skip_next`-driven decode path does not run off the end of the
/// slice or misaccount its position when the program is densely
/// packed with two-slot ops. Also exercises the same pattern in
/// `jump_targets`'s pre-pass — both must agree on which slots are
/// second-half placeholders.
/// Helper: build a BTF blob carrying:
///   - `u64` (id 1)
///   - struct `M` (id 2) with one `u64 cgx_raw` member at byte
///     offset 8
///   - `void *` (id 3) — `Ptr -> 0` (the BTF void marker)
///   - `FuncProto` returning id 3 with no params (id 4)
///   - `BTF_KIND_FUNC` named `func_name` extern-linkage referring
///     to FuncProto id 4 (id 5)
///
/// Returns the byte blob plus `(M_id, kfunc_id) = (2, 5)`. Used
/// by the kfunc-allocator-arm tests below — the analyzer's
/// `handle_kfunc_call` arm peels the kfunc's return type to
/// `Ptr -> Void`, looks up the kfunc's name, and applies the
/// `ARENA_ALLOC_KFUNC_NAMES` allowlist to decide whether to tag
/// R0 as `ArenaU64FromAlloc`.
fn btf_with_arena_alloc_kfunc(func_name: &str) -> (Vec<u8>, u32, u32) {
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_m = push_name(&mut strings, "M");
    let n_cgx = push_name(&mut strings, "cgx_raw");
    let n_func = push_name(&mut strings, func_name);
    let types = vec![
        // id 1: u64
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        // id 2: struct M { u64 cgx_raw @ 8 } size=16
        SynType::Struct {
            name_off: n_m,
            size: 16,
            members: vec![SynMember {
                name_off: n_cgx,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        // id 3: Ptr -> Void (pointee type id == 0). The
        // `void *` shape kfunc allocators declare.
        SynType::Ptr { type_id: 0 },
        // id 4: FuncProto returning id 3 with no params.
        SynType::FuncProto {
            return_type_id: 3,
            params: vec![],
        },
        // id 5: Func named func_name, extern, type id = 4.
        SynType::Func {
            name_off: n_func,
            type_id: 4,
            linkage: 2, // BTF_FUNC_EXTERN
        },
    ];
    let blob = build_btf(&types, &strings);
    (blob, 2, 5)
}

/// Kfunc allocator arm — happy path. Calling
/// `bpf_arena_alloc_pages` (an allowlisted kfunc whose return
/// peels to `Ptr -> Void`) tags R0 as
/// [`RegState::ArenaU64FromAlloc`]; the subsequent STX of R0
/// into a u64 slot of a typed parent records an Arena finding.
#[test]
fn kfunc_arena_alloc_allowlist_records_arena_finding() {
    let (blob, m_id, kfunc_id) = btf_with_arena_alloc_kfunc("bpf_arena_alloc_pages");
    let btf = Btf::from_bytes(&blob).unwrap();
    // R6 holds `Pointer{M}` and is callee-saved per the BPF
    // ABI, so it survives the R0..=R5 clobber the kfunc call
    // applies. Seeding R1 instead would be wiped by the call
    // and the post-call STX would have an Unknown parent.
    //
    // Insn 0: BPF_PSEUDO_KFUNC_CALL with imm=kfunc_id. The
    //         analyzer's `handle_kfunc_call` resolves the
    //         kfunc, peels the return through `Ptr -> Void`,
    //         matches the name against
    //         `ARENA_ALLOC_KFUNC_NAMES`, and tags R0 as
    //         ArenaU64FromAlloc.
    // Insn 1: STX [R6 + 8] = R0 — records (M, 8) -> Arena.
    let kfunc_call = mk_insn(
        BPF_CLASS_JMP | BPF_OP_CALL,
        0,
        BPF_PSEUDO_KFUNC_CALL,
        0,
        kfunc_id as i32,
    );
    let insns = vec![kfunc_call, stx(BPF_SIZE_DW, 6, 0, 8), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: m_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(m_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: 0,
            addr_space: AddrSpace::Arena,
        }),
        "allowlisted kfunc with `Ptr -> Void` return must seed R0 \
             as ArenaU64FromAlloc; subsequent STX must record an Arena \
             finding: {map:?}"
    );
}

/// Kfunc allocator arm — strict gate: a kfunc whose name is on
/// the allowlist BUT whose return type is NOT `Ptr -> Void`
/// (e.g. a same-named kfunc with a typed-pointer return) must
/// fall through to the typed-pointer arm OR no-op. Drift between
/// the kernel BTF and the analyzer's allowlist must not produce
/// a false positive.
#[test]
fn kfunc_arena_alloc_typed_return_falls_through() {
    // BTF: u64(1), M(2), struct R(3, u64@0), Ptr->R(4),
    // FuncProto returning Ptr->R(5), Func named
    // "bpf_arena_alloc_pages" -> proto 5 (id 6).
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_m = push_name(&mut strings, "M");
    let n_cgx = push_name(&mut strings, "cgx_raw");
    let n_r = push_name(&mut strings, "R");
    let n_x = push_name(&mut strings, "x");
    let n_func = push_name(&mut strings, "bpf_arena_alloc_pages");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_m,
            size: 16,
            members: vec![SynMember {
                name_off: n_cgx,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        // id 3: struct R { u64 x @ 0 } — a TYPED struct, not Void.
        SynType::Struct {
            name_off: n_r,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        // id 4: Ptr -> R (pointee type id == 3, NOT 0).
        SynType::Ptr { type_id: 3 },
        // id 5: FuncProto returning id 4.
        SynType::FuncProto {
            return_type_id: 4,
            params: vec![],
        },
        // id 6: Func named the allowlisted name, but with a
        // typed-pointer return.
        SynType::Func {
            name_off: n_func,
            type_id: 5,
            linkage: 2,
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let m_id = 2;
    let kfunc_id = 6;
    let kfunc_call = mk_insn(
        BPF_CLASS_JMP | BPF_OP_CALL,
        0,
        BPF_PSEUDO_KFUNC_CALL,
        0,
        kfunc_id,
    );
    // R6 holds `Pointer{M}` (callee-saved, survives the call).
    // The post-call STX through R6 records the kptr finding
    // for the (M, 8) slot.
    let insns = vec![kfunc_call, stx(BPF_SIZE_DW, 6, 0, 8), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: m_id,
        }],
        &[],
        &[],
        &[],
    );
    // The typed-pointer arm fires first and tags R0 as
    // `Pointer{R}` (not ArenaU64FromAlloc). The subsequent STX
    // records a Kernel kptr finding `(M, 8) -> R`, NOT an
    // Arena finding. The allowlist arm DID NOT execute because
    // arm 1 returned first.
    assert_eq!(
        map.get(&(m_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: 3, // R's id
            addr_space: AddrSpace::Kernel,
        }),
        "kfunc whose return is typed (Ptr -> Struct) must take the \
             typed-pointer arm, NOT the arena allocator arm; the \
             allowlist arm must not produce a false-positive Arena \
             finding: {map:?}"
    );
}

/// Kfunc allocator arm — strict gate: a kfunc whose return
/// peels to `Ptr -> Void` but whose name is NOT on the
/// allowlist must NOT seed R0 as ArenaU64FromAlloc. Without
/// the name gate, every `void *`-returning kfunc would tag
/// arbitrary u64 slots as arena-shaped.
#[test]
fn kfunc_arena_alloc_non_allowlist_name_drops() {
    // Use an unrelated kfunc name. The BTF still has a
    // `Ptr -> Void` return.
    let (blob, m_id, kfunc_id) = btf_with_arena_alloc_kfunc("ktstr_unlisted_kfunc");
    let btf = Btf::from_bytes(&blob).unwrap();
    let kfunc_call = mk_insn(
        BPF_CLASS_JMP | BPF_OP_CALL,
        0,
        BPF_PSEUDO_KFUNC_CALL,
        0,
        kfunc_id as i32,
    );
    // R6 (callee-saved) holds `Pointer{M}`; survives the call
    // clobber. The post-call STX through R6 has a typed parent;
    // the only way the assertion (`map.is_empty()`) could fail
    // is if the analyzer mistakenly tagged R0 as
    // ArenaU64FromAlloc despite the non-allowlist name. Using
    // R6 ensures the test is not falsely passing because the
    // STX itself failed (R1 clobbered).
    let insns = vec![kfunc_call, stx(BPF_SIZE_DW, 6, 0, 8), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: m_id,
        }],
        &[],
        &[],
        &[],
    );
    // R0 stays Unknown (arm 1 sees a non-Struct return and
    // returns; arm 2 sees a non-allowlist name and drops).
    // The STX with R0=Unknown produces no finding regardless
    // of whether the parent base register is typed.
    assert!(
        map.is_empty(),
        "kfunc with `Ptr -> Void` return but non-allowlist name must \
             NOT seed an arena finding: {map:?}"
    );
}

// -----------------------------------------------------------------
//
// Plain-helper return tests: bpf_map_lookup_elem (helper id 1)
//
// These tests exercise the analyzer's `BPF_OP_CALL` plain-helper
// arm. The arm fires when `src_reg == 0` (helper-call pseudo per
// linux uapi `bpf.h`), `imm == BPF_FUNC_map_lookup_elem` (== 1),
// and the saved-pre-clobber R1 was a [`RegState::DatasecPointer`]
// into a `BTF_KIND_DATASEC` named `.maps`. The analyzer types R0
// as `Pointer{value_struct_id}` only when the targeted map's BTF
// declaration carries a `value` member whose type peels to
// `Ptr -> Struct/Union`. Stat-counter maps and other shapes drop.
//
// Fixtures synthesise a `.maps` datasec with one map declaration
// matching the libbpf `parse_btf_map_def` shape (a per-map struct
// whose `value` member type is `typeof(T) *` per the
// `__type(value, T)` macro in `tools/lib/bpf/bpf_helpers.h`).

/// `BPF_CALL` for the plain-helper form: `code = BPF_JMP|BPF_CALL`,
/// `src_reg == 0` (helper, not pseudo), `imm == helper_id`. Mirrors
/// what clang emits for `bpf_map_lookup_elem(...)` and friends.
fn helper_call(helper_id: i32) -> BpfInsn {
    mk_insn(BPF_CLASS_JMP | BPF_OP_CALL, 0, 0, 0, helper_id)
}

/// Selector for the `value` member's underlying shape in the
/// synthetic `.maps` BTF fixture built by
/// [`btf_with_maps_and_task_ctx`].
///
/// - `Struct`: `Ptr -> struct cbw_cgrp_entry { u64 cgx @ 0 }`
///   (the canonical case — should resolve to the entry struct id).
/// - `U64`: `Ptr -> u64` (stat-counter map — should drop because
///   `resolve_to_struct_id` rejects a non-struct pointee).
/// - `Typedef`: `Ptr -> Typedef -> struct cbw_cgrp_entry`
///   (typedef-wrapped struct; resolution must peel the typedef).
/// - `Void`: `Ptr -> void` (`__type(value, void)` — not a real
///   libbpf shape but exercises the `resolve_to_struct_id`
///   `pointee == 0` reject path).
enum MapValueShape {
    Struct,
    U64,
    Typedef,
    #[allow(dead_code)] // Void shape is reserved for a follow-up
    // void-pointee assertion; the existing tests do not exercise
    // it directly because the U64 case already covers the
    // `resolve_to_struct_id` reject path.
    Void,
}

/// Happy path: `entry = bpf_map_lookup_elem(&map, &key)` types
/// R0 as `Pointer{cbw_cgrp_entry}`, then a follow-up STX of R0
/// into a u64 slot of an outer `Pointer{task_ctx}` records a
/// kernel kptr finding.
///
/// This is the load-bearing end-to-end test: it proves the
/// helper-return arm types R0 AND that the typed R0 flows into
/// the existing kptr STX path without any other plumbing.
/// Without Delta A landing this test would fail because R0
/// would stay Unknown after the call, and the STX would record
/// nothing.
///
/// Sequence (mirrors clang's `__always_inline`'d inline
/// `cbw_get_cgroup_ctx_raw` codegen):
///   r1 = LD_IMM64(.maps, 0)        ; r1 = DatasecPointer{maps,0}
///   r2 = key                       ; analyzer ignores R2 (the
///                                  ; ARG_PTR_TO_MAP_KEY is a
///                                  ; verifier-side gate, not a
///                                  ; cast-finding signal)
///   call helper(BPF_FUNC_map_lookup_elem)
///   *(u64 *)(r6 + 8) = r0          ; STX R0 into task_ctx.cgx_raw
///
/// R6 is seeded as `Pointer{task_ctx}` so the STX's parent base
/// resolves to a struct with a u64 field at offset 8. The
/// expected finding keys on `(task_ctx_id, 8) ->
/// (cbw_cgrp_entry_id, Kernel)`.
#[test]
fn helper_map_lookup_elem_typed_value_seeds_r0() {
    let (blob, datasec_id, var_off, value_sid, parent_id) =
        btf_with_maps_and_task_ctx(MapValueShape::Struct);
    let btf = Btf::from_bytes(&blob).unwrap();

    let [ld_lo, ld_hi] = ld_imm64(1, var_off as i32);
    let mov_key = mov_k(2, 0); // R2 = key (Unknown — analyzer ignores)
    let call_lookup = helper_call(BPF_FUNC_MAP_LOOKUP_ELEM);
    // *(u64 *)(R6 + 8) = R0 — STX R0 into task_ctx.cgx_raw.
    let stx_kptr = stx(BPF_SIZE_DW, 6, 0, 8);

    let insns = vec![ld_lo, ld_hi, mov_key, call_lookup, stx_kptr, exit()];
    // PC numbering: 0=ld_lo, 1=ld_hi (skip), 2=mov_key,
    // 3=call_lookup, 4=stx_kptr, 5=exit. The DatasecPointer
    // marks PC=0 (the LD_IMM64 lo slot) as targeting `.maps`.
    let datasec_pointers = vec![DatasecPointer {
        insn_offset: 0,
        datasec_type_id: datasec_id,
        base_offset: var_off,
    }];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: parent_id,
        }],
        &[],
        &datasec_pointers,
        &[],
    );
    assert_eq!(
        map.get(&(parent_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: value_sid,
            addr_space: AddrSpace::Kernel,
        }),
        "lookup-derived R0 stored into task_ctx.cgx_raw must record \
             (task_ctx, 8) -> (cbw_cgrp_entry, Kernel): {map:?}"
    );
}

/// Stat-counter map shape: `__type(value, u64)` produces a
/// `value` member of type `Ptr -> u64`. `resolve_to_struct_id`
/// returns None (u64 is not a struct), so the helper-return
/// arm leaves R0 Unknown. The follow-up STX records nothing.
#[test]
fn helper_map_lookup_elem_value_type_unresolvable_keeps_r0_unknown() {
    let (blob, datasec_id, var_off, _value_sid, parent_id) =
        btf_with_maps_and_task_ctx(MapValueShape::U64);
    let btf = Btf::from_bytes(&blob).unwrap();
    let [ld_lo, ld_hi] = ld_imm64(1, var_off as i32);
    let mov_key = mov_k(2, 0);
    let call_lookup = helper_call(BPF_FUNC_MAP_LOOKUP_ELEM);
    let stx_kptr = stx(BPF_SIZE_DW, 6, 0, 8);
    let insns = vec![ld_lo, ld_hi, mov_key, call_lookup, stx_kptr, exit()];
    let datasec_pointers = vec![DatasecPointer {
        insn_offset: 0,
        datasec_type_id: datasec_id,
        base_offset: var_off,
    }];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: parent_id,
        }],
        &[],
        &datasec_pointers,
        &[],
    );
    assert!(
        map.is_empty(),
        "stat-counter map (`__type(value, u64)`) must keep R0 Unknown \
             so the STX records nothing: {map:?}"
    );
}

#[test]
fn helper_map_lookup_elem_value_type_void_keeps_r0_unknown() {
    let (blob, datasec_id, var_off, _value_sid, parent_id) =
        btf_with_maps_and_task_ctx(MapValueShape::Void);
    let btf = Btf::from_bytes(&blob).unwrap();
    let [ld_lo, ld_hi] = ld_imm64(1, var_off as i32);
    let mov_key = mov_k(2, 0);
    let call_lookup = helper_call(BPF_FUNC_MAP_LOOKUP_ELEM);
    let stx_kptr = stx(BPF_SIZE_DW, 6, 0, 8);
    let insns = vec![ld_lo, ld_hi, mov_key, call_lookup, stx_kptr, exit()];
    let datasec_pointers = vec![DatasecPointer {
        insn_offset: 0,
        datasec_type_id: datasec_id,
        base_offset: var_off,
    }];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: parent_id,
        }],
        &[],
        &datasec_pointers,
        &[],
    );
    assert!(
        map.is_empty(),
        "void-value map (`Ptr -> Void`) must keep R0 Unknown: {map:?}"
    );
}

/// Typedef-wrapped value type: `__type(value, cbw_cgrp_entry_t)`
/// where `typedef struct cbw_cgrp_entry cbw_cgrp_entry_t;`. The
/// analyzer must peel the typedef via `peel_modifiers` /
/// `resolve_to_struct_id` and resolve to the underlying struct id.
#[test]
fn helper_map_lookup_elem_value_type_struct_via_typedef() {
    let (blob, datasec_id, var_off, value_sid, parent_id) =
        btf_with_maps_and_task_ctx(MapValueShape::Typedef);
    let btf = Btf::from_bytes(&blob).unwrap();
    let [ld_lo, ld_hi] = ld_imm64(1, var_off as i32);
    let mov_key = mov_k(2, 0);
    let call_lookup = helper_call(BPF_FUNC_MAP_LOOKUP_ELEM);
    let stx_kptr = stx(BPF_SIZE_DW, 6, 0, 8);
    let insns = vec![ld_lo, ld_hi, mov_key, call_lookup, stx_kptr, exit()];
    let datasec_pointers = vec![DatasecPointer {
        insn_offset: 0,
        datasec_type_id: datasec_id,
        base_offset: var_off,
    }];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: parent_id,
        }],
        &[],
        &datasec_pointers,
        &[],
    );
    assert_eq!(
        map.get(&(parent_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: value_sid,
            addr_space: AddrSpace::Kernel,
        }),
        "typedef-wrapped value type must peel to the underlying struct id: {map:?}"
    );
}

/// Missing-`.maps`-datasec case: the call site's R1 is Unknown
/// (no DatasecPointer annotation was emitted), so the
/// helper-return arm cannot resolve R0. Analogous to the
/// `ld_imm64_without_annotation_no_record` test for the kptr
/// path.
#[test]
fn helper_map_lookup_elem_no_map_metadata_keeps_r0_unknown() {
    let (blob, _datasec_id, var_off, _value_sid, parent_id) =
        btf_with_maps_and_task_ctx(MapValueShape::Struct);
    let btf = Btf::from_bytes(&blob).unwrap();
    let [ld_lo, ld_hi] = ld_imm64(1, var_off as i32);
    let mov_key = mov_k(2, 0);
    let call_lookup = helper_call(BPF_FUNC_MAP_LOOKUP_ELEM);
    let stx_kptr = stx(BPF_SIZE_DW, 6, 0, 8);
    let insns = vec![ld_lo, ld_hi, mov_key, call_lookup, stx_kptr, exit()];
    // Empty datasec_pointers — analyzer leaves R1 Unknown
    // through the LD_IMM64; helper-return arm sees a non-
    // DatasecPointer and falls through.
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: parent_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "without DatasecPointer annotation R1 stays Unknown so the \
             helper-return arm cannot type R0: {map:?}"
    );
}

/// Helper allowlist gate: a non-`bpf_map_lookup_elem` helper id
/// (e.g. `BPF_FUNC_get_current_task = 35`) must NOT seed R0 even
/// when R1 is a valid `.maps` DatasecPointer. The arm keys on
/// `imm == BPF_FUNC_map_lookup_elem` exactly.
#[test]
fn helper_not_in_allowlist_keeps_r0_unknown() {
    let (blob, datasec_id, var_off, _value_sid, parent_id) =
        btf_with_maps_and_task_ctx(MapValueShape::Struct);
    let btf = Btf::from_bytes(&blob).unwrap();
    let [ld_lo, ld_hi] = ld_imm64(1, var_off as i32);
    let mov_key = mov_k(2, 0);
    // BPF_FUNC_get_current_task = 35 per linux uapi `bpf.h`.
    // The arm rejects this id even though R1 is a valid `.maps`
    // descriptor.
    let call_other = helper_call(35);
    let stx_kptr = stx(BPF_SIZE_DW, 6, 0, 8);
    let insns = vec![ld_lo, ld_hi, mov_key, call_other, stx_kptr, exit()];
    let datasec_pointers = vec![DatasecPointer {
        insn_offset: 0,
        datasec_type_id: datasec_id,
        base_offset: var_off,
    }];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: parent_id,
        }],
        &[],
        &datasec_pointers,
        &[],
    );
    assert!(
        map.is_empty(),
        "non-bpf_map_lookup_elem helper must not type R0 even with \
             a valid `.maps` R1: {map:?}"
    );
}

/// Boundary check: `imm <= 0` (negative or zero) must drop. A
/// pre-relocation kfunc placeholder uses `imm == -1`, but those
/// carry `src_reg == BPF_PSEUDO_CALL` so the helper arm's
/// `pseudo == 0` gate already rejects them. This test exercises
/// the explicit boundary on a synthetic plain helper with
/// negative or zero imm — `BPF_FUNC_unspec == 0` and any
/// negative value must NOT match BPF_FUNC_map_lookup_elem (== 1).
#[test]
fn helper_imm_negative_or_zero_keeps_r0_unknown() {
    let (blob, datasec_id, var_off, _value_sid, parent_id) =
        btf_with_maps_and_task_ctx(MapValueShape::Struct);
    let btf = Btf::from_bytes(&blob).unwrap();
    let [ld_lo, ld_hi] = ld_imm64(1, var_off as i32);
    let mov_key = mov_k(2, 0);
    let stx_kptr = stx(BPF_SIZE_DW, 6, 0, 8);
    let datasec_pointers = vec![DatasecPointer {
        insn_offset: 0,
        datasec_type_id: datasec_id,
        base_offset: var_off,
    }];
    // Try imm == 0 (BPF_FUNC_unspec).
    {
        let call_zero = helper_call(0);
        let insns = vec![ld_lo, ld_hi, mov_key, call_zero, stx_kptr, exit()];
        let map = analyze_casts(
            &insns,
            &btf,
            &[InitialReg {
                reg: 6,
                struct_type_id: parent_id,
            }],
            &[],
            &datasec_pointers,
            &[],
        );
        assert!(
            map.is_empty(),
            "helper id 0 (BPF_FUNC_unspec) must not seed R0: {map:?}"
        );
    }
    // Try imm == -1 (placeholder shape with plain pseudo).
    {
        let call_neg = helper_call(-1);
        let insns = vec![ld_lo, ld_hi, mov_key, call_neg, stx_kptr, exit()];
        let map = analyze_casts(
            &insns,
            &btf,
            &[InitialReg {
                reg: 6,
                struct_type_id: parent_id,
            }],
            &[],
            &datasec_pointers,
            &[],
        );
        assert!(map.is_empty(), "helper id -1 must not seed R0: {map:?}");
    }
}

/// End-to-end: lookup → STX into typed slot → CastMap entry.
///
/// This is the load-bearing test for the user's stated goal: the
/// `bpf_map_lookup_elem` returned pointer must thread through the
/// existing kptr STX path and produce a CastMap entry the
/// renderer can chase. Distinct from
/// `helper_map_lookup_elem_typed_value_seeds_r0` (which uses the
/// same flow but is named for the seeding step) by adding a MOV
/// between the call and the STX, exercising the typed-pointer
/// propagation path the analyzer already supports.
#[test]
fn stx_through_helper_returned_pointer_records_finding() {
    let (blob, datasec_id, var_off, value_sid, parent_id) =
        btf_with_maps_and_task_ctx(MapValueShape::Struct);
    let btf = Btf::from_bytes(&blob).unwrap();
    let [ld_lo, ld_hi] = ld_imm64(1, var_off as i32);
    let mov_key = mov_k(2, 0);
    let call_lookup = helper_call(BPF_FUNC_MAP_LOOKUP_ELEM);
    // r7 = r0 — propagate the typed pointer through a callee-
    // saved register before the STX. Verifies the typed-pointer
    // state survives an ALU64|MOV|X.
    let mov_r7 = mov_x(7, 0);
    let stx_kptr = stx(BPF_SIZE_DW, 6, 7, 8);
    let insns = vec![ld_lo, ld_hi, mov_key, call_lookup, mov_r7, stx_kptr, exit()];
    let datasec_pointers = vec![DatasecPointer {
        insn_offset: 0,
        datasec_type_id: datasec_id,
        base_offset: var_off,
    }];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: parent_id,
        }],
        &[],
        &datasec_pointers,
        &[],
    );
    assert_eq!(
        map.get(&(parent_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: value_sid,
            addr_space: AddrSpace::Kernel,
        }),
        "lookup -> mov -> stx into task_ctx.cgx_raw must record a kernel \
             cast finding: {map:?}"
    );
}

/// Build a BTF that includes a `.maps` datasec with a single
/// map declaration AND a separate `task_ctx { u64 cgx_raw @ 8 }`
/// parent struct used as the STX destination base for the
/// end-to-end tests above. Returns `(blob, datasec_id,
/// var_offset, value_struct_id, parent_struct_id)`.
///
/// `value_struct_id` is `0` when the resolution is expected to
/// drop ([`MapValueShape::U64`], [`MapValueShape::Void`]) — the
/// callers compare the analyzer's CastMap against an empty map
/// in those branches and never deref the id.
///
/// The parent struct is distinct from the map's value type so
/// the test's STX target is a different struct id, avoiding
/// the analyzer's self-store rejection in [`Analyzer::handle_stx`].
fn btf_with_maps_and_task_ctx(value_kind: MapValueShape) -> (Vec<u8>, u32, u32, u32, u32) {
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_entry = push_name(&mut strings, "cbw_cgrp_entry");
    let n_cgx = push_name(&mut strings, "cgx");
    let n_value = push_name(&mut strings, "value");
    let n_type = push_name(&mut strings, "type");
    let n_map_def = push_name(&mut strings, "anon_map_def");
    let n_map_var = push_name(&mut strings, "cbw_cgrp_map");
    let n_maps = push_name(&mut strings, ".maps");
    let n_entry_typedef = push_name(&mut strings, "cbw_cgrp_entry_t");
    let n_task_ctx = push_name(&mut strings, "task_ctx");
    let n_cgx_raw = push_name(&mut strings, "cgx_raw");

    let mut types = vec![
        // id 1: u64
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        // id 2: struct cbw_cgrp_entry { u64 cgx @ 0 }
        SynType::Struct {
            name_off: n_entry,
            size: 8,
            members: vec![SynMember {
                name_off: n_cgx,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        // id 3: struct task_ctx { u64 cgx_raw @ 8 } (size = 16
        // so the cgx_raw slot at offset 8 has a backing byte).
        SynType::Struct {
            name_off: n_task_ctx,
            size: 16,
            members: vec![SynMember {
                name_off: n_cgx_raw,
                type_id: 1,
                byte_offset: 8,
            }],
        },
    ];
    let parent_id = 3u32;
    let (value_ptr_id, expected_struct_id) = match value_kind {
        MapValueShape::Struct => {
            // id 4: Ptr -> id 2
            types.push(SynType::Ptr { type_id: 2 });
            (4u32, 2u32)
        }
        MapValueShape::U64 => {
            // id 4: Ptr -> id 1 (u64). resolve_to_struct_id
            // returns None on a non-struct pointee.
            types.push(SynType::Ptr { type_id: 1 });
            (4u32, 0u32)
        }
        MapValueShape::Typedef => {
            // id 4: Ptr -> id 5 (typedef cbw_cgrp_entry_t -> 2)
            // id 5: Typedef cbw_cgrp_entry_t -> 2
            types.push(SynType::Ptr { type_id: 5 });
            types.push(SynType::Typedef {
                name_off: n_entry_typedef,
                type_id: 2,
            });
            (4u32, 2u32)
        }
        MapValueShape::Void => {
            // id 4: Ptr -> 0 (BTF void marker).
            types.push(SynType::Ptr { type_id: 0 });
            (4u32, 0u32)
        }
    };
    let map_def_id = types.len() as u32 + 1;
    types.push(SynType::Struct {
        name_off: n_map_def,
        size: 16,
        members: vec![
            SynMember {
                name_off: n_type,
                type_id: 1,
                byte_offset: 0,
            },
            SynMember {
                name_off: n_value,
                type_id: value_ptr_id,
                byte_offset: 8,
            },
        ],
    });
    let map_var_id = map_def_id + 1;
    types.push(SynType::Var {
        name_off: n_map_var,
        type_id: map_def_id,
        linkage: 1,
    });
    let datasec_id = map_var_id + 1;
    types.push(SynType::Datasec {
        name_off: n_maps,
        size: 16,
        entries: vec![SynVarSecinfo {
            type_id: map_var_id,
            offset: 0,
            size: 16,
        }],
    });
    let blob = build_btf(&types, &strings);
    (blob, datasec_id, 0, expected_struct_id, parent_id)
}

/// Datasec name gate: a non-`.maps` datasec must NOT drive the
/// helper-return arm even when the structural shape (Var ->
/// Struct -> Ptr -> Struct member named `value`) coincidentally
/// matches. Pins the strict `name == ".maps"` check. Without
/// this gate, a `.bss` global whose underlying type happened to
/// be a struct with a `value` member of pointer type would
/// silently drive a false-positive kptr finding.
///
/// This test reuses [`btf_with_maps_and_task_ctx`] but the
/// caller mis-identifies the datasec section name. We synthesize
/// a fresh BTF with the datasec named `.bss` instead.
#[test]
fn helper_map_lookup_elem_non_dot_maps_datasec_drops() {
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_entry = push_name(&mut strings, "cbw_cgrp_entry");
    let n_cgx = push_name(&mut strings, "cgx");
    let n_value = push_name(&mut strings, "value");
    let n_type = push_name(&mut strings, "type");
    let n_map_def = push_name(&mut strings, "anon_map_def");
    let n_map_var = push_name(&mut strings, "fake_map");
    let n_bss = push_name(&mut strings, ".bss");
    let n_task_ctx = push_name(&mut strings, "task_ctx");
    let n_cgx_raw = push_name(&mut strings, "cgx_raw");

    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_entry,
            size: 8,
            members: vec![SynMember {
                name_off: n_cgx,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        SynType::Struct {
            name_off: n_task_ctx,
            size: 16,
            members: vec![SynMember {
                name_off: n_cgx_raw,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        // id 4: Ptr -> id 2 (cbw_cgrp_entry)
        SynType::Ptr { type_id: 2 },
        // id 5: map-def-shaped struct in `.bss` (NOT `.maps`).
        SynType::Struct {
            name_off: n_map_def,
            size: 16,
            members: vec![
                SynMember {
                    name_off: n_type,
                    type_id: 1,
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_value,
                    type_id: 4,
                    byte_offset: 8,
                },
            ],
        },
        // id 6: Var
        SynType::Var {
            name_off: n_map_var,
            type_id: 5,
            linkage: 1,
        },
        // id 7: Datasec ".bss" (NOT `.maps`)
        SynType::Datasec {
            name_off: n_bss,
            size: 16,
            entries: vec![SynVarSecinfo {
                type_id: 6,
                offset: 0,
                size: 16,
            }],
        },
    ];
    let parent_id = 3u32;
    let datasec_id = 7u32;
    let var_off = 0u32;
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let [ld_lo, ld_hi] = ld_imm64(1, var_off as i32);
    let mov_key = mov_k(2, 0);
    let call_lookup = helper_call(BPF_FUNC_MAP_LOOKUP_ELEM);
    let stx_kptr = stx(BPF_SIZE_DW, 6, 0, 8);
    let insns = vec![ld_lo, ld_hi, mov_key, call_lookup, stx_kptr, exit()];
    let datasec_pointers = vec![DatasecPointer {
        insn_offset: 0,
        datasec_type_id: datasec_id,
        base_offset: var_off,
    }];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: parent_id,
        }],
        &[],
        &datasec_pointers,
        &[],
    );
    assert!(
        map.is_empty(),
        "non-`.maps` datasec must not drive the helper-return arm even \
             with a structurally matching map-def shape: {map:?}"
    );
}

#[test]
fn empty_access_pattern_does_not_trigger_conflict_with_kptr() {
    let (blob, t_id, q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let insns = vec![ldx(BPF_SIZE_DW, 3, 1, 8), stx(BPF_SIZE_DW, 1, 5, 8), exit()];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 5,
                struct_type_id: q_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.contains_key(&(t_id, 8)),
        "kptr finding on slot with empty-access pattern (LDX without deref) \
             must NOT be dropped by conflict detection: {map:?}"
    );
}

#[test]
fn only_ld_imm64_no_oob() {
    const N_PAIRS: usize = 50;
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let mut insns: Vec<BpfInsn> = Vec::with_capacity(2 * N_PAIRS + 1);
    let lo = mk_insn(BPF_CLASS_LD | BPF_SIZE_DW | BPF_MODE_IMM, 2, 0, 0, 0);
    let hi = mk_insn(0, 0, 0, 0, 0);
    for _ in 0..N_PAIRS {
        insns.push(lo);
        insns.push(hi);
    }
    insns.push(exit());
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "all-LD_IMM64 stream must produce no findings, no OOB panic: {map:?}"
    );
}

#[test]
fn arena_stx_pending_then_duplicate_is_idempotent() {
    let (blob, t_id, _q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let pseudo_call = mk_insn(BPF_CLASS_JMP | BPF_OP_CALL, 0, BPF_PSEUDO_CALL, 0, 0);
    let insns = vec![
        pseudo_call,
        stx(BPF_SIZE_DW, 6, 0, 8),
        stx(BPF_SIZE_DW, 6, 0, 8),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[SubprogReturn {
            alloc_size: None,
            insn_offset: 0,
        }],
    );
    assert!(
        !map.is_empty(),
        "duplicate STX to same slot must not conflict; map: {map:?}"
    );
}

#[test]
fn three_way_conflict_arena_kptr_pattern_drops_all() {
    let (blob, t_id, q_id) = btf_with_source_and_target(8, 0);
    let btf = Btf::from_bytes(&blob).unwrap();
    let cast = addr_space_cast(3, 2, 1);
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        cast,
        stx(BPF_SIZE_DW, 1, 3, 8),
        stx(BPF_SIZE_DW, 1, 5, 8),
        ldx(BPF_SIZE_DW, 6, 1, 8),
        ldx(BPF_SIZE_DW, 7, 6, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[
            InitialReg {
                reg: 1,
                struct_type_id: t_id,
            },
            InitialReg {
                reg: 5,
                struct_type_id: q_id,
            },
        ],
        &[],
        &[],
        &[],
    );
    assert!(
        map.is_empty(),
        "arena + kptr + pattern on same slot must all drop: {map:?}"
    );
}

/// Verify `struct_member_at` recognises offsets that land INSIDE
/// an array member as the array's element type. The peel detects
/// `Type::Array(arr)`, computes `arr.len()` × `elem_size` to bound
/// `byte_offset` relative to `member_off`, and returns
/// `MemberAt::Struct { member_type_id: elem_tid }` for queried
/// offsets that fall within the array's bytes AND are
/// `elem_size`-aligned, so the LDX / STX paths see the element's
/// BTF type rather than the array's.
///
/// Pattern: `struct T { u64 history[4] @ 0 }`. The third element
/// (`history[2]`) sits at byte offset 16. The BPF program loads
/// `history[2]` through the typed pointer in r1, casts the loaded
/// u64 through `bpf_addr_space_cast(off=1, imm=1)` so the source
/// slot tags `arena_confirmed`, stores the cast result back into
/// the same slot, then dereferences the cast result with a u64
/// load at offset 0:
///
/// ```text
/// r2 = *(u64 *)(r1 + 16)              -- load history[2]
/// r4 = bpf_addr_space_cast(r2, 0, 1)  -- arena_confirmed += (T, 16)
/// *(u64 *)(r1 + 16) = r4              -- STX back into the same slot
/// r3 = *(u64 *)(r4 + 0)               -- deref the cast result
/// ```
///
/// The first LDX is the array-recognition exercise: with r1 typed
/// `Pointer{T}`, `struct_member_at(btf, T_id, 16)` walks T's
/// single member at offset 0, peels its type to
/// `Type::Array(u64; 4)`, computes `elem_size = 8 × nelems = 4 ⇒
/// arr_byte_size = 32`, checks `rel = 16 < 32` AND `rel %
/// elem_size == 0`, and returns
/// `MemberAt::Struct { member_type_id = u64_id }`. The Plain u64
/// field arm in `handle_ldx` then tags r2 as
/// `LoadedU64Field { source_struct_id: T_id, field_offset: 16 }`
/// — `canonical_field_off = 16` because `MemberAt::Struct` keys
/// on the queried offset directly.
///
/// `addr_space_cast(4, 2, 1)` propagates r2's state into r4 and
/// inserts `(T_id, 16)` into `arena_confirmed` (the F1 mitigation
/// gate's "direct evidence" channel). The STX-back of r4 mirrors
/// real schedulers' arena-pointer write-back idiom; its src is
/// `LoadedU64Field` (cast propagates state verbatim) so the
/// production STX path's value-state arm does not match
/// `Pointer{T}` / `ArenaU64FromAlloc` and the store has no
/// side-effect on the analyzer state — `addr_space_cast_arena_alone_does_not_emit`
/// pins this exact "cast alone produces no map entry" property.
///
/// The trailing `r3 = *(u64 *)(r4 + 0)` records an `Access {
/// offset: 0, size: 8 }` on `patterns[(T_id, 16)]` (because r4 is
/// `LoadedU64Field`, the LDX-through-`LoadedU64Field` arm is the
/// only path that adds accesses). Combined with the
/// `arena_confirmed` evidence, `finalize`'s shape-inference loop
/// intersects the BTF layout for `(off=0, size=8)`: only
/// `Q { u64 @ 0 }` matches that shape, so the F1-gated emit fires
/// with `target_type_id = Q`. The presence of `(T_id, 16) →
/// CastHit { alloc_size: None, Q_id, Arena }` in the resulting `CastMap` is the
/// witness that the array peel produced
/// `MemberAt::Struct { member_type_id = u64_id }`: without it the
/// LDX would have dropped r2 to `Unknown`, neither the cast nor
/// the deref would have keyed `(T_id, 16)`, and the assertion
/// would fail.
#[test]
fn struct_member_at_resolves_array_element_offset() {
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_t = push_name(&mut strings, "T");
    let n_q = push_name(&mut strings, "Q");
    let n_history = push_name(&mut strings, "history");
    let n_x = push_name(&mut strings, "x");

    // id 1: u64 (size=8, bits=64). Doubles as element type for the
    //       array AND index-type stand-in — the analyzer never
    //       inspects the index type, and `Array::index_type` is
    //       not consulted along the `struct_member_at` path under
    //       test, so reusing id 1 keeps the BTF minimal without
    //       changing behaviour.
    // id 2: u64[4] — 32-byte total array-of-u64. The new
    //       `struct_member_at` array arm peels this when the
    //       queried offset lands inside the array's bytes.
    // id 3: struct T { u64 history[4] @ 0 } — size 32. Single
    //       member that the LDX walks; the queried offset 16
    //       falls into the array's range and the test verifies
    //       it resolves to the u64 element type.
    // id 4: struct Q { u64 x @ 0 } — size 8. Unique-shape target
    //       so the F1-gated shape inference resolves the
    //       cast-confirmed slot to a single candidate. T's only
    //       member is the array (size 32), so T is not a
    //       candidate for the (0, 8) access shape and the
    //       intersection collapses to {Q} alone.
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Array {
            type_id: 1,
            index_type_id: 1,
            nelems: 4,
        },
        SynType::Struct {
            name_off: n_t,
            size: 32,
            members: vec![SynMember {
                name_off: n_history,
                type_id: 2,
                byte_offset: 0,
            }],
        },
        SynType::Struct {
            name_off: n_q,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let t_id = 3u32;
    let q_id = 4u32;

    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 16),
        addr_space_cast(4, 2, 1),
        stx(BPF_SIZE_DW, 1, 4, 16),
        ldx(BPF_SIZE_DW, 3, 4, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: t_id,
        }],
        &[],
        &[],
        &[],
    );
    assert_eq!(
        map.get(&(t_id, 16)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: q_id,
            addr_space: AddrSpace::Arena,
        }),
        "(T={t_id}, 16) — third u64 element of `history[4]` — must \
         appear in the cast map with target=Q ({q_id}) after \
         struct_member_at peels the array member type to `u64`: \
         {map:?}"
    );
}

#[test]
fn stx_nested_struct_arena_finding_keys_on_inner() {
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_inner = push_name(&mut strings, "Inner");
    let n_cgx = push_name(&mut strings, "cgx_raw");
    let n_llcx = push_name(&mut strings, "llcx_raw");
    let n_outer = push_name(&mut strings, "Outer");
    let n_inner_field = push_name(&mut strings, "inner");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_inner,
            size: 16,
            members: vec![
                SynMember {
                    name_off: n_cgx,
                    type_id: 1,
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_llcx,
                    type_id: 1,
                    byte_offset: 8,
                },
            ],
        },
        SynType::Struct {
            name_off: n_outer,
            size: 16,
            members: vec![SynMember {
                name_off: n_inner_field,
                type_id: 2,
                byte_offset: 0,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let inner_id: u32 = 2;
    let outer_id: u32 = 3;
    let pseudo_call = mk_insn(BPF_CLASS_JMP | BPF_OP_CALL, 0, BPF_PSEUDO_CALL, 0, 0);
    let insns = vec![
        pseudo_call,
        stx(BPF_SIZE_DW, 6, 0, 0),
        mov_x(7, 0),
        stx(BPF_SIZE_DW, 6, 7, 8),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: outer_id,
        }],
        &[],
        &[],
        &[SubprogReturn {
            alloc_size: None,
            insn_offset: 0,
        }],
    );
    assert_eq!(
        map.get(&(inner_id, 0)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: 0,
            addr_space: AddrSpace::Arena,
        }),
        "nested struct STX must key on (Inner, 0) not (Outer, 0): {map:?}"
    );
    assert_eq!(
        map.get(&(inner_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: 0,
            addr_space: AddrSpace::Arena,
        }),
        "nested struct STX must key on (Inner, 8) not (Outer, 8): {map:?}"
    );
    assert!(
        !map.contains_key(&(outer_id, 0)),
        "outer struct id must NOT appear as key: {map:?}"
    );
    assert!(
        !map.contains_key(&(outer_id, 8)),
        "outer struct id must NOT appear as key: {map:?}"
    );
}

#[test]
fn ldx_nested_struct_loads_inner_key() {
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_inner = push_name(&mut strings, "Inner");
    let n_field = push_name(&mut strings, "ptr_field");
    let n_outer = push_name(&mut strings, "Outer");
    let n_embed = push_name(&mut strings, "embed");
    let n_target = push_name(&mut strings, "Target");
    let n_x = push_name(&mut strings, "x");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_inner,
            size: 16,
            members: vec![SynMember {
                name_off: n_field,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        SynType::Struct {
            name_off: n_outer,
            size: 16,
            members: vec![SynMember {
                name_off: n_embed,
                type_id: 2,
                byte_offset: 0,
            }],
        },
        SynType::Struct {
            name_off: n_target,
            size: 8,
            members: vec![SynMember {
                name_off: n_x,
                type_id: 1,
                byte_offset: 0,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let inner_id: u32 = 2;
    let outer_id: u32 = 3;
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        addr_space_cast(2, 2, 1),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: outer_id,
        }],
        &[],
        &[],
        &[],
    );
    assert!(
        map.contains_key(&(inner_id, 8)),
        "nested LDX + deref must key on (Inner={inner_id}, 8) \
         not (Outer={outer_id}, 8): {map:?}"
    );
    assert!(
        !map.contains_key(&(outer_id, 8)),
        "outer id must NOT appear as key for nested member: {map:?}"
    );
}

#[test]
fn cross_function_u64_param_inherits_caller_pointer_type() {
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_m = push_name(&mut strings, "M");
    let n_cgx = push_name(&mut strings, "cgx_raw");
    let n_caller = push_name(&mut strings, "caller");
    let n_callee = push_name(&mut strings, "callee");
    let n_taskc_raw = push_name(&mut strings, "taskc_raw");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_m,
            size: 16,
            members: vec![SynMember {
                name_off: n_cgx,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        SynType::FuncProto {
            return_type_id: 0,
            params: vec![SynParam {
                name_off: n_taskc_raw,
                type_id: 1,
            }],
        },
        SynType::Func {
            name_off: n_callee,
            type_id: 3,
            linkage: 1,
        },
        SynType::Func {
            name_off: n_caller,
            type_id: 3,
            linkage: 1,
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let m_id = 2;
    // Caller at PC 0..2: R1 = Pointer{M}, BPF_PSEUDO_CALL to callee at PC 4.
    // Callee at PC 4..6 (func_entry): FuncProto says param 0 is u64,
    // but caller had R1 = Pointer{M}. Cross-function propagation
    // should type R1 as Pointer{M} in the callee. Then:
    // PC 4: (func entry, R1 = Pointer{M} via caller propagation)
    // PC 5: STX [R1 + 8] = R6 (R6 = ArenaU64FromAlloc from seed)
    // PC 6: EXIT
    let insns = vec![
        // PC 0: caller func entry (via FuncEntry at pc=0)
        // R1 is seeded as Pointer{M} from InitialReg
        mk_insn(BPF_CLASS_JMP | BPF_OP_CALL, 0, BPF_PSEUDO_CALL, 0, 2),
        // PC 1: EXIT
        exit(),
        // PC 2: padding (unreachable)
        exit(),
        // PC 3: callee func entry (via FuncEntry at pc=3)
        // R1 typed as Pointer{M} via cross-function propagation
        // Save R1 to R6 before inner call clobbers R1
        mov_x(6, 1),
        // PC 4: inner BPF_PSEUDO_CALL (allocator) → R0 = ArenaU64FromAlloc
        mk_insn(BPF_CLASS_JMP | BPF_OP_CALL, 0, BPF_PSEUDO_CALL, 0, 0),
        // PC 5: STX [R6 + 8] = R0 (store arena alloc return to
        //        the u64 param's struct field via callee-saved R6)
        stx(BPF_SIZE_DW, 6, 0, 8),
        // PC 6: EXIT
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: m_id,
        }],
        &[FuncEntry {
            insn_offset: 3,
            func_proto_id: 3,
        }],
        &[],
        &[SubprogReturn {
            alloc_size: None,
            insn_offset: 4,
        }],
    );
    assert_eq!(
        map.get(&(m_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: 0,
            addr_space: AddrSpace::Arena,
        }),
        "cross-function u64 param must inherit caller's Pointer{{M}} \
         and record arena STX at (M, 8): {map:?}"
    );
}

/// Map-value arena propagation: an arena pointer stashed into a
/// `u64` field of a stack-local map-value struct V at
/// `bpf_map_update_elem(map, key, &V)` must round-trip through the
/// map so that the matching `bpf_map_lookup_elem(map)` returned R0
/// carries V-typed arena evidence on the same field. A subsequent
/// `LDX r2 = *(u64 *)(r0 + 8)` must therefore tag r2 as
/// [`RegState::ArenaU64FromAlloc`], and a follow-up
/// `STX *(u64 *)(r6 + 0) = r2` into a typed `Pointer{P}` parent
/// must record `(P, 0) -> Arena` via the existing
/// `arena_stx_findings` finalize path.
///
/// This is the load-bearing contract for the map-value arena
/// propagation feature: scx schedulers stash `scx_static_alloc` /
/// `scx_alloc_internal` returns inside map-value structs so the
/// arena pointer survives across BPF program invocations. The
/// renderer chases the recovered pointer from a parent struct
/// field that received the lookup-loaded value — without the
/// round-trip propagation the field renders as a raw u64 counter
/// even though the runtime byte pattern is an arena VA.
///
/// Synthesized program (clang-style codegen for the
/// "stack-local V, update_elem(&V), then lookup_elem to read V
/// back" pattern):
///
/// ```text
///   pc 0: pseudo_call          ; SubprogReturn @ pc=0 -> R0 = ArenaU64FromAlloc
///   pc 1: stx [r10 + (-16)] = r0
///                              ; spill arena value at the V.field
///                              ; offset within the stack-local V
///                              ; (V base lives at r10-24, V.field
///                              ; at +8 -> r10-16)
///   pc 2-3: ld_imm64 r1, .maps@0
///                              ; r1 = DatasecPointer{maps, 0}
///   pc 4: r2 = r10             ; key pointer (content irrelevant)
///   pc 5: r2 += -24
///   pc 6: r3 = r10             ; value pointer = &V on the stack
///   pc 7: r3 += -24
///   pc 8: call helper(BPF_FUNC_map_update_elem)
///                              ; FUTURE FEATURE: walks V's u64
///                              ; fields, sees stack_slot[-16] is
///                              ; ArenaU64FromAlloc, tags map's
///                              ; (V, 8) as arena-backed.
///   pc 9-10: ld_imm64 r1, .maps@0
///   pc 11: call helper(BPF_FUNC_map_lookup_elem)
///                              ; R0 = Pointer{V}.
///   pc 12: ldx r2 = *(u64 *)(r0 + 8)
///                              ; FUTURE FEATURE: V.field is the
///                              ; map's tagged arena field, so r2
///                              ; takes ArenaU64FromAlloc instead
///                              ; of LoadedU64Field{V, 8}.
///   pc 13: stx *(u64 *)(r6 + 0) = r2
///                              ; records (P, 0) -> Arena via the
///                              ; arena_stx_findings path.
///   pc 14: exit
/// ```
///
/// R6 is seeded `Pointer{P}` via [`InitialReg`]; R6 is callee-
/// saved per the BPF ABI so it survives both helper-call clobbers.
/// The map's value type V is distinct from the parent struct P so
/// the analyzer's self-store rejection in [`Analyzer::handle_stx`]
/// does not fire — the recorded finding is `parent=P, target=V`'s
/// value, not `P -> P`.
///
/// Helper id 2 is `BPF_FUNC_map_update_elem` per linux uapi
/// `bpf.h` (`FN(map_update_elem, 2, ##ctx)`); helper id 1 is
/// `BPF_FUNC_map_lookup_elem`. Both are plain helpers (`src_reg
/// == 0`). The numeric literal 2 is used here directly because
/// the analyzer does not yet expose a `BPF_FUNC_MAP_UPDATE_ELEM`
/// constant — that constant is part of the feature this test
/// guards.
#[test]
fn helper_map_update_then_lookup_propagates_arena_through_map_value() {
    // BTF: u64(1), V(2, u64@8), P(3, u64@0), Ptr->V(4),
    // map_def(5, type@0 + V*@8), Var "the_map"(6),
    // Datasec ".maps"(7).
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_v = push_name(&mut strings, "V");
    let n_v_field = push_name(&mut strings, "field");
    let n_p = push_name(&mut strings, "P");
    let n_p_field = push_name(&mut strings, "field");
    let n_type = push_name(&mut strings, "type");
    let n_value = push_name(&mut strings, "value");
    let n_map_def = push_name(&mut strings, "anon_map_def");
    let n_map_var = push_name(&mut strings, "the_map");
    let n_maps = push_name(&mut strings, ".maps");
    let types = vec![
        // id 1: u64 (size=8, bits=64).
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        // id 2: struct V { u64 field @ 8 }, size=16. The map's
        // value type — V.field at offset 8 is the slot the
        // pre-update STX spills the arena value into.
        SynType::Struct {
            name_off: n_v,
            size: 16,
            members: vec![SynMember {
                name_off: n_v_field,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        // id 3: struct P { u64 field @ 0 }, size=8. The parent
        // struct that receives the post-lookup arena STX —
        // distinct from V so the analyzer's self-store rejection
        // in handle_stx does not fire.
        SynType::Struct {
            name_off: n_p,
            size: 8,
            members: vec![SynMember {
                name_off: n_p_field,
                type_id: 1,
                byte_offset: 0,
            }],
        },
        // id 4: Ptr -> V. The map_def's `value` member type per
        // libbpf's `__type(value, V)` macro expansion (`typeof(V) *`).
        SynType::Ptr { type_id: 2 },
        // id 5: anonymous map_def struct {
        //   u32 type @ 0;  /* placeholder for __uint(type, ...) */
        //   V *value @ 8;
        // } size=16. Mirrors the per-map struct shape libbpf's
        // `parse_btf_map_def` consumes.
        SynType::Struct {
            name_off: n_map_def,
            size: 16,
            members: vec![
                SynMember {
                    name_off: n_type,
                    type_id: 1,
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_value,
                    type_id: 4,
                    byte_offset: 8,
                },
            ],
        },
        // id 6: Var "the_map" of type map_def, GLOBAL linkage.
        SynType::Var {
            name_off: n_map_var,
            type_id: 5,
            linkage: 1,
        },
        // id 7: Datasec ".maps" containing the_map at offset 0.
        SynType::Datasec {
            name_off: n_maps,
            size: 16,
            entries: vec![SynVarSecinfo {
                type_id: 6,
                offset: 0,
                size: 16,
            }],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let v_id = 2u32;
    let p_id = 3u32;
    let datasec_id = 7u32;
    let var_off = 0u32;

    let pseudo_call = mk_insn(BPF_CLASS_JMP | BPF_OP_CALL, 0, BPF_PSEUDO_CALL, 0, 0);
    let stx_spill = stx(BPF_SIZE_DW, 10, 0, -16);
    let [ld_lo_pre, ld_hi_pre] = ld_imm64(1, var_off as i32);
    let mov_r2_from_r10 = mov_x(2, 10);
    // R2 += -24 (ALU64 ADD K). Encoded as
    // `BPF_CLASS_ALU64 | BPF_ADD | BPF_SRC_K` per linux uapi
    // `bpf.h`; src field is unused, imm carries the constant.
    let r2_minus_24 = mk_insn(BPF_CLASS_ALU64 | (bs::BPF_ADD as u8), 2, 0, 0, -24);
    let mov_r3_from_r10 = mov_x(3, 10);
    let r3_minus_24 = mk_insn(BPF_CLASS_ALU64 | (bs::BPF_ADD as u8), 3, 0, 0, -24);
    // BPF_FUNC_map_update_elem == 2 per linux uapi `bpf.h`
    // (`FN(map_update_elem, 2, ...)`). The analyzer does not yet
    // export a BPF_FUNC_MAP_UPDATE_ELEM constant — that addition
    // is part of the feature this test guards.
    let call_update = helper_call(2);
    let [ld_lo_post, ld_hi_post] = ld_imm64(1, var_off as i32);
    let call_lookup = helper_call(BPF_FUNC_MAP_LOOKUP_ELEM);
    let ldx_v_field = ldx(BPF_SIZE_DW, 2, 0, 8);
    let stx_into_p = stx(BPF_SIZE_DW, 6, 2, 0);

    let insns = vec![
        // pc 0: pseudo_call -> R0 = ArenaU64FromAlloc.
        pseudo_call,
        // pc 1: spill R0 to stack at the V.field offset.
        stx_spill,
        // pc 2-3: ld_imm64 r1, .maps@0 (DatasecPointer for update).
        ld_lo_pre,
        ld_hi_pre,
        // pc 4-5: r2 = r10 + (-24) (key pointer; content
        // irrelevant — `bpf_map_update_elem`'s key arg is a
        // verifier-side gate, not a cast-finding signal).
        mov_r2_from_r10,
        r2_minus_24,
        // pc 6-7: r3 = r10 + (-24) (value pointer = &V on stack).
        mov_r3_from_r10,
        r3_minus_24,
        // pc 8: call bpf_map_update_elem.
        call_update,
        // pc 9-10: ld_imm64 r1, .maps@0 again (the post-update
        // R1 was clobbered by the helper call — pre-relocation
        // bytecode reloads the descriptor).
        ld_lo_post,
        ld_hi_post,
        // pc 11: call bpf_map_lookup_elem -> R0 = Pointer{V}.
        call_lookup,
        // pc 12: ldx r2 = *(u64 *)(r0 + 8) — load V.field.
        ldx_v_field,
        // pc 13: stx *(u64 *)(r6 + 0) = r2 — store into P.field.
        stx_into_p,
        // pc 14: exit.
        exit(),
    ];
    // PC layout summary (LD_IMM64 second slots are skipped via
    // skip_next; numbering above counts every BpfInsn slot):
    //   0 pseudo_call
    //   1 stx [r10-16] = r0
    //   2 ld_lo_pre, 3 ld_hi_pre
    //   4 mov r2,r10, 5 r2 += -24
    //   6 mov r3,r10, 7 r3 += -24
    //   8 call(2)        -- bpf_map_update_elem
    //   9 ld_lo_post, 10 ld_hi_post
    //   11 call(1)       -- bpf_map_lookup_elem
    //   12 ldx r2, [r0+8]
    //   13 stx [r6+0] = r2
    //   14 exit
    let datasec_pointers = vec![
        DatasecPointer {
            insn_offset: 2,
            datasec_type_id: datasec_id,
            base_offset: var_off,
        },
        DatasecPointer {
            insn_offset: 9,
            datasec_type_id: datasec_id,
            base_offset: var_off,
        },
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: p_id,
        }],
        &[],
        &datasec_pointers,
        &[SubprogReturn {
            alloc_size: None,
            insn_offset: 0,
        }],
    );
    // The end-to-end contract: the post-lookup LDX of V.field
    // produces R2 = ArenaU64FromAlloc (because the prior
    // update_elem tagged V's u64@8 slot as arena-backed via the
    // stack-spilled value), and the subsequent STX into P.field
    // records (P, 0) -> Arena via the arena_stx_findings finalize
    // path. `target_type_id == 0` because the renderer's
    // `MemReader::resolve_arena_type` bridge supplies the actual
    // payload BTF id at chase time — same convention every
    // arena-STX finding uses (see
    // `stx_flow_alloc_return_records_arena_finding`).
    //
    // Until the map-value propagation feature lands, this test
    // fails — the analyzer treats `bpf_map_update_elem` as an
    // ordinary helper that clobbers R0..=R5 without inspecting
    // R3's pointee, so V's (2, 8) slot never receives the arena
    // tag, the post-lookup LDX produces `LoadedU64Field{V, 8}`
    // instead of `ArenaU64FromAlloc`, and the final STX records
    // nothing in `arena_stx_findings`. Reference is V's id
    // (2) for the Var var_off==0 → the_map → V layout.
    let _ = v_id;
    assert_eq!(
        map.get(&(p_id, 0)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: 0,
            addr_space: AddrSpace::Arena,
        }),
        "map-value arena propagation must surface `(P, 0) -> Arena` \
         after update_elem(&V_with_arena_at_off_8) -> lookup_elem -> \
         LDX V.field -> STX into P.field: {map:?}"
    );
}

/// Cross-subprog fixpoint: callee at LOWER PC than caller. Single-pass
/// misses this because caller_arg_types isn't populated when the callee's
/// FuncEntry runs. The fixpoint carries caller_arg_types from pass 1 into
/// pass 2 so the callee inherits the caller's typed arguments.
///
/// Pattern mirrors scx_cgroup_bw_consume (callee, PC 8064) called from
/// account_task_runtime (caller, PC 18292) in lavd — the exact chain
/// that required the fixpoint to detect cgx_raw as an arena pointer.
#[test]
fn cross_function_fixpoint_callee_before_caller() {
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_parent = push_name(&mut strings, "Parent");
    let n_field = push_name(&mut strings, "arena_field");
    let n_caller = push_name(&mut strings, "caller");
    let n_callee = push_name(&mut strings, "callee");
    let n_p1 = push_name(&mut strings, "parent_raw");
    let n_p2 = push_name(&mut strings, "val_raw");

    let types = vec![
        // id 1: u64
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        // id 2: struct Parent { u64 arena_field @ offset 8 }
        SynType::Struct {
            name_off: n_parent,
            size: 16,
            members: vec![SynMember {
                name_off: n_field,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        // id 3: Ptr -> Parent
        SynType::Ptr { type_id: 2 },
        // id 4: callee FuncProto: (u64 parent_raw, u64 val_raw)
        SynType::FuncProto {
            return_type_id: 0,
            params: vec![
                SynParam {
                    name_off: n_p1,
                    type_id: 1,
                },
                SynParam {
                    name_off: n_p2,
                    type_id: 1,
                },
            ],
        },
        // id 5: Func "callee" -> proto 4
        SynType::Func {
            name_off: n_callee,
            type_id: 4,
            linkage: 1,
        },
        // id 6: caller FuncProto: (Ptr->Parent)
        SynType::FuncProto {
            return_type_id: 0,
            params: vec![SynParam {
                name_off: n_p1,
                type_id: 3,
            }],
        },
        // id 7: Func "caller" -> proto 6
        SynType::Func {
            name_off: n_caller,
            type_id: 6,
            linkage: 1,
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let parent_id: u32 = 2;

    // Callee at PC 0..1 (BEFORE caller — exercises fixpoint):
    //   PC 0: STX [R1 + 8] = R2
    //         R1 = Pointer{Parent} (from caller_arg_types, pass 2)
    //         R2 = ArenaU64FromAlloc (from caller_arg_types, pass 2)
    //   PC 1: EXIT
    //
    // Caller at PC 2..5 (AFTER callee):
    //   PC 2: FuncEntry. R1 = Pointer{Parent} from FuncProto.
    //   PC 2: allocator call → R0 = ArenaU64FromAlloc
    //   PC 3: R2 = R0 (move arena result to R2 for callee arg)
    //   PC 4: BPF_PSEUDO_CALL to callee (PC 0). imm = -5.
    //         caller_arg_types[0] = [Pointer{Parent}, ArenaU64FromAlloc, ...]
    //   PC 5: EXIT
    let alloc_call = mk_insn(BPF_CLASS_JMP | BPF_OP_CALL, 0, BPF_PSEUDO_CALL, 0, 0);
    let callee_call = mk_insn(BPF_CLASS_JMP | BPF_OP_CALL, 0, BPF_PSEUDO_CALL, 0, -7);

    let insns = vec![
        // --- callee at PC 0..1 ---
        stx(BPF_SIZE_DW, 1, 2, 8), // PC 0: STX [R1+8] = R2
        exit(),                    // PC 1
        // --- caller at PC 2..7 ---
        mov_x(6, 1), // PC 2: save R1 to callee-saved R6
        alloc_call,  // PC 3: allocator → R0=ArenaU64FromAlloc
        mov_x(2, 0), // PC 4: R2 = R0 (arena result)
        mov_x(1, 6), // PC 5: R1 = R6 (restore parent ptr)
        callee_call, // PC 6: call callee at PC 0
        exit(),      // PC 7
    ];

    let map = analyze_casts(
        &insns,
        &btf,
        &[],
        &[
            FuncEntry {
                insn_offset: 0,
                func_proto_id: 4,
            }, // callee (u64, u64)
            FuncEntry {
                insn_offset: 2,
                func_proto_id: 6,
            }, // caller (Ptr->Parent)
        ],
        &[],
        &[SubprogReturn {
            alloc_size: None,
            insn_offset: 3,
        }], // allocator at PC 3
    );

    assert_eq!(
        map.get(&(parent_id, 8)),
        Some(&CastHit {
            alloc_size: None,
            target_type_id: 0,
            addr_space: AddrSpace::Arena,
        }),
        "fixpoint must propagate caller's [Pointer{{Parent}}, ArenaU64FromAlloc] \
         into callee at lower PC, producing (Parent, 8) -> Arena: {map:?}"
    );
}

// -- finalize-order tests ----------------------------------------
//
// `Analyzer::finalize` runs the arena_stx loop (cast_analysis/mod.rs:2672)
// BEFORE the standalone shape-inference loop (cast_analysis/mod.rs:2746).
// The standalone loop's `if out.contains_key(&key) { continue; }`
// gate at line 2759 prevents it from overwriting an arena_stx
// emission for the same key. The internal shape-inference inside
// the arena_stx loop (lines 2685-2710) computes the same candidate
// intersection, so the two paths produce the same target_type_id
// when shape inference is unique.
//
// The bug surface for the ambiguous-shape fix is
// the AMBIGUOUS-shape case: when shape inference yields 0 or 2+
// candidates, the arena_stx loop emits with target_type_id=0
// (deferred resolve sentinel) AND the standalone loop's gate
// preserves that emission. Without this test, a refactor that
// swapped the loop order (running shape-inference first) would
// drop the deferred-resolve entry entirely for ambiguous-shape
// slots — every cgx_raw / llcx_raw chase would silently miss
// because the analyzer never emitted the slot.

/// Ambiguous shape preserves arena_stx deferred-resolve emit.
///
/// BTF: u64(1), P(2, u64@8 source) parent struct, two structs Q
/// and R both 16 bytes with `u64@0 + u64@8` shape. Shape inference
/// on accesses (0, 8) and (8, 8) intersects to {Q, R} — TWO
/// candidates, ambiguous. The standalone shape-inference loop drops
/// the slot per cast_analysis/mod.rs:2810-2811 ("0 or 2+ candidates
/// -> drop silently"). The arena_stx loop's internal inference at
/// 2685-2709 also yields `inferred_target = None`, so it falls back
/// to `target_type_id = 0` per line 2710 (`unwrap_or(0)`). The map
/// must contain `(P, 8) -> CastHit { alloc_size: None, target_type_id: 0,
/// addr_space: Arena }` — the deferred-resolve sentinel — so the
/// renderer's `chase_arena_pointer` special case (btf_render/mod.rs:3392)
/// can call `MemReader::resolve_arena_type` at chase time.
///
/// Pin both:
///   (a) the entry IS present (arena_stx loop emitted it), and
///   (b) target_type_id == 0 (shape inference did not resolve).
///
/// A regression that ran shape-inference FIRST would drop this slot
/// entirely (no entry in `out`), and the chase-arm `MemReader::
/// resolve_arena_type` bridge would have nothing to resolve against.
/// A regression that emitted with one of {Q, R} arbitrarily would
/// produce a wrong-type render at chase time.
#[test]
fn finalize_arena_stx_emits_deferred_resolve_when_shape_inference_ambiguous() {
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_p = push_name(&mut strings, "P");
    let n_q = push_name(&mut strings, "Q");
    let n_r = push_name(&mut strings, "R");
    let n_f = push_name(&mut strings, "f");
    let n_a = push_name(&mut strings, "a");
    let n_b = push_name(&mut strings, "b");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        // id 2: P { u64 f @ 8 } — parent struct, slot at offset 8.
        SynType::Struct {
            name_off: n_p,
            size: 16,
            members: vec![SynMember {
                name_off: n_f,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        // id 3: Q { u64 a @ 0; u64 b @ 8 } — candidate A.
        SynType::Struct {
            name_off: n_q,
            size: 16,
            members: vec![
                SynMember {
                    name_off: n_a,
                    type_id: 1,
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_b,
                    type_id: 1,
                    byte_offset: 8,
                },
            ],
        },
        // id 4: R { u64 a @ 0; u64 b @ 8 } — candidate B with same
        // shape. Two candidates collide on the access pattern; shape
        // inference yields {Q, R} — ambiguous.
        SynType::Struct {
            name_off: n_r,
            size: 16,
            members: vec![
                SynMember {
                    name_off: n_a,
                    type_id: 1,
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_b,
                    type_id: 1,
                    byte_offset: 8,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let p_id = 2;
    let pseudo_call = mk_insn(BPF_CLASS_JMP | BPF_OP_CALL, 0, BPF_PSEUDO_CALL, 0, 0);
    // Shape-inference accesses (0, 8) and (8, 8) on (P, 8) plus
    // an STX-flow tag on (P, 8) — both Q and R match the shape.
    //
    //   r2 = LDX[r1 + 8]   ; LoadedU64Field{P, 8}
    //   r3 = LDX[r2 + 0]   ; records access (0, 8) into patterns[(P, 8)]
    //   r4 = LDX[r2 + 8]   ; records access (8, 8) into patterns[(P, 8)]
    //   r6 = r1            ; preserve P* across the call (R6 callee-saved)
    //   pseudo_call (PC 4) ; SubprogReturn at PC=4 → R0 = ArenaU64FromAlloc
    //   STX[r6 + 8] = r0   ; arena_stx_findings.insert((P, 8), Pending)
    let insns = vec![
        ldx(BPF_SIZE_DW, 2, 1, 8),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        ldx(BPF_SIZE_DW, 4, 2, 8),
        mov_x(6, 1),
        pseudo_call,
        stx(BPF_SIZE_DW, 6, 0, 8),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 1,
            struct_type_id: p_id,
        }],
        &[],
        &[],
        &[SubprogReturn {
            alloc_size: None,
            insn_offset: 4,
        }],
    );
    // The slot MUST be emitted. Drop = silent failure — chase_arena_pointer
    // would never enter the deferred-resolve special case for this slot.
    let hit = map
        .get(&(p_id, 8))
        .expect("(P, 8) must be in CastMap even when shape inference is ambiguous");
    assert_eq!(
        hit.addr_space,
        AddrSpace::Arena,
        "ambiguous-shape STX-flow tag must still emit AddrSpace::Arena: {map:?}"
    );
    assert_eq!(
        hit.target_type_id, 0,
        "ambiguous shape (Q and R both 16-byte u64@0+u64@8) must yield \
         target_type_id=0 (deferred resolve via MemReader::resolve_arena_type \
         bridge at chase time). target_type_id={} suggests one of Q/R was \
         picked arbitrarily — false-positive render of the wrong struct \
         shape: {map:?}",
        hit.target_type_id
    );
    // Cross-check: assert the picked id is NOT one of the candidate
    // structs. A regression that picked Q or R would set
    // target_type_id to 3 or 4.
    assert!(
        hit.target_type_id != 3 && hit.target_type_id != 4,
        "target_type_id={} must NOT be one of the ambiguous candidates Q (3) or R (4); \
         picking one arbitrarily would render the slot's payload against the wrong \
         struct shape at chase time: {map:?}",
        hit.target_type_id
    );
}

/// Order-independence: when the STX-flow tag for a slot
/// fires BEFORE the dereference pattern through the same slot, the
/// dereference accesses must still flow into shape inference. The
/// failing pre-fix behaviour was: pseudo_call + STX(slot) tagged
/// the slot in pass 1; pass 2's LDX off the slot inherited
/// `RegState::ArenaU64FromAlloc` via alias-tracking; downstream
/// LDXs through the alias-tagged register dropped accesses (the
/// arena arm in `handle_ldx` set dst to Unknown without populating
/// patterns), so shape inference saw an empty access set even
/// though the access pattern uniquely identified the target
/// struct.
///
/// Post-fix the alias-tagged variant carries the source slot
/// identity (`source: Some((parent, off))`) and the LDX arm
/// records the access against that slot. Shape inference at
/// finalize sees the access pattern and resolves
/// `target_type_id` to the unique BTF id when the pattern
/// uniquely matches one struct.
///
/// Test fixture: struct Q { u64@0; u64@8 } is the unique 16-byte
/// candidate matching accesses (0, 8) and (8, 8). The bug
/// surface for cgx_raw / llcx_raw in `lib/cgroup_bw.bpf.c`'s
/// `scx_static_alloc()`-backed pointers — the STX-flow tag fires
/// at the allocator-return STX, the deref pattern fires later
/// when the cached pointer is consulted, and shape inference
/// must bridge the two evidence sources to recover the per-cgroup
/// payload type.
#[test]
fn stx_flow_stx_before_deref_resolves_target_via_shape_inference() {
    // P { u64 cgx_raw @ 8 }, Q { u64@0; u64@8 } — Q is the unique
    // 16-byte candidate.
    let mut strings: Vec<u8> = vec![0];
    let n_u64 = push_name(&mut strings, "u64");
    let n_p = push_name(&mut strings, "P");
    let n_q = push_name(&mut strings, "Q");
    let n_cgx = push_name(&mut strings, "cgx_raw");
    let n_a = push_name(&mut strings, "a");
    let n_b = push_name(&mut strings, "b");
    let types = vec![
        SynType::Int {
            name_off: n_u64,
            size: 8,
            encoding: 0,
            offset: 0,
            bits: 64,
        },
        SynType::Struct {
            name_off: n_p,
            size: 16,
            members: vec![SynMember {
                name_off: n_cgx,
                type_id: 1,
                byte_offset: 8,
            }],
        },
        SynType::Struct {
            name_off: n_q,
            size: 16,
            members: vec![
                SynMember {
                    name_off: n_a,
                    type_id: 1,
                    byte_offset: 0,
                },
                SynMember {
                    name_off: n_b,
                    type_id: 1,
                    byte_offset: 8,
                },
            ],
        },
    ];
    let blob = build_btf(&types, &strings);
    let btf = Btf::from_bytes(&blob).unwrap();
    let p_id = 2;
    let q_id = 3;
    let pseudo_call = mk_insn(BPF_CLASS_JMP | BPF_OP_CALL, 0, BPF_PSEUDO_CALL, 0, 0);
    // Order: STX-flow tag FIRST, then deref pattern. The deref
    // happens AFTER the slot is already in `arena_stx_findings`.
    //
    //   pseudo_call (PC 0)  ; SubprogReturn at PC=0 sets R0 to
    //                         RegState::ArenaU64FromAlloc { source: None }
    //                         after the standard R0..=R5 clobber.
    //   STX[r6 + 8] = r0    ; (P, 8) → arena_stx_findings.insert(Pending).
    //   r2 = LDX[r6 + 8]    ; pass 2 sees (P, 8) in arena_stx_findings,
    //                         re-types as ArenaU64FromAlloc { source:
    //                         Some((P, 8)) }.
    //   r3 = LDX[r2 + 0]    ; records access (0, 8) against (P, 8)
    //                         via the source field.
    //   r4 = LDX[r2 + 8]    ; records access (8, 8).
    //
    // R6 must be Pointer{P} (callee-saved → survives the call).
    let insns = vec![
        pseudo_call,
        stx(BPF_SIZE_DW, 6, 0, 8),
        ldx(BPF_SIZE_DW, 2, 6, 8),
        ldx(BPF_SIZE_DW, 3, 2, 0),
        ldx(BPF_SIZE_DW, 4, 2, 8),
        exit(),
    ];
    let map = analyze_casts(
        &insns,
        &btf,
        &[InitialReg {
            reg: 6,
            struct_type_id: p_id,
        }],
        &[],
        &[],
        &[SubprogReturn {
            alloc_size: None,
            insn_offset: 0,
        }],
    );
    let hit = map
        .get(&(p_id, 8))
        .expect("(P, 8) must be in CastMap — STX-flow gates emission");
    assert_eq!(
        hit.addr_space,
        AddrSpace::Arena,
        "STX-flow tag must yield AddrSpace::Arena: {map:?}"
    );
    assert_eq!(
        hit.target_type_id, q_id,
        "post-fix shape inference must resolve target_type_id=q_id ({q_id}) \
         even when the STX-flow tag fires BEFORE the deref pattern \
         (pre-fix bug: alias-tagged register dropped accesses, leaving \
         target_type_id=0): {map:?}"
    );
}