binscout 0.9.0

Headless, agent-first binary analysis: functions, CFGs, xrefs, strings, and IR over a JSON CLI or MCP server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
//! M2 disassembler: x86_64 via iced-x86, AArch64/ARM32/Thumb via
//! yaxpeax-arm, RISC-V 32/64 via rvdasm, MIPS32 via rabbitizer,
//! PowerPC 32/64 via powerpc.
//!
//! [`Disassembler::disasm_range`] decodes `bytes` assumed loaded at virtual
//! address `va`. Decoding stops at the first invalid opcode
//! ([`Error::Invalid`]) or when `max_insns` would be exceeded
//! ([`Error::Limit`]). [`Disassembler::disasm_range_partial`] (and the free
//! [`disasm_range_partial`]) instead return the valid prefix plus
//! [`PartialDisasm::error_at`], so agents keep the decodable instructions
//! rather than losing them to the first bad opcode.
//!
//! MIPS32 decodes fixed 4-byte little-endian words (big-endian containers
//! are rejected at load). Branch delay slots stay plain sequential rows
//! here; [`crate::analysis`] keeps each delay slot in its branch's block.

use iced_x86::{
    Decoder, DecoderOptions, Formatter as _, Instruction, IntelFormatter, OpKind, Register,
};
use powerpc::{Extensions as PpcExtensions, Ins as PpcIns};
use rabbitizer::isa::IsaVersion as MipsIsa;
use rabbitizer::operands::DefaultLabelDisplay as MipsLabelDisplay;
use rabbitizer::{
    Instruction as MipsInstruction, InstructionDisplayFlags as MipsDisplayFlags,
    InstructionFlags as MipsFlags, Vram as MipsVram,
};
use rvdasm::disassembler::{Disassembler as RiscvDecoder, Xlen as RiscvXlen};
use rvdasm::insn::Insn as RiscvInsn;
use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use yaxpeax_arch::Decoder as ArmDecoder;
use yaxpeax_arm::armv7::{
    ConditionCode as ArmV7Condition, InstDecoder as ArmV7Decoder, Instruction as ArmV7Instruction,
    Opcode as ArmV7Opcode, Operand as ArmV7Operand,
};
use yaxpeax_arm::armv8::a64::{InstDecoder, Opcode, Operand as A64Operand};

use crate::error::{Error, Result};

/// Default cap on instructions per [`Disassembler::disasm_range`] call.
pub const DEFAULT_MAX_INSNS: usize = 100_000;

/// Target architecture for disassembly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Arch {
    /// 64-bit x86.
    X86_64,
    /// 32-bit x86 (LE/DOS code).
    X86_32,
    /// 64-bit ARM.
    Aarch64,
    /// 32-bit ARM (ARM mode, fixed 4-byte instructions).
    Arm32,
    /// 32-bit ARM (Thumb mode, mixed 2/4-byte instructions).
    Thumb,
    /// 32-bit RISC-V (mixed 2/4-byte instructions with the C extension).
    Riscv32,
    /// 64-bit RISC-V (mixed 2/4-byte instructions with the C extension).
    Riscv64,
    /// 32-bit MIPS (fixed 4-byte little-endian instructions).
    Mips32,
    /// 32-bit PowerPC (fixed 4-byte big-endian instructions, base ISA).
    Ppc32,
    /// 64-bit PowerPC (fixed 4-byte big-endian instructions, base ISA).
    Ppc64,
}

impl Arch {
    /// Whether this is an x86 mode (32- or 64-bit).
    ///
    /// Corpus signatures scoped to "any x86" match exactly these modes;
    /// ARM-family modes never match x86 byte idioms.
    #[must_use]
    pub fn is_x86(self) -> bool {
        matches!(self, Self::X86_64 | Self::X86_32)
    }

    /// Default disassembler for this architecture.
    #[must_use]
    pub fn disassembler(self) -> AnyDisasm {
        match self {
            Self::X86_64 => AnyDisasm::X86_64(X86_64Disasm::new()),
            Self::X86_32 => AnyDisasm::X86_32(X86_32Disasm::new()),
            Self::Aarch64 => AnyDisasm::Aarch64(Aarch64Disasm::new()),
            Self::Arm32 => AnyDisasm::Arm32(Arm32Disasm::new()),
            Self::Thumb => AnyDisasm::Thumb(ThumbDisasm::new()),
            Self::Riscv32 => AnyDisasm::Riscv32(Riscv32Disasm::new()),
            Self::Riscv64 => AnyDisasm::Riscv64(Riscv64Disasm::new()),
            Self::Mips32 => AnyDisasm::Mips32(Mips32Disasm::new()),
            Self::Ppc32 => AnyDisasm::Ppc32(Ppc32Disasm::new()),
            Self::Ppc64 => AnyDisasm::Ppc64(Ppc64Disasm::new()),
        }
    }
}

/// Structured x86 operand decoded from iced-x86 at disassembly time.
///
/// Additive typed form alongside [`Insn::ops`]: the strings stay the
/// display rendering (and the only cross-arch form), while `operands`
/// carries decoder facts in assembly order for x86 (`op_count` order).
/// AArch64/ARM32/Thumb rows report an empty vec: structured decode there
/// is a follow-up, never a silent mistranslation. Old rows without the
/// key still deserialize.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Operand {
    /// Register operand: lowercase iced name (`rax`, `eax`, `xmm0`) plus
    /// width in bits.
    Reg {
        /// Lowercase register name.
        reg: String,
        /// Width in bits.
        bits: u32,
    },
    /// Immediate operand: signed value plus width in bits. Unsigned
    /// immediates zero-extend; `imm8to*`/`imm32to64` sign-extend; 64-bit
    /// immediates wrap into `i64` bit-preservingly.
    Imm {
        /// Signed immediate value.
        value: i64,
        /// Width in bits.
        bits: u32,
    },
    /// Memory operand: base/index register names (lowercase, `None` when
    /// absent), scale, signed displacement, access width in bits, and the
    /// explicit segment prefix (`None` when no prefix; default DS/SS is
    /// not recorded). Absolute slots have no base/index with the address
    /// in `disp`; RIP-relative forms keep `base "rip"` with the signed
    /// offset in `disp`.
    Mem {
        /// Lowercase base register, if any.
        base: Option<String>,
        /// Lowercase index register, if any.
        index: Option<String>,
        /// Index scale (1 when no index).
        scale: u32,
        /// Signed displacement.
        disp: i64,
        /// Access width in bits (0 when unknown, e.g. `lea`).
        bits: u32,
        /// Explicit segment prefix, if any.
        segment: Option<String>,
    },
}

impl Operand {
    /// Lowercase register name when this is a register operand.
    #[must_use]
    pub fn as_reg(&self) -> Option<&str> {
        match self {
            Self::Reg { reg, .. } => Some(reg),
            _ => None,
        }
    }

    /// Immediate value when this is an immediate operand.
    #[must_use]
    pub fn as_imm(&self) -> Option<i64> {
        match self {
            Self::Imm { value, .. } => Some(*value),
            _ => None,
        }
    }

    /// `(base, disp)` when this is a plain base-plus-displacement memory
    /// operand with no index register.
    #[must_use]
    pub fn as_base_disp(&self) -> Option<(&str, i64)> {
        match self {
            Self::Mem {
                base, index, disp, ..
            } if index.is_none() => base.as_deref().map(|b| (b, *disp)),
            _ => None,
        }
    }
}

/// `(base, disp, bits)` when `op` is a stack-slot memory operand:
/// base is `rsp`/`esp`/`rbp`/`ebp` (case-insensitive) with no index
/// register. Anything else reports `None`.
#[must_use]
pub fn stack_slot(op: &Operand) -> Option<(&str, i64, u32)> {
    match op {
        Operand::Mem {
            base,
            index,
            disp,
            bits,
            ..
        } if index.is_none() => match base.as_deref() {
            Some(b)
                if b.eq_ignore_ascii_case("rsp")
                    || b.eq_ignore_ascii_case("esp")
                    || b.eq_ignore_ascii_case("rbp")
                    || b.eq_ignore_ascii_case("ebp") =>
            {
                Some((b, *disp, *bits))
            }
            _ => None,
        },
        _ => None,
    }
}

/// One decoded instruction.
///
/// JSON carries every address twice: the integer (`addr`, `branch_target`,
/// `mem_target`) plus its canonical `0x`-hex twin (`addr_hex`, ...), via
/// [`crate::addr_hex`]. Old rows without the twins still deserialize (the
/// twins are recomputed on serialize, never stored).
///
/// Render-time enrichment (never stored, filled by
/// [`crate::Project`] read paths): `target_name` names the branch target
/// (or data target when there is no branch), `comment` carries the
/// annotation at `addr`, and `string` previews the referenced string.
/// Old rows without these keys still deserialize.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct Insn {
    /// Virtual address of the first byte.
    pub addr: u64,
    /// Length in bytes (x86: 1-15, AArch64/ARM32/MIPS32/PowerPC: always 4,
    /// Thumb and RISC-V: 2 or 4).
    pub size: u8,
    /// Raw instruction bytes.
    pub bytes: Vec<u8>,
    /// Lowercase mnemonic (`nop`, `ret`, `bl`, ...).
    pub mnem: String,
    /// Operand strings in assembly order.
    pub ops: Vec<String>,
    /// Absolute target for direct branches/calls, if any.
    pub branch_target: Option<u64>,
    /// Absolute address of a data access, if any: x86 RIP-relative memory
    /// operands, x86 absolute immediates and displacements (32-bit
    /// `push 0x402100`, `mov eax, [0x403000]`; 64-bit non-PIE
    /// `mov edi, <str>` = `bf imm32`, `mov eax, [abs32]`, `lea` with
    /// disp32), AArch64
    /// `adr`/`adrp`/literal loads, ARM32/Thumb PC-relative literal
    /// loads (`ldr r0, [pc, ...]`), the RISC-V `auipc` page base, and the
    /// MIPS32 `lui` high-halfword base (pairs resolve the exact address
    /// via `resolve_mips_pair`). MIPS32 has no PC-relative access.
    /// Distinct from [`Insn::branch_target`]: an indirect `call [rip+..]`
    /// reports its pointer slot here and `None` for `branch_target`.
    pub mem_target: Option<u64>,
    /// Typed base of a scaled-index table load (`jmp [index*scale+base]`),
    /// if any: x86 only, from the decoder's memory-operand fields (index
    /// register present, no base register, scale equal to the slot width,
    /// displacement as the table start). Never parsed from operand text;
    /// indexed forms report `None` for [`Insn::mem_target`], and plain
    /// absolute/RIP-relative slots report `None` here. ARM `tbb`/`tbh`
    /// carry no displacement and are excluded.
    #[serde(default)]
    pub table_base: Option<u64>,
    /// Name of the import this instruction calls through, if any:
    /// indirect `call`/`jmp` sites whose slot resolves to an import, and
    /// direct `call`/`jmp` sites targeting a PLT stub or import thunk.
    /// Pure agent-pivot annotation; never affects decoding. Old rows
    /// without the key still deserialize.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub import: Option<String>,
    /// Render-time display name of the branch target, or of the data
    /// target when there is no branch: rename wins over symbol-table and
    /// import names, with a `func@0x...` fallback for code targets.
    /// Pure listing annotation; never affects decoding. Old rows without
    /// the key still deserialize.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_name: Option<String>,
    /// Render-time copy of the annotation comment at [`Insn::addr`], if
    /// any. Pure listing annotation; old rows without the key still
    /// deserialize.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub comment: Option<String>,
    /// Render-time preview of the string referenced by the data target
    /// (escaped, clipped to [`STRING_PREVIEW_MAX_CHARS`] characters), if
    /// the target lands in a recovered string. Pure listing annotation;
    /// old rows without the key still deserialize.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub string: Option<String>,
    /// Structured x86 operands in decoder (`op_count`) order (see
    /// [`Operand`]). Empty for AArch64/ARM32/Thumb/RISC-V/MIPS32 and for
    /// rows decoded before typed operands existed. Omitted from JSON when empty so
    /// old goldens keep passing; `ops` stays the display form.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub operands: Vec<Operand>,
    /// Whether this instruction decoded in Thumb mode (32-bit ARM only).
    ///
    /// Always false on other architectures, including [`Arch::Arm32`]
    /// rows. Pure decode fact, like `size`: set by the range decoders,
    /// never edited by analysis or enrichment.
    #[serde(default)]
    pub thumb: bool,
}

/// Max characters in an [`Insn::string`] preview (counted after escaping).
pub const STRING_PREVIEW_MAX_CHARS: usize = 64;

/// Escape `value` for one-line display, clipped to
/// [`STRING_PREVIEW_MAX_CHARS`] characters.
///
/// Backslash and double quote are backslash-escaped, newline/carriage
/// return/tab become `\\n`/`\\r`/`\\t`, and any other control character
/// becomes `\\u{...}`; printable text passes through untouched. Clipping
/// counts escaped characters, so the result is always one line of at most
/// [`STRING_PREVIEW_MAX_CHARS`] characters.
#[must_use]
pub fn string_preview(value: &str) -> String {
    let mut out = String::new();
    for c in value.chars() {
        let escaped = match c {
            '\\' => "\\\\".to_string(),
            '"' => "\\\"".to_string(),
            '\n' => "\\n".to_string(),
            '\r' => "\\r".to_string(),
            '\t' => "\\t".to_string(),
            c if c.is_control() => format!("\\u{{{:x}}}", c as u32),
            c => c.to_string(),
        };
        if out.chars().count() + escaped.chars().count() > STRING_PREVIEW_MAX_CHARS {
            break;
        }
        out.push_str(&escaped);
    }
    out
}

impl Serialize for Insn {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut len = 13;
        for present in [
            self.import.is_some(),
            self.target_name.is_some(),
            self.comment.is_some(),
            self.string.is_some(),
            !self.operands.is_empty(),
        ] {
            if present {
                len += 1;
            }
        }
        let mut st = serializer.serialize_struct("Insn", len)?;
        st.serialize_field("addr", &self.addr)?;
        st.serialize_field("addr_hex", &crate::addr_hex(self.addr))?;
        st.serialize_field("size", &self.size)?;
        st.serialize_field("bytes", &self.bytes)?;
        st.serialize_field("mnem", &self.mnem)?;
        st.serialize_field("ops", &self.ops)?;
        st.serialize_field("branch_target", &self.branch_target)?;
        st.serialize_field(
            "branch_target_hex",
            &self.branch_target.map(crate::addr_hex),
        )?;
        st.serialize_field("mem_target", &self.mem_target)?;
        st.serialize_field("mem_target_hex", &self.mem_target.map(crate::addr_hex))?;
        st.serialize_field("table_base", &self.table_base)?;
        st.serialize_field("table_base_hex", &self.table_base.map(crate::addr_hex))?;
        st.serialize_field("thumb", &self.thumb)?;
        if self.import.is_some() {
            st.serialize_field("import", &self.import)?;
        } else {
            st.skip_field("import")?;
        }
        if self.target_name.is_some() {
            st.serialize_field("target_name", &self.target_name)?;
        } else {
            st.skip_field("target_name")?;
        }
        if self.comment.is_some() {
            st.serialize_field("comment", &self.comment)?;
        } else {
            st.skip_field("comment")?;
        }
        if self.string.is_some() {
            st.serialize_field("string", &self.string)?;
        } else {
            st.skip_field("string")?;
        }
        if !self.operands.is_empty() {
            st.serialize_field("operands", &self.operands)?;
        } else {
            st.skip_field("operands")?;
        }
        st.end()
    }
}

/// Address and reason of the first undecodable instruction in a partial
/// decode. The message names only the virtual address and opcode context;
/// it never carries host paths. JSON pairs `addr` with `addr_hex`
/// (see [`Insn`]).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct DecodeError {
    /// Virtual address of the failing instruction.
    pub addr: u64,
    /// Human-readable reason (e.g. `x86 invalid opcode at 0x4 (64-bit)`).
    pub message: String,
}

impl Serialize for DecodeError {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut st = serializer.serialize_struct("DecodeError", 3)?;
        st.serialize_field("addr", &self.addr)?;
        st.serialize_field("addr_hex", &crate::addr_hex(self.addr))?;
        st.serialize_field("message", &self.message)?;
        st.end()
    }
}

/// Prefix decode: the valid instructions plus the first failure, if any.
///
/// A clean range reports `error_at: None`; a range with trailing garbage
/// keeps every instruction before the first bad opcode and reports it in
/// `error_at`. Instruction-cap overruns are still [`Error::Limit`], never a
/// partial result.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PartialDisasm {
    /// Valid instructions before the first failure (empty when the first
    /// byte fails).
    pub insns: Vec<Insn>,
    /// First failure, or `None` for a clean decode.
    pub error_at: Option<DecodeError>,
}

/// Byte-range disassembler over already-loaded bytes.
pub trait Disassembler {
    /// Decode `bytes` loaded at `va`.
    ///
    /// # Errors
    /// [`Error::Invalid`] on the first undecodable instruction,
    /// [`Error::Limit`] if the range holds more than the cap.
    fn disasm_range(&self, bytes: &[u8], va: u64) -> Result<Vec<Insn>>;

    /// Decode the valid prefix of `bytes` loaded at `va`.
    ///
    /// Returns every instruction before the first bad opcode plus
    /// `error_at` for it (`None` when the whole range decodes).
    ///
    /// # Errors
    /// [`Error::Limit`] if the range holds more than the cap; undecodable
    /// bytes are reported in `error_at`, never as an error.
    fn disasm_range_partial(&self, bytes: &[u8], va: u64) -> Result<PartialDisasm>;
}

/// x86_64 disassembler (iced-x86).
#[derive(Debug, Clone, Copy)]
pub struct X86_64Disasm {
    max_insns: usize,
}

/// 32-bit x86 disassembler (iced-x86; covers DOS4GW/LE code for M1).
#[derive(Debug, Clone, Copy)]
pub struct X86_32Disasm {
    max_insns: usize,
}

/// AArch64 disassembler (yaxpeax-arm).
#[derive(Debug, Clone, Copy)]
pub struct Aarch64Disasm {
    max_insns: usize,
}

/// ARM32 disassembler in ARM mode (yaxpeax-arm armv7, fixed 4-byte words).
#[derive(Debug, Clone, Copy)]
pub struct Arm32Disasm {
    max_insns: usize,
}

/// Thumb disassembler (yaxpeax-arm armv7 in Thumb mode, mixed 2/4-byte).
#[derive(Debug, Clone, Copy)]
pub struct ThumbDisasm {
    max_insns: usize,
}

/// RISC-V 32-bit disassembler (rvdasm, mixed 2/4-byte with the C extension).
#[derive(Debug, Clone, Copy)]
pub struct Riscv32Disasm {
    max_insns: usize,
}

/// RISC-V 64-bit disassembler (rvdasm, mixed 2/4-byte with the C extension).
#[derive(Debug, Clone, Copy)]
pub struct Riscv64Disasm {
    max_insns: usize,
}

/// MIPS32 disassembler (rabbitizer, fixed 4-byte little-endian words).
#[derive(Debug, Clone, Copy)]
pub struct Mips32Disasm {
    max_insns: usize,
}

/// PowerPC 32-bit disassembler (powerpc crate, fixed 4-byte big-endian).
#[derive(Debug, Clone, Copy)]
pub struct Ppc32Disasm {
    max_insns: usize,
}

/// PowerPC 64-bit disassembler (powerpc crate, fixed 4-byte big-endian).
#[derive(Debug, Clone, Copy)]
pub struct Ppc64Disasm {
    max_insns: usize,
}

impl X86_64Disasm {
    /// Default instruction cap ([`DEFAULT_MAX_INSNS`]).
    #[must_use]
    pub fn new() -> Self {
        Self {
            max_insns: DEFAULT_MAX_INSNS,
        }
    }

    /// Custom instruction cap.
    #[must_use]
    pub fn with_limit(max_insns: usize) -> Self {
        Self { max_insns }
    }
}

impl Default for X86_64Disasm {
    fn default() -> Self {
        Self::new()
    }
}

impl X86_32Disasm {
    /// Default instruction cap ([`DEFAULT_MAX_INSNS`]).
    #[must_use]
    pub fn new() -> Self {
        Self {
            max_insns: DEFAULT_MAX_INSNS,
        }
    }

    /// Custom instruction cap.
    #[must_use]
    pub fn with_limit(max_insns: usize) -> Self {
        Self { max_insns }
    }
}

impl Default for X86_32Disasm {
    fn default() -> Self {
        Self::new()
    }
}

impl Aarch64Disasm {
    /// Default instruction cap ([`DEFAULT_MAX_INSNS`]).
    #[must_use]
    pub fn new() -> Self {
        Self {
            max_insns: DEFAULT_MAX_INSNS,
        }
    }

    /// Custom instruction cap.
    #[must_use]
    pub fn with_limit(max_insns: usize) -> Self {
        Self { max_insns }
    }
}

impl Default for Aarch64Disasm {
    fn default() -> Self {
        Self::new()
    }
}

impl Arm32Disasm {
    /// Default instruction cap ([`DEFAULT_MAX_INSNS`]).
    #[must_use]
    pub fn new() -> Self {
        Self {
            max_insns: DEFAULT_MAX_INSNS,
        }
    }

    /// Custom instruction cap.
    #[must_use]
    pub fn with_limit(max_insns: usize) -> Self {
        Self { max_insns }
    }
}

impl Default for Arm32Disasm {
    fn default() -> Self {
        Self::new()
    }
}

impl ThumbDisasm {
    /// Default instruction cap ([`DEFAULT_MAX_INSNS`]).
    #[must_use]
    pub fn new() -> Self {
        Self {
            max_insns: DEFAULT_MAX_INSNS,
        }
    }

    /// Custom instruction cap.
    #[must_use]
    pub fn with_limit(max_insns: usize) -> Self {
        Self { max_insns }
    }
}

impl Default for ThumbDisasm {
    fn default() -> Self {
        Self::new()
    }
}

impl Riscv32Disasm {
    /// Default instruction cap ([`DEFAULT_MAX_INSNS`]).
    #[must_use]
    pub fn new() -> Self {
        Self {
            max_insns: DEFAULT_MAX_INSNS,
        }
    }

    /// Custom instruction cap.
    #[must_use]
    pub fn with_limit(max_insns: usize) -> Self {
        Self { max_insns }
    }
}

impl Default for Riscv32Disasm {
    fn default() -> Self {
        Self::new()
    }
}

impl Riscv64Disasm {
    /// Default instruction cap ([`DEFAULT_MAX_INSNS`]).
    #[must_use]
    pub fn new() -> Self {
        Self {
            max_insns: DEFAULT_MAX_INSNS,
        }
    }

    /// Custom instruction cap.
    #[must_use]
    pub fn with_limit(max_insns: usize) -> Self {
        Self { max_insns }
    }
}

impl Default for Riscv64Disasm {
    fn default() -> Self {
        Self::new()
    }
}

impl Mips32Disasm {
    /// Default instruction cap ([`DEFAULT_MAX_INSNS`]).
    #[must_use]
    pub fn new() -> Self {
        Self {
            max_insns: DEFAULT_MAX_INSNS,
        }
    }

    /// Custom instruction cap.
    #[must_use]
    pub fn with_limit(max_insns: usize) -> Self {
        Self { max_insns }
    }
}

impl Default for Mips32Disasm {
    fn default() -> Self {
        Self::new()
    }
}

impl Ppc32Disasm {
    /// Default instruction cap ([`DEFAULT_MAX_INSNS`]).
    #[must_use]
    pub fn new() -> Self {
        Self {
            max_insns: DEFAULT_MAX_INSNS,
        }
    }

    /// Custom instruction cap.
    #[must_use]
    pub fn with_limit(max_insns: usize) -> Self {
        Self { max_insns }
    }
}

impl Default for Ppc32Disasm {
    fn default() -> Self {
        Self::new()
    }
}

impl Ppc64Disasm {
    /// Default instruction cap ([`DEFAULT_MAX_INSNS`]).
    #[must_use]
    pub fn new() -> Self {
        Self {
            max_insns: DEFAULT_MAX_INSNS,
        }
    }

    /// Custom instruction cap.
    #[must_use]
    pub fn with_limit(max_insns: usize) -> Self {
        Self { max_insns }
    }
}

impl Default for Ppc64Disasm {
    fn default() -> Self {
        Self::new()
    }
}

impl Disassembler for X86_64Disasm {
    fn disasm_range(&self, bytes: &[u8], va: u64) -> Result<Vec<Insn>> {
        disasm_x86(bytes, va, self.max_insns, 64)
    }

    fn disasm_range_partial(&self, bytes: &[u8], va: u64) -> Result<PartialDisasm> {
        disasm_x86_partial(bytes, va, self.max_insns, 64)
    }
}

impl Disassembler for X86_32Disasm {
    fn disasm_range(&self, bytes: &[u8], va: u64) -> Result<Vec<Insn>> {
        disasm_x86(bytes, va, self.max_insns, 32)
    }

    fn disasm_range_partial(&self, bytes: &[u8], va: u64) -> Result<PartialDisasm> {
        disasm_x86_partial(bytes, va, self.max_insns, 32)
    }
}

impl Disassembler for Aarch64Disasm {
    fn disasm_range(&self, bytes: &[u8], va: u64) -> Result<Vec<Insn>> {
        disasm_aarch64(bytes, va, self.max_insns)
    }

    fn disasm_range_partial(&self, bytes: &[u8], va: u64) -> Result<PartialDisasm> {
        disasm_aarch64_partial(bytes, va, self.max_insns)
    }
}

impl Disassembler for Arm32Disasm {
    fn disasm_range(&self, bytes: &[u8], va: u64) -> Result<Vec<Insn>> {
        disasm_arm32(bytes, va, self.max_insns)
    }

    fn disasm_range_partial(&self, bytes: &[u8], va: u64) -> Result<PartialDisasm> {
        disasm_arm32_partial(bytes, va, self.max_insns)
    }
}

impl Disassembler for ThumbDisasm {
    fn disasm_range(&self, bytes: &[u8], va: u64) -> Result<Vec<Insn>> {
        disasm_thumb(bytes, va, self.max_insns)
    }

    fn disasm_range_partial(&self, bytes: &[u8], va: u64) -> Result<PartialDisasm> {
        disasm_thumb_partial(bytes, va, self.max_insns)
    }
}

impl Disassembler for Riscv32Disasm {
    fn disasm_range(&self, bytes: &[u8], va: u64) -> Result<Vec<Insn>> {
        disasm_riscv(bytes, va, self.max_insns, 32)
    }

    fn disasm_range_partial(&self, bytes: &[u8], va: u64) -> Result<PartialDisasm> {
        disasm_riscv_partial(bytes, va, self.max_insns, 32)
    }
}

impl Disassembler for Riscv64Disasm {
    fn disasm_range(&self, bytes: &[u8], va: u64) -> Result<Vec<Insn>> {
        disasm_riscv(bytes, va, self.max_insns, 64)
    }

    fn disasm_range_partial(&self, bytes: &[u8], va: u64) -> Result<PartialDisasm> {
        disasm_riscv_partial(bytes, va, self.max_insns, 64)
    }
}

impl Disassembler for Mips32Disasm {
    fn disasm_range(&self, bytes: &[u8], va: u64) -> Result<Vec<Insn>> {
        disasm_mips(bytes, va, self.max_insns)
    }

    fn disasm_range_partial(&self, bytes: &[u8], va: u64) -> Result<PartialDisasm> {
        disasm_mips_partial(bytes, va, self.max_insns)
    }
}

impl Disassembler for Ppc32Disasm {
    fn disasm_range(&self, bytes: &[u8], va: u64) -> Result<Vec<Insn>> {
        disasm_ppc(bytes, va, self.max_insns, false)
    }

    fn disasm_range_partial(&self, bytes: &[u8], va: u64) -> Result<PartialDisasm> {
        disasm_ppc_partial(bytes, va, self.max_insns, false)
    }
}

impl Disassembler for Ppc64Disasm {
    fn disasm_range(&self, bytes: &[u8], va: u64) -> Result<Vec<Insn>> {
        disasm_ppc(bytes, va, self.max_insns, true)
    }

    fn disasm_range_partial(&self, bytes: &[u8], va: u64) -> Result<PartialDisasm> {
        disasm_ppc_partial(bytes, va, self.max_insns, true)
    }
}

/// Arch-dispatched disassembler (object-safe use of [`Disassembler`]).
#[derive(Debug, Clone, Copy)]
pub enum AnyDisasm {
    /// 64-bit x86 backend.
    X86_64(X86_64Disasm),
    /// 32-bit x86 backend.
    X86_32(X86_32Disasm),
    /// AArch64 backend.
    Aarch64(Aarch64Disasm),
    /// ARM32 (ARM mode) backend.
    Arm32(Arm32Disasm),
    /// Thumb backend.
    Thumb(ThumbDisasm),
    /// RISC-V 32-bit backend.
    Riscv32(Riscv32Disasm),
    /// RISC-V 64-bit backend.
    Riscv64(Riscv64Disasm),
    /// MIPS32 backend.
    Mips32(Mips32Disasm),
    /// PowerPC 32-bit backend.
    Ppc32(Ppc32Disasm),
    /// PowerPC 64-bit backend.
    Ppc64(Ppc64Disasm),
}

impl Disassembler for AnyDisasm {
    fn disasm_range(&self, bytes: &[u8], va: u64) -> Result<Vec<Insn>> {
        match self {
            Self::X86_64(d) => d.disasm_range(bytes, va),
            Self::X86_32(d) => d.disasm_range(bytes, va),
            Self::Aarch64(d) => d.disasm_range(bytes, va),
            Self::Arm32(d) => d.disasm_range(bytes, va),
            Self::Thumb(d) => d.disasm_range(bytes, va),
            Self::Riscv32(d) => d.disasm_range(bytes, va),
            Self::Riscv64(d) => d.disasm_range(bytes, va),
            Self::Mips32(d) => d.disasm_range(bytes, va),
            Self::Ppc32(d) => d.disasm_range(bytes, va),
            Self::Ppc64(d) => d.disasm_range(bytes, va),
        }
    }

    fn disasm_range_partial(&self, bytes: &[u8], va: u64) -> Result<PartialDisasm> {
        match self {
            Self::X86_64(d) => d.disasm_range_partial(bytes, va),
            Self::X86_32(d) => d.disasm_range_partial(bytes, va),
            Self::Aarch64(d) => d.disasm_range_partial(bytes, va),
            Self::Arm32(d) => d.disasm_range_partial(bytes, va),
            Self::Thumb(d) => d.disasm_range_partial(bytes, va),
            Self::Riscv32(d) => d.disasm_range_partial(bytes, va),
            Self::Riscv64(d) => d.disasm_range_partial(bytes, va),
            Self::Mips32(d) => d.disasm_range_partial(bytes, va),
            Self::Ppc32(d) => d.disasm_range_partial(bytes, va),
            Self::Ppc64(d) => d.disasm_range_partial(bytes, va),
        }
    }
}

/// One-shot decode without holding a disassembler value.
pub fn disasm_range(arch: Arch, bytes: &[u8], va: u64, max_insns: usize) -> Result<Vec<Insn>> {
    match arch {
        Arch::X86_64 => disasm_x86(bytes, va, max_insns, 64),
        Arch::X86_32 => disasm_x86(bytes, va, max_insns, 32),
        Arch::Aarch64 => disasm_aarch64(bytes, va, max_insns),
        Arch::Arm32 => disasm_arm32(bytes, va, max_insns),
        Arch::Thumb => disasm_thumb(bytes, va, max_insns),
        Arch::Riscv32 => disasm_riscv(bytes, va, max_insns, 32),
        Arch::Riscv64 => disasm_riscv(bytes, va, max_insns, 64),
        Arch::Mips32 => disasm_mips(bytes, va, max_insns),
        Arch::Ppc32 => disasm_ppc(bytes, va, max_insns, false),
        Arch::Ppc64 => disasm_ppc(bytes, va, max_insns, true),
    }
}

/// One-shot prefix decode: valid instructions plus `error_at` for the first
/// bad opcode (`None` when the whole range decodes).
///
/// Cap overruns are still [`Error::Limit`]; undecodable bytes are data, not
/// an error.
///
/// # Errors
/// [`Error::Limit`] if the range holds more than `max_insns`.
pub fn disasm_range_partial(
    arch: Arch,
    bytes: &[u8],
    va: u64,
    max_insns: usize,
) -> Result<PartialDisasm> {
    match arch {
        Arch::X86_64 => disasm_x86_partial(bytes, va, max_insns, 64),
        Arch::X86_32 => disasm_x86_partial(bytes, va, max_insns, 32),
        Arch::Aarch64 => disasm_aarch64_partial(bytes, va, max_insns),
        Arch::Arm32 => disasm_arm32_partial(bytes, va, max_insns),
        Arch::Thumb => disasm_thumb_partial(bytes, va, max_insns),
        Arch::Riscv32 => disasm_riscv_partial(bytes, va, max_insns, 32),
        Arch::Riscv64 => disasm_riscv_partial(bytes, va, max_insns, 64),
        Arch::Mips32 => disasm_mips_partial(bytes, va, max_insns),
        Arch::Ppc32 => disasm_ppc_partial(bytes, va, max_insns, false),
        Arch::Ppc64 => disasm_ppc_partial(bytes, va, max_insns, true),
    }
}

/// Decode only the first instruction in `bytes` (loaded at `va`).
///
/// Uses the same decoder options and the same [`Insn`] conversion as the
/// range decoders, but stops after one instruction: trailing bytes are never
/// formatted or allocated, and trailing garbage cannot change the first
/// result. An empty input reports `Ok(None)`; an undecodable or truncated
/// first instruction is [`Error::Invalid`], never a partial result.
///
/// # Errors
/// [`Error::Invalid`] when the first instruction does not decode.
pub fn disasm_first(arch: Arch, bytes: &[u8], va: u64) -> Result<Option<Insn>> {
    match arch {
        Arch::X86_64 => disasm_first_x86(bytes, va, 64),
        Arch::X86_32 => disasm_first_x86(bytes, va, 32),
        Arch::Aarch64 => disasm_first_aarch64(bytes, va),
        Arch::Arm32 => disasm_first_arm32(bytes, va),
        Arch::Thumb => disasm_first_thumb(bytes, va),
        Arch::Riscv32 => disasm_first_riscv(bytes, va, 32),
        Arch::Riscv64 => disasm_first_riscv(bytes, va, 64),
        Arch::Mips32 => disasm_first_mips(bytes, va),
        Arch::Ppc32 => disasm_first_ppc(bytes, va, false),
        Arch::Ppc64 => disasm_first_ppc(bytes, va, true),
    }
}

fn limit_err(max_insns: usize) -> Error {
    Error::Limit(format!("more than {max_insns} instructions in range"))
}

/// Legacy x86 prefixes (plus the CET/MPX/HLE prefix words iced-x86 folds
/// into formatted text: `notrack`, `bnd`, `xacquire`, `xrelease`).
/// [`split_asm`]
/// strips these so the mnemonic is the real operation (`rep movsb` becomes
/// `movsb`, `lock add ..` becomes `add`); no ARM backend prints these words
/// as a mnemonic head, so the strip is x86-only in effect.
const X86_PREFIXES: &[&str] = &[
    "rep", "repe", "repne", "lock", "notrack", "bnd", "xacquire", "xrelease",
];

/// Split `mnem op1, op2` into a lowercase mnemonic and operand strings.
///
/// iced-x86 folds legacy prefixes into the formatted text
/// (`rep movsb`, `lock add ..`), which would otherwise surface as bogus
/// `rep`/`lock` mnemonics. [`X86_PREFIXES`] are stripped here so both the
/// disassembly listing and the IR lift see the real operation; operand
/// immediates leave iced-x86 in MASM suffix form (`402100h`), so each
/// operand goes through [`masm_to_hex`] so agents only ever see `0x` form.
///
/// Commas inside `[...]`/`{...}` never split: `ldr pc, [pc, #-4]` keeps
/// `[pc, #-4]` as one operand and `ldm r0, {r1, r2}` keeps `{r1, r2}`.
fn split_asm(text: &str) -> (String, Vec<String>) {
    let text = text.trim();
    let (mut head, mut tail) = match text.find(char::is_whitespace) {
        Some(i) => (&text[..i], text[i..].trim()),
        None => (text, ""),
    };
    // At most one prefix is ever present, but loop against the table length
    // so stacked prefixes (`lock` + `rep`) still terminate.
    for _ in 0..X86_PREFIXES.len() {
        if !X86_PREFIXES.contains(&head.to_ascii_lowercase().as_str()) {
            break;
        }
        match tail.find(char::is_whitespace) {
            Some(i) => {
                head = &tail[..i];
                tail = tail[i..].trim();
            }
            None => {
                head = tail;
                tail = "";
                break;
            }
        }
    }
    let ops = if tail.is_empty() {
        Vec::new()
    } else {
        split_operands(tail)
            .into_iter()
            .map(|s| masm_to_hex(s.trim()))
            .collect()
    };
    (head.to_lowercase(), ops)
}

/// Split an operand tail on commas at bracket/brace depth 0.
///
/// `[`/`{` nest one level deeper, `]`/`}` come back out (saturating at 0
/// so a stray closer cannot swallow the rest of the line); commas at
/// depth 0 separate operands, anything nested is operand-internal
/// (`[pc, #-4]`, `{r1, r2}`).
fn split_operands(tail: &str) -> Vec<&str> {
    let mut depth: u32 = 0;
    let mut start = 0;
    let bytes = tail.as_bytes();
    let mut ends: Vec<usize> = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'[' | b'{' => depth = depth.saturating_add(1),
            b']' | b'}' => depth = depth.saturating_sub(1),
            b',' if depth == 0 => {
                ends.push(i);
            }
            _ => {}
        }
        i += 1;
    }
    let mut splits: Vec<&str> = Vec::with_capacity(ends.len() + 1);
    for end in ends {
        splits.push(&tail[start..end]);
        start = end + 1;
    }
    splits.push(&tail[start..]);
    splits
}

/// Rewrite MASM-suffixed hex inside one operand as canonical `0x`-hex.
///
/// iced-x86's `IntelFormatter` emits `402100h` / `0052C2E0h` (with a leading
/// `0` when the digits start with `A`-`F`, e.g. `0FFFFFFFFh`). Only words
/// that start with a decimal digit qualify, so registers (`ah`, `bh`),
/// keywords (`short`, `near`, `ptr`), and symbols pass through untouched;
/// every other character (brackets, `+`, spaces) is preserved verbatim.
fn masm_to_hex(op: &str) -> String {
    let mut out = String::with_capacity(op.len());
    let mut word = String::new();
    for c in op.chars() {
        if c.is_ascii_alphanumeric() || c == '_' {
            word.push(c);
        } else {
            out.push_str(&masm_word(&word));
            word.clear();
            out.push(c);
        }
    }
    out.push_str(&masm_word(&word));
    out
}

/// Rewrite one word of [`masm_to_hex`]: `402100h` becomes `0x402100`.
fn masm_word(word: &str) -> String {
    let b = word.as_bytes();
    let is_suffixed = b.len() >= 2
        && b[0].is_ascii_digit()
        && (b[b.len() - 1] == b'h' || b[b.len() - 1] == b'H')
        && b[..b.len() - 1].iter().all(|c| c.is_ascii_hexdigit());
    if !is_suffixed {
        return word.to_string();
    }
    let digits = &word[..word.len() - 1];
    match u64::from_str_radix(digits, 16) {
        Ok(v) => crate::addr_hex(v),
        Err(_) => format!("0x{}", digits.to_ascii_lowercase()),
    }
}

fn disasm_x86(bytes: &[u8], va: u64, max_insns: usize, bitness: u32) -> Result<Vec<Insn>> {
    let partial = disasm_x86_partial(bytes, va, max_insns, bitness)?;
    match partial.error_at {
        Some(e) => Err(Error::Invalid(e.message)),
        None => Ok(partial.insns),
    }
}

thread_local! {
    /// Reused x86 format scratch for single-instruction decodes.
    ///
    /// [`disasm_first`] runs once per decoded instruction during the Pass-A
    /// walk, so a fresh [`IntelFormatter`] plus text buffer per call is pure
    /// churn; the range decoders already reuse one instance per call.
    /// Thread-local because decoding may run on any thread.
    static FIRST_FORMATTER: RefCell<IntelFormatter> = RefCell::new(IntelFormatter::new());
    static FIRST_TEXT: RefCell<String> = const { RefCell::new(String::new()) };
}

/// Decode only the first x86 instruction in `bytes` (loaded at `va`).
///
/// Uses the same [`Decoder`] options (`DecoderOptions::NONE`, IP `va`) and
/// the same [`x86_insn`] conversion as [`disasm_x86_partial`], but stops
/// after one instruction instead of formatting the whole window. Returns
/// [`Error::Invalid`] with the same message the range decoder reports when
/// the first instruction is undecodable or truncated.
///
/// # Errors
/// [`Error::Invalid`] when the first instruction does not decode.
fn disasm_first_x86(bytes: &[u8], va: u64, bitness: u32) -> Result<Option<Insn>> {
    if bytes.is_empty() {
        return Ok(None);
    }
    // x86 instructions are at most 15 bytes; the window bound mirrors the
    // old shrink-and-retry prefix and cannot change the first decode.
    let win = &bytes[..bytes.len().min(15)];
    let mut decoder = Decoder::new(bitness, win, DecoderOptions::NONE);
    decoder.set_ip(va);
    let addr = decoder.ip();
    let start = decoder.position();
    let insn = decoder.decode();
    if insn.is_invalid() {
        return Err(Error::Invalid(format!(
            "x86 invalid opcode at {addr:#x} ({bitness}-bit)"
        )));
    }
    let size = insn.len();
    let Some(raw) = win.get(start..start + size).map(<[u8]>::to_vec) else {
        return Err(Error::Invalid(format!(
            "x86 invalid opcode at {addr:#x} ({bitness}-bit)"
        )));
    };
    FIRST_FORMATTER.with(|formatter| {
        FIRST_TEXT.with(|text| {
            let mut formatter = formatter.borrow_mut();
            let mut text = text.borrow_mut();
            Ok(Some(x86_insn(
                &insn,
                addr,
                raw,
                bitness,
                &mut formatter,
                &mut text,
            )))
        })
    })
}

/// Lowercase iced register name (`rax`, `xmm0`, `rip`).
fn reg_name(reg: Register) -> String {
    format!("{reg:?}").to_lowercase()
}

/// Register width in bits (0 for [`Register::None`]).
fn reg_bits(reg: Register) -> u32 {
    u32::try_from(reg.size()).unwrap_or(0).saturating_mul(8)
}

/// Signed memory displacement for one iced instruction.
///
/// Absolute slots (no base, no index) keep the address zero-extended;
/// every other shape sign-extends per `memory_displ_size`, so
/// `[rbp-0x10]` reports `-16`.
fn mem_disp(insn: &Instruction) -> i64 {
    let base = insn.memory_base();
    let index = insn.memory_index();
    if base == Register::None && index == Register::None {
        return insn.memory_displacement64() as i64;
    }
    match insn.memory_displ_size() {
        0 => 0,
        1 => i64::from(insn.memory_displacement64() as u8 as i8),
        2 => i64::from(insn.memory_displacement64() as u16 as i16),
        4 => i64::from(insn.memory_displacement32() as i32),
        _ => insn.memory_displacement64() as i64,
    }
}

/// Explicit segment prefix, if any (default DS/SS is not recorded).
fn seg_prefix(insn: &Instruction) -> Option<String> {
    let seg = insn.segment_prefix();
    (seg != Register::None).then(|| reg_name(seg))
}

/// Structured x86 operands in decoder (`op_count`) order.
///
/// Maps every iced operand kind: registers, immediates (unsigned kinds
/// zero-extend, `imm8to*`/`imm32to64` sign-extend, 64-bit wraps), direct
/// branches (absolute target as an immediate), plain memory (typed
/// base/index/scale/disp), and the implicit string-operation slots
/// (`seg:[rsi]`/`es:[rdi]` families) as memory with their fixed base.
fn x86_operands(insn: &Instruction) -> Vec<Operand> {
    let mut out = Vec::with_capacity(insn.op_count() as usize);
    for op in 0..insn.op_count() {
        let operand = match insn.op_kind(op) {
            OpKind::Register => {
                let reg = insn.op_register(op);
                Operand::Reg {
                    reg: reg_name(reg),
                    bits: reg_bits(reg),
                }
            }
            OpKind::Memory => {
                let base = insn.memory_base();
                let index = insn.memory_index();
                let bits = u32::try_from(insn.memory_size().size())
                    .unwrap_or(0)
                    .saturating_mul(8);
                Operand::Mem {
                    base: (base != Register::None).then(|| reg_name(base)),
                    index: (index != Register::None).then(|| reg_name(index)),
                    scale: insn.memory_index_scale(),
                    disp: mem_disp(insn),
                    bits,
                    segment: seg_prefix(insn),
                }
            }
            OpKind::Immediate8 => Operand::Imm {
                value: i64::from(insn.immediate8()),
                bits: 8,
            },
            OpKind::Immediate8_2nd => Operand::Imm {
                value: i64::from(insn.immediate8_2nd()),
                bits: 8,
            },
            OpKind::Immediate16 => Operand::Imm {
                value: i64::from(insn.immediate16()),
                bits: 16,
            },
            OpKind::Immediate32 => Operand::Imm {
                value: i64::from(insn.immediate32()),
                bits: 32,
            },
            OpKind::Immediate64 => Operand::Imm {
                value: insn.immediate64() as i64,
                bits: 64,
            },
            OpKind::Immediate8to16 => Operand::Imm {
                value: i64::from(insn.immediate8to16()),
                bits: 16,
            },
            OpKind::Immediate8to32 => Operand::Imm {
                value: i64::from(insn.immediate8to32()),
                bits: 32,
            },
            OpKind::Immediate8to64 => Operand::Imm {
                value: insn.immediate8to64(),
                bits: 64,
            },
            OpKind::Immediate32to64 => Operand::Imm {
                value: insn.immediate32to64(),
                bits: 64,
            },
            OpKind::NearBranch16 => Operand::Imm {
                value: insn.near_branch_target() as i64,
                bits: 16,
            },
            OpKind::NearBranch32 => Operand::Imm {
                value: insn.near_branch_target() as i64,
                bits: 32,
            },
            OpKind::NearBranch64 => Operand::Imm {
                value: insn.near_branch_target() as i64,
                bits: 64,
            },
            OpKind::FarBranch16 => Operand::Imm {
                value: i64::from(insn.far_branch16()),
                bits: 16,
            },
            OpKind::FarBranch32 => Operand::Imm {
                value: i64::from(insn.far_branch32()),
                bits: 32,
            },
            OpKind::MemorySegSI
            | OpKind::MemorySegESI
            | OpKind::MemorySegRSI
            | OpKind::MemorySegDI
            | OpKind::MemorySegEDI
            | OpKind::MemorySegRDI
            | OpKind::MemoryESDI
            | OpKind::MemoryESEDI
            | OpKind::MemoryESRDI => {
                let kind = insn.op_kind(op);
                let base = match kind {
                    OpKind::MemorySegSI => "si",
                    OpKind::MemorySegESI => "esi",
                    OpKind::MemorySegRSI => "rsi",
                    OpKind::MemorySegDI => "di",
                    OpKind::MemorySegEDI => "edi",
                    OpKind::MemorySegRDI => "rdi",
                    OpKind::MemoryESDI => "di",
                    OpKind::MemoryESEDI => "edi",
                    _ => "rdi",
                };
                let bits = u32::try_from(insn.memory_size().size())
                    .unwrap_or(0)
                    .saturating_mul(8);
                Operand::Mem {
                    base: Some(base.to_string()),
                    index: None,
                    scale: 1,
                    disp: 0,
                    bits,
                    segment: seg_prefix(insn),
                }
            }
        };
        out.push(operand);
    }
    out
}

/// Convert one decoded iced-x86 instruction to [`Insn`].
///
/// Shared by the range prefix decoder and the first-instruction decoder so
/// both report identical mnemonics, operands, and branch/memory targets.
fn x86_insn(
    insn: &Instruction,
    addr: u64,
    raw: Vec<u8>,
    bitness: u32,
    formatter: &mut IntelFormatter,
    text: &mut String,
) -> Insn {
    text.clear();
    formatter.format(insn, text);
    let (mnem, ops) = split_asm(text);
    let branch_target = match insn.op0_kind() {
        OpKind::NearBranch16 | OpKind::NearBranch32 | OpKind::NearBranch64 => {
            Some(insn.near_branch_target())
        }
        _ => None,
    };
    let mem_target = insn
        .is_ip_rel_memory_operand()
        .then(|| insn.ip_rel_memory_address());
    let mem_target = match mem_target {
        Some(_) => mem_target,
        None => absolute_target(bitness, insn),
    };
    let table_base = table_base_for(bitness, insn);
    let operands = x86_operands(insn);
    Insn {
        addr,
        size: insn.len() as u8,
        bytes: raw,
        mnem,
        ops,
        branch_target,
        mem_target,
        table_base,
        import: None,
        target_name: None,
        comment: None,
        string: None,
        operands,
        thumb: false,
    }
}

/// Prefix decode over x86 bytes: each position decodes independently via
/// iced-x86, so trailing garbage cannot change the first decode (the same
/// prefix property [`crate::analysis`] relies on for single-instruction
/// `decode_one`). The first invalid opcode ends the prefix with `error_at`.
fn disasm_x86_partial(
    bytes: &[u8],
    va: u64,
    max_insns: usize,
    bitness: u32,
) -> Result<PartialDisasm> {
    let mut decoder = Decoder::new(bitness, bytes, DecoderOptions::NONE);
    decoder.set_ip(va);
    let mut formatter = IntelFormatter::new();
    let mut text = String::new();
    let mut out = Vec::new();
    while decoder.position() < bytes.len() {
        if out.len() >= max_insns {
            return Err(limit_err(max_insns));
        }
        let addr = decoder.ip();
        let start = decoder.position();
        let insn = decoder.decode();
        if insn.is_invalid() {
            return Ok(PartialDisasm {
                insns: out,
                error_at: Some(DecodeError {
                    addr,
                    message: format!("x86 invalid opcode at {addr:#x} ({bitness}-bit)"),
                }),
            });
        }
        let size = insn.len();
        let raw = match bytes.get(start..start + size) {
            Some(b) => b.to_vec(),
            None => {
                return Ok(PartialDisasm {
                    insns: out,
                    error_at: Some(DecodeError {
                        addr,
                        message: format!("x86 invalid opcode at {addr:#x} ({bitness}-bit)"),
                    }),
                });
            }
        };
        out.push(x86_insn(
            &insn,
            addr,
            raw,
            bitness,
            &mut formatter,
            &mut text,
        ));
    }
    Ok(PartialDisasm {
        insns: out,
        error_at: None,
    })
}

/// Typed base of a scaled-index table load, if any.
///
/// Reports the displacement of an x86 memory operand with an index register,
/// no base register, and a scale equal to the slot width (4 for 32-bit,
/// 8 for 64-bit): the compiler switch shape `jmp [index*scale+table]`.
/// RIP-relative forms (base `RIP`) and plain absolute slots (no index)
/// report `None` here; those keep their [`Insn::mem_target`] path.
/// Strided scales (e.g. `*2` in 32-bit mode) report `None`: the analysis
/// scan assumes dense slots. 64-bit displacements use the decoder's
/// sign-extended form.
fn table_base_for(bitness: u32, insn: &Instruction) -> Option<u64> {
    let width: u64 = match bitness {
        32 => 4,
        64 => 8,
        _ => return None,
    };
    for op in 0..insn.op_count() {
        if insn.op_kind(op) == OpKind::Memory
            && insn.memory_base() == Register::None
            && insn.memory_index() != Register::None
            && u64::from(insn.memory_index_scale()) == width
        {
            let disp = match bitness {
                32 => u64::from(insn.memory_displacement32()),
                _ => insn.memory_displacement64(),
            };
            return Some(disp);
        }
    }
    None
}

/// Absolute data address referenced by an x86 instruction, if any.
///
/// 32-bit code addresses data absolutely (`push 0x402100`,
/// `mov eax, 0x403000`, `mov eax, [0x403000]`); 64-bit non-PIE code does
/// the same (`mov edi, <str>` = `bf imm32`, `mov eax, [abs32]`, `lea`
/// with disp32) while PIE code uses RIP-relative operands instead
/// (handled by the caller). Absolute memory operands win over
/// immediates: in `mov [0x403000], 0x1` the store slot is the reference,
/// not the stored constant. Small constants report here too (e.g.
/// `mov eax, 0` reports `Some(0)`); the analysis layer filters
/// unmapped targets, so only mapped addresses become data/string xrefs.
fn absolute_target(bitness: u32, insn: &Instruction) -> Option<u64> {
    for op in 0..insn.op_count() {
        if insn.op_kind(op) == OpKind::Memory
            && insn.memory_base() == Register::None
            && insn.memory_index() == Register::None
        {
            return Some(match bitness {
                32 => u64::from(insn.memory_displacement32()),
                _ => insn.memory_displacement64(),
            });
        }
    }
    for op in 0..insn.op_count() {
        if insn.op_kind(op) == OpKind::Immediate32 {
            return Some(u64::from(insn.immediate32()));
        }
        if insn.op_kind(op) == OpKind::Immediate32to64 {
            return u64::try_from(insn.immediate32to64()).ok();
        }
    }
    None
}

fn disasm_aarch64(bytes: &[u8], va: u64, max_insns: usize) -> Result<Vec<Insn>> {
    let partial = disasm_aarch64_partial(bytes, va, max_insns)?;
    match partial.error_at {
        Some(e) => Err(Error::Invalid(e.message)),
        None => Ok(partial.insns),
    }
}

/// Decode only the first AArch64 instruction in `bytes` (loaded at `va`).
///
/// Decodes the leading 4-byte word with the same decoder and the same
/// [`aarch64_insn`] conversion as [`disasm_aarch64_partial`]; trailing bytes
/// cannot change the first word decode. Returns [`Error::Invalid`] with the
/// same message the range decoder reports when the first word is undecodable
/// or truncated.
///
/// # Errors
/// [`Error::Invalid`] when the first word does not decode.
fn disasm_first_aarch64(bytes: &[u8], va: u64) -> Result<Option<Insn>> {
    if bytes.is_empty() {
        return Ok(None);
    }
    let mut reader =
        <&[u8] as yaxpeax_arch::ReaderBuilder<u64, u8>>::read_from(&bytes[..4.min(bytes.len())]);
    let decoder = InstDecoder::default();
    let inst = match ArmDecoder::decode(&decoder, &mut reader) {
        Ok(inst) => inst,
        Err(e) => {
            return Err(Error::Invalid(format!(
                "aarch64 decode error at {va:#x}: {e:?}"
            )));
        }
    };
    let Some(raw) = bytes.get(..4).map(<[u8]>::to_vec) else {
        return Err(Error::Invalid(format!(
            "aarch64 decode error at {va:#x}: truncated word"
        )));
    };
    Ok(Some(aarch64_insn(va, raw, &inst)))
}

/// Convert one decoded AArch64 instruction to [`Insn`].
///
/// Shared by the range prefix decoder and the first-instruction decoder so
/// both report identical mnemonics, operands, and branch/memory targets.
fn aarch64_insn(addr: u64, raw: Vec<u8>, inst: &yaxpeax_arm::armv8::a64::Instruction) -> Insn {
    let (mnem, ops) = split_asm(&inst.to_string());
    Insn {
        addr,
        size: 4,
        bytes: raw,
        mnem,
        ops,
        branch_target: arm_branch_target(inst, addr),
        mem_target: arm_data_target(inst, addr),
        table_base: None,
        import: None,
        target_name: None,
        comment: None,
        string: None,
        operands: Vec::new(),
        thumb: false,
    }
}

/// Prefix decode over AArch64 bytes: fixed 4-byte words decode
/// independently, so the first bad word ends the prefix with `error_at`.
/// A short tail (< 4 bytes) fails its word decode the same way.
fn disasm_aarch64_partial(bytes: &[u8], va: u64, max_insns: usize) -> Result<PartialDisasm> {
    let mut reader = <&[u8] as yaxpeax_arch::ReaderBuilder<u64, u8>>::read_from(bytes);
    let decoder = InstDecoder::default();
    let mut out = Vec::new();
    let mut addr = va;
    let mut off = 0usize;
    while off < bytes.len() {
        if out.len() >= max_insns {
            return Err(limit_err(max_insns));
        }
        let inst = match ArmDecoder::decode(&decoder, &mut reader) {
            Ok(inst) => inst,
            Err(e) => {
                return Ok(PartialDisasm {
                    insns: out,
                    error_at: Some(DecodeError {
                        addr,
                        message: format!("aarch64 decode error at {addr:#x}: {e:?}"),
                    }),
                });
            }
        };
        let Some(raw) = bytes.get(off..off + 4).map(<[u8]>::to_vec) else {
            return Ok(PartialDisasm {
                insns: out,
                error_at: Some(DecodeError {
                    addr,
                    message: format!("aarch64 decode error at {addr:#x}: truncated word"),
                }),
            });
        };
        out.push(aarch64_insn(addr, raw, &inst));
        addr = addr.wrapping_add(4);
        off += 4;
    }
    Ok(PartialDisasm {
        insns: out,
        error_at: None,
    })
}

/// Absolute target of PC-relative data access (`adr`/`adrp`/literal loads),
/// else `None`. Branch opcodes are excluded (see [`arm_branch_target`).
/// `adrp` carries a page offset, so the PC is page-masked first.
fn arm_data_target(inst: &yaxpeax_arm::armv8::a64::Instruction, addr: u64) -> Option<u64> {
    if matches!(
        inst.opcode,
        Opcode::B
            | Opcode::BL
            | Opcode::Bcc(_)
            | Opcode::BCcc(_)
            | Opcode::CBZ
            | Opcode::CBNZ
            | Opcode::TBZ
            | Opcode::TBNZ
    ) {
        return None;
    }
    inst.operands.iter().find_map(|op| match op {
        A64Operand::PCOffset(off) if inst.opcode == Opcode::ADRP => {
            Some((addr & !0xfff).wrapping_add_signed(*off))
        }
        A64Operand::PCOffset(off) => Some(addr.wrapping_add_signed(*off)),
        _ => None,
    })
}

/// Absolute target for direct PC-relative branches, else `None`.
fn arm_branch_target(inst: &yaxpeax_arm::armv8::a64::Instruction, addr: u64) -> Option<u64> {
    if !matches!(
        inst.opcode,
        Opcode::B
            | Opcode::BL
            | Opcode::Bcc(_)
            | Opcode::BCcc(_)
            | Opcode::CBZ
            | Opcode::CBNZ
            | Opcode::TBZ
            | Opcode::TBNZ
    ) {
        return None;
    }
    inst.operands.iter().find_map(|op| match op {
        A64Operand::PCOffset(off) => Some(addr.wrapping_add_signed(*off)),
        _ => None,
    })
}

/// Final address of an `adrp` + `add`/`ldr` pair, if any.
///
/// `adrp` materializes only the 4K page base (see [`Insn::mem_target`]);
/// the page offset rides in the next instruction, so the referenced address
/// spans two instructions. Returns the `adrp` page plus the second
/// instruction's immediate when `first` is an `adrp` with a decoded page
/// base and `second` consumes the same register:
///
/// - `add <dst>, <base>, #<imm>` with exactly three operands (`<base>`
///   equals the `adrp` destination; shifted forms such as `lsl #12` add a
///   fourth operand and are rejected) and
/// - `ldr <dst>, [<base>, #<imm>]`, plus the zero-offset `ldr <dst>,
///   [<base>]` form (final address is the page itself).
///
/// The `add`/`ldr` destination may differ from the `adrp` register (e.g.
/// `ldr w0, [x0, #..]`); only the consumed base register must match.
/// Anything else (wrong mnemonics, register mismatch, unparseable
/// immediates, missing page base) returns `None`; the function never
/// guesses. Pairing (adjacency, same block) is the caller's job.
pub(crate) fn resolve_adrp_pair(first: &Insn, second: &Insn) -> Option<u64> {
    if first.mnem != "adrp" {
        return None;
    }
    let page = first.mem_target?;
    let base = first.ops.first()?;
    match second.mnem.as_str() {
        "add" => {
            if second.ops.len() != 3 || second.ops[1] != *base {
                return None;
            }
            let off = parse_hash_imm(&second.ops[2])?;
            Some(page.wrapping_add(off))
        }
        "ldr" => {
            if second.ops.len() == 2 {
                // Single-operand shape from depth-aware splitting:
                // `[<base>]` (final address is the page) or
                // `[<base>, #<imm>]` (page plus offset).
                if let Some(inner) = second.ops[1]
                    .strip_prefix('[')
                    .and_then(|s| s.strip_suffix(']'))
                {
                    let mut parts = inner.split(',');
                    let reg = parts.next()?.trim();
                    if reg != base.as_str() {
                        return None;
                    }
                    return match parts.next() {
                        None => Some(page),
                        Some(imm) => {
                            if parts.next().is_some() {
                                return None;
                            }
                            let off = parse_hash_imm(imm.trim())?;
                            Some(page.wrapping_add(off))
                        }
                    };
                }
                // Not a bracketed memory operand: fall through to the
                // legacy three-operand shape below, which rejects len 2.
                return None;
            }
            // Legacy three-operand shape (`[<base>`, `#<imm>]`) from
            // comma-oblivious splitting; kept so hand-built rows still
            // resolve.
            if second.ops.len() != 3 {
                return None;
            }
            let reg = second.ops[1].strip_prefix('[')?;
            if reg.contains(['[', ']']) || reg != base.as_str() {
                return None;
            }
            let off = parse_hash_imm(second.ops[2].strip_suffix(']')?)?;
            Some(page.wrapping_add(off))
        }
        _ => None,
    }
}

/// Strict `#`-immediate (`#0x10`, `#16`): anything else is `None`.
fn parse_hash_imm(op: &str) -> Option<u64> {
    parse_digits(op.strip_prefix('#')?)
}

/// Strict bare immediate (`0x10`, `16`): anything else is `None`.
///
/// ARM `mov`/`movt` immediates print without the `#` prefix (`mov r0,
/// 0x1234`), unlike AArch64 `add`/`ldr` forms, so the pair resolver takes
/// the operand as printed. An optional `#` is accepted so both shapes
/// resolve.
fn parse_bare_imm(digits: &str) -> Option<u64> {
    parse_digits(digits.strip_prefix('#').unwrap_or(digits))
}

fn parse_digits(digits: &str) -> Option<u64> {
    if let Some(hex) = digits
        .strip_prefix("0x")
        .or_else(|| digits.strip_prefix("0X"))
    {
        if hex.is_empty() || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
            return None;
        }
        u64::from_str_radix(hex, 16).ok()
    } else {
        if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
            return None;
        }
        digits.parse::<u64>().ok()
    }
}

/// Final address of a `movw` + `movt` pair materializing a 32-bit constant,
/// if any.
///
/// `movw` writes the low halfword (yaxpeax-arm prints it as plain `mov`:
/// `mov r0, 0x1234`) and `movt` the high halfword, so the referenced
/// address spans two instructions — the ARM32 equivalent of
/// [`resolve_adrp_pair`]. Returns `(hi << 16) | lo` when `first` is a
/// two-operand `mov` with a bare-hex immediate destination-equal to
/// `second`'s `movt` destination, else `None`. A plain `mov rX, #imm`
/// first row resolves identically: it fully writes the register, so the
/// following `movt` still determines the high halfword. Register sources
/// (`mov r0, r1`), extra operands, mismatched destinations, and
/// halfwords wider than 16 bits return `None`; the function never
/// guesses. Pairing (adjacency, same block) is the caller's job.
pub(crate) fn resolve_movw_pair(first: &Insn, second: &Insn) -> Option<u64> {
    if !matches!(first.mnem.as_str(), "mov" | "movw") || second.mnem != "movt" {
        return None;
    }
    if first.ops.len() != 2 || second.ops.len() != 2 {
        return None;
    }
    if first.ops[0] != second.ops[0] {
        return None;
    }
    let lo = parse_bare_imm(&first.ops[1])?;
    let hi = parse_bare_imm(&second.ops[1])?;
    if lo > 0xffff || hi > 0xffff {
        return None;
    }
    Some((hi << 16) | lo)
}

/// Base mnemonic of an ARMv7 row: one trailing `.w`/`.n` width suffix
/// stripped (`bl.w` decodes as `bl`).
///
/// Conditional suffixes stay intact (`blxeq` is not `blx`): mode-switch and
/// literal-pool checks only fire on unconditional forms.
pub(crate) fn arm_base_mnem(mnem: &str) -> &str {
    mnem.strip_suffix(".w")
        .or_else(|| mnem.strip_suffix(".n"))
        .unwrap_or(mnem)
}

/// Final address of a two-instruction constant pair ending at `second`,
/// if any: an AArch64 `adrp`+`add`/`ldr` pair, an ARM32 `movw`+`movt`
/// pair (see [`resolve_adrp_pair`] and [`resolve_movw_pair`]), a
/// MIPS32 `lui` pair (see [`resolve_mips_pair`]), or a RISC-V `auipc`
/// pair (see [`resolve_auipc_pair`]). The arches never share a row, so
/// trying each in turn never double-resolves.
pub(crate) fn resolve_const_pair(first: &Insn, second: &Insn) -> Option<u64> {
    resolve_adrp_pair(first, second)
        .or_else(|| resolve_movw_pair(first, second))
        .or_else(|| resolve_mips_pair(first, second))
        .or_else(|| resolve_auipc_pair(first, second))
}

/// Decode exactly one ARMv7 instruction from the start of `bytes`
/// (`thumb` selects the decoder mode), with the same decoder and the same
/// [`armv7_insn`] conversion as [`disasm_armv7_partial`].
///
/// Returns [`Error::Invalid`] with the same message the range decoder
/// reports when the instruction is undecodable or truncated.
///
/// # Errors
/// [`Error::Invalid`] when the first instruction does not decode.
fn decode_single_armv7(bytes: &[u8], va: u64, thumb: bool) -> Result<Insn> {
    let mut reader = <&[u8] as yaxpeax_arch::ReaderBuilder<u32, u8>>::read_from(bytes);
    let decoder = ArmV7Decoder::default().with_thumb_mode(thumb);
    let label = if thumb { "thumb" } else { "arm32" };
    // yaxpeax-arm panics on some words (e.g. STRD with Rt == 15 builds
    // Reg(16)); contain it so hostile bytes report Invalid, never abort.
    let decoded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        ArmDecoder::decode(&decoder, &mut reader)
    }));
    let inst = match decoded {
        Ok(Ok(inst)) => inst,
        Ok(Err(e)) => {
            return Err(Error::Invalid(format!(
                "{label} decode error at {va:#x}: {e:?}"
            )));
        }
        Err(_) => {
            return Err(Error::Invalid(format!(
                "{label} decode error at {va:#x}: invalid encoding (decoder panic)"
            )));
        }
    };
    let size: usize = if inst.thumb() && !inst.wide() { 2 } else { 4 };
    let Some(raw) = bytes.get(..size).map(<[u8]>::to_vec) else {
        return Err(Error::Invalid(format!(
            "{label} decode error at {va:#x}: truncated word"
        )));
    };
    Ok(armv7_insn(va, raw, &inst))
}

/// Decode only the first ARM32 instruction in `bytes` (loaded at `va`).
///
/// Decodes the leading 4-byte word; trailing bytes cannot change the first
/// word decode. A short tail fails the word decode the same way the range
/// decoder reports it.
///
/// # Errors
/// [`Error::Invalid`] when the first word does not decode.
fn disasm_first_arm32(bytes: &[u8], va: u64) -> Result<Option<Insn>> {
    if bytes.is_empty() {
        return Ok(None);
    }
    Ok(Some(decode_single_armv7(
        &bytes[..4.min(bytes.len())],
        va,
        false,
    )?))
}

/// Decode only the first Thumb instruction in `bytes` (loaded at `va`).
///
/// A 4-byte window decodes both 16- and 32-bit forms; only when it fails is
/// a lone halfword tried, so a 32-bit prefix is never misread as 16-bit —
/// the same fallback [`disasm_thumb`] relies on, minus decoding the rest of
/// the window.
///
/// # Errors
/// [`Error::Invalid`] when neither the 4-byte nor the 2-byte window decodes.
fn disasm_first_thumb(bytes: &[u8], va: u64) -> Result<Option<Insn>> {
    if bytes.is_empty() {
        return Ok(None);
    }
    if bytes.len() >= 4 {
        match decode_single_armv7(&bytes[..4], va, true) {
            Ok(insn) => return Ok(Some(insn)),
            Err(Error::Invalid(_)) => {}
            Err(e) => return Err(e),
        }
    }
    if bytes.len() >= 2 {
        return Ok(Some(decode_single_armv7(&bytes[..2], va, true)?));
    }
    Err(Error::Invalid(format!(
        "thumb decode error at {va:#x}: truncated word"
    )))
}

/// Convert one decoded ARMv7 instruction to [`Insn`].
///
/// Shared by the range prefix decoder and the first-instruction decoder so
/// both report identical mnemonics, operands, and branch/memory targets.
fn armv7_insn(addr: u64, raw: Vec<u8>, inst: &ArmV7Instruction) -> Insn {
    let size: usize = if inst.thumb() && !inst.wide() { 2 } else { 4 };
    let (mnem, ops) = split_asm(&inst.to_string());
    Insn {
        addr,
        size: size as u8,
        bytes: raw,
        mnem,
        ops,
        branch_target: armv7_branch_target(inst, addr),
        mem_target: armv7_data_target(inst, addr),
        table_base: None,
        import: None,
        target_name: None,
        comment: None,
        string: None,
        operands: Vec::new(),
        thumb: inst.thumb(),
    }
}

/// Length of the Thumb IT block opened by `mnem` (1-4), else `None`.
///
/// yaxpeax-arm prints the IT mask in the mnemonic (`it`, `ite`, `itt`,
/// `itet`, ...), so the predicated count is the mask length plus one; the
/// base condition rides in the first operand. Only the `e`/`t` mask guard
/// keeps non-IT mnemonics sharing the prefix out. Thumb-only: ARM mode has
/// no IT instruction, so callers gate on [`Arch::Thumb`].
pub(crate) fn it_block_len(mnem: &str) -> Option<u8> {
    let mask = mnem.strip_prefix("it")?;
    if mask.len() > 3 || !mask.bytes().all(|b| b == b'e' || b == b't') {
        return None;
    }
    Some(mask.len() as u8 + 1)
}

fn disasm_arm32(bytes: &[u8], va: u64, max_insns: usize) -> Result<Vec<Insn>> {
    let partial = disasm_arm32_partial(bytes, va, max_insns)?;
    match partial.error_at {
        Some(e) => Err(Error::Invalid(e.message)),
        None => Ok(partial.insns),
    }
}

/// Prefix decode over ARM32 bytes: fixed 4-byte words decode
/// independently, so the first bad word ends the prefix with `error_at`.
/// A short tail (< 4 bytes) fails its word decode the same way.
fn disasm_arm32_partial(bytes: &[u8], va: u64, max_insns: usize) -> Result<PartialDisasm> {
    disasm_armv7_partial(bytes, va, max_insns, false)
}

fn disasm_thumb(bytes: &[u8], va: u64, max_insns: usize) -> Result<Vec<Insn>> {
    let partial = disasm_thumb_partial(bytes, va, max_insns)?;
    match partial.error_at {
        Some(e) => Err(Error::Invalid(e.message)),
        None => Ok(partial.insns),
    }
}

/// Prefix decode over Thumb bytes: the first halfword decides the length
/// (2 or 4 bytes), so the first bad halfword pair ends the prefix with
/// `error_at`. A short tail, including a lone first halfword of a 32-bit
/// instruction, fails its decode the same way.
fn disasm_thumb_partial(bytes: &[u8], va: u64, max_insns: usize) -> Result<PartialDisasm> {
    disasm_armv7_partial(bytes, va, max_insns, true)
}

/// Shared ARMv7 prefix decode; `thumb` selects the decoder mode.
///
/// The reader is stateful across decodes, and each successful decode
/// consumes exactly its instruction (`inst.thumb() && !inst.wide()` is 2
/// bytes, anything else 4), so the byte window always matches what the
/// decoder read — including a 2-byte tail left by a 32-bit prefix, which
/// fails as exhausted input.
fn disasm_armv7_partial(
    bytes: &[u8],
    va: u64,
    max_insns: usize,
    thumb: bool,
) -> Result<PartialDisasm> {
    let mut reader = <&[u8] as yaxpeax_arch::ReaderBuilder<u32, u8>>::read_from(bytes);
    let decoder = ArmV7Decoder::default().with_thumb_mode(thumb);
    let label = if thumb { "thumb" } else { "arm32" };
    let mut out = Vec::new();
    let mut addr = va;
    let mut off = 0usize;
    while off < bytes.len() {
        if out.len() >= max_insns {
            return Err(limit_err(max_insns));
        }
        // See `decode_single_armv7`: contain yaxpeax-arm panics as the first
        // failure so hostile bytes end the prefix, never abort the process.
        let decoded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            ArmDecoder::decode(&decoder, &mut reader)
        }));
        let inst = match decoded {
            Ok(Ok(inst)) => inst,
            Ok(Err(e)) => {
                return Ok(PartialDisasm {
                    insns: out,
                    error_at: Some(DecodeError {
                        addr,
                        message: format!("{label} decode error at {addr:#x}: {e:?}"),
                    }),
                });
            }
            Err(_) => {
                return Ok(PartialDisasm {
                    insns: out,
                    error_at: Some(DecodeError {
                        addr,
                        message: format!(
                            "{label} decode error at {addr:#x}: invalid encoding (decoder panic)"
                        ),
                    }),
                });
            }
        };
        let size: usize = if inst.thumb() && !inst.wide() { 2 } else { 4 };
        let Some(raw) = bytes.get(off..off + size).map(<[u8]>::to_vec) else {
            return Ok(PartialDisasm {
                insns: out,
                error_at: Some(DecodeError {
                    addr,
                    message: format!("{label} decode error at {addr:#x}: truncated word"),
                }),
            });
        };
        out.push(armv7_insn(addr, raw, &inst));
        addr = addr.wrapping_add(size as u64);
        off += size;
    }
    Ok(PartialDisasm {
        insns: out,
        error_at: None,
    })
}

/// Absolute target for direct ARMv7 branches, else `None`.
///
/// `BranchOffset` (ARM `b`/`bl`) counts words from the instruction address:
/// the decoder already folded the architectural PC+8 bias in.
/// `BranchThumbOffset` counts halfwords (`off * 2`) from PC: `addr + 4` in
/// Thumb, `addr + 8` in ARM. Thumb `blx` switches to ARM state, so its PC
/// is aligned (`(addr + 4) & !3`) before adding the offset. The 16-bit
/// conditional branch (`B<cond>`) and `cbz`/`cbnz` forms carry the `+1` in
/// the decoded offset (the decoder prints `$+imm` with it folded in), so
/// their PC reads as `addr + 2`.
fn armv7_branch_target(inst: &ArmV7Instruction, addr: u64) -> Option<u64> {
    if !matches!(
        inst.opcode,
        ArmV7Opcode::B | ArmV7Opcode::BL | ArmV7Opcode::BLX | ArmV7Opcode::CBZ | ArmV7Opcode::CBNZ
    ) {
        return None;
    }
    inst.operands.iter().find_map(|op| match op {
        ArmV7Operand::BranchOffset(off) => Some(addr.wrapping_add_signed(i64::from(*off) * 4)),
        ArmV7Operand::BranchThumbOffset(off) if inst.thumb() => {
            let plus_one = matches!(inst.opcode, ArmV7Opcode::CBZ | ArmV7Opcode::CBNZ)
                || (inst.opcode == ArmV7Opcode::B
                    && !inst.wide()
                    && inst.condition != ArmV7Condition::AL);
            let base = if matches!(inst.opcode, ArmV7Opcode::BLX) {
                addr.wrapping_add(4) & !3
            } else if plus_one {
                addr.wrapping_add(2)
            } else {
                addr.wrapping_add(4)
            };
            Some(base.wrapping_add_signed(i64::from(*off) * 2))
        }
        ArmV7Operand::BranchThumbOffset(off) => Some(
            addr.wrapping_add(8)
                .wrapping_add_signed(i64::from(*off) * 2),
        ),
        _ => None,
    })
}

/// Absolute target of a PC-relative literal load (`ldr` family with a `pc`
/// base), else `None`. Branch opcodes are excluded (see
/// [`armv7_branch_target`]). ARM reads PC as `addr + 8`; Thumb reads an
/// aligned PC (`addr + 4` rounded down to 4) and the decoder already scaled
/// 16-bit offsets to bytes.
///
/// `adr` is deliberately excluded: its Display folds the add/sub form away
/// (`adr r0, pc, 0x4` for both), so the sign is unrecoverable from the
/// decoded instruction.
fn armv7_data_target(inst: &ArmV7Instruction, addr: u64) -> Option<u64> {
    if matches!(
        inst.opcode,
        ArmV7Opcode::B | ArmV7Opcode::BL | ArmV7Opcode::BLX | ArmV7Opcode::CBZ | ArmV7Opcode::CBNZ
    ) {
        return None;
    }
    if !matches!(
        inst.opcode,
        ArmV7Opcode::LDR
            | ArmV7Opcode::LDRB
            | ArmV7Opcode::LDRH
            | ArmV7Opcode::LDRSB
            | ArmV7Opcode::LDRSH
    ) {
        return None;
    }
    inst.operands.iter().find_map(|op| match op {
        ArmV7Operand::RegDerefPreindexOffset(reg, off, add, _) if reg.number() == 15 => {
            let base = if inst.thumb() {
                addr.wrapping_add(4) & !3
            } else {
                addr.wrapping_add(8)
            };
            let delta = u64::from(*off);
            Some(if *add {
                base.wrapping_add(delta)
            } else {
                base.wrapping_sub(delta)
            })
        }
        _ => None,
    })
}

/// Convert one decoded RISC-V instruction to [`Insn`].
///
/// Shared by the range prefix decoder and the first-instruction decoder so
/// both report identical mnemonics, operands, and branch/memory targets.
/// Text is rvdasm's `no-aliases` form (canonical mnemonics, ABI register
/// names, branch targets as absolute `0x` addresses) split by
/// [`split_asm`]; structured [`Operand`] rows stay empty like the other
/// non-x86 backends.
fn riscv_insn(addr: u64, raw: Vec<u8>, inst: &RiscvInsn, xlen: u8) -> Insn {
    let (mnem, ops) = split_asm(&inst.asm_no_aliases(addr));
    Insn {
        addr,
        size: inst.get_len(),
        bytes: raw,
        mnem,
        ops,
        branch_target: riscv_branch_target(inst, addr, xlen),
        mem_target: riscv_mem_target(inst, addr),
        table_base: None,
        import: None,
        target_name: None,
        comment: None,
        string: None,
        operands: Vec::new(),
        thumb: false,
    }
}

/// Absolute target for a direct PC-relative RISC-V branch or jump, else
/// `None`. rvdasm's `offset` is the already-scaled byte offset for branches,
/// jumps, and `auipc` alike; indirect jumps (`jalr` family, `ret`) carry no
/// target. RV32 wraps at 32 bits, matching the hardware PC.
fn riscv_branch_target(inst: &RiscvInsn, addr: u64, xlen: u8) -> Option<u64> {
    if !(inst.is_branch() || inst.is_direct_jump()) {
        return None;
    }
    let off = inst.offset;
    Some(if xlen == 32 {
        u64::from((addr as u32).wrapping_add_signed(off))
    } else {
        addr.wrapping_add_signed(i64::from(off))
    })
}

/// Absolute page base produced by `auipc`, else `None`. Loads and stores
/// need a base register, so only the PC-relative upper-immediate form
/// resolves; `lui` is not PC-relative. Branch and jump opcodes are excluded
/// (see [`riscv_branch_target`]).
fn riscv_mem_target(inst: &RiscvInsn, addr: u64) -> Option<u64> {
    if inst.get_name() != "auipc" {
        return None;
    }
    let off = i64::from(inst.offset);
    Some(addr.wrapping_add_signed(off))
}

/// Final address of an `auipc` + second-instruction pair, if any.
///
/// `auipc` materializes only the PC-relative page base (see
/// [`Insn::mem_target`]); the low 12 bits ride in the next instruction,
/// so the referenced address spans two instructions. Returns the `auipc`
/// page plus the second instruction's signed offset when `first` is an
/// `auipc` with a decoded page base and `second` consumes the same
/// register:
///
/// - `addi`/`addiw <dst>, <base>, <simm>` with exactly three operands
///   (`<base>` equals the `auipc` destination; `<dst>` may differ) and
/// - `lw`/`ld` loads `<dst>, <simm>(<base>)` plus `sw` stores `<src>,
///   <simm>(<base>)` (the final address is the referenced global).
///
/// These are the linker-relaxation shapes (`PCREL_HI20` paired with
/// `PCREL_LO12_I/S`: what `la` and global data accesses expand to).
/// Anything else (wrong mnemonics, register mismatch, unparseable
/// offsets, missing page base) returns `None`; the function never
/// guesses. Pairing (adjacency, same block) is the caller's job.
pub(crate) fn resolve_auipc_pair(first: &Insn, second: &Insn) -> Option<u64> {
    if first.mnem != "auipc" {
        return None;
    }
    let page = first.mem_target?;
    let base = first.ops.first()?;
    match second.mnem.as_str() {
        "addi" | "addiw" => {
            if second.ops.len() != 3 || second.ops[1] != *base {
                return None;
            }
            let off = parse_riscv_simm(&second.ops[2])?;
            Some(page.wrapping_add_signed(off))
        }
        "lw" | "ld" | "sw" => {
            if second.ops.len() != 2 {
                return None;
            }
            let (off, reg) = split_riscv_offset(&second.ops[1])?;
            if reg != base.as_str() {
                return None;
            }
            Some(page.wrapping_add_signed(off))
        }
        _ => None,
    }
}

/// Signed RISC-V immediate as printed (`52`, `-4`, `0x34`): an optional
/// sign, then decimal or `0x`-hex digits. Anything else is `None`.
fn parse_riscv_simm(op: &str) -> Option<i64> {
    let (neg, digits) = match op.strip_prefix('-') {
        Some(rest) => (true, rest),
        None => (false, op.strip_prefix('+').unwrap_or(op)),
    };
    let mag = i64::try_from(parse_digits(digits)?).ok()?;
    Some(if neg { mag.wrapping_neg() } else { mag })
}

/// Signed offset and base register of an `off(base)` memory operand, if
/// it has that shape.
fn split_riscv_offset(slot: &str) -> Option<(i64, &str)> {
    let (off, rest) = slot.split_once('(')?;
    let reg = rest.strip_suffix(')')?;
    if reg.is_empty() || reg.contains(['(', ')']) {
        return None;
    }
    Some((parse_riscv_simm(off)?, reg))
}

/// Decode only the first RISC-V instruction in `bytes` (loaded at `va`).
///
/// Reads the leading halfword to pick the 2- or 4-byte form, then decodes
/// with the same rvdasm decoder and the same [`riscv_insn`] conversion as
/// [`disasm_riscv_partial`]. Returns [`Error::Invalid`] with the same
/// message the range decoder reports when the first instruction is
/// undecodable or truncated.
///
/// # Errors
/// [`Error::Invalid`] when the first instruction does not decode.
fn disasm_first_riscv(bytes: &[u8], va: u64, xlen: u8) -> Result<Option<Insn>> {
    if bytes.is_empty() {
        return Ok(None);
    }
    let label = if xlen == 32 { "riscv32" } else { "riscv64" };
    let wide = bytes[0] & 0x03 == 0x03;
    let need = if wide { 4 } else { 2 };
    let Some(win) = bytes.get(..need) else {
        return Err(Error::Invalid(format!(
            "{label} decode error at {va:#x}: truncated word"
        )));
    };
    let mut word = [0u8; 4];
    word[..need].copy_from_slice(win);
    let decoder = RiscvDecoder::new(if xlen == 32 {
        RiscvXlen::XLEN32
    } else {
        RiscvXlen::XLEN64
    });
    let code = u32::from_le_bytes(word);
    let inst = decoder
        .disassmeble_one(code)
        .ok_or_else(|| Error::Invalid(format!("{label} invalid opcode at {va:#x}")))?;
    let raw = win.to_vec();
    Ok(Some(riscv_insn(va, raw, &inst, xlen)))
}

fn disasm_riscv(bytes: &[u8], va: u64, max_insns: usize, xlen: u8) -> Result<Vec<Insn>> {
    let partial = disasm_riscv_partial(bytes, va, max_insns, xlen)?;
    match partial.error_at {
        Some(e) => Err(Error::Invalid(e.message)),
        None => Ok(partial.insns),
    }
}

/// Prefix decode over RISC-V bytes: length follows the low two bits (2 or
/// 4 bytes with the C extension), so the first bad word ends the prefix
/// with `error_at`. A short tail (< 2 bytes, or a 4-byte form with only 3)
/// fails its word decode the same way.
fn disasm_riscv_partial(
    bytes: &[u8],
    va: u64,
    max_insns: usize,
    xlen: u8,
) -> Result<PartialDisasm> {
    let label = if xlen == 32 { "riscv32" } else { "riscv64" };
    let decoder = RiscvDecoder::new(if xlen == 32 {
        RiscvXlen::XLEN32
    } else {
        RiscvXlen::XLEN64
    });
    let mut out = Vec::new();
    let mut addr = va;
    let mut off = 0usize;
    while off < bytes.len() {
        if out.len() >= max_insns {
            return Err(limit_err(max_insns));
        }
        let wide = bytes[off] & 0x03 == 0x03;
        let need = if wide { 4 } else { 2 };
        let Some(win) = bytes.get(off..off + need) else {
            return Ok(PartialDisasm {
                insns: out,
                error_at: Some(DecodeError {
                    addr,
                    message: format!("{label} decode error at {addr:#x}: truncated word"),
                }),
            });
        };
        let mut word = [0u8; 4];
        word[..need].copy_from_slice(win);
        let code = u32::from_le_bytes(word);
        let Some(inst) = decoder.disassmeble_one(code) else {
            return Ok(PartialDisasm {
                insns: out,
                error_at: Some(DecodeError {
                    addr,
                    message: format!("{label} invalid opcode at {addr:#x}"),
                }),
            });
        };
        out.push(riscv_insn(addr, win.to_vec(), &inst, xlen));
        addr = addr.wrapping_add(need as u64);
        off += need;
    }
    Ok(PartialDisasm {
        insns: out,
        error_at: None,
    })
}

/// Decode flags for MIPS32: ISA level IV with pseudo-instructions
/// disabled.
///
/// Level IV covers the MIPS32r1 user-mode set over plain MIPS I:
/// branch-likely forms, `ll`/`sc`, `movn`/`movz`, `sync`, `pref`, and
/// `cache`. Disabling pseudos prints canonical base names (`beq`, not
/// `beqz`; `bgezal`, not `bal`), like the RISC-V `no-aliases` form, so
/// the lift tables stay small. MIPS32r2 bit operations (`seb`, `wsb`,
/// `ext`, `ins`, `rotr`) have no rabbitizer opcode and stay invalid.
fn mips_flags() -> MipsFlags {
    MipsFlags::new(MipsIsa::MIPS_IV).with_enable_pseudos(false)
}

/// Display flags for MIPS32: single-space opcode separator, `$`-prefixed
/// ABI register names, and branch/jump targets as `. + <offset>` relative
/// expressions (absolute labels would invent synthetic `func_...` names).
fn mips_display_flags() -> MipsDisplayFlags {
    MipsDisplayFlags::new()
        .with_opcode_ljust(0)
        .with_branch_default_label_display(MipsLabelDisplay::Computed)
        .with_jump_default_label_display(MipsLabelDisplay::Computed)
}

/// Convert one decoded MIPS32 instruction to [`Insn`].
///
/// Shared by the range prefix decoder and the first-instruction decoder so
/// both report identical mnemonics, operands, and branch targets.
/// Structured [`Operand`] rows stay empty like the other non-x86 backends.
fn mips_insn(addr: u64, raw: Vec<u8>, inst: &MipsInstruction) -> Insn {
    let flags = mips_display_flags();
    let text = inst.display::<&str>(&flags, None, 0).to_string();
    let (mnem, ops) = split_asm(&text);
    let mem_target = mips_lui_base(&mnem, &ops);
    Insn {
        addr,
        size: 4,
        bytes: raw,
        mnem,
        ops,
        branch_target: mips_branch_target(inst),
        mem_target,
        table_base: None,
        import: None,
        target_name: None,
        comment: None,
        string: None,
        operands: Vec::new(),
        thumb: false,
    }
}

/// Extensions decoded per PowerPC mode: base ISA only (32-bit), plus the
/// 64-bit extension on 64-bit. AltiVec, paired-singles, and VMX128 stay
/// off: their opcodes decode as [`powerpc::Opcode::Illegal`] and end the
/// prefix, never as silent mistranslations. Enabling them is a follow-up.
fn ppc_extensions(is64: bool) -> PpcExtensions {
    if is64 {
        PpcExtensions::from_extension(powerpc::Extension::Ppc64)
    } else {
        PpcExtensions::none()
    }
}

/// Convert one decoded PowerPC instruction to [`Insn`].
///
/// Text is the powerpc crate's `simplified` form (canonical mnemonics with
/// LK/AA/BO folded in, e.g. `bl`, `bne`, `blr`) split by [`split_asm`];
/// structured [`Operand`] rows stay empty like the other non-x86 backends.
fn ppc_insn(addr: u64, raw: Vec<u8>, ins: &PpcIns, is64: bool) -> Insn {
    let (mnem, ops) = split_asm(&ins.simplified().to_string());
    Insn {
        addr,
        size: 4,
        bytes: raw,
        mnem,
        ops,
        branch_target: ppc_branch_target(ins, addr, is64),
        mem_target: None,
        table_base: None,
        import: None,
        target_name: None,
        comment: None,
        string: None,
        operands: Vec::new(),
        thumb: false,
    }
}

/// Absolute target for a direct PowerPC branch (`b`/`bc` family), else
/// `None`. Register-indirect forms (`blr`, `bctr` and friends) carry no
/// target. 32-bit targets wrap at 32 bits, matching the hardware NIA;
/// 64-bit targets sign-extend like the 64-bit NIA.
fn ppc_branch_target(ins: &PpcIns, addr: u64, is64: bool) -> Option<u64> {
    let off = ins.branch_offset()?;
    if ins.field_aa() {
        return Some(if is64 {
            (i64::from(off)) as u64
        } else {
            u64::from(off as u32)
        });
    }
    Some(if is64 {
        addr.wrapping_add_signed(i64::from(off))
    } else {
        u64::from((addr as u32).wrapping_add_signed(off))
    })
}

/// Decode a raw PowerPC word: `None` for undecodable opcodes.
fn ppc_decode_word(code: u32, is64: bool) -> Option<PpcIns> {
    use powerpc::Opcode as PpcOpcode;
    let ins = PpcIns::new(code, ppc_extensions(is64));
    (ins.op != PpcOpcode::Illegal).then_some(ins)
}

/// Decode only the first PowerPC instruction in `bytes` (loaded at `va`).
///
/// Reads one big-endian word and converts with the same [`ppc_insn`]
/// mapping as [`disasm_ppc_partial`]. Returns [`Error::Invalid`] with the
/// same message the range decoder reports when the first word is
/// undecodable or truncated.
///
/// # Errors
/// [`Error::Invalid`] when the first instruction does not decode.
fn disasm_first_ppc(bytes: &[u8], va: u64, is64: bool) -> Result<Option<Insn>> {
    if bytes.is_empty() {
        return Ok(None);
    }
    let label = if is64 { "ppc64" } else { "ppc32" };
    let Some(win) = bytes.get(..4) else {
        return Err(Error::Invalid(format!(
            "{label} decode error at {va:#x}: truncated word"
        )));
    };
    let code = u32::from_be_bytes(win.try_into().expect("word converts"));
    let Some(ins) = ppc_decode_word(code, is64) else {
        return Err(Error::Invalid(format!("{label} invalid opcode at {va:#x}")));
    };
    Ok(Some(ppc_insn(va, win.to_vec(), &ins, is64)))
}

fn disasm_ppc(bytes: &[u8], va: u64, max_insns: usize, is64: bool) -> Result<Vec<Insn>> {
    let partial = disasm_ppc_partial(bytes, va, max_insns, is64)?;
    match partial.error_at {
        Some(e) => Err(Error::Invalid(e.message)),
        None => Ok(partial.insns),
    }
}

/// Absolute target for a direct MIPS32 jump or branch, else `None`.
///
/// `j`/`jal` carry their target in the instr-index field (upper bits from
/// the delay-slot address, per hardware semantics); conditional branches
/// and link-branches (`bgezal`) resolve through the generic branch
/// offset. Indirect jumps (`jr`/`jalr`) and non-control instructions
/// report `None`.
fn mips_branch_target(inst: &MipsInstruction) -> Option<u64> {
    inst.get_instr_index_as_vram()
        .or_else(|| inst.get_branch_vram_generic())
        .map(|vram| u64::from(vram.inner()))
}

/// Base address materialized by a MIPS32 `lui`, if any.
///
/// `lui $dst, 0x1234` writes `0x12340000`: the high halfword of an
/// absolute address, like the RISC-V `auipc` page base (see
/// [`Insn::mem_target`]). The low half rides in the following
/// instruction (see [`resolve_mips_pair`]). Anything else (wrong
/// mnemonic, wrong operand count, unparseable or wide immediates)
/// reports `None`.
fn mips_lui_base(mnem: &str, ops: &[String]) -> Option<u64> {
    if mnem != "lui" || ops.len() != 2 {
        return None;
    }
    let hi = parse_bare_imm(&ops[1])?;
    if hi > 0xffff {
        return None;
    }
    Some(u64::from((hi as u32) << 16))
}

/// MIPS32 mnemonics with an `off($base)` memory operand: the integer and
/// coprocessor load/store families (mirrors the `MIPS_LOAD`/`MIPS_STORE`
/// lift tables in [`crate::ir`]).
const MIPS_PAIR_MEM: &[&str] = &[
    "lb", "lh", "lw", "lbu", "lhu", "lwl", "lwr", "ll", "lwc1", "ldc1", "ld", "lld", "ldl", "ldr",
    "lwu", "sb", "sh", "sw", "swl", "swr", "sc", "swc1", "sdc1", "sd", "scd", "sdl", "sdr",
];

/// Signed MIPS32 16-bit immediate as printed (`0x10`, `-0x10`):
/// rabbitizer prints hex with an optional `-` sign for sign-extended
/// fields. Anything else (unparseable, wider than 16 bits) is `None`.
fn parse_mips_simm(op: &str) -> Option<i32> {
    let (neg, digits) = match op.strip_prefix('-') {
        Some(rest) => (true, rest),
        None => (false, op),
    };
    let mag = parse_bare_imm(digits)?;
    if mag > 0xffff {
        return None;
    }
    let v = mag as i32;
    Some(if neg { -v } else { v })
}

/// Split a MIPS32 `off($base)` memory operand into its signed offset and
/// base register: `0x10($t0)` splits to `(0x10, "$t0")`. A bare `($base)`
/// reads as a zero offset. Anything else is `None`.
fn parse_mips_mem(op: &str) -> Option<(i32, &str)> {
    let (off, rest) = op.split_once('(')?;
    let reg = rest.strip_suffix(')')?;
    if reg.is_empty() || reg.contains(['(', ')']) {
        return None;
    }
    let off = if off.is_empty() {
        0
    } else {
        parse_mips_simm(off)?
    };
    Some((off, reg))
}

/// Final address of a MIPS32 `lui` pair, if any.
///
/// `lui` materializes only the high halfword (see [`mips_lui_base`]);
/// the low half rides in the next instruction, so the referenced address
/// spans two instructions — the MIPS32 equivalent of
/// [`resolve_adrp_pair`]. Returns the `lui` base combined with the second
/// instruction's low part when `first` is a `lui` and `second` consumes
/// the same register:
///
/// - `addiu`/`addi` (plus `daddiu`/`daddi`): `addiu $dst, $base, $simm`
///   with exactly three operands; the immediate is signed, added with
///   32-bit wraparound like the hardware ALU;
/// - `addu`/`add` (plus `daddu`/`dadd`): the `move` idiom
///   `addu $dst, $base, $zero` (either operand order), copying the base;
/// - loads and stores (`lw`, `sw`, and the rest of [`MIPS_PAIR_MEM`]):
///   `lw $dst, off($base)` with a signed offset.
///
/// Anything else (wrong mnemonics, register mismatch, unparseable
/// immediates, wide `lui` halves) returns `None`; the function never
/// guesses. Pairing (adjacency, same block) is the caller's job.
pub(crate) fn resolve_mips_pair(first: &Insn, second: &Insn) -> Option<u64> {
    if first.mnem != "lui" || first.ops.len() != 2 {
        return None;
    }
    let base_reg = first.ops.first()?;
    let hi = parse_bare_imm(&first.ops[1])?;
    if hi > 0xffff {
        return None;
    }
    let base = (hi as u32) << 16;
    match second.mnem.as_str() {
        "addiu" | "addi" | "daddiu" | "daddi" => {
            if second.ops.len() != 3 || second.ops[1] != *base_reg {
                return None;
            }
            let lo = parse_mips_simm(&second.ops[2])?;
            Some(u64::from(base.wrapping_add_signed(lo)))
        }
        "addu" | "add" | "daddu" | "dadd" => {
            if second.ops.len() != 3 {
                return None;
            }
            let (src, other) = (&second.ops[1], &second.ops[2]);
            if (src == base_reg && other == "$zero") || (src == "$zero" && other == base_reg) {
                Some(u64::from(base))
            } else {
                None
            }
        }
        s if MIPS_PAIR_MEM.contains(&s) => {
            if second.ops.len() != 2 {
                return None;
            }
            let (off, reg) = parse_mips_mem(&second.ops[1])?;
            if reg != base_reg.as_str() {
                return None;
            }
            Some(u64::from(base.wrapping_add_signed(off)))
        }
        _ => None,
    }
}

/// Decode only the first MIPS32 instruction in `bytes` (loaded at `va`).
///
/// Decodes the leading 4-byte little-endian word with the same flags and
/// the same [`mips_insn`] conversion as [`disasm_mips_partial`]; trailing
/// bytes cannot change the first word decode. Returns [`Error::Invalid`]
/// with the same message the range decoder reports when the first word is
/// undecodable or truncated.
///
/// # Errors
/// [`Error::Invalid`] when the first word does not decode.
fn disasm_first_mips(bytes: &[u8], va: u64) -> Result<Option<Insn>> {
    if bytes.is_empty() {
        return Ok(None);
    }
    let Some(win) = bytes.get(..4) else {
        return Err(Error::Invalid(format!(
            "mips32 decode error at {va:#x}: truncated word"
        )));
    };
    let word = u32::from_le_bytes(win.try_into().expect("four bytes convert"));
    // MIPS32 addresses are 32-bit: the truncation matches hardware PC
    // semantics (RISC-V 32-bit wraps the same way).
    let vram = MipsVram::new(va as u32);
    let Some(inst) = MipsInstruction::new_checked(word, vram, mips_flags()) else {
        return Err(Error::Invalid(format!("mips32 invalid opcode at {va:#x}")));
    };
    Ok(Some(mips_insn(va, win.to_vec(), &inst)))
}

fn disasm_mips(bytes: &[u8], va: u64, max_insns: usize) -> Result<Vec<Insn>> {
    let partial = disasm_mips_partial(bytes, va, max_insns)?;
    match partial.error_at {
        Some(e) => Err(Error::Invalid(e.message)),
        None => Ok(partial.insns),
    }
}

/// Prefix decode over MIPS32 bytes: fixed 4-byte little-endian words
/// decode independently, so the first bad word ends the prefix with
/// `error_at`. A short tail (< 4 bytes) fails its word decode the same
/// way.
fn disasm_mips_partial(bytes: &[u8], va: u64, max_insns: usize) -> Result<PartialDisasm> {
    let flags = mips_flags();
    let mut out = Vec::new();
    let mut addr = va;
    let mut off = 0usize;
    while off < bytes.len() {
        if out.len() >= max_insns {
            return Err(limit_err(max_insns));
        }
        let Some(win) = bytes.get(off..off + 4) else {
            return Ok(PartialDisasm {
                insns: out,
                error_at: Some(DecodeError {
                    addr,
                    message: format!("mips32 decode error at {addr:#x}: truncated word"),
                }),
            });
        };
        let word = u32::from_le_bytes(win.try_into().expect("four bytes convert"));
        // See `disasm_first_mips`: 32-bit truncation matches hardware PC.
        let Some(inst) = MipsInstruction::new_checked(word, MipsVram::new(addr as u32), flags)
        else {
            return Ok(PartialDisasm {
                insns: out,
                error_at: Some(DecodeError {
                    addr,
                    message: format!("mips32 invalid opcode at {addr:#x}"),
                }),
            });
        };
        out.push(mips_insn(addr, win.to_vec(), &inst));
        addr = addr.wrapping_add(4);
        off += 4;
    }
    Ok(PartialDisasm {
        insns: out,
        error_at: None,
    })
}

/// Prefix decode over PowerPC bytes: fixed 4-byte big-endian words, so the
/// first [`powerpc::Opcode::Illegal`] word ends the prefix with `error_at`.
/// A short tail (< 4 bytes) fails its word decode the same way.
fn disasm_ppc_partial(
    bytes: &[u8],
    va: u64,
    max_insns: usize,
    is64: bool,
) -> Result<PartialDisasm> {
    let label = if is64 { "ppc64" } else { "ppc32" };
    let mut out = Vec::new();
    let mut addr = va;
    let mut off = 0usize;
    while off < bytes.len() {
        if out.len() >= max_insns {
            return Err(limit_err(max_insns));
        }
        let Some(win) = bytes.get(off..off + 4) else {
            return Ok(PartialDisasm {
                insns: out,
                error_at: Some(DecodeError {
                    addr,
                    message: format!("{label} decode error at {addr:#x}: truncated word"),
                }),
            });
        };
        let code = u32::from_be_bytes(win.try_into().expect("word converts"));
        let Some(ins) = ppc_decode_word(code, is64) else {
            return Ok(PartialDisasm {
                insns: out,
                error_at: Some(DecodeError {
                    addr,
                    message: format!("{label} invalid opcode at {addr:#x}"),
                }),
            });
        };
        out.push(ppc_insn(addr, win.to_vec(), &ins, is64));
        addr = addr.wrapping_add(4);
        off += 4;
    }
    Ok(PartialDisasm {
        insns: out,
        error_at: None,
    })
}

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

    #[test]
    fn string_preview_passes_plain_text_through() {
        assert_eq!(string_preview("Hello"), "Hello");
        assert_eq!(string_preview(""), "");
    }

    #[test]
    fn string_preview_escapes_quote_backslash_and_controls() {
        assert_eq!(string_preview("a\"b\\c"), "a\\\"b\\\\c");
        assert_eq!(string_preview("a\nb\rc\td"), "a\\nb\\rc\\td");
        assert_eq!(string_preview("a\x07b"), "a\\u{7}b");
    }

    #[test]
    fn string_preview_clips_to_64_escaped_chars() {
        let long = "x".repeat(100);
        let preview = string_preview(&long);
        assert_eq!(preview.chars().count(), STRING_PREVIEW_MAX_CHARS);
        assert_eq!(preview, "x".repeat(64));
        // A leading quote costs two escaped characters of budget.
        let preview = string_preview(&format!("\"{long}"));
        assert_eq!(preview.chars().count(), STRING_PREVIEW_MAX_CHARS);
        assert!(preview.starts_with("\\\""));
    }

    #[test]
    fn x86_32_push_imm32_reports_mem_target() {
        // push 0x402100 at 0x401003.
        let v = disasm_x86(&[0x68, 0x00, 0x21, 0x40, 0x00], 0x401003, 8, 32).expect("push decodes");
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].mem_target, Some(0x402100));
        assert_eq!(v[0].branch_target, None);
    }

    #[test]
    fn x86_32_mov_abs_mem_reports_mem_target() {
        // mov eax, [0x403000] at 0x401000.
        let v = disasm_x86(&[0xA1, 0x00, 0x30, 0x40, 0x00], 0x401000, 8, 32)
            .expect("moffs load decodes");
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].mem_target, Some(0x403000));
    }

    #[test]
    fn x86_64_push_imm32_reports_mem_target() {
        // Same bytes in 64-bit non-PIE mode: an absolute address.
        // Unmapped small constants are filtered downstream by the
        // analysis mapped check, not here.
        let v = disasm_x86(&[0x68, 0x00, 0x21, 0x40, 0x00], 0x401003, 8, 64).expect("push decodes");
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].mem_target, Some(0x402100));
    }

    #[test]
    fn x86_64_mov_edi_imm32_reports_mem_target() {
        // mov edi, 0x402000 at 0x400000: the non-PIE string-arg shape.
        let v = disasm_x86(&[0xBF, 0x00, 0x20, 0x40, 0x00], 0x400000, 8, 64)
            .expect("mov imm32 decodes");
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].mnem, "mov");
        assert_eq!(v[0].mem_target, Some(0x402000));
        assert_eq!(v[0].branch_target, None);
    }

    #[test]
    fn x86_64_mov_abs_mem_reports_mem_target() {
        // mov edi, [0x402000] at 0x400000: SIB disp32 absolute load.
        let v = disasm_x86(&[0x8B, 0x3C, 0x25, 0x00, 0x20, 0x40, 0x00], 0x400000, 8, 64)
            .expect("abs load decodes");
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].mem_target, Some(0x402000));
    }

    #[test]
    fn x86_64_lea_disp32_reports_mem_target() {
        // lea edi, [0x402000] at 0x400000: SIB disp32 absolute address.
        let v = disasm_x86(&[0x8D, 0x3C, 0x25, 0x00, 0x20, 0x40, 0x00], 0x400000, 8, 64)
            .expect("lea decodes");
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].mnem, "lea");
        assert_eq!(v[0].mem_target, Some(0x402000));
    }

    #[test]
    fn arm32_mov_bx_snapshot() {
        // mov r0, r1 ; bx lr at 0x10000.
        let v = disasm_arm32(
            &[0x01, 0x00, 0xA0, 0xE1, 0x1E, 0xFF, 0x2F, 0xE1],
            0x10000,
            8,
        )
        .expect("arm32 must decode");
        assert_eq!(v.len(), 2);
        assert_eq!(
            v.iter().map(|i| (i.addr, i.size)).collect::<Vec<_>>(),
            [(0x10000, 4), (0x10004, 4)]
        );
        assert_eq!(
            v.iter().map(|i| i.mnem.as_str()).collect::<Vec<_>>(),
            ["mov", "bx"]
        );
        assert_eq!(v[0].ops, ["r0", "r1"]);
        assert_eq!(v[0].bytes, [0x01, 0x00, 0xA0, 0xE1]);
        assert!(v.iter().all(|i| i.branch_target.is_none()));
    }

    #[test]
    fn arm32_b_targets_self() {
        // b . at 0x10000: word offset 0 already folds the PC+8 bias in.
        let v = disasm_arm32(&[0xFE, 0xFF, 0xFF, 0xEA], 0x10000, 8).expect("b decodes");
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].mnem, "b");
        assert_eq!(v[0].branch_target, Some(0x10000));
    }

    #[test]
    fn arm32_bl_folds_pc_bias() {
        // bl with zero field at 0x10000 targets addr+8.
        let v = disasm_arm32(&[0x00, 0x00, 0x00, 0xEB], 0x10000, 8).expect("bl decodes");
        assert_eq!(v[0].mnem, "bl");
        assert_eq!(v[0].branch_target, Some(0x10008));
    }

    #[test]
    fn arm32_literal_ldr_reports_mem_target() {
        // ldr r0, [pc, #4] at 0x10000 reads PC (addr+8) + 4.
        let v = disasm_arm32(&[0x04, 0x00, 0x9F, 0xE5], 0x10000, 8).expect("ldr decodes");
        assert_eq!(v[0].mem_target, Some(0x1000c));
        assert_eq!(v[0].branch_target, None);
        // Sub form subtracts.
        let v = disasm_arm32(&[0x04, 0x00, 0x1F, 0xE5], 0x10000, 8).expect("ldr decodes");
        assert_eq!(v[0].mem_target, Some(0x10004));
    }

    #[test]
    fn thumb_mixed_width_snapshot() {
        // nop (2B) ; bl #0 (4B) ; bx lr (2B) at 0x20000.
        let bytes = [0x00, 0xBF, 0x00, 0xF0, 0x00, 0xF8, 0x70, 0x47];
        let v = disasm_thumb(&bytes, 0x20000, 8).expect("thumb must decode");
        assert_eq!(
            v.iter().map(|i| (i.addr, i.size)).collect::<Vec<_>>(),
            [(0x20000, 2), (0x20002, 4), (0x20006, 2)]
        );
        assert_eq!(v[0].mnem, "nop");
        assert_eq!(v[2].mnem, "bx");
        assert_eq!(v[2].ops, ["lr"]);
        assert_eq!(v[1].branch_target, Some(0x20006));
        assert_eq!(v[1].bytes, [0x00, 0xF0, 0x00, 0xF8]);
    }

    #[test]
    fn thumb_b_targets_pc_relative() {
        // b . (0xE7FE) at 0x20000: halfword offset -2 from PC (addr+4).
        let v = disasm_thumb(&[0xFE, 0xE7], 0x20000, 8).expect("b decodes");
        assert_eq!(v[0].mnem, "b");
        assert_eq!(v[0].branch_target, Some(0x20000));
    }

    #[test]
    fn thumb_literal_ldr_aligns_pc() {
        // ldr r0, [pc, #16] at 0x20001: base is addr+4 rounded down to 4.
        let v = disasm_thumb(&[0x04, 0x48], 0x20001, 8).expect("ldr decodes");
        assert_eq!(v[0].mem_target, Some(((0x20001 + 4) & !3) + 16));
    }

    #[test]
    fn x86_32_scaled_index_reports_typed_table_base() {
        // jmp [eax*4+0x401012]: typed base, never a mem_target, never text.
        let v = disasm_x86(&[0xFF, 0x24, 0x85, 0x12, 0x10, 0x40, 0x00], 0x401005, 8, 32)
            .expect("indexed jmp decodes");
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].mnem, "jmp");
        assert_eq!(v[0].table_base, Some(0x401012));
        assert_eq!(v[0].mem_target, None);
        assert_eq!(v[0].branch_target, None);
    }

    #[test]
    fn x86_64_scaled_index_reports_typed_table_base() {
        // jmp [rax*8+0x400012]: the 64-bit switch shape.
        let v = disasm_x86(
            &[0x48, 0xFF, 0x24, 0xC5, 0x12, 0x00, 0x40, 0x00],
            0x400005,
            8,
            64,
        )
        .expect("indexed jmp decodes");
        assert_eq!(v[0].table_base, Some(0x400012));
        assert_eq!(v[0].mem_target, None);
        assert_eq!(v[0].branch_target, None);
    }

    #[test]
    fn x86_index_wrong_scale_reports_no_table_base() {
        // jmp [eax*2+0x401012] (scale 2, slot width 4): strided tables
        // are unsupported, so no typed base is reported.
        let v = disasm_x86(&[0xFF, 0x24, 0x45, 0x12, 0x10, 0x40, 0x00], 0x401005, 8, 32)
            .expect("strided jmp decodes");
        assert_eq!(v[0].table_base, None);
        assert_eq!(v[0].mem_target, None);
        assert_eq!(v[0].branch_target, None);
    }

    #[test]
    fn x86_plain_slot_reports_no_table_base() {
        // jmp [0x401006]: the single-slot shape keeps mem_target only.
        let v = disasm_x86(&[0xFF, 0x25, 0x06, 0x10, 0x40, 0x00], 0x401000, 8, 32)
            .expect("absolute jmp decodes");
        assert_eq!(v[0].mem_target, Some(0x401006));
        assert_eq!(v[0].table_base, None);
        // RIP-relative slots stay on the mem_target path too.
        let v = disasm_x86(&[0xFF, 0x25, 0x04, 0x00, 0x00, 0x00], 0x400000, 8, 64)
            .expect("rip-relative jmp decodes");
        assert_eq!(v[0].mem_target, Some(0x40000a));
        assert_eq!(v[0].table_base, None);
    }

    fn adrp_pair(bytes: &[u8], va: u64) -> Vec<Insn> {
        disasm_aarch64(bytes, va, 8).expect("adrp pair must decode")
    }

    fn movw_pair(bytes: &[u8], va: u64) -> Vec<Insn> {
        disasm_arm32(bytes, va, 8).expect("movw pair must decode")
    }

    fn auipc_pair(bytes: &[u8], va: u64) -> Vec<Insn> {
        disasm_riscv(bytes, va, 8, 64).expect("auipc pair must decode")
    }

    #[test]
    fn movw_movt_pair_resolves_final_address() {
        // movw r0, #0x9000; movt r0, #0x0 -> 0x9000.
        let v = movw_pair(&[0x00, 0x00, 0x09, 0xE3, 0x00, 0x00, 0x40, 0xE3], 0x8000);
        assert_eq!(v.len(), 2);
        assert_eq!(v[0].mnem, "mov");
        assert_eq!(v[0].ops, ["r0", "0x9000"]);
        assert_eq!(v[1].mnem, "movt");
        assert_eq!(v[1].ops, ["r0", "0x0"]);
        assert_eq!(resolve_movw_pair(&v[0], &v[1]), Some(0x9000));
        // Nonzero halves: movw r2, #0x1234; movt r2, #0x5678 -> 0x56781234.
        let v = movw_pair(&[0x34, 0x22, 0x01, 0xE3, 0x78, 0x26, 0x45, 0xE3], 0x8000);
        assert_eq!(resolve_movw_pair(&v[0], &v[1]), Some(0x5678_1234));
    }

    #[test]
    fn movw_pair_rejects_non_pairs() {
        // Register mismatch: movt writes r1.
        let v = movw_pair(&[0x00, 0x00, 0x09, 0xE3, 0x00, 0x10, 0x40, 0xE3], 0x8000);
        assert_eq!(resolve_movw_pair(&v[0], &v[1]), None);
        // Wrong second mnemonic: mov r0, #0x9000 twice.
        let v = movw_pair(&[0x00, 0x00, 0x09, 0xE3, 0x00, 0x00, 0x09, 0xE3], 0x8000);
        assert_eq!(resolve_movw_pair(&v[0], &v[1]), None);
        // Register source is not a constant: mov r0, r1.
        let v = movw_pair(&[0x01, 0x00, 0xA0, 0xE1, 0x00, 0x00, 0x40, 0xE3], 0x8000);
        assert_eq!(resolve_movw_pair(&v[0], &v[1]), None);
        // First instruction is not mov: movt; movt.
        let v = movw_pair(&[0x00, 0x00, 0x40, 0xE3, 0x00, 0x00, 0x40, 0xE3], 0x8000);
        assert_eq!(resolve_movw_pair(&v[0], &v[1]), None);
        // Unparseable immediates never resolve, never panic.
        let v = movw_pair(&[0x00, 0x00, 0x09, 0xE3, 0x00, 0x00, 0x40, 0xE3], 0x8000);
        let mut bad = v[0].clone();
        bad.ops[1] = "r1".to_string();
        assert_eq!(resolve_movw_pair(&bad, &v[1]), None);
        bad.ops[1] = "0x1_0000".to_string();
        assert_eq!(resolve_movw_pair(&bad, &v[1]), None);
        let mut wide = v[1].clone();
        wide.ops[1] = "0x10000".to_string();
        assert_eq!(resolve_movw_pair(&v[0], &wide), None);
    }

    #[test]
    fn adrp_add_pair_resolves_final_address() {
        // adrp x0, #0 at 0x4000 (page 0x4000); add x0, x0, #0x10.
        let v = adrp_pair(&[0x00, 0x00, 0x00, 0x90, 0x00, 0x40, 0x00, 0x91], 0x4000);
        assert_eq!(v.len(), 2);
        assert_eq!(v[0].mem_target, Some(0x4000));
        assert_eq!(resolve_adrp_pair(&v[0], &v[1]), Some(0x4010));
        // Nonzero page: adrp x2, +0x1000 (page 0x5000); add x2, x2, #0x123.
        let v = adrp_pair(&[0x02, 0x00, 0x00, 0xB0, 0x42, 0x8c, 0x04, 0x91], 0x4000);
        assert_eq!(v[0].mem_target, Some(0x5000));
        assert_eq!(resolve_adrp_pair(&v[0], &v[1]), Some(0x5123));
        // Cross-destination add still resolves: add x1, x0, #0x10.
        let v = adrp_pair(&[0x00, 0x00, 0x00, 0x90, 0x01, 0x40, 0x00, 0x91], 0x4000);
        assert_eq!(resolve_adrp_pair(&v[0], &v[1]), Some(0x4010));
    }

    #[test]
    fn adrp_ldr_pair_resolves_final_address() {
        // adrp x0, #0 at 0x4000; ldr x0, [x0, #0x8].
        let v = adrp_pair(&[0x00, 0x00, 0x00, 0x90, 0x00, 0x04, 0x40, 0xF9], 0x4000);
        assert_eq!(v.len(), 2);
        assert_eq!(resolve_adrp_pair(&v[0], &v[1]), Some(0x4008));
        // Zero-offset form (ldr x0, [x0]) resolves to the page itself.
        let v = adrp_pair(&[0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x40, 0xF9], 0x4000);
        assert_eq!(v[1].ops, ["x0", "[x0]"]);
        assert_eq!(resolve_adrp_pair(&v[0], &v[1]), Some(0x4000));
        // Narrow-destination load resolves too: ldr x1, [x0, #0x10].
        let v = adrp_pair(&[0x00, 0x00, 0x00, 0x90, 0x01, 0x08, 0x40, 0xF9], 0x4000);
        assert_eq!(resolve_adrp_pair(&v[0], &v[1]), Some(0x4010));
    }

    #[test]
    fn adrp_pair_rejects_non_pairs() {
        // Register mismatch: adrp x0 but add x0, x1, #0x10.
        let v = adrp_pair(&[0x00, 0x00, 0x00, 0x90, 0x20, 0x40, 0x00, 0x91], 0x4000);
        assert_eq!(resolve_adrp_pair(&v[0], &v[1]), None);
        // Wrong second mnemonic: sub x0, x0, #0x10.
        let v = adrp_pair(&[0x00, 0x00, 0x00, 0x90, 0x00, 0x40, 0x00, 0xD1], 0x4000);
        assert_eq!(v[1].mnem, "sub");
        assert_eq!(resolve_adrp_pair(&v[0], &v[1]), None);
        // Shifted add (lsl #12) changes the offset encoding: rejected.
        let v = adrp_pair(&[0x00, 0x00, 0x00, 0x90, 0x00, 0x04, 0x40, 0x91], 0x4000);
        assert_eq!(v[1].ops.len(), 4);
        assert_eq!(resolve_adrp_pair(&v[0], &v[1]), None);
        // First instruction is not adrp.
        let v = adrp_pair(&[0x00, 0x40, 0x00, 0x91, 0x00, 0x40, 0x00, 0x91], 0x4000);
        assert_eq!(resolve_adrp_pair(&v[0], &v[1]), None);
        // Missing page base never resolves.
        let v = adrp_pair(&[0x00, 0x00, 0x00, 0x90, 0x00, 0x40, 0x00, 0x91], 0x4000);
        let mut no_page = v[0].clone();
        no_page.mem_target = None;
        assert_eq!(resolve_adrp_pair(&no_page, &v[1]), None);
        // Unparseable immediates never resolve, never panic.
        let mut bad_imm = v[1].clone();
        bad_imm.ops[2] = "#zz".to_string();
        assert_eq!(resolve_adrp_pair(&v[0], &bad_imm), None);
        bad_imm.ops[2] = "x1".to_string();
        assert_eq!(resolve_adrp_pair(&v[0], &bad_imm), None);
        let mut bad_ldr = v[1].clone();
        bad_ldr.mnem = "ldr".to_string();
        bad_ldr.ops = vec!["x0".to_string(), "[x1".to_string(), "#0x8]".to_string()];
        assert_eq!(resolve_adrp_pair(&v[0], &bad_ldr), None);
    }

    #[test]
    fn auipc_addi_pair_resolves_final_address() {
        // auipc a0, 2 at 0x10000 (page 0x12000); addi a0, a0, 52.
        let v = auipc_pair(&[0x17, 0x25, 0x00, 0x00, 0x13, 0x05, 0x45, 0x03], 0x10000);
        assert_eq!(v.len(), 2);
        assert_eq!(v[0].mem_target, Some(0x12000));
        assert_eq!(resolve_auipc_pair(&v[0], &v[1]), Some(0x12034));
        // addiw decodes the same shape and resolves identically.
        let v = auipc_pair(&[0x17, 0x25, 0x00, 0x00, 0x9B, 0x05, 0x45, 0x03], 0x10000);
        assert_eq!(v[1].ops, ["a1", "a0", "52"]);
        assert_eq!(v[1].mnem, "addiw");
        assert_eq!(resolve_auipc_pair(&v[0], &v[1]), Some(0x12034));
        // Negative offsets sign-extend: addi a0, a0, -1 off the page.
        let v = auipc_pair(&[0x17, 0x25, 0x00, 0x00, 0x13, 0x05, 0xF5, 0xFF], 0x10000);
        assert_eq!(resolve_auipc_pair(&v[0], &v[1]), Some(0x11FFF));
        // Cross-destination addi still resolves: only the base must match.
        let v = auipc_pair(&[0x17, 0x25, 0x00, 0x00, 0x93, 0x05, 0x45, 0x03], 0x10000);
        assert_eq!(v[1].ops, ["a1", "a0", "52"]);
        assert_eq!(resolve_auipc_pair(&v[0], &v[1]), Some(0x12034));
    }

    #[test]
    fn auipc_load_store_pair_resolves_final_address() {
        // auipc a0, 2 at 0x10000 (page 0x12000); lw a0, 52(a0).
        let v = auipc_pair(&[0x17, 0x25, 0x00, 0x00, 0x03, 0x25, 0x45, 0x03], 0x10000);
        assert_eq!(v.len(), 2);
        assert_eq!(resolve_auipc_pair(&v[0], &v[1]), Some(0x12034));
        // ld resolves the same slot shape.
        let v = auipc_pair(&[0x17, 0x25, 0x00, 0x00, 0x03, 0x35, 0x45, 0x03], 0x10000);
        assert_eq!(v[1].mnem, "ld");
        assert_eq!(resolve_auipc_pair(&v[0], &v[1]), Some(0x12034));
        // sw references the stored-to global the same way.
        let v = auipc_pair(&[0x17, 0x26, 0x00, 0x00, 0x23, 0x22, 0xA6, 0x02], 0x10010);
        assert_eq!(v[0].mem_target, Some(0x12010));
        assert_eq!(v[1].mnem, "sw");
        assert_eq!(resolve_auipc_pair(&v[0], &v[1]), Some(0x12034));
        // Negative load offsets sign-extend: lw a0, -4(a0) off the page.
        let v = auipc_pair(&[0x17, 0x25, 0x00, 0x00, 0x03, 0x25, 0xC5, 0xFF], 0x10000);
        assert_eq!(resolve_auipc_pair(&v[0], &v[1]), Some(0x11FFC));
    }

    #[test]
    fn auipc_pair_rejects_non_pairs() {
        // Base mismatch: auipc a0 but addi a1, a1, 52.
        let v = auipc_pair(&[0x17, 0x25, 0x00, 0x00, 0x93, 0x85, 0x45, 0x03], 0x10000);
        assert_eq!(resolve_auipc_pair(&v[0], &v[1]), None);
        // Wrong second mnemonic: register-register add never resolves.
        let v = auipc_pair(&[0x17, 0x25, 0x00, 0x00, 0x33, 0x05, 0xB5, 0x00], 0x10000);
        assert_eq!(v[1].mnem, "add");
        assert_eq!(resolve_auipc_pair(&v[0], &v[1]), None);
        // Load base mismatch: lw a0, 52(a1).
        let v = auipc_pair(&[0x17, 0x25, 0x00, 0x00, 0x03, 0xA5, 0x45, 0x03], 0x10000);
        assert_eq!(resolve_auipc_pair(&v[0], &v[1]), None);
        // First instruction is not auipc.
        let v = auipc_pair(&[0x13, 0x05, 0x45, 0x03, 0x13, 0x05, 0x45, 0x03], 0x10000);
        assert_eq!(resolve_auipc_pair(&v[0], &v[1]), None);
        // Missing page base never resolves.
        let v = auipc_pair(&[0x17, 0x25, 0x00, 0x00, 0x13, 0x05, 0x45, 0x03], 0x10000);
        let mut no_page = v[0].clone();
        no_page.mem_target = None;
        assert_eq!(resolve_auipc_pair(&no_page, &v[1]), None);
        // Unparseable offsets never resolve, never panic.
        let mut bad_imm = v[1].clone();
        bad_imm.ops[2] = "zz".to_string();
        assert_eq!(resolve_auipc_pair(&v[0], &bad_imm), None);
        let mut bad_slot =
            auipc_pair(&[0x17, 0x25, 0x00, 0x00, 0x03, 0x25, 0x45, 0x03], 0x10000)[1].clone();
        bad_slot.ops[1] = "52a0)".to_string();
        assert_eq!(resolve_auipc_pair(&v[0], &bad_slot), None);
        bad_slot.ops[1] = "52()".to_string();
        assert_eq!(resolve_auipc_pair(&v[0], &bad_slot), None);
    }

    fn mips_pair(bytes: &[u8], va: u64) -> Vec<Insn> {
        disasm_mips(bytes, va, 8).expect("mips pair must decode")
    }

    #[test]
    fn mips_lui_reports_high_halfword_base() {
        // lui $t0, 0x1234 writes 0x12340000; the low half rides in the
        // next row, so the row itself carries only the base.
        let v = mips_pair(&[0x34, 0x12, 0x08, 0x3C], 0x10000);
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].mnem, "lui");
        assert_eq!(v[0].ops, ["$t0", "0x1234"]);
        assert_eq!(v[0].mem_target, Some(0x1234_0000));
        // A non-lui row carries no base.
        let v = mips_pair(&[0x10, 0x00, 0x08, 0x25], 0x10000);
        assert_eq!(v[0].mnem, "addiu");
        assert_eq!(v[0].mem_target, None);
    }

    #[test]
    fn mips_lui_addiu_pair_resolves_final_address() {
        // lui $t0, 0x4; addiu $t0, $t0, 0x10 -> 0x40010.
        let v = mips_pair(&[0x04, 0x00, 0x08, 0x3C, 0x10, 0x00, 0x08, 0x25], 0x40000);
        assert_eq!(v.len(), 2);
        assert_eq!(v[0].mem_target, Some(0x40000));
        assert_eq!(resolve_mips_pair(&v[0], &v[1]), Some(0x40010));
        // A negative low part wraps at 32 bits: -0x10 off 0x40000.
        let v = mips_pair(&[0x04, 0x00, 0x08, 0x3C, 0xF0, 0xFF, 0x08, 0x25], 0x40000);
        assert_eq!(v[1].ops, ["$t0", "$t0", "-0x10"]);
        assert_eq!(resolve_mips_pair(&v[0], &v[1]), Some(0x3FFF0));
        // Cross-destination addiu still resolves: addiu $t1, $t0, 0x10.
        let v = mips_pair(&[0x04, 0x00, 0x08, 0x3C, 0x10, 0x00, 0x09, 0x25], 0x40000);
        assert_eq!(resolve_mips_pair(&v[0], &v[1]), Some(0x40010));
    }

    #[test]
    fn mips_lui_addu_move_pair_resolves_base() {
        // lui $t0, 0x4; addu $t1, $t0, $zero copies the base.
        let v = mips_pair(&[0x04, 0x00, 0x08, 0x3C, 0x21, 0x48, 0x00, 0x01], 0x40000);
        assert_eq!(v[1].mnem, "addu");
        assert_eq!(v[1].ops, ["$t1", "$t0", "$zero"]);
        assert_eq!(resolve_mips_pair(&v[0], &v[1]), Some(0x40000));
        // Either operand order copies: addu $t1, $zero, $t0.
        let v = mips_pair(&[0x04, 0x00, 0x08, 0x3C, 0x21, 0x48, 0x08, 0x00], 0x40000);
        assert_eq!(v[1].ops, ["$t1", "$zero", "$t0"]);
        assert_eq!(resolve_mips_pair(&v[0], &v[1]), Some(0x40000));
        // A real add of two live registers is not exact.
        let v = mips_pair(&[0x04, 0x00, 0x08, 0x3C, 0x21, 0x40, 0x09, 0x01], 0x40000);
        assert_eq!(v[1].ops, ["$t0", "$t0", "$t1"]);
        assert_eq!(resolve_mips_pair(&v[0], &v[1]), None);
    }

    #[test]
    fn mips_lui_mem_pair_resolves_final_address() {
        // lui $t0, 0x4; lw $t1, 0x10($t0) -> 0x40010.
        let v = mips_pair(&[0x04, 0x00, 0x08, 0x3C, 0x10, 0x00, 0x09, 0x8D], 0x40000);
        assert_eq!(v.len(), 2);
        assert_eq!(v[1].ops, ["$t1", "0x10($t0)"]);
        assert_eq!(resolve_mips_pair(&v[0], &v[1]), Some(0x40010));
        // Negative offsets wrap too: lw $t1, -0x10($t0) -> 0x3FFF0.
        let v = mips_pair(&[0x04, 0x00, 0x08, 0x3C, 0xF0, 0xFF, 0x09, 0x8D], 0x40000);
        assert_eq!(resolve_mips_pair(&v[0], &v[1]), Some(0x3FFF0));
        // Stores reference their slot the same way: sw $t1, 0x20($t0).
        let v = mips_pair(&[0x04, 0x00, 0x08, 0x3C, 0x20, 0x00, 0x09, 0xAD], 0x40000);
        assert_eq!(v[1].mnem, "sw");
        assert_eq!(resolve_mips_pair(&v[0], &v[1]), Some(0x40020));
    }

    #[test]
    fn mips_pair_rejects_non_pairs() {
        // Register mismatch: addiu reads $t1, not the lui $t0.
        let v = mips_pair(&[0x04, 0x00, 0x08, 0x3C, 0x10, 0x00, 0x29, 0x25], 0x40000);
        assert_eq!(v[1].ops, ["$t1", "$t1", "0x10"]);
        assert_eq!(resolve_mips_pair(&v[0], &v[1]), None);
        // Wrong second mnemonic: subu $t0, $t0, $t1.
        let v = mips_pair(&[0x04, 0x00, 0x08, 0x3C, 0x23, 0x40, 0x09, 0x01], 0x40000);
        assert_eq!(v[1].mnem, "subu");
        assert_eq!(resolve_mips_pair(&v[0], &v[1]), None);
        // First instruction is not lui.
        let v = mips_pair(&[0x10, 0x00, 0x08, 0x25, 0x10, 0x00, 0x08, 0x25], 0x40000);
        assert_eq!(resolve_mips_pair(&v[0], &v[1]), None);
        // Memory base mismatch: lw through $t1.
        let v = mips_pair(&[0x04, 0x00, 0x08, 0x3C, 0x10, 0x00, 0x29, 0x8D], 0x40000);
        assert_eq!(resolve_mips_pair(&v[0], &v[1]), None);
        // Unparseable immediates never resolve, never panic.
        let v = mips_pair(&[0x04, 0x00, 0x08, 0x3C, 0x10, 0x00, 0x08, 0x25], 0x40000);
        let mut bad = v[1].clone();
        bad.ops[2] = "r1".to_string();
        assert_eq!(resolve_mips_pair(&v[0], &bad), None);
        let mut wide = v[0].clone();
        wide.ops[1] = "0x1_0000".to_string();
        assert_eq!(resolve_mips_pair(&wide, &v[1]), None);
        let mut bad_mem = v[1].clone();
        bad_mem.mnem = "lw".to_string();
        bad_mem.ops = vec!["$t1".to_string(), "0x10($t1)".to_string()];
        assert_eq!(resolve_mips_pair(&v[0], &bad_mem), None);
    }
}