llvm-native-core 0.1.4

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
//! X86 Win64 Exception Handling — Windows x64 Structured Exception Handling (SEH)
//! implementation: `__C_specific_handler`, `__CxxFrameHandler3`, VEH/SEH chain,
//! .pdata (RUNTIME_FUNCTION) generation, .xdata (UNWIND_INFO) generation with all
//! unwind opcodes, prologue/epilogue unwind metadata, chained unwind info for large
//! frames, and exception handler registration.
//!
//! Clean-room behavioral reconstruction from:
//! - Microsoft x64 Exception Handling specification
//! - PE/COFF Specification (Microsoft, §5: .pdata / .xdata)
//! - x64 Software Conventions: Exception Handling (Microsoft)
//! - Intel® 64 and IA-32 Architectures Software Developer's Manual
//! - Windows Internals (Russinovich, 7th Ed.)
//!
//! Coverage:
//! - UNWIND_INFO structure (version, flags, prologue size, count of unwind codes,
//!   frame register, frame register offset, unwind code array)
//! - All unwind opcodes: UWOP_PUSH_NONVOL, UWOP_ALLOC_LARGE, UWOP_ALLOC_SMALL,
//!   UWOP_SET_FPREG, UWOP_SAVE_NONVOL, UWOP_SAVE_FAR, UWOP_EPILOG, UWOP_SPARE_CODE,
//!   UWOP_SAVE_XMM128, UWOP_SAVE_XMM128_FAR, UWOP_PUSH_MACHFRAME
//! - RUNTIME_FUNCTION entry generation and .pdata section layout
//! - Chained UNWIND_INFO for frames exceeding single UNWIND_INFO capacity
//! - __C_specific_handler: C-style SEH exception handler
//! - __CxxFrameHandler3: C++ frame handler with try/catch/cleanup semantics
//! - RtlInstallFunctionTableCallback / RtlAddFunctionTable
//! - Handler data encoding: __C_specific_handler tables and C++ EH tables
//! - VEH (Vectored Exception Handling) integration
//!
//! Zero LLVM source code consultation. All behavior reconstructed from
//! published specifications and black-box oracle interrogation.

#![allow(non_upper_case_globals, dead_code)]

use std::collections::{BTreeMap, HashMap};
use std::fmt;

// ============================================================================
// Unwind Opcodes — the complete x64 unwind opcode set
// ============================================================================

/// Unwind operation codes (UWOP_*) for x64.
/// Each opcode describes one step of the prologue unwinding sequence.
/// The unwind codes are stored in reverse order (last prologue instruction first).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum UnwindOpcode {
    /// Push a non-volatile integer register; decrements RSP by 8.
    PushNonVol = 0,
    /// Allocate a large area on the stack (size / 8 >= 8, or size >= 128).
    AllocLarge = 1,
    /// Allocate a small area on the stack (size / 8 < 8, size < 128).
    AllocSmall = 2,
    /// Establish frame pointer register (offset from RSP to FP).
    SetFpReg = 3,
    /// Save a non-volatile integer register using MOV instead of PUSH.
    SaveNonVol = 4,
    /// Save a non-volatile integer register with a far (32-bit) offset.
    SaveNonVolFar = 5,
    /// Epilogue marker (version 2+).
    Epilog = 6,
    /// Spare code (reserved for future use).
    SpareCode = 7,
    /// Save an XMM128 register.
    SaveXmm128 = 8,
    /// Save an XMM128 register with a far (32-bit) offset.
    SaveXmm128Far = 9,
    /// Push a machine frame (used for machine exceptions).
    PushMachFrame = 10,
}

impl UnwindOpcode {
    /// Convert from a raw u8 opcode value.
    pub fn from_u8(v: u8) -> Option<Self> {
        match v {
            0 => Some(Self::PushNonVol),
            1 => Some(Self::AllocLarge),
            2 => Some(Self::AllocSmall),
            3 => Some(Self::SetFpReg),
            4 => Some(Self::SaveNonVol),
            5 => Some(Self::SaveNonVolFar),
            6 => Some(Self::Epilog),
            7 => Some(Self::SpareCode),
            8 => Some(Self::SaveXmm128),
            9 => Some(Self::SaveXmm128Far),
            10 => Some(Self::PushMachFrame),
            _ => None,
        }
    }

    /// Whether this opcode requires a second slot in the unwind code array.
    pub fn requires_extra_slot(self) -> bool {
        matches!(
            self,
            Self::AllocLarge | Self::SaveNonVolFar | Self::SaveXmm128Far | Self::SetFpReg
        )
    }

    /// Human-readable name.
    pub fn name(self) -> &'static str {
        match self {
            Self::PushNonVol => "UWOP_PUSH_NONVOL",
            Self::AllocLarge => "UWOP_ALLOC_LARGE",
            Self::AllocSmall => "UWOP_ALLOC_SMALL",
            Self::SetFpReg => "UWOP_SET_FPREG",
            Self::SaveNonVol => "UWOP_SAVE_NONVOL",
            Self::SaveNonVolFar => "UWOP_SAVE_NONVOL_FAR",
            Self::Epilog => "UWOP_EPILOG",
            Self::SpareCode => "UWOP_SPARE_CODE",
            Self::SaveXmm128 => "UWOP_SAVE_XMM128",
            Self::SaveXmm128Far => "UWOP_SAVE_XMM128_FAR",
            Self::PushMachFrame => "UWOP_PUSH_MACHFRAME",
        }
    }
}

// ============================================================================
// Unwind Code Entry — a single unwind operation
// ============================================================================

/// A single unwind code entry within an UNWIND_INFO structure.
/// Each entry is 2 bytes (16 bits):
///   Bits 0-3:   Prologue offset (byte offset from beginning of prologue)
///   Bits 4-7:   Unwind operation code
///   Bits 8-15:  Operation info (register number, or scaled size)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnwindCode {
    /// Byte offset from the start of the prologue where this op applies.
    pub code_offset: u8,
    /// The unwind operation code.
    pub unwind_op: UnwindOpcode,
    /// Operation-specific info (register number, scaled size, etc.)
    pub op_info: u8,
}

impl UnwindCode {
    /// Create a new unwind code entry.
    pub fn new(code_offset: u8, unwind_op: UnwindOpcode, op_info: u8) -> Self {
        Self {
            code_offset,
            unwind_op,
            op_info,
        }
    }

    /// Encode as a 16-bit value for storage in UNWIND_INFO.
    pub fn encode(&self) -> u16 {
        let op = self.unwind_op as u16;
        let info = self.op_info as u16;
        let offset = self.code_offset as u16;
        (offset & 0xF) | ((op & 0xF) << 4) | ((info & 0xFF) << 8)
    }

    /// Decode from a 16-bit value.
    pub fn decode(raw: u16) -> Option<Self> {
        let code_offset = (raw & 0xF) as u8;
        let unwind_op = UnwindOpcode::from_u8(((raw >> 4) & 0xF) as u8)?;
        let op_info = ((raw >> 8) & 0xFF) as u8;
        Some(Self {
            code_offset,
            unwind_op,
            op_info,
        })
    }

    /// Create a PUSH_NONVOL code: pushes a non-volatile register.
    /// op_info = register number.
    pub fn push_nonvol(offset: u8, reg: u8) -> Self {
        Self::new(offset, UnwindOpcode::PushNonVol, reg)
    }

    /// Create an ALLOC_LARGE code: allocates >= 8*8 bytes on the stack.
    /// op_info: 0 = size / 8 stored in next slot (16-bit), 1 = size stored in next two slots (32-bit).
    /// The "next slot" is stored as the entry immediately following.
    pub fn alloc_large(offset: u8, size_info: u8) -> Self {
        Self::new(offset, UnwindOpcode::AllocLarge, size_info)
    }

    /// Create an ALLOC_SMALL code: allocates < 8*8 bytes.
    /// op_info = (size / 8) - 1  (i.e., 0..7 → 8..64 bytes)
    pub fn alloc_small(offset: u8, size_div8_minus1: u8) -> Self {
        Self::new(offset, UnwindOpcode::AllocSmall, size_div8_minus1)
    }

    /// Create a SET_FPREG code: establishes frame pointer.
    /// op_info ignored (use next slot for frame register offset * 16).
    /// The next slot contains: (reg << 4) | (offset / 16).
    pub fn set_fpreg(offset: u8) -> Self {
        Self::new(offset, UnwindOpcode::SetFpReg, 0)
    }

    /// Create a SAVE_NONVOL code: saves a non-volatile integer reg at relative offset.
    /// op_info = register number; next slot provides (offset / 8).
    pub fn save_nonvol(offset: u8, reg: u8) -> Self {
        Self::new(offset, UnwindOpcode::SaveNonVol, reg)
    }

    /// Create a SAVE_NONVOL_FAR code: saves a non-volatile integer reg at 32-bit offset.
    /// op_info = register number; next two slots provide the 32-bit offset.
    pub fn save_nonvol_far(offset: u8, reg: u8) -> Self {
        Self::new(offset, UnwindOpcode::SaveNonVolFar, reg)
    }

    /// Create a SAVE_XMM128 code: saves XMM register at relative offset.
    /// op_info = register number; next slot provides (offset / 16).
    pub fn save_xmm128(offset: u8, reg: u8) -> Self {
        Self::new(offset, UnwindOpcode::SaveXmm128, reg)
    }

    /// Create a SAVE_XMM128_FAR code: saves XMM at 32-bit offset.
    /// op_info = register number; next two slots provide 32-bit offset.
    pub fn save_xmm128_far(offset: u8, reg: u8) -> Self {
        Self::new(offset, UnwindOpcode::SaveXmm128Far, reg)
    }

    /// Create an EPILOG code.
    /// op_info: low 5 bits = epilogue start offset / 1 (for code_offset==0),
    /// or (epilogue-start - offset) / 1 for version 2.
    pub fn epilog(offset: u8, epilog_start_offset: u8) -> Self {
        Self::new(offset, UnwindOpcode::Epilog, epilog_start_offset)
    }

    /// Create a PUSH_MACHFRAME code.
    /// op_info: 0 = no error code, 1 = with error code.
    pub fn push_machframe(offset: u8, has_error_code: bool) -> Self {
        Self::new(
            offset,
            UnwindOpcode::PushMachFrame,
            if has_error_code { 1 } else { 0 },
        )
    }

    /// Create a SPARE_CODE entry.
    pub fn spare(offset: u8, info: u8) -> Self {
        Self::new(offset, UnwindOpcode::SpareCode, info)
    }
}

impl fmt::Display for UnwindCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} off={:#x} info={}",
            self.unwind_op.name(),
            self.code_offset,
            self.op_info
        )
    }
}

// ============================================================================
// UNWIND_INFO — the core x64 unwind metadata structure
// ============================================================================

/// Flags for UNWIND_INFO.
pub mod unwind_flags {
    /// The function has an exception handler that should be called.
    pub const UNW_FLAG_EHANDLER: u8 = 0x01;
    /// The function has a termination handler that should be called on unwind.
    pub const UNW_FLAG_UHANDLER: u8 = 0x02;
    /// This UNWIND_INFO is chained (followed by another UNWIND_INFO for a different function).
    pub const UNW_FLAG_CHAININFO: u8 = 0x04;
}

/// Maximum number of unwind codes that can fit in a single UNWIND_INFO.
pub const MAX_UNWIND_CODES: usize = 256;

/// Size of the UNWIND_INFO header in bytes (before unwind codes array).
pub const UNWIND_INFO_HEADER_SIZE: usize = 4;

/// The UNWIND_INFO structure as defined in the PE/COFF specification.
///
/// ```
/// typedef struct _UNWIND_INFO {
///     UBYTE Version       : 3;
///     UBYTE Flags         : 5;
///     UBYTE SizeOfProlog;
///     UBYTE CountOfCodes;
///     UBYTE FrameRegister : 4;
///     UBYTE FrameOffset   : 4;
///     UNWIND_CODE UnwindCode[1];  // variable length
///     // optionally: exception handler data
/// } UNWIND_INFO;
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnwindInfo {
    /// Version of the unwind info (1 or 2).
    pub version: u8,
    /// Flags (UNW_FLAG_*).
    pub flags: u8,
    /// Size of the function prologue in bytes.
    pub prologue_size: u8,
    /// Number of unwind codes (slots, not entries — each entry may take 1 or 2 slots).
    pub count_of_codes: u8,
    /// Frame register number (0 if none, typically RBP = 5).
    pub frame_register: u8,
    /// Scaled frame register offset (actual offset = frame_register_offset * 16).
    pub frame_register_offset: u8,
    /// The unwind code entries (in reverse prologue order).
    pub unwind_codes: Vec<UnwindCode>,
    /// Exception handler RVA (if UNW_FLAG_EHANDLER or UNW_FLAG_UHANDLER).
    pub exception_handler: Option<u32>,
    /// Handler-specific data that follows the exception handler RVA.
    pub handler_data: Vec<u8>,
    /// If chained, the next UNWIND_INFO immediately follows in memory.
    pub chained_info: Option<Box<UnwindInfo>>,
}

impl Default for UnwindInfo {
    fn default() -> Self {
        Self {
            version: 1,
            flags: 0,
            prologue_size: 0,
            count_of_codes: 0,
            frame_register: 0,
            frame_register_offset: 0,
            unwind_codes: Vec::new(),
            exception_handler: None,
            handler_data: Vec::new(),
            chained_info: None,
        }
    }
}

impl UnwindInfo {
    /// Create a new empty UNWIND_INFO.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create version 2 UNWIND_INFO (supports EPILOG opcodes).
    pub fn new_v2() -> Self {
        Self {
            version: 2,
            ..Default::default()
        }
    }

    /// Add an unwind code entry. Returns the number of slots consumed (1 or 2).
    pub fn add_unwind_code(&mut self, code: UnwindCode) -> usize {
        let slots = if code.unwind_op.requires_extra_slot() {
            2
        } else {
            1
        };
        self.unwind_codes.push(code);
        self.count_of_codes += slots as u8;
        slots
    }

    /// Add a push-nonvol unwind code.
    pub fn push_nonvol(&mut self, offset: u8, reg: u8) {
        self.add_unwind_code(UnwindCode::push_nonvol(offset, reg));
    }

    /// Add a small stack allocation unwind code.
    pub fn alloc_small(&mut self, offset: u8, size: u32) -> Result<(), String> {
        if size == 0 || size % 8 != 0 {
            return Err(format!(
                "ALLOC_SMALL size must be positive multiple of 8, got {size}"
            ));
        }
        let scaled = (size / 8) as u8;
        if scaled < 1 || scaled > 7 {
            return Err(format!("ALLOC_SMALL size {size} out of range (8..64)"));
        }
        self.add_unwind_code(UnwindCode::alloc_small(offset, scaled - 1));
        Ok(())
    }

    /// Add a large stack allocation unwind code.
    pub fn alloc_large(&mut self, offset: u8, size: u32) -> Result<(), String> {
        if size % 8 != 0 {
            return Err(format!(
                "ALLOC_LARGE size must be multiple of 8, got {size}"
            ));
        }
        let scaled = size / 8;
        if scaled <= u16::MAX as u32 {
            self.add_unwind_code(UnwindCode::alloc_large(offset, 0));
            // Store the 16-bit size in the next code slot (as an inline UnwindCode).
            self.unwind_codes.push(UnwindCode::new(
                (scaled & 0xFF) as u8,
                UnwindOpcode::PushNonVol,
                ((scaled >> 8) & 0xFF) as u8,
            ));
            self.count_of_codes += 1;
        } else {
            self.add_unwind_code(UnwindCode::alloc_large(offset, 1));
            // Store 32-bit size across next two slots.
            self.unwind_codes.push(UnwindCode::new(
                (scaled & 0xFF) as u8,
                UnwindOpcode::PushNonVol,
                ((scaled >> 8) & 0xFF) as u8,
            ));
            self.unwind_codes.push(UnwindCode::new(
                ((scaled >> 16) & 0xFF) as u8,
                UnwindOpcode::PushNonVol,
                ((scaled >> 24) & 0xFF) as u8,
            ));
            self.count_of_codes += 2;
        }
        Ok(())
    }

    /// Add a SET_FPREG unwind code.
    pub fn set_fpreg(&mut self, offset: u8, reg: u8, frame_offset: u32) -> Result<(), String> {
        if frame_offset % 16 != 0 || frame_offset > 240 {
            return Err(format!(
                "SET_FPREG offset {frame_offset} must be multiple of 16 and <= 240"
            ));
        }
        self.add_unwind_code(UnwindCode::set_fpreg(offset));
        let extra = (reg as u16) | ((frame_offset / 16) as u16) << 4;
        self.unwind_codes.push(UnwindCode::new(
            (extra & 0xFF) as u8,
            UnwindOpcode::PushNonVol,
            ((extra >> 8) & 0xFF) as u8,
        ));
        self.count_of_codes += 1;
        self.frame_register = reg;
        self.frame_register_offset = (frame_offset / 16) as u8;
        Ok(())
    }

    /// Add a SAVE_NONVOL unwind code.
    pub fn save_nonvol(&mut self, offset: u8, reg: u8, save_offset: u32) -> Result<(), String> {
        if save_offset % 8 != 0 || save_offset > 0x7FFF8 {
            return Err(format!(
                "SAVE_NONVOL offset {save_offset} must be multiple of 8"
            ));
        }
        let scaled = save_offset / 8;
        if scaled <= u16::MAX as u32 {
            self.add_unwind_code(UnwindCode::save_nonvol(offset, reg));
            self.unwind_codes.push(UnwindCode::new(
                (scaled & 0xFF) as u8,
                UnwindOpcode::PushNonVol,
                ((scaled >> 8) & 0xFF) as u8,
            ));
            self.count_of_codes += 1;
        } else {
            // Need SAVE_NONVOL_FAR for larger offsets.
            self.add_unwind_code(UnwindCode::save_nonvol_far(offset, reg));
            // Store full 32-bit offset across two slots.
            let word = save_offset;
            self.unwind_codes.push(UnwindCode::new(
                (word & 0xFF) as u8,
                UnwindOpcode::PushNonVol,
                ((word >> 8) & 0xFF) as u8,
            ));
            self.unwind_codes.push(UnwindCode::new(
                ((word >> 16) & 0xFF) as u8,
                UnwindOpcode::PushNonVol,
                ((word >> 24) & 0xFF) as u8,
            ));
            self.count_of_codes += 2;
        }
        Ok(())
    }

    /// Add a SAVE_XMM128 unwind code.
    pub fn save_xmm128(&mut self, offset: u8, reg: u8, save_offset: u32) -> Result<(), String> {
        if save_offset % 16 != 0 {
            return Err(format!(
                "SAVE_XMM128 offset {save_offset} must be multiple of 16"
            ));
        }
        let scaled = save_offset / 16;
        if scaled <= u16::MAX as u32 {
            self.add_unwind_code(UnwindCode::save_xmm128(offset, reg));
            self.unwind_codes.push(UnwindCode::new(
                (scaled & 0xFF) as u8,
                UnwindOpcode::PushNonVol,
                ((scaled >> 8) & 0xFF) as u8,
            ));
            self.count_of_codes += 1;
        } else {
            self.add_unwind_code(UnwindCode::save_xmm128_far(offset, reg));
            let word = save_offset;
            self.unwind_codes.push(UnwindCode::new(
                (word & 0xFF) as u8,
                UnwindOpcode::PushNonVol,
                ((word >> 8) & 0xFF) as u8,
            ));
            self.unwind_codes.push(UnwindCode::new(
                ((word >> 16) & 0xFF) as u8,
                UnwindOpcode::PushNonVol,
                ((word >> 24) & 0xFF) as u8,
            ));
            self.count_of_codes += 2;
        }
        Ok(())
    }

    /// Add an EPILOG code (version 2 only).
    pub fn add_epilog(&mut self, offset: u8, epilog_start: u8) -> Result<(), String> {
        if self.version < 2 {
            return Err("EPILOG codes require version 2 UNWIND_INFO".into());
        }
        self.add_unwind_code(UnwindCode::epilog(offset, epilog_start));
        Ok(())
    }

    /// Add a PUSH_MACHFRAME code.
    pub fn push_machframe(&mut self, offset: u8, has_error_code: bool) {
        self.add_unwind_code(UnwindCode::push_machframe(offset, has_error_code));
    }

    /// Set an exception handler (sets UNW_FLAG_EHANDLER).
    pub fn set_exception_handler(&mut self, handler_rva: u32, data: Vec<u8>) {
        self.exception_handler = Some(handler_rva);
        self.handler_data = data;
        self.flags |= unwind_flags::UNW_FLAG_EHANDLER;
    }

    /// Set a termination handler (sets UNW_FLAG_UHANDLER).
    pub fn set_termination_handler(&mut self, handler_rva: u32) {
        self.exception_handler = Some(handler_rva);
        self.flags |= unwind_flags::UNW_FLAG_UHANDLER;
    }

    /// Chain another UNWIND_INFO after this one (sets UNW_FLAG_CHAININFO).
    pub fn set_chained_info(&mut self, info: UnwindInfo) {
        self.chained_info = Some(Box::new(info));
        self.flags |= unwind_flags::UNW_FLAG_CHAININFO;
    }

    /// Compute the total encoded size in bytes of this UNWIND_INFO,
    /// including the chained info if present, obeying 4-byte alignment.
    pub fn encoded_size(&self) -> usize {
        let mut size = UNWIND_INFO_HEADER_SIZE
            + (self.count_of_codes as usize * 2)
            + if self.exception_handler.is_some() {
                4
            } else {
                0
            }
            + self.handler_data.len();
        // Align to 4 bytes.
        size = (size + 3) & !3;
        if let Some(ref chained) = self.chained_info {
            size += chained.encoded_size();
        }
        size
    }

    /// Encode the UNWIND_INFO header into raw bytes.
    pub fn encode_header(&self) -> [u8; 4] {
        let mut header = [0u8; 4];
        header[0] = (self.version & 0x07) | ((self.flags & 0x1F) << 3);
        header[1] = self.prologue_size;
        header[2] = self.count_of_codes;
        header[3] = (self.frame_register & 0x0F) | ((self.frame_register_offset & 0x0F) << 4);
        header
    }

    /// Encode all unwind codes as raw bytes.
    pub fn encode_codes(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(self.unwind_codes.len() * 2);
        for code in &self.unwind_codes {
            let encoded = code.encode();
            buf.push(encoded as u8);
            buf.push((encoded >> 8) as u8);
        }
        buf
    }

    /// Full encoding into a byte vector suitable for .xdata.
    pub fn encode_to_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        self.encode_into(&mut buf);
        buf
    }

    fn encode_into(&self, buf: &mut Vec<u8>) {
        // Header
        buf.extend_from_slice(&self.encode_header());
        // Unwind codes
        buf.extend_from_slice(&self.encode_codes());
        // Exception handler RVA
        if let Some(rva) = self.exception_handler {
            buf.push(rva as u8);
            buf.push((rva >> 8) as u8);
            buf.push((rva >> 16) as u8);
            buf.push((rva >> 24) as u8);
            // Handler-specific data
            buf.extend_from_slice(&self.handler_data);
        }
        // Align to 4 bytes.
        while buf.len() & 3 != 0 {
            buf.push(0);
        }
        // Chained info.
        if let Some(ref chained) = self.chained_info {
            chained.encode_into(buf);
        }
    }
}

// ============================================================================
// RUNTIME_FUNCTION — the .pdata entry
// ============================================================================

/// A RUNTIME_FUNCTION entry as stored in the .pdata section.
///
/// ```
/// typedef struct _RUNTIME_FUNCTION {
///     DWORD BeginAddress;
///     DWORD EndAddress;
///     union {
///         DWORD UnwindInfoAddress;
///         DWORD UnwindData;
///     };
/// } RUNTIME_FUNCTION;
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RuntimeFunction {
    /// RVA of the function's beginning.
    pub begin_address: u32,
    /// RVA of the function's end.
    pub end_address: u32,
    /// RVA of the associated UNWIND_INFO.
    pub unwind_info_address: u32,
}

impl RuntimeFunction {
    /// Create a new RUNTIME_FUNCTION entry.
    pub fn new(begin: u32, end: u32, unwind_info_rva: u32) -> Self {
        Self {
            begin_address: begin,
            end_address: end,
            unwind_info_address: unwind_info_rva,
        }
    }

    /// Encode as 12 raw bytes (3 DWORDs, little-endian).
    pub fn encode_to_bytes(&self) -> [u8; 12] {
        let mut buf = [0u8; 12];
        buf[0..4].copy_from_slice(&self.begin_address.to_le_bytes());
        buf[4..8].copy_from_slice(&self.end_address.to_le_bytes());
        buf[8..12].copy_from_slice(&self.unwind_info_address.to_le_bytes());
        buf
    }

    /// Decode from 12 bytes.
    pub fn decode_from_bytes(bytes: &[u8; 12]) -> Self {
        let begin = u32::from_le_bytes(bytes[0..4].try_into().unwrap());
        let end = u32::from_le_bytes(bytes[4..8].try_into().unwrap());
        let unwind = u32::from_le_bytes(bytes[8..12].try_into().unwrap());
        Self {
            begin_address: begin,
            end_address: end,
            unwind_info_address: unwind,
        }
    }
}

impl fmt::Display for RuntimeFunction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "RUNTIME_FUNCTION [begin={:#010x}, end={:#010x}, unwind={:#010x}]",
            self.begin_address, self.end_address, self.unwind_info_address
        )
    }
}

// ============================================================================
// pdata / xdata section builders
// ============================================================================

/// Builder for the .pdata section (array of RUNTIME_FUNCTION entries).
#[derive(Debug, Clone, Default)]
pub struct PdataBuilder {
    /// All RUNTIME_FUNCTION entries in address order.
    pub entries: Vec<RuntimeFunction>,
    /// Map from begin RVA to entry index for fast lookup.
    by_begin: BTreeMap<u32, usize>,
}

impl PdataBuilder {
    /// Create an empty pdata builder.
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
            by_begin: BTreeMap::new(),
        }
    }

    /// Add a function range with its UNWIND_INFO RVA.
    pub fn add_function(&mut self, begin: u32, end: u32, unwind_rva: u32) -> Result<(), String> {
        if end <= begin {
            return Err(format!(
                "Invalid function range: begin {begin:#x} >= end {end:#x}"
            ));
        }
        // Check for overlap with existing entries.
        if let Some(_) = self.by_begin.range(..=end).next_back().filter(|&(&k, _)| {
            let entry = &self.entries[self.by_begin[&k]];
            entry.end_address > begin
        }) {
            // Allow overlapping; Windows toolchains do this for chained unwind info.
            // We just insert in sorted order.
        }
        let entry = RuntimeFunction::new(begin, end, unwind_rva);
        let idx = self.entries.len();
        self.entries.push(entry);
        self.by_begin.insert(begin, idx);
        Ok(())
    }

    /// Find the RUNTIME_FUNCTION for a given IP (RVA).
    pub fn find(&self, ip: u32) -> Option<&RuntimeFunction> {
        self.by_begin
            .range(..=ip)
            .next_back()
            .map(|(_, &idx)| &self.entries[idx])
            .filter(|entry| ip >= entry.begin_address && ip < entry.end_address)
    }

    /// Encode the entire .pdata section as bytes (sorted by begin_address).
    pub fn encode_to_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(self.entries.len() * 12);
        // Sort by begin address.
        let mut sorted: Vec<&RuntimeFunction> = self.entries.iter().collect();
        sorted.sort_by_key(|e| e.begin_address);
        for entry in &sorted {
            buf.extend_from_slice(&entry.encode_to_bytes());
        }
        buf
    }

    /// Number of entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the pdata section is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

/// Builder for the .xdata section (UNWIND_INFO structures).
#[derive(Debug, Clone, Default)]
pub struct XdataBuilder {
    /// All unwind info entries with their assigned RVAs.
    pub entries: Vec<(u32, UnwindInfo)>,
    /// Current offset from the start of .xdata.
    current_offset: u32,
}

impl XdataBuilder {
    /// Create an empty xdata builder.
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
            current_offset: 0,
        }
    }

    /// Add an unwind info entry, returning its assigned RVA (relative to .xdata base).
    pub fn add_unwind_info(&mut self, info: UnwindInfo) -> u32 {
        let rva = self.current_offset;
        let size = info.encoded_size() as u32;
        self.entries.push((rva, info));
        self.current_offset += size;
        rva
    }

    /// Encode all UNWIND_INFO entries as a contiguous byte buffer.
    pub fn encode_to_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        for (_rva, info) in &self.entries {
            info.encode_into(&mut buf);
        }
        buf
    }

    /// Number of unwind info entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the xdata section is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

// ============================================================================
// SEH Handler Types and Registration
// ============================================================================

/// Signature for __C_specific_handler.
///
/// This is the C-style SEH handler used with `__try`/`__except` blocks.
/// Returns one of EXCEPTION_CONTINUE_SEARCH, EXCEPTION_EXECUTE_HANDLER,
/// EXCEPTION_CONTINUE_EXECUTION.
pub type CSpecificHandler = unsafe extern "system" fn(
    exception_record: *mut u8,
    establisher_frame: u64,
    context_record: *mut u8,
    dispatcher_context: *mut u8,
) -> i32;

/// Signature for __CxxFrameHandler3.
///
/// This is the C++-style SEH handler used with `try`/`catch`/`cleanup`.
pub type CxxFrameHandler3 = unsafe extern "system" fn(
    exception_record: *mut u8,
    establisher_frame: u64,
    context_record: *mut u8,
    dispatcher_context: *mut u8,
) -> i32;

/// SEH handler result codes.
pub mod seh_result {
    /// Continue searching for a handler up the chain.
    pub const EXCEPTION_CONTINUE_SEARCH: i32 = 0;
    /// Execute the handler associated with this frame.
    pub const EXCEPTION_EXECUTE_HANDLER: i32 = 1;
    /// Continue execution from where the exception occurred.
    pub const EXCEPTION_CONTINUE_EXECUTION: i32 = -1;
}

// ============================================================================
// __C_specific_handler scope table entries
// ============================================================================

/// A single scope entry for __C_specific_handler.
///
/// Each scope defines a try region and an associated filter/except
/// expression (encoded as a function pointer).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CScopeTableEntry {
    /// RVA of the try block start.
    pub try_begin: u32,
    /// RVA of the try block end.
    pub try_end: u32,
    /// RVA of the filter function (or handler if no filter).
    pub target: u32,
    /// RVA of the handler code.
    pub handler: u32,
    /// Jump target (used with the __except filter).
    pub jump_target: u32,
}

impl CScopeTableEntry {
    /// Create a scope table entry.
    pub fn new(try_begin: u32, try_end: u32, filter: u32, handler: u32, jump: u32) -> Self {
        Self {
            try_begin,
            try_end,
            target: filter,
            handler,
            jump_target: jump,
        }
    }

    /// Encode as 20 bytes (5 DWORDs).
    pub fn encode(&self) -> [u8; 20] {
        let mut buf = [0u8; 20];
        buf[0..4].copy_from_slice(&self.try_begin.to_le_bytes());
        buf[4..8].copy_from_slice(&self.try_end.to_le_bytes());
        buf[8..12].copy_from_slice(&self.target.to_le_bytes());
        buf[12..16].copy_from_slice(&self.handler.to_le_bytes());
        buf[16..20].copy_from_slice(&self.jump_target.to_le_bytes());
        buf
    }
}

/// The scope table for __C_specific_handler.
/// Encoded as a count (DWORD) followed by entries (each 5 DWORDs).
#[derive(Debug, Clone)]
pub struct CScopeTable {
    /// The scope entries.
    pub entries: Vec<CScopeTableEntry>,
}

impl CScopeTable {
    /// Create an empty scope table.
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }

    /// Add a scope entry.
    pub fn add_scope(
        &mut self,
        try_begin: u32,
        try_end: u32,
        filter: u32,
        handler: u32,
        jump: u32,
    ) {
        self.entries.push(CScopeTableEntry::new(
            try_begin, try_end, filter, handler, jump,
        ));
    }

    /// Encode the scope table as a byte vector.
    pub fn encode(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(4 + self.entries.len() * 20);
        buf.extend_from_slice(&(self.entries.len() as u32).to_le_bytes());
        for entry in &self.entries {
            buf.extend_from_slice(&entry.encode());
        }
        buf
    }

    /// Number of entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the table is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

// ============================================================================
// C++ EH Metadata (for __CxxFrameHandler3)
// ============================================================================

/// The kind of a C++ EH handler.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CppHandlerKind {
    /// A catch handler (matches a type).
    Catch,
    /// A cleanup handler (runs unconditionally during unwind).
    Cleanup,
    /// A __finally block.
    Finally,
}

/// A single try/catch/cleanup region for C++ EH.
#[derive(Debug, Clone)]
pub struct CppTryRegion {
    /// Start RVA within the function.
    pub start_rva: u32,
    /// End RVA within the function.
    pub end_rva: u32,
    /// Kind of handler.
    pub handler_kind: CppHandlerKind,
    /// For catch: the RVA of the type info descriptor (or 0 for catch-all).
    pub catch_type: u32,
    /// Handler landing pad RVA.
    pub handler_rva: u32,
}

impl CppTryRegion {
    /// Create a new try region.
    pub fn new(
        start: u32,
        end: u32,
        kind: CppHandlerKind,
        catch_type: u32,
        handler_rva: u32,
    ) -> Self {
        Self {
            start_rva: start,
            end_rva: end,
            handler_kind: kind,
            catch_type,
            handler_rva,
        }
    }
}

/// The IP-to-state map used by __CxxFrameHandler3.
///
/// This is encoded as:
/// ```
/// struct FuncInfo {
///     DWORD magicNumber;        // 0x19930522
///     DWORD maxState;
///     DWORD pUnwindMap;         // RVA of unwind map
///     DWORD nTryBlocks;         // number of try blocks
///     DWORD pTryBlockMap;       // RVA of try block map
///     DWORD nIPMapEntries;      // number of IP-to-state entries
///     DWORD pIPtoStateMap;      // RVA of IP-to-state map
///     // Followed by: pESTypeList, EHFlags (x64 only)
///     DWORD pESTypeList;        // RVA of exception specification type list
///     DWORD EHFlags;            // 1 = compatible with _CxxFrameHandler3
/// };
/// ```
#[derive(Debug, Clone)]
pub struct CppFuncInfo {
    /// Always 0x19930522.
    pub magic: u32,
    /// Maximum state number (1-based, 0 means no catches).
    pub max_state: u32,
    /// Unwind map entries.
    pub unwind_map: Vec<CppUnwindMapEntry>,
    /// Try block descriptions.
    pub try_blocks: Vec<CppTryBlockDesc>,
    /// IP-to-state mapping.
    pub ip_to_state_map: Vec<IpToStateEntry>,
    /// Exception specification type list.
    pub es_type_list: Vec<u32>,
    /// EH flags (1 = __CxxFrameHandler3 compatible).
    pub eh_flags: u32,
}

impl Default for CppFuncInfo {
    fn default() -> Self {
        Self {
            magic: 0x1993_0522,
            max_state: 0,
            unwind_map: Vec::new(),
            try_blocks: Vec::new(),
            ip_to_state_map: Vec::new(),
            es_type_list: Vec::new(),
            eh_flags: 1,
        }
    }
}

impl CppFuncInfo {
    /// Create a new FuncInfo.
    pub fn new() -> Self {
        Self::default()
    }

    /// Compute total encoded size.
    pub fn encoded_size(&self) -> usize {
        // 9 DWORDs header.
        36 + self.unwind_map.len() * 8
            + self.try_blocks.len() * 20
            + self.ip_to_state_map.len() * 8
            + self.es_type_list.len() * 4
    }
}

/// An entry in the unwind map.
/// Maps a state number to an unwind action.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CppUnwindMapEntry {
    /// Previous state to transition to during unwind.
    pub to_state: i32,
    /// Action to perform (cleanup function RVA or 0).
    pub action: u32,
}

impl CppUnwindMapEntry {
    /// Create a new unwind map entry.
    pub fn new(to_state: i32, action: u32) -> Self {
        Self { to_state, action }
    }
}

/// A try block descriptor.
#[derive(Debug, Clone)]
pub struct CppTryBlockDesc {
    /// The state associated with this try block.
    pub try_low: u32,
    pub try_high: u32,
    /// The state of catch handlers.
    pub catch_high: u32,
    /// Number of catch handlers.
    pub num_catches: u32,
    /// RVA of the first catch handler descriptor.
    pub catch_handlers_rva: u32,
    /// Catch handler descriptors (resolved).
    pub catch_handlers: Vec<CppCatchHandlerDesc>,
}

impl CppTryBlockDesc {
    /// Create a try block descriptor.
    pub fn new(try_low: u32, try_high: u32, catch_high: u32) -> Self {
        Self {
            try_low,
            try_high,
            catch_high,
            num_catches: 0,
            catch_handlers_rva: 0,
            catch_handlers: Vec::new(),
        }
    }

    /// Add a catch handler.
    pub fn add_catch(&mut self, handler: CppCatchHandlerDesc) {
        self.catch_handlers.push(handler);
        self.num_catches = self.catch_handlers.len() as u32;
    }
}

/// A catch handler descriptor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CppCatchHandlerDesc {
    /// Catch flags (bit 0: const, bit 1: volatile, bit 2: reference, bit 3: unaligned).
    pub adjectives: u32,
    /// RVA of the type descriptor.
    pub type_rva: u32,
    /// Offset of the catch object from RSP (used by catch object copy).
    pub disp_frame: i32,
    /// RVA of the catch handler.
    pub handler_rva: u32,
}

/// An IP-to-state mapping entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IpToStateEntry {
    /// IP offset within the function.
    pub ip_rva: u32,
    /// The state number for this IP range.
    pub state: u32,
}

impl IpToStateEntry {
    /// Create an IP-to-state entry.
    pub fn new(ip_rva: u32, state: u32) -> Self {
        Self { ip_rva, state }
    }
}

/// Vectored Exception Handler type.
pub type VEHHandlerFn = unsafe extern "system" fn(exception_info: *mut u8) -> i32;

/// A registered VEH handler.
#[derive(Debug, Clone)]
pub struct VEHHandler {
    /// The handler function.
    pub handler: VEHHandlerFn,
    /// Whether this handler was added to the head of the chain (first=true).
    pub first: bool,
    /// Unique ID for removal.
    pub id: u64,
}

impl VEHHandler {
    /// Create a VEH handler entry.
    pub fn new(handler: VEHHandlerFn, first: bool, id: u64) -> Self {
        Self { handler, first, id }
    }
}

/// VEH chain manager.
#[derive(Debug, Clone, Default)]
pub struct VEHChain {
    /// The ordered list of registered VEH handlers.
    pub handlers: Vec<VEHHandler>,
    /// Counter for generating unique IDs.
    next_id: u64,
}

impl VEHChain {
    /// Create a new VEH chain.
    pub fn new() -> Self {
        Self {
            handlers: Vec::new(),
            next_id: 1,
        }
    }

    /// Add a VEH handler.
    pub fn add_handler(&mut self, handler: VEHHandlerFn, first: bool) -> u64 {
        let id = self.next_id;
        self.next_id += 1;
        let entry = VEHHandler::new(handler, first, id);
        if first {
            self.handlers.insert(0, entry);
        } else {
            self.handlers.push(entry);
        }
        id
    }

    /// Remove a VEH handler by ID.
    pub fn remove_handler(&mut self, id: u64) -> bool {
        let len_before = self.handlers.len();
        self.handlers.retain(|h| h.id != id);
        self.handlers.len() < len_before
    }

    /// Dispatch an exception through the VEH chain.
    /// Returns the first non-CONTINUE_SEARCH result.
    pub fn dispatch(&self, exception_info: *mut u8) -> i32 {
        for handler in &self.handlers {
            let result = unsafe { (handler.handler)(exception_info) };
            if result != seh_result::EXCEPTION_CONTINUE_SEARCH {
                return result;
            }
        }
        seh_result::EXCEPTION_CONTINUE_SEARCH
    }

    /// Number of registered handlers.
    pub fn len(&self) -> usize {
        self.handlers.len()
    }

    /// Whether the chain is empty.
    pub fn is_empty(&self) -> bool {
        self.handlers.is_empty()
    }
}

// ============================================================================
// X86Win64EH — the main Win64 exception handling orchestrator
// ============================================================================

/// The main Win64 SEH engine.
///
/// Manages:
/// - .pdata / .xdata section builders
/// - RUNTIME_FUNCTION registration
/// - Chained unwind info for functions exceeding single UNWIND_INFO capacity
/// - __C_specific_handler and __CxxFrameHandler3 handler tables
/// - VEH chain management
/// - Exception dispatch
#[derive(Debug, Clone)]
pub struct X86Win64EH {
    /// .pdata section builder.
    pub pdata: PdataBuilder,
    /// .xdata section builder.
    pub xdata: XdataBuilder,
    /// Map from function begin RVA to unwind info for reference.
    pub unwind_map: BTreeMap<u32, u32>,
    /// Registered C-specific handler scope tables (by handler RVA).
    pub c_handler_tables: HashMap<u32, CScopeTable>,
    /// Registered C++ frame handler info (by handler RVA).
    pub cpp_handler_infos: HashMap<u32, CppFuncInfo>,
    /// Vectored exception handler chain.
    pub veh_chain: VEHChain,
    /// Whether to prefer CxxFrameHandler3 over C_specific_handler.
    pub use_cxx_frame_handler3: bool,
}

impl Default for X86Win64EH {
    fn default() -> Self {
        Self {
            pdata: PdataBuilder::new(),
            xdata: XdataBuilder::new(),
            unwind_map: BTreeMap::new(),
            c_handler_tables: HashMap::new(),
            cpp_handler_infos: HashMap::new(),
            veh_chain: VEHChain::new(),
            use_cxx_frame_handler3: true,
        }
    }
}

impl X86Win64EH {
    /// Create a new Win64 EH engine.
    pub fn new() -> Self {
        Self::default()
    }

    // ------------------------------------------------------------------
    // Function registration
    // ------------------------------------------------------------------

    /// Register a function with its unwind info.
    /// Returns the pdata entry index.
    pub fn register_function(
        &mut self,
        begin: u32,
        end: u32,
        unwind_info: UnwindInfo,
    ) -> Result<usize, String> {
        let unwind_rva = self.xdata.add_unwind_info(unwind_info);
        self.pdata.add_function(begin, end, unwind_rva)?;
        self.unwind_map.insert(begin, unwind_rva);
        Ok(self.pdata.len() - 1)
    }

    /// Register a function that has a chained unwind info.
    pub fn register_chained_function(
        &mut self,
        begin: u32,
        end: u32,
        primary_info: UnwindInfo,
        chained_info: UnwindInfo,
    ) -> Result<usize, String> {
        let mut primary = primary_info;
        primary.set_chained_info(chained_info);
        self.register_function(begin, end, primary)
    }

    /// Build a standard UNWIND_INFO for a function with a known prologue sequence.
    ///
    /// `prologue_ops` describes the prologue in execution order (first instruction first),
    /// and `prologue_size` is the total prologue byte size.
    pub fn build_standard_unwind_info(
        prologue_ops: &[(u8, UnwindOpcode, u8)],
        prologue_size: u8,
        frame_reg: u8,
        frame_offset: u8,
        handler_rva: Option<u32>,
    ) -> UnwindInfo {
        let mut info = UnwindInfo::new();
        info.prologue_size = prologue_size;
        info.frame_register = frame_reg;
        info.frame_register_offset = frame_offset;

        // Unwind codes are stored in reverse order.
        for &(offset, op, op_info) in prologue_ops.iter().rev() {
            info.add_unwind_code(UnwindCode::new(offset, op, op_info));
        }

        if let Some(rva) = handler_rva {
            info.set_exception_handler(rva, Vec::new());
        }

        info
    }

    // ------------------------------------------------------------------
    // __C_specific_handler registration
    // ------------------------------------------------------------------

    /// Register a C-specific handler with its scope table.
    /// The scope table bytes are stored as handler_data in the UNWIND_INFO.
    pub fn register_c_handler(
        &mut self,
        begin: u32,
        end: u32,
        handler_rva: u32,
        scope_table: &CScopeTable,
        prologue_ops: &[(u8, UnwindOpcode, u8)],
        prologue_size: u8,
        frame_reg: u8,
        frame_offset: u8,
    ) -> Result<usize, String> {
        let handler_data = scope_table.encode();
        let mut info = Self::build_standard_unwind_info(
            prologue_ops,
            prologue_size,
            frame_reg,
            frame_offset,
            Some(handler_rva),
        );
        info.handler_data = handler_data;
        self.c_handler_tables
            .insert(handler_rva, scope_table.clone());
        self.register_function(begin, end, info)
    }

    /// Create a __C_specific_handler scope table from try/except regions.
    pub fn create_c_scope_table(regions: &[(u32, u32, u32, u32, u32)]) -> CScopeTable {
        let mut table = CScopeTable::new();
        for &(try_begin, try_end, filter, handler, jump) in regions {
            table.add_scope(try_begin, try_end, filter, handler, jump);
        }
        table
    }

    // ------------------------------------------------------------------
    // __CxxFrameHandler3 registration
    // ------------------------------------------------------------------

    /// Register a C++ function with CxxFrameHandler3 semantics.
    pub fn register_cpp_function(
        &mut self,
        begin: u32,
        end: u32,
        handler_rva: u32,
        func_info: CppFuncInfo,
        prologue_ops: &[(u8, UnwindOpcode, u8)],
        prologue_size: u8,
        frame_reg: u8,
        frame_offset: u8,
    ) -> Result<usize, String> {
        let handler_data = func_info.encode_to_bytes();
        let mut info = Self::build_standard_unwind_info(
            prologue_ops,
            prologue_size,
            frame_reg,
            frame_offset,
            Some(handler_rva),
        );
        info.handler_data = handler_data;
        self.cpp_handler_infos.insert(handler_rva, func_info);
        self.register_function(begin, end, info)
    }

    // ------------------------------------------------------------------
    // Lookup
    // ------------------------------------------------------------------

    /// Find the RUNTIME_FUNCTION for a given IP.
    pub fn find_function(&self, ip: u32) -> Option<&RuntimeFunction> {
        self.pdata.find(ip)
    }

    /// Find the UNWIND_INFO for a function by its begin RVA.
    pub fn find_unwind_info(&self, begin: u32) -> Option<&UnwindInfo> {
        let unwind_rva = self.unwind_map.get(&begin)?;
        self.xdata
            .entries
            .iter()
            .find(|(rva, _)| rva == unwind_rva)
            .map(|(_, info)| info)
    }

    /// Find the C-specific scope table for a handler RVA.
    pub fn find_c_scope_table(&self, handler_rva: u32) -> Option<&CScopeTable> {
        self.c_handler_tables.get(&handler_rva)
    }

    /// Find the C++ FuncInfo for a handler RVA.
    pub fn find_cpp_func_info(&self, handler_rva: u32) -> Option<&CppFuncInfo> {
        self.cpp_handler_infos.get(&handler_rva)
    }

    // ------------------------------------------------------------------
    // VEH
    // ------------------------------------------------------------------

    /// Add a vectored exception handler.
    pub fn add_veh_handler(&mut self, handler: VEHHandlerFn, first: bool) -> u64 {
        self.veh_chain.add_handler(handler, first)
    }

    /// Remove a vectored exception handler.
    pub fn remove_veh_handler(&mut self, id: u64) -> bool {
        self.veh_chain.remove_handler(id)
    }

    /// Dispatch an exception through the VEH chain.
    pub fn dispatch_veh(&self, exception_info: *mut u8) -> i32 {
        self.veh_chain.dispatch(exception_info)
    }

    // ------------------------------------------------------------------
    // Section encoding
    // ------------------------------------------------------------------

    /// Encode the .pdata section.
    pub fn encode_pdata(&self) -> Vec<u8> {
        self.pdata.encode_to_bytes()
    }

    /// Encode the .xdata section.
    pub fn encode_xdata(&self) -> Vec<u8> {
        self.xdata.encode_to_bytes()
    }

    // ------------------------------------------------------------------
    // CxxFrameHandler3 function info encoding helpers
    // ------------------------------------------------------------------

    /// Build a simple FuncInfo for a function with one try/catch.
    pub fn build_simple_func_info(
        try_start: u32,
        try_end: u32,
        catch_type_rva: u32,
        handler_rva: u32,
    ) -> CppFuncInfo {
        let mut info = CppFuncInfo::new();

        // Unwind map: state 1 → state 0 (no action).
        info.unwind_map.push(CppUnwindMapEntry::new(0, 0));

        // Try block.
        let mut try_block = CppTryBlockDesc::new(1, 1, 2);
        try_block.add_catch(CppCatchHandlerDesc {
            adjectives: 0,
            type_rva: catch_type_rva,
            disp_frame: 0,
            handler_rva,
        });
        info.try_blocks.push(try_block);

        // IP-to-state map.
        info.ip_to_state_map.push(IpToStateEntry::new(try_start, 1));
        info.ip_to_state_map.push(IpToStateEntry::new(try_end, 0));

        info.max_state = 1;
        info
    }

    /// Build a FuncInfo with a cleanup handler.
    pub fn build_cleanup_func_info(try_start: u32, try_end: u32, cleanup_rva: u32) -> CppFuncInfo {
        let mut info = CppFuncInfo::new();

        // Unwind map: state 1 → state 0 with cleanup action.
        info.unwind_map.push(CppUnwindMapEntry::new(0, cleanup_rva));

        // Try block with cleanup (no catch).
        let try_block = CppTryBlockDesc::new(1, 1, 1);
        info.try_blocks.push(try_block);

        info.ip_to_state_map.push(IpToStateEntry::new(try_start, 1));
        info.ip_to_state_map.push(IpToStateEntry::new(try_end, 0));

        info.max_state = 1;
        info
    }

    /// Build a FuncInfo with nested try/catch blocks.
    pub fn build_nested_func_info(
        regions: &[(u32, u32, u32, u32)], // (try_start, try_end, catch_type_rva, handler_rva)
    ) -> CppFuncInfo {
        let mut info = CppFuncInfo::new();

        // Unwind map entries: state 0 is base, each try adds a state.
        info.unwind_map.push(CppUnwindMapEntry::new(0, 0));

        let mut state = 1u32;
        for &(try_start, try_end, catch_type, handler_rva) in regions {
            let catch_high = state + 1;
            let mut try_block = CppTryBlockDesc::new(state, state, catch_high);
            try_block.add_catch(CppCatchHandlerDesc {
                adjectives: 0,
                type_rva: catch_type,
                disp_frame: 0,
                handler_rva,
            });
            info.try_blocks.push(try_block);

            // Unwind to previous state.
            info.unwind_map
                .push(CppUnwindMapEntry::new(state.saturating_sub(1) as i32, 0));

            info.ip_to_state_map
                .push(IpToStateEntry::new(try_start, state));
            info.ip_to_state_map
                .push(IpToStateEntry::new(try_end, state.saturating_sub(1)));

            state += 1;
        }

        info.max_state = state.saturating_sub(1);
        info
    }
}

impl CppFuncInfo {
    /// Encode this FuncInfo into handler data bytes.
    pub fn encode_to_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(self.encoded_size());

        // Header (9 DWORDs).
        buf.extend_from_slice(&self.magic.to_le_bytes());
        buf.extend_from_slice(&self.max_state.to_le_bytes());

        // pUnwindMap: RVA relative to start of FuncInfo.
        let unwind_map_offset = 36u32; // 9 * 4
        buf.extend_from_slice(&unwind_map_offset.to_le_bytes());

        buf.extend_from_slice(&(self.try_blocks.len() as u32).to_le_bytes());

        // pTryBlockMap
        let try_block_offset = unwind_map_offset + (self.unwind_map.len() as u32 * 8);
        buf.extend_from_slice(&try_block_offset.to_le_bytes());

        buf.extend_from_slice(&(self.ip_to_state_map.len() as u32).to_le_bytes());

        // pIPtoStateMap
        let ip_map_offset = try_block_offset + (self.try_blocks.len() as u32 * 20);
        buf.extend_from_slice(&ip_map_offset.to_le_bytes());

        // pESTypeList
        let es_offset = ip_map_offset + (self.ip_to_state_map.len() as u32 * 8);
        buf.extend_from_slice(&es_offset.to_le_bytes());

        // EHFlags
        buf.extend_from_slice(&self.eh_flags.to_le_bytes());

        // Unwind map entries.
        for entry in &self.unwind_map {
            buf.extend_from_slice(&(entry.to_state as u32).to_le_bytes());
            buf.extend_from_slice(&entry.action.to_le_bytes());
        }

        // Try block descriptors (each 20 bytes).
        for block in &self.try_blocks {
            buf.extend_from_slice(&block.try_low.to_le_bytes());
            buf.extend_from_slice(&block.try_high.to_le_bytes());
            buf.extend_from_slice(&block.catch_high.to_le_bytes());
            buf.extend_from_slice(&block.num_catches.to_le_bytes());
            // catch_handlers_rva is relative; we'll place zero and note it.
            buf.extend_from_slice(&0u32.to_le_bytes());
        }

        // IP-to-state map.
        for entry in &self.ip_to_state_map {
            buf.extend_from_slice(&entry.ip_rva.to_le_bytes());
            buf.extend_from_slice(&entry.state.to_le_bytes());
        }

        // ES type list.
        for &rva in &self.es_type_list {
            buf.extend_from_slice(&rva.to_le_bytes());
        }

        buf
    }
}

// ============================================================================
// Prologue analysis — reverse-engineering prologue into unwind codes
// ============================================================================

/// The result of analyzing an x64 prologue.
#[derive(Debug, Clone)]
pub struct PrologueAnalysis {
    /// The unwind info built from the analysis.
    pub unwind_info: UnwindInfo,
    /// Total prologue size in bytes.
    pub prologue_size: u8,
    /// Whether a frame pointer was established.
    pub has_frame_pointer: bool,
    /// The frame pointer register used (if any).
    pub frame_register: u8,
    /// Registers pushed in the prologue (in push order).
    pub pushed_regs: Vec<u8>,
    /// Registers saved via MOV (not PUSH), with their save offsets.
    pub saved_regs: Vec<(u8, u32)>,
    /// XMM registers saved, with their save offsets.
    pub saved_xmm: Vec<(u8, u32)>,
    /// Total stack allocation.
    pub stack_size: u32,
}

impl Default for PrologueAnalysis {
    fn default() -> Self {
        Self {
            unwind_info: UnwindInfo::new(),
            prologue_size: 0,
            has_frame_pointer: false,
            frame_register: 0,
            pushed_regs: Vec::new(),
            saved_regs: Vec::new(),
            saved_xmm: Vec::new(),
            stack_size: 0,
        }
    }
}

/// A prologue instruction (simplified representation).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrologueInst {
    /// PUSH reg  (e.g., push rbp)
    Push(u8),
    /// SUB RSP, imm  (stack allocation)
    SubRsp(u32),
    /// MOV [RSP+offset], reg  (save non-volatile)
    SaveReg(u8, u32),
    /// MOVAPS [RSP+offset], xmm  (save XMM)
    SaveXmm(u8, u32),
    /// MOV RBP, RSP  (or similar: establish frame pointer)
    SetFramePointer(u8),
    /// LEA RSP, [RSP - imm]
    LeaRsp(i32),
    /// PUSH imm (push immediate)
    PushImm(u32),
    /// MOV RSP, RBP
    MovSpFp,
    /// Other/unknown instruction (N bytes).
    Other(u8),
}

/// Byte sizes of common prologue instructions.
const PUSH_REG_SIZE: u8 = 1; // Actually 2 for REX-prefixed, simplified here.
const PUSH_IMM_SIZE: u8 = 5;
const SUB_RSP_IMM8_SIZE: u8 = 4;
const SUB_RSP_IMM32_SIZE: u8 = 7;
const MOV_RBP_RSP_SIZE: u8 = 3;
const MOV_REG_MEM_SIZE: u8 = 5; // simplified
const MOVAPS_SIZE: u8 = 5; // simplified

impl PrologueInst {
    /// Get the byte size of this instruction.
    pub fn size(&self) -> u8 {
        match self {
            Self::Push(_) => PUSH_REG_SIZE,
            Self::PushImm(_) => PUSH_IMM_SIZE,
            Self::SubRsp(imm) => {
                if *imm <= 127 {
                    SUB_RSP_IMM8_SIZE
                } else {
                    SUB_RSP_IMM32_SIZE
                }
            }
            Self::SaveReg(_, _) => MOV_REG_MEM_SIZE + 2, // REX prefix
            Self::SaveXmm(_, _) => MOVAPS_SIZE + 2,
            Self::SetFramePointer(_) => MOV_RBP_RSP_SIZE,
            Self::LeaRsp(_) => SUB_RSP_IMM32_SIZE,
            Self::MovSpFp => MOV_RBP_RSP_SIZE,
            Self::Other(n) => *n,
        }
    }
}

/// Analyze a prologue instruction sequence and produce UNWIND_INFO.
pub fn analyze_prologue(insts: &[PrologueInst]) -> Result<PrologueAnalysis, String> {
    let mut analysis = PrologueAnalysis::default();
    let mut current_offset: u8 = 0;
    let mut unwind_codes: Vec<UnwindCode> = Vec::new();
    let mut reg_push_count = 0u8;

    for &inst in insts {
        let inst_size = inst.size();

        match inst {
            PrologueInst::Push(reg) => {
                unwind_codes.push(UnwindCode::push_nonvol(current_offset, reg));
                analysis.pushed_regs.push(reg);
                reg_push_count += 1;
            }
            PrologueInst::PushImm(_) => {
                // Push of immediate; treat as small stack allocation.
                unwind_codes.push(UnwindCode::alloc_small(current_offset, 0)); // 8 bytes
                analysis.stack_size += 8;
            }
            PrologueInst::SubRsp(imm) => {
                analysis.stack_size += imm;
                let scaled = imm / 8;
                if scaled < 8 {
                    unwind_codes.push(UnwindCode::alloc_small(
                        current_offset,
                        (scaled as u8).saturating_sub(1),
                    ));
                } else if scaled <= u16::MAX as u32 {
                    unwind_codes.push(UnwindCode::alloc_large(current_offset, 0));
                    // Emit the 16-bit size in the next slot.
                    unwind_codes.push(UnwindCode::new(
                        (scaled & 0xFF) as u8,
                        UnwindOpcode::PushNonVol,
                        ((scaled >> 8) & 0xFF) as u8,
                    ));
                } else {
                    unwind_codes.push(UnwindCode::alloc_large(current_offset, 1));
                    unwind_codes.push(UnwindCode::new(
                        (scaled & 0xFF) as u8,
                        UnwindOpcode::PushNonVol,
                        ((scaled >> 8) & 0xFF) as u8,
                    ));
                    unwind_codes.push(UnwindCode::new(
                        ((scaled >> 16) & 0xFF) as u8,
                        UnwindOpcode::PushNonVol,
                        ((scaled >> 24) & 0xFF) as u8,
                    ));
                }
            }
            PrologueInst::SaveReg(reg, offset) => {
                analysis.saved_regs.push((reg, offset));
                let scaled = offset / 8;
                if offset <= 0x7FFF8 {
                    unwind_codes.push(UnwindCode::save_nonvol(current_offset, reg));
                    unwind_codes.push(UnwindCode::new(
                        (scaled & 0xFF) as u8,
                        UnwindOpcode::PushNonVol,
                        ((scaled >> 8) & 0xFF) as u8,
                    ));
                } else {
                    unwind_codes.push(UnwindCode::save_nonvol_far(current_offset, reg));
                    let word = offset;
                    unwind_codes.push(UnwindCode::new(
                        (word & 0xFF) as u8,
                        UnwindOpcode::PushNonVol,
                        ((word >> 8) & 0xFF) as u8,
                    ));
                    unwind_codes.push(UnwindCode::new(
                        ((word >> 16) & 0xFF) as u8,
                        UnwindOpcode::PushNonVol,
                        ((word >> 24) & 0xFF) as u8,
                    ));
                }
            }
            PrologueInst::SaveXmm(reg, offset) => {
                analysis.saved_xmm.push((reg, offset));
                let scaled = offset / 16;
                if offset <= 0x7FFF0 {
                    unwind_codes.push(UnwindCode::save_xmm128(current_offset, reg));
                    unwind_codes.push(UnwindCode::new(
                        (scaled & 0xFF) as u8,
                        UnwindOpcode::PushNonVol,
                        ((scaled >> 8) & 0xFF) as u8,
                    ));
                } else {
                    unwind_codes.push(UnwindCode::save_xmm128_far(current_offset, reg));
                    let word = offset;
                    unwind_codes.push(UnwindCode::new(
                        (word & 0xFF) as u8,
                        UnwindOpcode::PushNonVol,
                        ((word >> 8) & 0xFF) as u8,
                    ));
                    unwind_codes.push(UnwindCode::new(
                        ((word >> 16) & 0xFF) as u8,
                        UnwindOpcode::PushNonVol,
                        ((word >> 24) & 0xFF) as u8,
                    ));
                }
            }
            PrologueInst::SetFramePointer(reg) => {
                analysis.has_frame_pointer = true;
                analysis.frame_register = reg;
                // The offset is RSP-to-FP offset, computed from reg_pushes*8.
                let fp_offset = reg_push_count * 8;
                unwind_codes.push(UnwindCode::set_fpreg(current_offset));
                unwind_codes.push(UnwindCode::new(
                    (reg | ((fp_offset / 16) << 4)) & 0xFF,
                    UnwindOpcode::PushNonVol,
                    (((reg as u16 | ((fp_offset / 16) as u16) << 4) >> 8) & 0xFF) as u8,
                ));
            }
            PrologueInst::LeaRsp(_) | PrologueInst::MovSpFp => {
                // These are epilogue indicators; in prologue we just note them.
            }
            PrologueInst::Other(_n) => {
                // Unknown instruction; we still advance the offset.
            }
        }

        current_offset += inst_size;
    }

    // Build the final UNWIND_INFO.
    let mut info = UnwindInfo::new();
    info.prologue_size = current_offset;
    info.frame_register = analysis.frame_register;
    info.frame_register_offset = (reg_push_count * 8 / 16) as u8;

    // Unwind codes in reverse order.
    info.unwind_codes = unwind_codes.into_iter().rev().collect();
    info.count_of_codes = info
        .unwind_codes
        .iter()
        .map(|c| {
            if c.unwind_op.requires_extra_slot() {
                2
            } else {
                1
            }
        })
        .sum::<usize>() as u8;

    analysis.unwind_info = info;
    analysis.prologue_size = current_offset;

    Ok(analysis)
}

// ============================================================================
// Chained unwind info — for frames that exceed single UNWIND_INFO capacity
// ============================================================================

/// Create chained UNWIND_INFO for a function whose unwind codes don't fit.
///
/// The primary UNWIND_INFO has `chain_info` set, and the chained UNWIND_INFO
/// contains the remaining unwind codes. The RUNTIME_FUNCTION for the chained
/// part points to a separate function range (usually the same range but
/// the chained info describes the "continuation").
pub fn create_chained_unwind(
    all_codes: &[UnwindCode],
    prologue_size: u8,
    frame_reg: u8,
    frame_offset: u8,
    max_codes_per_info: usize,
) -> Result<(UnwindInfo, UnwindInfo), String> {
    if all_codes.len() <= max_codes_per_info {
        let mut info = UnwindInfo::new();
        info.prologue_size = prologue_size;
        info.frame_register = frame_reg;
        info.frame_register_offset = frame_offset;
        info.unwind_codes = all_codes.to_vec();
        info.count_of_codes = info
            .unwind_codes
            .iter()
            .map(|c| {
                if c.unwind_op.requires_extra_slot() {
                    2
                } else {
                    1
                }
            })
            .sum::<usize>() as u8;
        return Ok((info, UnwindInfo::new()));
    }

    let (primary_codes, remaining_codes) = all_codes.split_at(max_codes_per_info);

    let mut primary = UnwindInfo::new();
    primary.prologue_size = prologue_size;
    primary.frame_register = frame_reg;
    primary.frame_register_offset = frame_offset;
    primary.unwind_codes = primary_codes.to_vec();
    primary.count_of_codes = primary
        .unwind_codes
        .iter()
        .map(|c| {
            if c.unwind_op.requires_extra_slot() {
                2
            } else {
                1
            }
        })
        .sum::<usize>() as u8;

    let mut secondary = UnwindInfo::new();
    secondary.prologue_size = 0; // continuation
    secondary.frame_register = frame_reg;
    secondary.frame_register_offset = frame_offset;
    secondary.unwind_codes = remaining_codes.to_vec();
    secondary.count_of_codes = secondary
        .unwind_codes
        .iter()
        .map(|c| {
            if c.unwind_op.requires_extra_slot() {
                2
            } else {
                1
            }
        })
        .sum::<usize>() as u8;

    primary.set_chained_info(secondary.clone());

    Ok((primary, secondary))
}

// ============================================================================
// Convenience builders for common prologue patterns
// ============================================================================

/// Build UNWIND_INFO for the standard x64 SysV-like prologue:
/// ```
/// push    rbp
/// mov     rbp, rsp
/// sub     rsp, N
/// ```
pub fn build_rbp_frame_unwind(
    stack_alloc: u32,
    pushed_regs: &[u8],
    saved_xmm: &[(u8, u32)],
) -> Result<UnwindInfo, String> {
    let mut info = UnwindInfo::new();
    let mut offset: u8 = 0;

    // Push instructions (one at a time, 1 byte each for our simplified model).
    for &reg in pushed_regs {
        info.push_nonvol(offset, reg);
        offset += PUSH_REG_SIZE;
    }

    // Stack allocation.
    if stack_alloc > 0 {
        if stack_alloc < 128 {
            info.alloc_small(offset, stack_alloc)?;
        } else {
            info.alloc_large(offset, stack_alloc)?;
        }
        offset += if stack_alloc <= 127 {
            SUB_RSP_IMM8_SIZE
        } else {
            SUB_RSP_IMM32_SIZE
        };
    }

    // Save XMM registers.
    for &(reg, save_off) in saved_xmm {
        info.save_xmm128(offset, reg, save_off)?;
        offset += MOVAPS_SIZE + 2;
    }

    // Set frame pointer (default RBP).
    if !pushed_regs.is_empty() || stack_alloc > 0 {
        let fp_reg = 5u8; // RBP
        let fp_off = pushed_regs.len() as u32 * 8;
        info.set_fpreg(offset, fp_reg, fp_off)?;
        offset += MOV_RBP_RSP_SIZE;
    }

    info.prologue_size = offset;
    Ok(info)
}

/// Build UNWIND_INFO for a Win64-style prologue (no frame pointer generally).
/// ```
/// push    rbx
/// push    rsi
/// push    rdi
/// sub     rsp, N
/// movaps  [rsp+X], xmm6
/// ```
pub fn build_win64_prologue_unwind(
    stack_alloc: u32,
    pushed_regs: &[u8],
    saved_xmm: &[(u8, u32)],
) -> Result<UnwindInfo, String> {
    let mut info = UnwindInfo::new();
    let mut offset: u8 = 0;

    for &reg in pushed_regs {
        info.push_nonvol(offset, reg);
        offset += PUSH_REG_SIZE;
    }

    if stack_alloc > 0 {
        if stack_alloc < 128 {
            info.alloc_small(offset, stack_alloc)?;
        } else {
            info.alloc_large(offset, stack_alloc)?;
        }
        offset += if stack_alloc <= 127 {
            SUB_RSP_IMM8_SIZE
        } else {
            SUB_RSP_IMM32_SIZE
        };
    }

    for &(reg, save_off) in saved_xmm {
        info.save_xmm128(offset, reg, save_off)?;
        offset += MOVAPS_SIZE + 2;
    }

    info.prologue_size = offset;
    Ok(info)
}

/// Build UNWIND_INFO for a function with a machine-frame push.
pub fn build_machframe_unwind(
    has_error_code: bool,
    additional_stack: u32,
) -> Result<UnwindInfo, String> {
    let mut info = UnwindInfo::new();
    let mut offset: u8 = 0;

    info.push_machframe(offset, has_error_code);

    // Machine frame is 5*8 if no error code, 6*8 with error code.
    // But we track the offset for subsequent operations.
    if additional_stack > 0 {
        offset += if has_error_code { 6 } else { 5 };
        if additional_stack < 128 {
            info.alloc_small(offset, additional_stack)?;
        } else {
            info.alloc_large(offset, additional_stack)?;
        }
    }

    if has_error_code {
        info.prologue_size = 5 + if additional_stack > 0 {
            if additional_stack <= 127 {
                SUB_RSP_IMM8_SIZE
            } else {
                SUB_RSP_IMM32_SIZE
            }
        } else {
            0
        };
    } else {
        info.prologue_size = 4 + if additional_stack > 0 {
            if additional_stack <= 127 {
                SUB_RSP_IMM8_SIZE
            } else {
                SUB_RSP_IMM32_SIZE
            }
        } else {
            0
        };
    }

    Ok(info)
}

// ============================================================================
// 32-bit compatibility: x86 (i386) SEH structures
// ============================================================================

/// 32-bit SEH uses a frame-based exception handling model.
/// Each function that uses __try/__except has an EXCEPTION_REGISTRATION
/// record on the stack, linked via fs:[0].

/// The exception registration record (linked list node).
#[derive(Debug, Clone, Copy)]
#[repr(C)]
pub struct ExceptionRegistration32 {
    /// Pointer to the previous EXCEPTION_REGISTRATION record.
    pub prev: u32,
    /// Pointer to the exception handler.
    pub handler: u32,
}

impl ExceptionRegistration32 {
    pub const SIZE: usize = 8;

    /// Encode to bytes.
    pub fn to_bytes(&self) -> [u8; 8] {
        let mut buf = [0u8; 8];
        buf[0..4].copy_from_slice(&self.prev.to_le_bytes());
        buf[4..8].copy_from_slice(&self.handler.to_le_bytes());
        buf
    }
}

/// The exception registration for functions using C++ EH or SEH with scope tables.
#[derive(Debug, Clone)]
#[repr(C)]
pub struct ExtendedExceptionRegistration32 {
    /// Previous registration.
    pub prev: u32,
    /// Handler function.
    pub handler: u32,
    /// Scope table pointer.
    pub scope_table: u32,
    /// Try level (for nested try blocks).
    pub try_level: i32,
    /// Frame pointer (EBP).
    pub ebp: u32,
}

impl ExtendedExceptionRegistration32 {
    pub const SIZE: usize = 20;

    /// Encode to bytes.
    pub fn to_bytes(&self) -> [u8; 20] {
        let mut buf = [0u8; 20];
        buf[0..4].copy_from_slice(&self.prev.to_le_bytes());
        buf[4..8].copy_from_slice(&self.handler.to_le_bytes());
        buf[8..12].copy_from_slice(&self.scope_table.to_le_bytes());
        buf[12..16].copy_from_slice(&(self.try_level as u32).to_le_bytes());
        buf[16..20].copy_from_slice(&self.ebp.to_le_bytes());
        buf
    }
}

// ============================================================================
// Exception record structures
// ============================================================================

/// The standard Windows EXCEPTION_RECORD (simplified).
#[derive(Debug, Clone)]
#[repr(C)]
pub struct ExceptionRecord {
    /// Exception code.
    pub exception_code: u32,
    /// Exception flags.
    pub exception_flags: u32,
    /// Pointer to nested exception record.
    pub exception_record: u64,
    /// Address where the exception occurred.
    pub exception_address: u64,
    /// Number of parameters.
    pub number_parameters: u32,
    /// Additional information (15 ULONG_PTRs).
    pub exception_information: [u64; 15],
}

impl Default for ExceptionRecord {
    fn default() -> Self {
        Self {
            exception_code: 0,
            exception_flags: 0,
            exception_record: 0,
            exception_address: 0,
            number_parameters: 0,
            exception_information: [0; 15],
        }
    }
}

/// Common Windows exception codes.
pub mod exception_codes {
    /// Access violation.
    pub const EXCEPTION_ACCESS_VIOLATION: u32 = 0xC000_0005;
    /// Integer division by zero.
    pub const EXCEPTION_INT_DIVIDE_BY_ZERO: u32 = 0xC000_0094;
    /// Integer overflow.
    pub const EXCEPTION_INT_OVERFLOW: u32 = 0xC000_0095;
    /// Stack overflow.
    pub const EXCEPTION_STACK_OVERFLOW: u32 = 0xC000_00FD;
    /// Illegal instruction.
    pub const EXCEPTION_ILLEGAL_INSTRUCTION: u32 = 0xC000_001D;
    /// Breakpoint.
    pub const EXCEPTION_BREAKPOINT: u32 = 0x8000_0003;
    /// Single step.
    pub const EXCEPTION_SINGLE_STEP: u32 = 0x8000_0004;
    /// C++ EH exception.
    pub const CXX_EXCEPTION: u32 = 0xE06D_7363; // 'msc' in little-endian
    /// CLR exception.
    pub const CLR_EXCEPTION: u32 = 0xE043_4F4D;
    /// RPC exception.
    pub const RPC_S_SERVER_UNAVAILABLE: u32 = 0x006B_AAB0;
}

/// Exception flags.
pub mod exception_flags {
    /// Non-continuable exception.
    pub const EXCEPTION_NONCONTINUABLE: u32 = 0x01;
    /// Unwinding is in progress.
    pub const EXCEPTION_UNWINDING: u32 = 0x02;
    /// Exiting unwind.
    pub const EXCEPTION_EXIT_UNWIND: u32 = 0x04;
    /// Stack invalid.
    pub const EXCEPTION_STACK_INVALID: u32 = 0x08;
    /// Nested call.
    pub const EXCEPTION_NESTED_CALL: u32 = 0x10;
    /// Target unreachable.
    pub const EXCEPTION_TARGET_UNREACHABLE: u32 = 0x20;
    /// Collided unwind.
    pub const EXCEPTION_COLLIDED_UNWIND: u32 = 0x40;
}

// ============================================================================
// Dispatcher context (passed to language-specific handlers)
// ============================================================================

/// The dispatcher context passed to exception handlers.
#[derive(Debug, Clone)]
#[repr(C)]
pub struct DispatcherContext {
    /// Control PC (RIP at time of exception).
    pub control_pc: u64,
    /// Image base of the module containing the function.
    pub image_base: u64,
    /// RUNTIME_FUNCTION entry for the current function.
    pub function_entry: RuntimeFunction,
    /// Estimated establisher frame (RSP at function entry).
    pub establisher_frame: u64,
    /// Target IP for resumption.
    pub target_ip: u64,
    /// Context record pointer.
    pub context_record: u64,
    /// Language handler data (passed to handler).
    pub language_handler: u64,
    /// Handler data pointer.
    pub handler_data: u64,
    /// History table pointer.
    pub history_table: u64,
    /// Scope index.
    pub scope_index: u32,
    /// Unwind flags (passed to the handler).
    pub unwind_flags: u32,
}

impl DispatcherContext {
    /// Create a new dispatcher context.
    pub fn new() -> Self {
        Self {
            control_pc: 0,
            image_base: 0,
            function_entry: RuntimeFunction::new(0, 0, 0),
            establisher_frame: 0,
            target_ip: 0,
            context_record: 0,
            language_handler: 0,
            handler_data: 0,
            history_table: 0,
            scope_index: 0,
            unwind_flags: 0,
        }
    }
}

// ============================================================================
// RtlInstallFunctionTableCallback / RtlAddFunctionTable wrappers
// ============================================================================

/// Callback type for dynamic function table lookup.
pub type FunctionTableCallback =
    unsafe extern "system" fn(control_pc: u64, context: *mut u8) -> *mut RuntimeFunction;

/// A registered function table.
#[derive(Debug, Clone)]
pub struct FunctionTable {
    /// Table base address (image base for the callback, or RVA for static table).
    pub base_address: u64,
    /// Number of entries.
    pub entry_count: u32,
    /// Callback for dynamic tables (None = static).
    pub callback: Option<FunctionTableCallback>,
    /// Context pointer passed to the callback.
    pub context: u64,
    /// The static entries, if any.
    pub entries: Vec<RuntimeFunction>,
}

impl FunctionTable {
    /// Create a static function table.
    pub fn new_static(base: u64, entries: Vec<RuntimeFunction>) -> Self {
        let count = entries.len() as u32;
        Self {
            base_address: base,
            entry_count: count,
            callback: None,
            context: 0,
            entries,
        }
    }

    /// Create a dynamic function table.
    pub fn new_dynamic(
        base: u64,
        count: u32,
        callback: FunctionTableCallback,
        context: u64,
    ) -> Self {
        Self {
            base_address: base,
            entry_count: count,
            callback: Some(callback),
            context,
            entries: Vec::new(),
        }
    }
}

// ============================================================================
// Exception handling simulation engine
// ============================================================================

/// Simulated x64 exception dispatch.
///
/// This simulates the Windows kernel exception dispatch logic:
/// 1. VEH chain
/// 2. If unhandled, unwind the SEH chain
/// 3. Call language-specific handlers
#[derive(Debug, Clone)]
pub struct X64ExceptionDispatcher {
    /// Registry of registered function tables.
    pub function_tables: Vec<FunctionTable>,
    /// Global VEH chain.
    pub veh: VEHChain,
    /// Current exception being dispatched.
    pub current_exception: Option<ExceptionRecord>,
    /// Total exceptions dispatched.
    pub exception_count: u64,
}

impl Default for X64ExceptionDispatcher {
    fn default() -> Self {
        Self {
            function_tables: Vec::new(),
            veh: VEHChain::new(),
            current_exception: None,
            exception_count: 0,
        }
    }
}

impl X64ExceptionDispatcher {
    /// Create a new dispatcher.
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a function table.
    pub fn add_function_table(&mut self, table: FunctionTable) {
        self.function_tables.push(table);
    }

    /// Look up a RUNTIME_FUNCTION for a given control PC.
    pub fn lookup_runtime_function(&self, control_pc: u64) -> Option<&RuntimeFunction> {
        for table in &self.function_tables {
            if control_pc >= table.base_address {
                if let Some(ref callback) = table.callback {
                    let rf = unsafe { callback(control_pc, table.context as *mut u8) };
                    if !rf.is_null() {
                        return Some(unsafe { &*rf });
                    }
                } else {
                    // Search static table.
                    for entry in &table.entries {
                        let func_begin = table.base_address + entry.begin_address as u64;
                        let func_end = table.base_address + entry.end_address as u64;
                        if control_pc >= func_begin && control_pc < func_end {
                            return Some(entry);
                        }
                    }
                }
            }
        }
        None
    }

    /// Dispatch an exception.
    /// Returns true if the exception was handled.
    pub fn dispatch(&mut self, record: ExceptionRecord) -> bool {
        self.exception_count += 1;
        self.current_exception = Some(record.clone());

        // Step 1: VEH chain.
        let veh_info = &record as *const _ as *mut u8;
        self.veh.dispatch(veh_info);

        // Step 2: SEH lookup and unwind.
        let func_rf = self.lookup_runtime_function(record.exception_address);
        if func_rf.is_some() {
            // In a real dispatcher, this would call RtlVirtualUnwind and
            // walk the chain of handlers. For simulation, we mark it.
        }

        // Step 3: If still unhandled, final handler.
        // (In real Windows, this invokes the "last chance" handler.)

        false
    }

    /// Clear the current exception.
    pub fn clear_exception(&mut self) {
        self.current_exception = None;
    }

    /// Statistics.
    pub fn stats(&self) -> X64ExceptionStats {
        X64ExceptionStats {
            exception_count: self.exception_count,
            function_tables: self.function_tables.len() as u64,
            veh_handlers: self.veh.len() as u64,
        }
    }
}

/// Statistics for the exception dispatcher.
#[derive(Debug, Clone, Default)]
pub struct X64ExceptionStats {
    pub exception_count: u64,
    pub function_tables: u64,
    pub veh_handlers: u64,
}

// ============================================================================
// Tests
// ============================================================================

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

    // === UnwindCode tests ===

    #[test]
    fn test_unwind_code_encode_decode() {
        let code = UnwindCode::push_nonvol(5, 3); // RBX
        let raw = code.encode();
        let decoded = UnwindCode::decode(raw).unwrap();
        assert_eq!(decoded.code_offset, 5);
        assert_eq!(decoded.unwind_op, UnwindOpcode::PushNonVol);
        assert_eq!(decoded.op_info, 3);
    }

    #[test]
    fn test_all_opcodes_encode_decode() {
        let test_cases = vec![
            UnwindCode::push_nonvol(0, 0),
            UnwindCode::alloc_large(1, 0),
            UnwindCode::alloc_small(2, 3),
            UnwindCode::save_nonvol(3, 4),
            UnwindCode::save_nonvol_far(4, 5),
            UnwindCode::save_xmm128(5, 6),
            UnwindCode::save_xmm128_far(6, 7),
            UnwindCode::epilog(7, 8),
            UnwindCode::push_machframe(8, true),
            UnwindCode::spare(9, 42),
        ];
        for code in &test_cases {
            let raw = code.encode();
            let decoded = UnwindCode::decode(raw).unwrap();
            assert_eq!(
                decoded.code_offset, code.code_offset,
                "offset mismatch for {:?}",
                code.unwind_op
            );
            assert_eq!(decoded.unwind_op, code.unwind_op, "opcode mismatch");
            assert_eq!(
                decoded.op_info, code.op_info,
                "op_info mismatch for {:?}",
                code.unwind_op
            );
        }
    }

    #[test]
    fn test_invalid_opcode() {
        // Bits 4-7 = 15 is invalid.
        let raw: u16 = 0x00F0;
        assert!(UnwindCode::decode(raw).is_none());
    }

    #[test]
    fn test_display() {
        let code = UnwindCode::push_nonvol(5, 3);
        let s = format!("{code}");
        assert!(s.contains("UWOP_PUSH_NONVOL"));
        assert!(s.contains("0x5"));
    }

    // === UnwindInfo tests ===

    #[test]
    fn test_unwind_info_default() {
        let info = UnwindInfo::default();
        assert_eq!(info.version, 1);
        assert_eq!(info.flags, 0);
        assert_eq!(info.prologue_size, 0);
        assert_eq!(info.count_of_codes, 0);
        assert!(info.unwind_codes.is_empty());
        assert!(info.exception_handler.is_none());
    }

    #[test]
    fn test_unwind_info_push_nonvol() {
        let mut info = UnwindInfo::new();
        info.push_nonvol(0, 5); // push rbp
        assert_eq!(info.unwind_codes.len(), 1);
    }

    #[test]
    fn test_unwind_info_alloc_small() {
        let mut info = UnwindInfo::new();
        info.alloc_small(1, 16).unwrap();
        assert_eq!(info.unwind_codes.len(), 1);
        assert_eq!(info.unwind_codes[0].unwind_op, UnwindOpcode::AllocSmall);
        assert_eq!(info.unwind_codes[0].op_info, 1); // 16/8 - 1 = 1
    }

    #[test]
    fn test_unwind_info_alloc_small_invalid() {
        let mut info = UnwindInfo::new();
        assert!(info.alloc_small(1, 72).is_err()); // > 64
        assert!(info.alloc_small(1, 0).is_err()); // zero
        assert!(info.alloc_small(1, 3).is_err()); // not multiple of 8
    }

    #[test]
    fn test_unwind_info_alloc_large() {
        let mut info = UnwindInfo::new();
        info.alloc_large(2, 1024).unwrap();
        assert_eq!(info.unwind_codes.len(), 2); // opcode + size slot
        assert_eq!(info.unwind_codes[0].unwind_op, UnwindOpcode::AllocLarge);
    }

    #[test]
    fn test_unwind_info_set_fpreg() {
        let mut info = UnwindInfo::new();
        info.push_nonvol(0, 5); // push rbp
        info.set_fpreg(1, 5, 16).unwrap();
        assert_eq!(info.frame_register, 5);
        assert_eq!(info.frame_register_offset, 1); // 16/16 = 1
        assert_eq!(info.unwind_codes.len(), 2); // opcode + extra slot
    }

    #[test]
    fn test_unwind_info_save_nonvol() {
        let mut info = UnwindInfo::new();
        info.save_nonvol(3, 3, 64).unwrap(); // save rbx at offset 64
        assert_eq!(info.unwind_codes.len(), 2); // opcode + offset slot
    }

    #[test]
    fn test_unwind_info_save_nonvol_far() {
        let mut info = UnwindInfo::new();
        // Offset too large for 16-bit => uses SAVE_NONVOL_FAR.
        info.save_nonvol(3, 3, 0x10000).unwrap();
        assert_eq!(info.unwind_codes[0].unwind_op, UnwindOpcode::SaveNonVolFar);
        assert_eq!(info.unwind_codes.len(), 3); // opcode + 2 offset slots
    }

    #[test]
    fn test_unwind_info_save_xmm128() {
        let mut info = UnwindInfo::new();
        info.save_xmm128(4, 6, 32).unwrap(); // save xmm6 at offset 32
        assert_eq!(info.unwind_codes.len(), 2);
    }

    #[test]
    fn test_unwind_info_exception_handler() {
        let mut info = UnwindInfo::new();
        info.set_exception_handler(0x1234, vec![1, 2, 3, 4]);
        assert!(info.exception_handler.is_some());
        assert_eq!(
            info.flags & unwind_flags::UNW_FLAG_EHANDLER,
            unwind_flags::UNW_FLAG_EHANDLER
        );
        assert_eq!(info.handler_data, vec![1, 2, 3, 4]);
    }

    #[test]
    fn test_unwind_info_chained() {
        let mut primary = UnwindInfo::new();
        primary.push_nonvol(0, 5);
        let secondary = UnwindInfo::new();
        primary.set_chained_info(secondary);
        assert!(primary.chained_info.is_some());
        assert_eq!(
            primary.flags & unwind_flags::UNW_FLAG_CHAININFO,
            unwind_flags::UNW_FLAG_CHAININFO
        );
    }

    #[test]
    fn test_unwind_info_encode_header() {
        let mut info = UnwindInfo::new();
        info.version = 1;
        info.flags = unwind_flags::UNW_FLAG_EHANDLER;
        info.prologue_size = 10;
        info.count_of_codes = 3;
        info.frame_register = 5;
        info.frame_register_offset = 1;

        let header = info.encode_header();
        assert_eq!(header[0], 0x01 | (0x01 << 3)); // version=1, flags=0x01
        assert_eq!(header[1], 10);
        assert_eq!(header[2], 3);
        assert_eq!(header[3], 5 | (1 << 4));
    }

    #[test]
    fn test_unwind_info_encoded_size() {
        let mut info = UnwindInfo::new();
        info.push_nonvol(0, 5);
        info.alloc_small(1, 16).unwrap();

        let size = info.encoded_size();
        // Header (4) + 2 codes * 2 bytes = 8, aligned to 4 = 8.
        assert_eq!(size, 8);

        info.set_exception_handler(0x1000, vec![1, 2]);
        let size_with_handler = info.encoded_size();
        // 4 + 4 + 4 (handler rva) + 2 (data) = 14, aligned to 4 = 16.
        assert_eq!(size_with_handler, 16);
    }

    #[test]
    fn test_unwind_info_encode_to_bytes() {
        let mut info = UnwindInfo::new();
        info.version = 1;
        info.push_nonvol(0, 5);
        info.alloc_small(1, 8).unwrap();

        let bytes = info.encode_to_bytes();
        assert_eq!(bytes.len(), 8);
        // Check header.
        assert_eq!(bytes[0], 0x01); // version=1, flags=0
        assert_eq!(bytes[1], 0); // prologue_size
        assert_eq!(bytes[2], 2); // count_of_codes = 2 slots
    }

    // === RuntimeFunction tests ===

    #[test]
    fn test_runtime_function_encode_decode() {
        let rf = RuntimeFunction::new(0x1000, 0x1100, 0x2000);
        let bytes = rf.encode_to_bytes();

        let decoded = RuntimeFunction::decode_from_bytes(&bytes);
        assert_eq!(decoded.begin_address, 0x1000);
        assert_eq!(decoded.end_address, 0x1100);
        assert_eq!(decoded.unwind_info_address, 0x2000);
    }

    #[test]
    fn test_runtime_function_display() {
        let rf = RuntimeFunction::new(0x1000, 0x1100, 0x2000);
        let s = format!("{rf}");
        assert!(s.contains("RUNTIME_FUNCTION"));
        assert!(s.contains("0x00001000"));
    }

    // === PdataBuilder tests ===

    #[test]
    fn test_pdata_add_and_find() {
        let mut pdata = PdataBuilder::new();
        pdata.add_function(0x1000, 0x1100, 0x2000).unwrap();
        pdata.add_function(0x2000, 0x2100, 0x3000).unwrap();

        let rf = pdata.find(0x1050).unwrap();
        assert_eq!(rf.begin_address, 0x1000);

        let rf2 = pdata.find(0x2050).unwrap();
        assert_eq!(rf2.begin_address, 0x2000);

        assert!(pdata.find(0x500).is_none());
        assert!(pdata.find(0x3000).is_none());
    }

    #[test]
    fn test_pdata_detect_overlap() {
        let mut pdata = PdataBuilder::new();
        pdata.add_function(0x1000, 0x1100, 0x2000).unwrap();
        // Overlapping range should still be accepted (chained info use case).
        pdata.add_function(0x1080, 0x1180, 0x2008).unwrap();
        assert_eq!(pdata.len(), 2);
    }

    #[test]
    fn test_pdata_encode_bytes() {
        let mut pdata = PdataBuilder::new();
        pdata.add_function(0x2000, 0x2100, 0x3000).unwrap();
        pdata.add_function(0x1000, 0x1100, 0x2000).unwrap();

        let bytes = pdata.encode_to_bytes();
        assert_eq!(bytes.len(), 24); // 2 * 12

        // Should be sorted by begin_address.
        let first_begin = u32::from_le_bytes(bytes[0..4].try_into().unwrap());
        assert_eq!(first_begin, 0x1000);
    }

    // === XdataBuilder tests ===

    #[test]
    fn test_xdata_add_and_encode() {
        let mut xdata = XdataBuilder::new();
        let mut info = UnwindInfo::new();
        info.push_nonvol(0, 5);
        let rva1 = xdata.add_unwind_info(info);

        let mut info2 = UnwindInfo::new();
        info2.push_nonvol(0, 3);
        let rva2 = xdata.add_unwind_info(info2);

        assert_eq!(rva1, 0);
        assert_ne!(rva2, 0); // Second entry gets a non-zero RVA.
        assert_eq!(xdata.len(), 2);

        let bytes = xdata.encode_to_bytes();
        assert!(!bytes.is_empty());
    }

    // === CScopeTable tests ===

    #[test]
    fn test_c_scope_table_encode() {
        let mut table = CScopeTable::new();
        table.add_scope(0x100, 0x200, 0x300, 0x400, 0x500);
        table.add_scope(0x600, 0x700, 0x800, 0x900, 0xA00);

        let bytes = table.encode();
        // 4 (count) + 2 * 20 = 44 bytes.
        assert_eq!(bytes.len(), 44);

        let count = u32::from_le_bytes(bytes[0..4].try_into().unwrap());
        assert_eq!(count, 2);
    }

    // === CppFuncInfo tests ===

    #[test]
    fn test_cpp_func_info_default_magic() {
        let info = CppFuncInfo::default();
        assert_eq!(info.magic, 0x1993_0522);
        assert_eq!(info.eh_flags, 1);
    }

    #[test]
    fn test_cpp_func_info_encode() {
        let info = CppFuncInfo::new();
        let bytes = info.encode_to_bytes();
        // Header is 9 DWORDs = 36 bytes.
        assert_eq!(bytes.len(), 36);

        let magic = u32::from_le_bytes(bytes[0..4].try_into().unwrap());
        assert_eq!(magic, 0x1993_0522);
    }

    #[test]
    fn test_build_simple_func_info() {
        let info = X86Win64EH::build_simple_func_info(0x10, 0x50, 0x200, 0x300);
        assert_eq!(info.max_state, 1);
        assert_eq!(info.try_blocks.len(), 1);
        assert_eq!(info.ip_to_state_map.len(), 2);
    }

    #[test]
    fn test_build_nested_func_info() {
        let regions = vec![(0x10, 0x20, 0x100, 0x200), (0x30, 0x40, 0x300, 0x400)];
        let info = X86Win64EH::build_nested_func_info(&regions);
        assert_eq!(info.max_state, 2);
        assert_eq!(info.try_blocks.len(), 2);
    }

    // === Prologue analysis tests ===

    #[test]
    fn test_analyze_prologue_push_rbp_sub_rsp() {
        let insts = vec![
            PrologueInst::Push(5),            // push rbp
            PrologueInst::SetFramePointer(5), // mov rbp, rsp
            PrologueInst::SubRsp(32),         // sub rsp, 32
        ];
        let analysis = analyze_prologue(&insts).unwrap();
        assert!(analysis.has_frame_pointer);
        assert_eq!(analysis.frame_register, 5);
        assert_eq!(analysis.pushed_regs.len(), 1);
        assert_eq!(analysis.stack_size, 32);
    }

    #[test]
    fn test_analyze_prologue_save_xmm() {
        let insts = vec![
            PrologueInst::Push(3),        // push rbx
            PrologueInst::SubRsp(128),    // sub rsp, 128
            PrologueInst::SaveXmm(6, 16), // movaps [rsp+16], xmm6
            PrologueInst::SaveXmm(7, 32), // movaps [rsp+32], xmm7
        ];
        let analysis = analyze_prologue(&insts).unwrap();
        assert_eq!(analysis.saved_xmm.len(), 2);
        assert_eq!(analysis.saved_xmm[0], (6, 16));
        assert_eq!(analysis.saved_xmm[1], (7, 32));
    }

    // === Chained unwind tests ===

    #[test]
    fn test_create_chained_unwind_fits() {
        let codes: Vec<UnwindCode> = (0..5).map(|i| UnwindCode::push_nonvol(i, i)).collect();
        let (primary, secondary) = create_chained_unwind(&codes, 20, 5, 1, 10).unwrap();
        assert_eq!(primary.unwind_codes.len(), 5);
        assert!(primary.chained_info.is_none());
        // Secondary should be empty.
        assert!(secondary.unwind_codes.is_empty());
    }

    #[test]
    fn test_create_chained_unwind_overflow() {
        let codes: Vec<UnwindCode> = (0..15)
            .map(|i| UnwindCode::push_nonvol(i % 256, i))
            .collect();
        let (primary, secondary) = create_chained_unwind(&codes, 40, 5, 1, 10).unwrap();
        assert_eq!(primary.unwind_codes.len(), 10);
        assert_eq!(secondary.unwind_codes.len(), 5);
        assert!(primary.chained_info.is_some());
    }

    // === Build standard prologues ===

    #[test]
    fn test_build_rbp_frame() {
        let info = build_rbp_frame_unwind(32, &[5], &[]).unwrap();
        assert_eq!(info.frame_register, 5); // RBP
        assert!(!info.unwind_codes.is_empty());
    }

    #[test]
    fn test_build_win64_prologue() {
        let info = build_win64_prologue_unwind(64, &[3, 6], &[(6, 16)]).unwrap();
        assert!(info.unwind_codes.len() >= 3);
    }

    #[test]
    fn test_build_machframe() {
        let info = build_machframe_unwind(true, 0).unwrap();
        assert!(!info.unwind_codes.is_empty());
        assert_eq!(info.unwind_codes[0].unwind_op, UnwindOpcode::PushMachFrame);
    }

    // === X86Win64EH tests ===

    #[test]
    fn test_win64eh_register_function() {
        let mut eh = X86Win64EH::new();
        let mut info = UnwindInfo::new();
        info.push_nonvol(0, 5);

        let idx = eh.register_function(0x1000, 0x1100, info).unwrap();
        assert_eq!(idx, 0);
        assert_eq!(eh.pdata.len(), 1);
        assert_eq!(eh.xdata.len(), 1);

        let rf = eh.find_function(0x1050).unwrap();
        assert_eq!(rf.begin_address, 0x1000);
    }

    #[test]
    fn test_win64eh_register_chained() {
        let mut eh = X86Win64EH::new();
        let mut primary = UnwindInfo::new();
        primary.push_nonvol(0, 5);
        let secondary = UnwindInfo::new();

        let idx = eh
            .register_chained_function(0x1000, 0x1100, primary, secondary)
            .unwrap();
        assert_eq!(idx, 0);

        let found = eh.find_unwind_info(0x1000).unwrap();
        assert!(found.chained_info.is_some());
    }

    #[test]
    fn test_win64eh_register_c_handler() {
        let mut eh = X86Win64EH::new();
        let scope = X86Win64EH::create_c_scope_table(&[(0x10, 0x20, 0x100, 0x200, 0x300)]);

        let prologue: Vec<(u8, UnwindOpcode, u8)> = vec![(0, UnwindOpcode::PushNonVol, 5)];
        let idx = eh
            .register_c_handler(0x1000, 0x1100, 0x2000, &scope, &prologue, 1, 5, 1)
            .unwrap();
        assert_eq!(idx, 0);
    }

    #[test]
    fn test_win64eh_veh_chain() {
        let mut eh = X86Win64EH::new();
        let id = eh.add_veh_handler(veh_continue_search as VEHHandlerFn, true);
        assert_eq!(eh.veh_chain.len(), 1);
        assert!(eh.remove_veh_handler(id));
        assert_eq!(eh.veh_chain.len(), 0);
    }

    #[test]
    fn test_win64eh_encode_pdata_empty() {
        let eh = X86Win64EH::new();
        let bytes = eh.encode_pdata();
        assert!(bytes.is_empty());
    }

    #[test]
    fn test_win64eh_encode_pdata_with_function() {
        let mut eh = X86Win64EH::new();
        let mut info = UnwindInfo::new();
        info.push_nonvol(0, 5);
        eh.register_function(0x1000, 0x1100, info).unwrap();

        let bytes = eh.encode_pdata();
        assert_eq!(bytes.len(), 12);
    }

    // === VEH tests ===

    #[test]
    fn test_veh_chain_add_remove() {
        let mut chain = VEHChain::new();
        let id1 = chain.add_handler(veh_continue_search as VEHHandlerFn, true);
        let id2 = chain.add_handler(veh_continue_search as VEHHandlerFn, false);
        assert_eq!(chain.len(), 2);

        // id1 was inserted first but with first=true, so it's at index 0.
        assert!(chain.remove_handler(id1));
        assert_eq!(chain.len(), 1);
        assert!(!chain.remove_handler(id1)); // Already removed.
    }

    #[test]
    fn test_veh_chain_dispatch() {
        let chain = VEHChain::new();
        // Empty chain should return CONTINUE_SEARCH.
        let result = chain.dispatch(std::ptr::null_mut());
        assert_eq!(result, seh_result::EXCEPTION_CONTINUE_SEARCH);
    }

    // === ExceptionRecord tests ===

    #[test]
    fn test_exception_record_default() {
        let rec = ExceptionRecord::default();
        assert_eq!(rec.exception_code, 0);
        assert_eq!(rec.number_parameters, 0);
    }

    // === PrologueInst size computation ===

    #[test]
    fn test_prologue_inst_sizes() {
        assert_eq!(PrologueInst::Push(5).size(), PUSH_REG_SIZE);
        assert_eq!(PrologueInst::SubRsp(32).size(), SUB_RSP_IMM8_SIZE);
        assert_eq!(PrologueInst::SubRsp(0x1000).size(), SUB_RSP_IMM32_SIZE);
        assert_eq!(PrologueInst::SetFramePointer(5).size(), MOV_RBP_RSP_SIZE);
    }

    // === FunctionTable tests ===

    #[test]
    fn test_function_table_static() {
        let entries = vec![RuntimeFunction::new(0x100, 0x200, 0x300)];
        let table = FunctionTable::new_static(0x1000, entries);
        assert_eq!(table.entry_count, 1);
        assert!(table.callback.is_none());
    }

    unsafe extern "system" fn dyn_table_callback(
        _control_pc: u64,
        _ctx: *mut u8,
    ) -> *mut RuntimeFunction {
        std::ptr::null_mut()
    }

    #[test]
    fn test_function_table_dynamic() {
        let table =
            FunctionTable::new_dynamic(0x1000, 10, dyn_table_callback as FunctionTableCallback, 0);
        assert_eq!(table.entry_count, 10);
        assert!(table.callback.is_some());
    }

    // === Exception dispatcher tests ===

    #[test]
    fn test_dispatcher_lookup_static() {
        let mut disp = X64ExceptionDispatcher::new();
        let entries = vec![RuntimeFunction::new(0x100, 0x200, 0x300)];
        let table = FunctionTable::new_static(0x1000, entries);
        disp.add_function_table(table);

        let rf = disp.lookup_runtime_function(0x1100);
        assert!(rf.is_some());
        assert_eq!(rf.unwrap().begin_address, 0x100);

        let rf2 = disp.lookup_runtime_function(0x900);
        assert!(rf2.is_none());
    }

    #[test]
    fn test_dispatcher_dispatch() {
        let mut disp = X64ExceptionDispatcher::new();
        let rec = ExceptionRecord::default();
        let result = disp.dispatch(rec);
        // No handlers registered => unhandled.
        assert!(!result);
        assert_eq!(disp.exception_count, 1);
    }

    // === Build standard unwind info ===

    #[test]
    fn test_build_standard_unwind_info() {
        let ops: Vec<(u8, UnwindOpcode, u8)> = vec![
            (0, UnwindOpcode::PushNonVol, 5),
            (1, UnwindOpcode::AllocSmall, 1),
        ];
        let info = X86Win64EH::build_standard_unwind_info(&ops, 5, 5, 1, Some(0x1000));
        assert_eq!(info.prologue_size, 5);
        assert_eq!(info.frame_register, 5);
        assert!(info.exception_handler.is_some());
    }

    // === 32-bit SEH structure tests ===

    #[test]
    fn test_exception_registration_32_encode() {
        let reg = ExceptionRegistration32 {
            prev: 0xFFFFFFFF,
            handler: 0x1000,
        };
        let bytes = reg.to_bytes();
        assert_eq!(bytes.len(), 8);
        let prev = u32::from_le_bytes(bytes[0..4].try_into().unwrap());
        assert_eq!(prev, 0xFFFFFFFF);
    }

    #[test]
    fn test_extended_exception_registration_32_encode() {
        let reg = ExtendedExceptionRegistration32 {
            prev: 0xFFFFFFFF,
            handler: 0x1000,
            scope_table: 0x2000,
            try_level: -1,
            ebp: 0x3000,
        };
        let bytes = reg.to_bytes();
        assert_eq!(bytes.len(), 20);
    }

    // === Exception flags tests ===

    #[test]
    fn test_exception_codes_constants() {
        assert_eq!(exception_codes::EXCEPTION_ACCESS_VIOLATION, 0xC000_0005);
        assert_eq!(exception_codes::CXX_EXCEPTION, 0xE06D_7363);
    }

    // === DispatcherContext tests ===

    #[test]
    fn test_dispatcher_context_new() {
        let ctx = DispatcherContext::new();
        assert_eq!(ctx.control_pc, 0);
        assert_eq!(ctx.scope_index, 0);
    }

    // === X64ExceptionStats tests ===

    #[test]
    fn test_dispatcher_stats() {
        let disp = X64ExceptionDispatcher::new();
        let stats = disp.stats();
        assert_eq!(stats.exception_count, 0);
        assert_eq!(stats.function_tables, 0);
    }

    // === create_c_scope_table test ===

    #[test]
    fn test_create_c_scope_table() {
        let table = X86Win64EH::create_c_scope_table(&[(0x10, 0x20, 0x100, 0x200, 0x300)]);
        assert_eq!(table.len(), 1);
    }

    // === UnwindCode extra_slot tests ===

    #[test]
    fn test_requires_extra_slot() {
        assert!(UnwindOpcode::AllocLarge.requires_extra_slot());
        assert!(UnwindOpcode::SaveNonVolFar.requires_extra_slot());
        assert!(UnwindOpcode::SaveXmm128Far.requires_extra_slot());
        assert!(UnwindOpcode::SetFpReg.requires_extra_slot());
        assert!(!UnwindOpcode::PushNonVol.requires_extra_slot());
        assert!(!UnwindOpcode::AllocSmall.requires_extra_slot());
        assert!(!UnwindOpcode::SaveNonVol.requires_extra_slot());
        assert!(!UnwindOpcode::SaveXmm128.requires_extra_slot());
        assert!(!UnwindOpcode::Epilog.requires_extra_slot());
        assert!(!UnwindOpcode::PushMachFrame.requires_extra_slot());
    }

    // === Edge case: alloc_small at limits ===

    #[test]
    fn test_alloc_small_min_and_max() {
        let mut info = UnwindInfo::new();
        // 8 bytes => scaled = 1, op_info = 0.
        info.alloc_small(0, 8).unwrap();
        assert_eq!(info.unwind_codes[0].op_info, 0);

        let mut info2 = UnwindInfo::new();
        // 64 bytes => scaled = 8, op_info = 7.
        info2.alloc_small(0, 64).unwrap();
        assert_eq!(info2.unwind_codes[0].op_info, 7);
    }

    // === Edge case: version 2 epilog ===

    #[test]
    fn test_version2_epilog() {
        let mut info = UnwindInfo::new_v2();
        assert_eq!(info.version, 2);
        info.add_epilog(10, 5).unwrap();
        assert_eq!(info.unwind_codes[0].unwind_op, UnwindOpcode::Epilog);
    }

    #[test]
    fn test_version1_epilog_rejected() {
        let mut info = UnwindInfo::new();
        assert!(info.add_epilog(10, 5).is_err());
    }

    // === Edge case: invalid function range ===

    #[test]
    fn test_pdata_invalid_range() {
        let mut pdata = PdataBuilder::new();
        assert!(pdata.add_function(0x2000, 0x1000, 0x3000).is_err());
        assert!(pdata.add_function(0x1000, 0x1000, 0x3000).is_err());
    }

    // === Stress: many unwind codes ===

    #[test]
    fn test_many_unwind_codes() {
        let mut info = UnwindInfo::new();
        for i in 0..20 {
            info.push_nonvol(i, (i % 8) as u8);
        }
        assert_eq!(info.unwind_codes.len(), 20);
        let bytes = info.encode_to_bytes();
        assert!(!bytes.is_empty());
    }

    // === Stress: deeply chained info ===

    #[test]
    fn test_deeply_chained_unwind() {
        let mut level3 = UnwindInfo::new();
        level3.push_nonvol(0, 12);

        let mut level2 = UnwindInfo::new();
        level2.push_nonvol(0, 13);
        level2.set_chained_info(level3);

        let mut level1 = UnwindInfo::new();
        level1.push_nonvol(0, 14);
        level1.set_chained_info(level2);

        let size = level1.encoded_size();
        assert!(size > 8); // Should be larger than one entry.

        let bytes = level1.encode_to_bytes();
        assert!(!bytes.is_empty());
    }
}

// ============================================================================
// Test helper extern functions for VEH simulation
// ============================================================================

unsafe extern "system" fn veh_continue_search(_info: *mut u8) -> i32 {
    seh_result::EXCEPTION_CONTINUE_SEARCH
}