rsleigh-decompile 0.4.2

P-code decompiler — turns rsleigh P-code IR into C-like pseudocode
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
//! Taint-flow CVE explorer (SMT M1).
//!
//! Configures attacker-controlled `Source` APIs and dangerous `Sink`
//! APIs, walks straight-line SSA paths from a Source's tainted output
//! to a Sink's watched argument, and asks Z3 whether attacker-supplied
//! bytes can drive the watched value into a CVE-class state (over-long
//! buffer, format-string char, command separator, etc.).
//!
//! This module owns the spec tables, call-name resolution, and the
//! straight-line SSA path collector. The Z3-driven SAT prover lands
//! in commit 4 per
//! `.opt/campaigns/smt-backend-implementation-plan.md`.

use std::collections::HashMap;

use crate::ir::{CallTarget, SsaCfg, SsaTerminator, Stmt, VarId};

/// One slot in the platform calling convention. M1 only needs to
/// describe the slots used by the source/sink configurations below;
/// fuller ABI coverage (variadic, return registers, x87 stack, NEON)
/// is deferred.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AbiSlot {
    /// Argument in register N (zero-indexed, e.g. RDI=0 on x86-64
    /// SystemV, X0=0 on AArch64 AAPCS, $a0=0 on MIPS o32).
    Arg(u8),
    /// Return value (typically RAX/X0/v0).
    Ret,
    /// v5.W2.D2a: a global RAM address (or a global pointer slot
    /// whose contents alias to a buffer). Used by inter-procedural
    /// summary propagation to bridge a callee's `recv(_, GLOBAL,
    /// _, _)` source to a peer's `strcpy(_, GLOBAL)` sink without
    /// requiring the buffer to flow through the caller's arg
    /// registers (which it almost never does in real router code).
    Global(u64),
}

/// What kind of CVE-class violation the sink exposes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SinkKind {
    /// `dst` is a stack-resident buffer; tainted source overflowing
    /// it is a stack BOF (strcpy/strcat/sprintf/gets-class).
    StackBuffer,
    /// `arg0` is a printf-family format string — `%n`/`%s`/`%x`
    /// substrings produce read/write primitives.
    FormatArg,
    /// Single string argument runs through a shell (system/popen)
    /// or exec*() — `;`/`&&`/`|` enables command injection.
    Command,
    /// Length operand of a bounded copy (memcpy/strncpy/memmove);
    /// SAT when the tainted length can exceed the dst capacity.
    LengthArg,
    /// v9: synthetic sink for compiler-emitted store loops (the
    /// extract_name / parser pattern: `*dst++ = byte_from_taint`).
    /// No libc API is involved — the store is raw SSA. SAT modeling
    /// is deferred (v10); v9 surfaces these in the candidate dump
    /// for LLM triage with verdict Unsupported.
    TaintedStore,
    /// Unbounded C-string readers (`strlen`, `strcmp`, `strchr`,
    /// etc.) scan memory until a NUL byte. When fed a non-terminated
    /// attacker-controlled packet buffer, they are an OOB-read class
    /// primitive common in protocol parser CVEs.
    CStringRead,
}

/// Attacker-controlled API. The function returns or fills a buffer
/// whose contents are byte-for-byte controlled.
#[derive(Debug, Clone, Copy)]
pub struct SourceSpec {
    /// libc / kernel-style API name, e.g. `"recv"`, `"read"`, `"argv"`.
    /// `"argv"` is treated specially — it isn't a function call,
    /// it's the second argument to `main`, and the path collector
    /// will need to recognise that.
    pub name: &'static str,
    /// The slot whose contents become tainted when the call returns.
    /// `Ret` for `gets`-class returns; `Arg(N)` for fill-buffer APIs
    /// like `recv(sock, BUF, len, flags)` where N=1.
    pub tainted: AbiSlot,
}

/// Dangerous API. Tainted data reaching `watched` produces a
/// CVE-class outcome of the configured `kind`.
#[derive(Debug, Clone, Copy)]
pub struct SinkSpec {
    pub name: &'static str,
    /// The argument slot whose taint we test for the SAT proof.
    pub watched: AbiSlot,
    pub kind: SinkKind,
}

/// Default attacker-controlled APIs. M1 covers the canonical libc
/// network/IO surface plus `argv`. Aliases (e.g. checked wrappers
/// `__recv_chk`) are deferred.
pub const DEFAULT_SOURCES: &[SourceSpec] = &[
    SourceSpec { name: "recv",       tainted: AbiSlot::Arg(1) },
    SourceSpec { name: "recvfrom",   tainted: AbiSlot::Arg(1) },
    SourceSpec { name: "recvmsg",    tainted: AbiSlot::Arg(1) },
    SourceSpec { name: "read",       tainted: AbiSlot::Arg(1) },
    SourceSpec { name: "fread",      tainted: AbiSlot::Arg(0) },
    SourceSpec { name: "fgets",      tainted: AbiSlot::Arg(0) },
    SourceSpec { name: "gets",       tainted: AbiSlot::Arg(0) },
    SourceSpec { name: "scanf",      tainted: AbiSlot::Arg(1) },
    SourceSpec { name: "sscanf",     tainted: AbiSlot::Arg(2) },
    SourceSpec { name: "fscanf",     tainted: AbiSlot::Arg(2) },
    SourceSpec { name: "getenv",     tainted: AbiSlot::Ret    },
    // `argv` is a marker — the path collector recognises it as
    // "second arg of main" rather than a function call.
    SourceSpec { name: "argv",       tainted: AbiSlot::Arg(1) },
];

/// Default dangerous APIs. M1 covers the canonical libc CVE class
/// surface. Bounded-copy primitives whose length argument is the
/// CVE primitive use `LengthArg`; everything else watches the
/// primary string slot.
pub const DEFAULT_SINKS: &[SinkSpec] = &[
    SinkSpec { name: "strcpy",  watched: AbiSlot::Arg(1), kind: SinkKind::StackBuffer },
    SinkSpec { name: "strcat",  watched: AbiSlot::Arg(1), kind: SinkKind::StackBuffer },
    SinkSpec { name: "sprintf", watched: AbiSlot::Arg(1), kind: SinkKind::FormatArg   },
    SinkSpec { name: "vsprintf",watched: AbiSlot::Arg(1), kind: SinkKind::FormatArg   },
    SinkSpec { name: "printf",  watched: AbiSlot::Arg(0), kind: SinkKind::FormatArg   },
    SinkSpec { name: "fprintf", watched: AbiSlot::Arg(1), kind: SinkKind::FormatArg   },
    SinkSpec { name: "memcpy",  watched: AbiSlot::Arg(2), kind: SinkKind::LengthArg   },
    SinkSpec { name: "memmove", watched: AbiSlot::Arg(2), kind: SinkKind::LengthArg   },
    SinkSpec { name: "strncpy", watched: AbiSlot::Arg(2), kind: SinkKind::LengthArg   },
    SinkSpec { name: "strncat", watched: AbiSlot::Arg(2), kind: SinkKind::LengthArg   },
    SinkSpec { name: "system",  watched: AbiSlot::Arg(0), kind: SinkKind::Command     },
    SinkSpec { name: "popen",   watched: AbiSlot::Arg(0), kind: SinkKind::Command     },
    SinkSpec { name: "execve",  watched: AbiSlot::Arg(0), kind: SinkKind::Command     },
    SinkSpec { name: "execlp",  watched: AbiSlot::Arg(0), kind: SinkKind::Command     },
    SinkSpec { name: "execvp",  watched: AbiSlot::Arg(0), kind: SinkKind::Command     },
    SinkSpec { name: "strlen",  watched: AbiSlot::Arg(0), kind: SinkKind::CStringRead },
    SinkSpec { name: "strnlen", watched: AbiSlot::Arg(0), kind: SinkKind::CStringRead },
    SinkSpec { name: "strcmp",  watched: AbiSlot::Arg(0), kind: SinkKind::CStringRead },
    SinkSpec { name: "strncmp", watched: AbiSlot::Arg(0), kind: SinkKind::CStringRead },
    SinkSpec { name: "strcasecmp",  watched: AbiSlot::Arg(0), kind: SinkKind::CStringRead },
    SinkSpec { name: "strncasecmp", watched: AbiSlot::Arg(0), kind: SinkKind::CStringRead },
    SinkSpec { name: "strchr",  watched: AbiSlot::Arg(0), kind: SinkKind::CStringRead },
    SinkSpec { name: "strrchr", watched: AbiSlot::Arg(0), kind: SinkKind::CStringRead },
    SinkSpec { name: "strstr",  watched: AbiSlot::Arg(0), kind: SinkKind::CStringRead },
    SinkSpec { name: "strcasestr", watched: AbiSlot::Arg(0), kind: SinkKind::CStringRead },
];

/// v9: synthetic sink spec for compiler-emitted Store loops. Used
/// only by `build_function_summary` when it detects a function
/// that writes from a Param-region pointer into another Param-
/// region pointer (the "copy_until_zero" / extract_name pattern).
///
/// v10: `watched: Arg(0)` is the SRC-pointer slot — the parameter
/// whose buffer contents flow into the destination. The lineage
/// walker checks taint flow from the source to this slot in the
/// caller; the dst-is-param precondition is enforced at detection
/// time, not at solve time.
pub const STORE_SINK_SPEC: SinkSpec = SinkSpec {
    name: "<tainted_store>",
    watched: AbiSlot::Arg(0),
    kind: SinkKind::TaintedStore,
};

/// Resolve a call-target address against the import map. Returns
/// `Some(SpecRef)` when the target matches one of the configured
/// sources or sinks.
///
/// Name normalisation: ELF/Mach-O often expose stub names with a
/// leading `_` or `__` and PLT names with an `@plt` suffix; strip
/// both before matching. Demangled C++ names that happen to overlap
/// with libc identifiers are out of scope (M1 is libc-targeted).
pub fn resolve_call(
    target_addr: u64,
    imports: &HashMap<u64, String>,
) -> Option<SpecRef> {
    let raw = imports.get(&target_addr)?;
    let normalised = normalise_name(raw);
    if let Some(spec) = DEFAULT_SOURCES.iter().find(|s| s.name == normalised) {
        return Some(SpecRef::Source(*spec));
    }
    if let Some(spec) = DEFAULT_SINKS.iter().find(|s| s.name == normalised) {
        return Some(SpecRef::Sink(*spec));
    }
    None
}

/// Result of `resolve_call`. Either a Source whose return/output
/// taints memory, or a Sink whose watched arg we follow.
#[derive(Debug, Clone, Copy)]
pub enum SpecRef {
    Source(SourceSpec),
    Sink(SinkSpec),
}

fn normalise_name(raw: &str) -> &str {
    // Strip a `@plt`/`@@VERSION` suffix.
    let stripped = raw.split('@').next().unwrap_or(raw);
    // Strip leading underscores (Mach-O `_recv`, glibc internal
    // `__recv`, etc.).
    let unprefixed = stripped.trim_start_matches('_');
    // v2.V10: collapse fortify-source `*_chk` checked variants to
    // their canonical name (Mach-O exposes `___strcpy_chk` for
    // strcpy under -D_FORTIFY_SOURCE). The chk wrapper has the
    // same arg layout for the slots we watch.
    unprefixed.strip_suffix("_chk").unwrap_or(unprefixed)
}

/// SAT-as-CVE-proof outcome for one `TaintPath`. Produced by
/// `solve` (gated on `smt` feature).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SmtFinding {
    /// Z3 found a symbolic input that drives the sink's watched arg
    /// into a CVE-class state. The model is exposed as
    /// `(input_byte_offset, value)` pairs.
    Reachable {
        input_bytes: Vec<(usize, u8)>,
        /// v2.V9: chain of caller PCs traversed when this path was
        /// constructed via inter-procedural summary synthesis.
        /// Empty for direct (intra-function) Source→Sink pairs.
        call_chain: Vec<u64>,
    },
    /// Solver proved no input drives the violation under the path's
    /// constraints — false-positive cull.
    NotReachable,
    /// Lineage check or sink-kind modelling is out of v0 scope. The
    /// reason string is shown to the analyst so the gap is auditable.
    Unsupported(&'static str),
}

/// Reasons the v0 path collector rejected an SSA function.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathRejection {
    /// Walk reached a non-Call terminator (CBranch, Branch, Return,
    /// Indirect, Fallthrough). M1 forbids multi-block paths.
    UnsupportedTerminator(&'static str),
    /// Entry block contains a Phi-introducing assignment. v0 cannot
    /// reason across phi joins.
    PhiInPath,
    /// Entry block makes an indirect call before a sink is reached.
    IndirectCall,
    /// Walk completed, no Sink was encountered. Not a hard error —
    /// caller may treat this as "function does nothing CVE-class".
    NoSinkFound,
}

/// One event in the linear SSA walk: assignments, stores, calls.
/// Calls are classified up front against the import map so the
/// downstream SAT prover doesn't repeat the lookup.
#[derive(Debug, Clone)]
pub struct TaintEvent<'a> {
    pub stmt_index: usize,
    pub kind: TaintEventKind<'a>,
}

#[derive(Debug, Clone)]
pub enum TaintEventKind<'a> {
    Assign(VarId),
    Store { addr: VarId, val: VarId },
    SourceCall {
        spec: &'a SourceSpec,
        args: Vec<VarId>,
        out: Option<VarId>,
        /// v2.V8: empty for direct (intra-function) source calls.
        /// Populated when this event was synthesized from a callee's
        /// FunctionSummary — the chain records the call-site PCs
        /// traversed from the analysed function down to the actual
        /// source invocation.
        call_chain: Vec<u64>,
    },
    SinkCall {
        spec: &'a SinkSpec,
        args: Vec<VarId>,
        out: Option<VarId>,
        /// v2.V8: see SourceCall::call_chain.
        call_chain: Vec<u64>,
    },
    OtherCall {
        target_addr: Option<u64>,
        args: Vec<VarId>,
        out: Option<VarId>,
    },
}

/// One CBranch decision encountered while walking from entry to a
/// Source→Sink pair. `taken == true` means the path took the
/// CBranch's `taken` arm; `false` is the fallthrough.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BranchDecision {
    pub block_addr: u64,
    pub cond: VarId,
    pub taken: bool,
}

/// One Source -> Sink pair found by `collect_paths`. The SAT prover
/// takes the path and asks Z3 whether tainted input from `source`
/// can force the `sink`'s watched arg into a CVE-class state.
///
/// `branch_decisions` records the CBranch arms taken between entry
/// and the sink invocation. v0 paths always have an empty list
/// (linear walk only); v1 paths can include up to MAX_BRANCH_DEPTH
/// decisions.
#[derive(Debug, Clone)]
pub struct TaintPath<'a> {
    pub source: &'a SourceSpec,
    pub source_event: usize,
    pub sink: &'a SinkSpec,
    pub sink_event: usize,
    pub events: Vec<TaintEvent<'a>>,
    pub branch_decisions: Vec<BranchDecision>,
}

/// Maximum number of CBranch arms followed from entry to any path
/// before the walker bails. Real router-firmware functions have
/// 20+ branches before reaching a sink; 4 was too low. 32 covers
/// the realistic depth without burning memory because we also cap
/// the global worklist size.
pub const MAX_BRANCH_DEPTH: u32 = 64;

/// Hard cap on total `WalkState`s the worklist can hold. With
/// MAX_BRANCH_DEPTH=32 the unbounded worst case is 2^32 — never
/// happens in practice because most CBranches reconverge, but we
/// still ceiling at this number to keep memory bounded on
/// pathological dispatch tables. When the cap is hit, surplus
/// states are dropped and the rejection reason is recorded.
pub const MAX_WORKLIST_SIZE: usize = 16384;

/// v16: hard cap on the number of (source, sink) pairs the path
/// collector will enumerate per function. Without it, parser-style
/// functions with hundreds of `fgets`/`sprintf` call sites
/// generate `O(sources × sinks × paths)` candidates which can
/// balloon to 96k+ records (observed on dnsmasq-2.78::read_file)
/// and OOM the candidate dump. Once the cap is hit, path
/// collection returns the truncated list rather than continuing
/// to enumerate. CLI's `--smt-candidates-cap` is downstream of
/// this; this cap protects the in-memory enumeration itself.
///
/// Set high (8192) so dropbear-class functions with hundreds of
/// real source-sink pairs aren't truncated; low enough that
/// pathological dnsmasq read_file (96k+) hits the cap and stops.
pub const MAX_PATHS_PER_FN: usize = 8192;

/// One in-progress walk state in the v1 collector's worklist.
struct WalkState<'a> {
    current: crate::ir::BlockId,
    events: Vec<TaintEvent<'a>>,
    visited: std::collections::HashSet<crate::ir::BlockId>,
    branch_decisions: Vec<BranchDecision>,
}

/// Walk every CFG path from the entry block to a Source→Sink pair,
/// k-bounded at `MAX_BRANCH_DEPTH` CBranch arms. Returns the list
/// of paths surfaced, or `PathRejection` if no walk produces a
/// usable path.
///
/// v0 (linear-fallthrough only) is the trivial case: entry block
/// has no CBranch reachable, the worklist degenerates to a single
/// walk identical to v0 collection. v1 adds CBranch exploration:
/// when a walk hits a CBranch, both arms get queued as separate
/// states, each with `branch_decisions` extended.
///
/// Rejected paths (loop back-edges, indirect calls, Phi nodes,
/// depth limit) are dropped; if no successful path remains, the
/// most-specific rejection reason is returned.
///
/// Loop guard: `visited` BlockId set is per-state, not global —
/// two distinct paths through the same block via different arms
/// are both legal. A revisit within the SAME walk aborts that walk.
pub fn collect_paths<'a>(
    ssa: &'a SsaCfg,
    imports: &HashMap<u64, String>,
) -> Result<Vec<TaintPath<'a>>, PathRejection> {
    let empty: HashMap<crate::callgraph::FuncId, crate::function_summary::FunctionSummary> =
        HashMap::new();
    collect_paths_with_summaries(ssa, imports, &empty)
}

/// v2.V8: inter-procedural path collection. Same walker as
/// `collect_paths` but on every direct call to a known function
/// (FuncId in `summaries`, not a library import) the walker pushes
/// synthetic SourceCall / SinkCall events onto the path so the SAT
/// prover can reason about callee taint without inlining the
/// callee's body.
///
/// Synthetic events carry a `call_chain` recording the caller PCs
/// traversed; v9 surfaces this in the JSON output.
pub fn collect_paths_with_summaries<'a>(
    ssa: &'a SsaCfg,
    imports: &HashMap<u64, String>,
    summaries: &HashMap<crate::callgraph::FuncId, crate::function_summary::FunctionSummary>,
) -> Result<Vec<TaintPath<'a>>, PathRejection> {
    collect_paths_with_summaries_named(ssa, imports, summaries, None)
}

/// v13: variant that knows the function's name. When name is "main"
/// (or `_main` Mach-O mangling), the walker prepends a synthetic
/// SourceCall for the `argv` source spec — `argv` isn't a libc
/// call, it's the second arg to `main`, so without this injection
/// path collection in main can never see argv-tainted bytes flowing
/// to a sink even when the SSA carries the chain perfectly.
pub fn collect_paths_with_summaries_named<'a>(
    ssa: &'a SsaCfg,
    imports: &HashMap<u64, String>,
    summaries: &HashMap<crate::callgraph::FuncId, crate::function_summary::FunctionSummary>,
    func_name: Option<&str>,
) -> Result<Vec<TaintPath<'a>>, PathRejection> {
    let mut initial_events: Vec<TaintEvent<'a>> = Vec::new();
    if let Some(name) = func_name {
        let trimmed = name.trim_start_matches('_');
        if trimmed == "main" {
            // Find param_1 (argv) — the SSA's first VarDef whose
            // param_name == "param_1" carries the argv pointer.
            for v in &ssa.vars {
                if v.param_name.as_deref() == Some("param_1") {
                    let argv_spec = DEFAULT_SOURCES
                        .iter()
                        .find(|s| s.name == "argv")
                        .expect("argv spec missing from DEFAULT_SOURCES");
                    initial_events.push(TaintEvent {
                        stmt_index: 0,
                        kind: TaintEventKind::SourceCall {
                            spec: argv_spec,
                            args: vec![VarId(0), v.id],
                            out: None,
                            call_chain: Vec::new(),
                        },
                    });
                    break;
                }
            }
        }
    }
    let initial = WalkState {
        current: ssa.entry,
        events: initial_events,
        visited: std::collections::HashSet::new(),
        branch_decisions: Vec::new(),
    };
    let mut worklist: Vec<WalkState<'a>> = vec![initial];
    let mut completed: Vec<WalkState<'a>> = Vec::new();
    let mut last_reject: Option<PathRejection> = None;

    while let Some(mut state) = worklist.pop() {
        if state.branch_decisions.len() as u32 > MAX_BRANCH_DEPTH {
            last_reject = Some(PathRejection::UnsupportedTerminator("depth limit"));
            continue;
        }
        let mut keep_walking = true;
        while keep_walking {
            if !state.visited.insert(state.current) {
                last_reject = Some(PathRejection::UnsupportedTerminator("loop back-edge"));
                keep_walking = false;
                break;
            }
            let block = match ssa.blocks.iter().find(|b| b.id == state.current) {
                Some(b) => b,
                None => {
                    last_reject =
                        Some(PathRejection::UnsupportedTerminator("dangling block id"));
                    keep_walking = false;
                    break;
                }
            };

            let mut phi_or_indirect = false;
            for (idx, stmt) in block.stmts.iter().enumerate() {
                match stmt {
                    Stmt::Assign(v) => {
                        // Skip Phi assignments — v1 lineage walk
                        // can't propagate taint through them without
                        // per-path predecessor resolution. Recording
                        // them as Assign events is harmless when the
                        // sink doesn't depend on the Phi result, and
                        // saves the walker from rejecting any path
                        // that touches a real-world reconvergence
                        // point. Per-path Phi resolution is v2 work.
                        if matches!(
                            ssa.vars.get(v.0 as usize).map(|d| &d.expr),
                            Some(crate::ir::Expr::Phi(_))
                        ) {
                            continue;
                        }
                        state.events.push(TaintEvent {
                            stmt_index: idx,
                            kind: TaintEventKind::Assign(*v),
                        });
                    }
                    Stmt::Store { addr, val } => {
                        state.events.push(TaintEvent {
                            stmt_index: idx,
                            kind: TaintEventKind::Store {
                                addr: *addr,
                                val: *val,
                            },
                        });
                    }
                    Stmt::Call { target, args, out } => {
                        match classify_call(idx, target, args, *out, imports, &ssa.vars) {
                            Ok(ev) => {
                                state.events.push(ev);
                                synthesize_summary_events(
                                    idx,
                                    target,
                                    args,
                                    block.addr,
                                    imports,
                                    &ssa.vars,
                                    summaries,
                                    &mut state.events,
                                );
                            }
                            Err(e) => {
                                last_reject = Some(e);
                                phi_or_indirect = true;
                                break;
                            }
                        }
                    }
                }
            }
            if phi_or_indirect {
                keep_walking = false;
                break;
            }

            let term_idx = block.stmts.len();
            match &block.terminator {
                SsaTerminator::Call {
                    target,
                    args,
                    out,
                    fallthrough,
                } => match classify_call(term_idx, target, args, *out, imports, &ssa.vars) {
                    Ok(ev) => {
                        state.events.push(ev);
                        synthesize_summary_events(
                            term_idx,
                            target,
                            args,
                            block.addr,
                            imports,
                            &ssa.vars,
                            summaries,
                            &mut state.events,
                        );
                        state.current = *fallthrough;
                    }
                    Err(e) => {
                        last_reject = Some(e);
                        keep_walking = false;
                    }
                },
                SsaTerminator::Fallthrough(next) => {
                    state.current = *next;
                }
                SsaTerminator::Return(_) => {
                    completed.push(state);
                    keep_walking = false;
                    break;
                }
                SsaTerminator::Branch(next) => {
                    // Unconditional jump — walk through. Same loop
                    // guard via `visited` covers infinite-Branch
                    // loops. Original v0 break-on-Branch was a
                    // conservative bail; v1 just keeps walking.
                    state.current = *next;
                }
                SsaTerminator::CBranch {
                    cond,
                    taken,
                    fallthrough,
                } => {
                    // Spawn a copy on the fallthrough arm; keep
                    // walking on the taken arm. Two caps: depth
                    // (MAX_BRANCH_DEPTH) and global worklist size
                    // (MAX_WORKLIST_SIZE). Surplus states are
                    // dropped — a real CVE candidate either fits in
                    // the budget or surfaces in a later pass.
                    if (state.branch_decisions.len() as u32) >= MAX_BRANCH_DEPTH {
                        last_reject =
                            Some(PathRejection::UnsupportedTerminator("depth limit"));
                        keep_walking = false;
                        break;
                    }
                    let block_addr = block.addr;
                    if worklist.len() < MAX_WORKLIST_SIZE {
                        let mut alt = WalkState {
                            current: *fallthrough,
                            events: state.events.clone(),
                            visited: state.visited.clone(),
                            branch_decisions: state.branch_decisions.clone(),
                        };
                        alt.branch_decisions.push(BranchDecision {
                            block_addr,
                            cond: *cond,
                            taken: false,
                        });
                        worklist.push(alt);
                    } else {
                        last_reject =
                            Some(PathRejection::UnsupportedTerminator("worklist cap"));
                    }

                    state.current = *taken;
                    state.branch_decisions.push(BranchDecision {
                        block_addr,
                        cond: *cond,
                        taken: true,
                    });
                }
                SsaTerminator::Indirect(_) => {
                    // Unresolved register-indirect branch — usually
                    // a tail-call or a jump-table dispatch we can't
                    // statically follow. Treat as a path endpoint
                    // rather than rejecting outright: any Source→
                    // Sink pair collected before this point is still
                    // a valid candidate for SAT. v2 will resolve
                    // jump tables through Load(GOT_table + idx).
                    completed.push(state);
                    keep_walking = false;
                    break;
                }
            }
        }
    }

    // Pair each Source with EVERY subsequent Sink in each
    // completed walk. v3: previous "next-Sink-only" rule meant a
    // path like `fgets(...) → strncpy(LengthArg) → popen(Command)`
    // got paired off as fgets→strncpy and the popen sink was lost
    // when LengthArg returned Unsupported. Emitting one path per
    // (source, downstream-sink) tuple lets SAT prove the deeper
    // sink even when an intermediate one is unsupported.
    let mut paths = Vec::new();
    for state in completed {
        let mut sources: Vec<(usize, &'a SourceSpec)> = Vec::new();
        for (i, ev) in state.events.iter().enumerate() {
            match &ev.kind {
                TaintEventKind::SourceCall { spec, .. } => {
                    sources.push((i, spec));
                }
                TaintEventKind::SinkCall { spec, .. } => {
                    for (src_i, src_spec) in &sources {
                        paths.push(TaintPath {
                            source: src_spec,
                            source_event: *src_i,
                            sink: spec,
                            sink_event: i,
                            events: state.events.clone(),
                            branch_decisions: state.branch_decisions.clone(),
                        });
                    }
                }
                _ => {}
            }
        }
    }
    // v16: hard truncate. Without this, parser-style functions
    // can balloon `paths.len()` past 96k (observed on dnsmasq-2.78
    // ::read_file) and OOM downstream solve()/JSON-serialize
    // pipelines. Truncation happens AFTER full enumeration so
    // small-function recall is unchanged; only pathological large
    // outputs get cropped.
    if paths.len() > MAX_PATHS_PER_FN {
        paths.truncate(MAX_PATHS_PER_FN);
    }

    if paths.is_empty() {
        return Err(last_reject.unwrap_or(PathRejection::NoSinkFound));
    }
    Ok(paths)
}

/// v1.N1: resolve an Indirect call's target VarId to a constant
/// address by walking the SSA expression cone. Two patterns
/// supported:
///   1. Const(addr) directly — fully resolved.
///   2. Load(addr_var) where addr_var resolves to Const(slot_addr)
///      AND `imports` knows that slot's name. Common for GOT-based
///      calls and Mach-O lazy-binding stubs.
///
/// Returns `Some(addr)` whose lookup in imports yields a configured
/// Source or Sink, else `None`. v2 extends to BinOp(base, idx) for
/// vtable-style dispatch.
fn resolve_indirect_target(
    target_vn: &pcode_ir::Varnode,
    vars: &[crate::ir::VarDef],
    imports: &HashMap<u64, String>,
) -> Option<u64> {
    // Find a VarDef whose varnode matches the indirect target's
    // varnode. Walk Var-chains and Load(Const) edges up to a depth
    // budget. Return the first Const-or-Load-resolved address whose
    // imports.get matches a Source or Sink spec.
    let mut visited: std::collections::HashSet<u32> =
        std::collections::HashSet::new();
    let mut stack: Vec<u32> = vars
        .iter()
        .rev()
        .filter(|d| d.varnode == *target_vn)
        .map(|d| d.id.0)
        .collect();
    while let Some(id) = stack.pop() {
        if !visited.insert(id) {
            continue;
        }
        if visited.len() > 32 {
            break;
        }
        let Some(def) = vars.get(id as usize) else {
            continue;
        };
        match &def.expr {
            crate::ir::Expr::Const(c, _) => {
                let addr = *c & 0x0FFF_FFFF;
                if imports.contains_key(&addr) || imports.contains_key(c) {
                    return Some(if imports.contains_key(c) { *c } else { addr });
                }
            }
            crate::ir::Expr::Var(inner) => stack.push(inner.0),
            crate::ir::Expr::Load(addr_var) => {
                if let Some(addr_def) = vars.get(addr_var.0 as usize) {
                    if let crate::ir::Expr::Const(slot, _) = addr_def.expr {
                        let candidates = [slot, slot & 0x0FFF_FFFF];
                        for c in candidates {
                            if imports.contains_key(&c) {
                                return Some(c);
                            }
                        }
                    }
                }
            }
            _ => {}
        }
    }
    None
}

fn classify_call<'a>(
    stmt_index: usize,
    target: &CallTarget,
    args: &[VarId],
    out: Option<VarId>,
    imports: &HashMap<u64, String>,
    vars: &[crate::ir::VarDef],
) -> Result<TaintEvent<'a>, PathRejection> {
    // v1.N1: try to resolve Indirect call targets through the SSA
    // cone. Direct(addr) is the trivial case; Indirect(vn) attempts
    // a Var-chain + Load(Const) walk for GOT-style dispatch.
    let direct_addr = match target {
        CallTarget::Direct(a) => Some(*a),
        CallTarget::Indirect(vn) => resolve_indirect_target(vn, vars, imports),
    };
    let kind = match direct_addr.and_then(|a| resolve_call(a, imports)) {
        Some(SpecRef::Source(s)) => {
            // Find the matching SourceSpec from DEFAULT_SOURCES so
            // the lifetime ties to 'static (avoids cloning into the
            // event, keeps the spec table the single source of truth).
            let spec = DEFAULT_SOURCES
                .iter()
                .find(|sp| sp.name == s.name)
                .expect("resolve_call returned a SourceSpec not in DEFAULT_SOURCES");
            TaintEventKind::SourceCall {
                spec,
                args: args.to_vec(),
                out,
                call_chain: Vec::new(),
            }
        }
        Some(SpecRef::Sink(s)) => {
            let spec = DEFAULT_SINKS
                .iter()
                .find(|sp| sp.name == s.name)
                .expect("resolve_call returned a SinkSpec not in DEFAULT_SINKS");
            TaintEventKind::SinkCall {
                spec,
                args: args.to_vec(),
                out,
                call_chain: Vec::new(),
            }
        }
        None => {
            if direct_addr.is_none() {
                return Err(PathRejection::IndirectCall);
            }
            TaintEventKind::OtherCall {
                target_addr: direct_addr,
                args: args.to_vec(),
                out,
            }
        }
    };
    Ok(TaintEvent { stmt_index, kind })
}

/// v2.V8: when the walker hits a direct call whose target is a
/// FuncId with a built FunctionSummary (not a library import),
/// expand the callee's recorded sources/sinks into synthetic events
/// at the caller's call site. The args list is reconstructed so
/// `solve` can look up the watched VarId at the spec's slot index;
/// non-watched slots are filler `VarId(0)` because the SAT prover
/// only reads the watched slot.
fn synthesize_summary_events<'a>(
    stmt_index: usize,
    target: &CallTarget,
    caller_args: &[VarId],
    caller_addr: u64,
    imports: &HashMap<u64, String>,
    vars: &[crate::ir::VarDef],
    summaries: &HashMap<crate::callgraph::FuncId, crate::function_summary::FunctionSummary>,
    events: &mut Vec<TaintEvent<'a>>,
) {
    let direct_addr = match target {
        CallTarget::Direct(a) => Some(*a),
        CallTarget::Indirect(vn) => resolve_indirect_target(vn, vars, imports),
    };
    let Some(addr) = direct_addr else {
        return;
    };
    // v2.V10: prefer summary lookup over imports check. In Mach-O
    // (and stripped ELF) both imports and intra-binary symbols can
    // coexist in the import map; skipping any addr present in
    // imports would suppress all inter-procedural propagation. If
    // a summary exists, the call is intra-binary and worth lifting.
    let callee_sum = match summaries.get(&crate::callgraph::FuncId(addr)) {
        Some(s) => s,
        None => return,
    };
    for src in &callee_sum.sources {
        let Some(var) =
            synth_pick_caller_var(&src.tainted_caller_slots, caller_args, vars)
        else {
            continue;
        };
        let watched_idx = match src.source.tainted {
            AbiSlot::Arg(n) => n as usize,
            AbiSlot::Ret => continue, // Ret-tainted sources can't be retargeted via arg slot
            AbiSlot::Global(_) => continue, // libc specs never use Global
        };
        let mut args_vec = vec![VarId(0); watched_idx + 1];
        args_vec[watched_idx] = var;
        let spec = DEFAULT_SOURCES
            .iter()
            .find(|sp| sp.name == src.source.name)
            .expect("summary source not in DEFAULT_SOURCES");
        events.push(TaintEvent {
            stmt_index,
            kind: TaintEventKind::SourceCall {
                spec,
                args: args_vec,
                out: None,
                call_chain: vec![caller_addr, src.call_site],
            },
        });
    }
    for snk in &callee_sum.sinks {
        let Some(var) =
            synth_pick_caller_var(&snk.tainted_caller_slots, caller_args, vars)
        else {
            continue;
        };
        let watched_idx = match snk.sink.watched {
            AbiSlot::Arg(n) => n as usize,
            AbiSlot::Ret => continue,
            AbiSlot::Global(_) => continue,
        };
        let mut args_vec = vec![VarId(0); watched_idx + 1];
        args_vec[watched_idx] = var;
        let spec: &SinkSpec = if snk.sink.name == STORE_SINK_SPEC.name {
            &STORE_SINK_SPEC
        } else {
            DEFAULT_SINKS
                .iter()
                .find(|sp| sp.name == snk.sink.name)
                .expect("summary sink not in DEFAULT_SINKS")
        };
        events.push(TaintEvent {
            stmt_index,
            kind: TaintEventKind::SinkCall {
                spec,
                args: args_vec,
                out: None,
                call_chain: vec![caller_addr, snk.call_site],
            },
        });
    }
}

fn synth_pick_caller_var(
    tainted_slots: &[AbiSlot],
    caller_args: &[VarId],
    caller_vars: &[crate::ir::VarDef],
) -> Option<VarId> {
    for slot in tainted_slots {
        match slot {
            AbiSlot::Arg(n) => {
                if let Some(v) = caller_args.get(*n as usize) {
                    return Some(*v);
                }
            }
            AbiSlot::Global(va) => {
                // v5.W2.D2a: find any caller VarDef whose expr is
                // `Const(va)` or `Load(Const(va))` — the global
                // address is materialised somewhere in the caller's
                // SSA (otherwise the caller couldn't have passed it
                // to the callee). Return the first match so the
                // synthesized event's args carry that VarId; v4's
                // region-keyed MemMap then aliases this load with
                // any sink's Load of the same VA.
                for vd in caller_vars {
                    match &vd.expr {
                        crate::ir::Expr::Const(c, _) if *c == *va => {
                            return Some(vd.id);
                        }
                        crate::ir::Expr::Load(addr) => {
                            if let Some(addr_def) = caller_vars.get(addr.0 as usize) {
                                if let crate::ir::Expr::Const(c, _) = addr_def.expr {
                                    if c == *va {
                                        return Some(vd.id);
                                    }
                                }
                            }
                        }
                        _ => {}
                    }
                }
            }
            AbiSlot::Ret => {}
        }
    }
    None
}

/// Map of last-Store addresses (as canonical-form keys) to the
/// VarId of the stored value. Built once per `solve` invocation by
/// walking the path's events. Used by `varid_lineage_eq` to follow
/// Load(addr) back to the value most recently stored at that addr.
///
/// v3 region-lite: the key is a recursive stringification of the
/// address expression so two address-computations that produce the
/// SAME logical address via different SSA Unique varnodes alias
/// correctly. Without this, every `-O0` reload pattern (`add fp,
/// #const_off` recomputed at each call site) defeats Store→Load
/// matching because each instance lands in a distinct Unique slot.
/// v4 region-keyed mem map. Each Store insert keys by
/// `(Region, OffsetClass)` derived from `region::infer_regions`,
/// so two -O0 reload sites recomputing the same `add(fp, c)`
/// shape with different Unique varnodes collide on the same key.
type MemMap = HashMap<(crate::region::Region, crate::region::OffsetClass), VarId>;

fn build_mem_map(
    events: &[TaintEvent<'_>],
    vars: &[crate::ir::VarDef],
    regions: &crate::region::RegionMap,
) -> MemMap {
    let mut m = MemMap::new();
    for ev in events {
        if let TaintEventKind::Store { addr, val } = ev.kind {
            let key = mem_key(addr, vars, regions);
            m.insert(key, val);
        }
    }
    m
}

/// Compute the region-keyed alias key for an address expression.
fn mem_key(
    addr: VarId,
    vars: &[crate::ir::VarDef],
    regions: &crate::region::RegionMap,
) -> (crate::region::Region, crate::region::OffsetClass) {
    let region = regions.region_of(addr);
    let offset = classify_offset(addr, vars);
    (region, offset)
}

fn classify_offset(addr: VarId, vars: &[crate::ir::VarDef]) -> crate::region::OffsetClass {
    use crate::ir::{BinOpKind, Expr};
    use crate::region::OffsetClass;
    let Some(def) = vars.get(addr.0 as usize) else {
        return OffsetClass::ConstOffset(0);
    };
    match &def.expr {
        Expr::FieldAccess(_, off) => OffsetClass::ConstOffset(*off as i64),
        Expr::BinOp(BinOpKind::Add, a, b) => {
            if let Some(c) = const_value(*a, vars) {
                return OffsetClass::ConstOffset(c);
            }
            if let Some(c) = const_value(*b, vars) {
                return OffsetClass::ConstOffset(c);
            }
            OffsetClass::Symbolic
        }
        Expr::BinOp(BinOpKind::Sub, a, b) => {
            if let Some(c) = const_value(*b, vars) {
                if let Some(ca) = const_value(*a, vars) {
                    return OffsetClass::ConstOffset(ca.wrapping_sub(c));
                }
                return OffsetClass::ConstOffset(-c);
            }
            OffsetClass::Symbolic
        }
        Expr::Var(inner) => classify_offset(*inner, vars),
        Expr::Const(c, _) => OffsetClass::ConstOffset(*c as i64),
        _ => OffsetClass::ConstOffset(0),
    }
}

fn const_value(v: VarId, vars: &[crate::ir::VarDef]) -> Option<i64> {
    let mut cur = v;
    for _ in 0..16 {
        let def = vars.get(cur.0 as usize)?;
        match &def.expr {
            crate::ir::Expr::Const(c, _) => return Some(*c as i64),
            crate::ir::Expr::Var(inner) => cur = *inner,
            _ => return None,
        }
    }
    None
}

/// Map of a Call's `out` VarId to the Call's argument VarIds.
/// v2.V5: a return value carries taint forward from any tainted arg
/// (intra-procedural pass-through assumption). The lineage walker
/// uses this so a sink VarId derived from `out = strdup(tainted)`
/// resolves back to the source.
type CallReturnMap = HashMap<VarId, Vec<VarId>>;

/// v5.W2.D2b: libc functions whose return value is a strict upper
/// bound on the length of their string/buffer input. Lineage from
/// network/file input that flows through one of these can no longer
/// drive a length-overflow at a downstream memcpy/strncpy/memmove,
/// because the wrapper has clipped the length to a known small
/// range. Used by the LengthArg solver to reject FP candidates
/// like `strncpy(dst, fgets_buf, strlen(fgets_buf))` where strlen
/// caps at 511 ≤ fgets-cap.
const LENGTH_BOUNDING_WRAPPERS: &[&str] = &[
    "strlen", "strnlen", "wcslen", "wcsnlen",
    // snprintf / vsnprintf return value is the count of bytes that
    // would have been written — clipped to size by the caller in
    // every sane code path. Treat as bounded.
    "snprintf", "vsnprintf",
    // v5.W2.D2b: read/recv-class return value is the count of
    // bytes received, bounded by the count arg. When the count is
    // a Const (the dominant case in real code), the return is a
    // small constant upper bound — using it as a memcpy length
    // can't drive a > 0xFFFF overflow regardless of attacker-
    // controlled BUFFER content. Treating their returns as
    // bounded gives up some inter-procedural recall in exchange
    // for FP elimination on the AX6000 corpus (dropbear FUN_-
    // 0001ba3c was the only hit before this filter and was
    // bounded by `read(_, _, 4096)`).
    "read", "recv", "recvfrom", "recvmsg", "fread", "fgets",
];

fn build_bounded_returns_set(
    ssa: &crate::ir::SsaCfg,
    imports: &HashMap<u64, String>,
) -> std::collections::HashSet<VarId> {
    let mut out = std::collections::HashSet::new();
    let wrapper_kind = |target: &CallTarget| -> Option<&'static str> {
        if let CallTarget::Direct(addr) = target {
            if let Some(raw) = imports.get(addr) {
                let n = normalise_name(raw);
                if let Some(name) = LENGTH_BOUNDING_WRAPPERS
                    .iter()
                    .find(|w| **w == n)
                    .copied()
                {
                    return Some(name);
                }
            }
        }
        None
    };
    let mut consider = |target: &CallTarget, args: &[VarId], o: VarId| {
        let Some(name) = wrapper_kind(target) else { return };
        // v6.W1: read/recv-class returns are bounded only when
        // their `count` operand is statically Const. When the
        // count itself comes from network input or another Load,
        // the return value can grow as large as the attacker
        // wants — treating it as bounded would suppress real
        // protocol-field length-overflow flows.
        let count_idx: Option<usize> = match name {
            "read" | "recv" | "recvfrom" | "recvmsg" => Some(2),
            "fread" => Some(2),
            "fgets" => Some(1),
            _ => None,
        };
        if let Some(idx) = count_idx {
            if !arg_resolves_to_const(args.get(idx).copied(), &ssa.vars) {
                return;
            }
        }
        out.insert(o);
    };
    for block in &ssa.blocks {
        for stmt in &block.stmts {
            if let crate::ir::Stmt::Call {
                target,
                args,
                out: Some(o),
                ..
            } = stmt
            {
                consider(target, args, *o);
            }
        }
        if let crate::ir::SsaTerminator::Call {
            target,
            args,
            out: Some(o),
            ..
        } = &block.terminator
        {
            consider(target, args, *o);
        }
    }
    out
}

/// v6.W1: walk the Var/Phi DAG from `var` and return true iff every
/// reachable leaf is `Const`. Phi joins of constant counts (e.g.
/// `count = cond ? 4096 : 1024;`) are statically bounded. Bounded
/// depth + visited-set to avoid pathological IRs.
fn arg_resolves_to_const(var: Option<VarId>, vars: &[crate::ir::VarDef]) -> bool {
    let Some(start) = var else { return false };
    let mut visited: std::collections::HashSet<u32> = std::collections::HashSet::new();
    let mut stack = vec![start];
    let mut steps = 0usize;
    while let Some(cur) = stack.pop() {
        if !visited.insert(cur.0) {
            continue;
        }
        steps += 1;
        if steps > 64 {
            return false;
        }
        let Some(def) = vars.get(cur.0 as usize) else { return false };
        match &def.expr {
            crate::ir::Expr::Var(inner) => stack.push(*inner),
            crate::ir::Expr::Const(_, _) => {}
            crate::ir::Expr::Phi(inputs) => {
                for v in inputs {
                    stack.push(*v);
                }
            }
            _ => return false,
        }
    }
    true
}

fn build_call_return_map(ssa: &crate::ir::SsaCfg) -> CallReturnMap {
    let mut m = CallReturnMap::new();
    for block in &ssa.blocks {
        for stmt in &block.stmts {
            if let crate::ir::Stmt::Call {
                args,
                out: Some(o),
                ..
            } = stmt
            {
                m.insert(*o, args.clone());
            }
        }
        if let crate::ir::SsaTerminator::Call {
            args,
            out: Some(o),
            ..
        } = &block.terminator
        {
            m.insert(*o, args.clone());
        }
    }
    m
}

/// True if `a` and `b` share a common logical location after
/// following SSA `Var` chains AND a single layer of Store→Load
/// indirection through `mem`. Lifters split a buffer pointer into
/// many SSA versions across Store/Load round-trips; without the
/// memory map this lineage trace would miss every realistic flow.
fn varid_lineage_eq(
    a: VarId,
    b: VarId,
    vars: &[crate::ir::VarDef],
    mem: &MemMap,
    calls: &CallReturnMap,
    regions: &crate::region::RegionMap,
) -> bool {
    if a == b {
        return true;
    }
    let chain_a = chain_varnodes(a, vars, mem, calls, regions);
    let chain_b = chain_varnodes(b, vars, mem, calls, regions);
    for vn_a in &chain_a {
        if chain_b.iter().any(|vn_b| vn_a == vn_b) {
            return true;
        }
    }
    false
}

/// Alias key for two-chain intersection in `varid_lineage_eq`.
/// Two VarIds alias when their alias sets share at least one key.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum AliasKey {
    /// Stable Varnode (Ram / Unique / Const) of a non-call_return def.
    Vn(pcode_ir::Varnode),
    /// Region+offset class derived from the VarId's region
    /// classification. Lets two distinct VarIds that point at
    /// the same logical region+offset alias even when their
    /// SSA expressions don't share a Varnode.
    Region(crate::region::Region, crate::region::OffsetClass),
}

/// Collect the set of alias keys reached from `start` via SSA
/// Var-chain, BinOp/UnaryOp/Phi/FieldAccess propagation, and one
/// layer of Store→Load redirection through the region-keyed
/// `mem`. Bounded depth so cyclic IRs don't hang the prover.
fn chain_varnodes(
    start: VarId,
    vars: &[crate::ir::VarDef],
    mem: &MemMap,
    calls: &CallReturnMap,
    regions: &crate::region::RegionMap,
) -> Vec<AliasKey> {
    chain_varnodes_with_bound(start, vars, mem, calls, regions, None)
}

/// v5.W2.D2b: variant that stops the call-return pass-through at
/// VarIds present in `bounded_outs` (returns from length-bounding
/// wrappers like strlen / snprintf). Used by the LengthArg solver
/// to reject FP paths where the tainted length flows through a
/// bound-shrinking wrapper.
fn chain_varnodes_with_bound(
    start: VarId,
    vars: &[crate::ir::VarDef],
    mem: &MemMap,
    calls: &CallReturnMap,
    regions: &crate::region::RegionMap,
    bounded_outs: Option<&std::collections::HashSet<VarId>>,
) -> Vec<AliasKey> {
    let mut out = Vec::new();
    let mut visited: std::collections::HashSet<u32> = std::collections::HashSet::new();
    let mut stack = vec![start];
    while let Some(current) = stack.pop() {
        if !visited.insert(current.0) {
            continue;
        }
        if visited.len() > 64 {
            break;
        }
        // v2.V5: if `current` is a Call's `out`, push every arg —
        // the return value is treated as carrying taint forward
        // from any tainted argument (intra-procedural pass-through).
        // v5.W2.D2b: skip args when the call target is a length-
        // bounding wrapper (strlen, snprintf, ...) — the wrapper's
        // return is bounded by definition, so taint upstream of
        // the wrapper isn't a length-overflow predicate.
        if let Some(args) = calls.get(&current) {
            let is_bounded = bounded_outs
                .map(|s| s.contains(&current))
                .unwrap_or(false);
            if !is_bounded {
                for a in args {
                    stack.push(*a);
                }
            }
        }
        let Some(def) = vars.get(current.0 as usize) else {
            continue;
        };
        // v3 precision: only emit a Varnode-level alias key for
        // spaces where varnode identity implies value identity.
        // Register-space reuse (ARM32 `r0 = popen(); r0 = fgets()`)
        // and per-instruction Unique slots get DIFFERENT VarIds
        // under SSA, but if we cross-link them via Varnode equality
        // every register-reuse pair becomes a spurious lineage hit.
        // Call-return VarIds always get fresh data — never alias by
        // their outgoing register.
        let space_aliases = !matches!(
            def.varnode.space,
            pcode_ir::AddressSpaceId::Register
        ) && !def.call_return;
        if space_aliases {
            out.push(AliasKey::Vn(def.varnode));
        }
        // v4: region+offset is a more robust alias key than
        // raw varnode for stack-spilled pointer values. We
        // include it for any VarId whose region resolved to a
        // non-Unknown AllocSite — Unknown regions are minted
        // per-VarId so they'd never alias anyway.
        let region = regions.region_of(current);
        if let Some(site) = regions.site_of(region) {
            if !matches!(site, crate::region::AllocSite::Unknown(_)) {
                let off = classify_offset(current, vars);
                out.push(AliasKey::Region(region, off));
            }
        }
        match &def.expr {
            crate::ir::Expr::Var(inner) => stack.push(*inner),
            crate::ir::Expr::Load(addr) => {
                let key = mem_key(*addr, vars, regions);
                if let Some(stored) = mem.get(&key).copied() {
                    stack.push(stored);
                } else {
                    // v4 over-approximate: any Symbolic-offset
                    // Store on the same region aliases this Load.
                    let sym_key = (
                        key.0,
                        crate::region::OffsetClass::Symbolic,
                    );
                    if let Some(stored) = mem.get(&sym_key).copied() {
                        stack.push(stored);
                    }
                }
            }
            // v3 lineage widening: taint propagates through
            // arithmetic / type-casts / phi joins. A loop counter
            // mixed with a tainted byte still leaves the result
            // attacker-influenced; the per-SinkKind constraint
            // does the actual feasibility check.
            crate::ir::Expr::BinOp(_, a, b) => {
                stack.push(*a);
                stack.push(*b);
            }
            crate::ir::Expr::UnaryOp(_, a) => stack.push(*a),
            crate::ir::Expr::FieldAccess(base, _off) => stack.push(*base),
            crate::ir::Expr::Phi(args) => {
                for a in args {
                    stack.push(*a);
                }
            }
            _ => {}
        }
    }
    out
}

/// v0 SAT prover: takes a `TaintPath` produced by `collect_paths`,
/// confirms the sink's watched VarId lineage descends from the
/// source's tainted slot, and asks Z3 whether a symbolic input can
/// satisfy the per-`SinkKind` violation constraint.
///
/// v0 simplifications (locked):
///   - 32-byte fresh symbolic input array; no flat memory model yet.
///   - No Load/Store/FieldAccess lowering inside the SSA cone.
///   - LengthArg sinks return `Unsupported` (modelling deferred).
///   - Lineage check is `Expr::Var` chain only — no BinOp/Phi taint.
#[cfg(feature = "smt")]
pub fn solve(path: &TaintPath, ssa: &crate::ir::SsaCfg) -> SmtFinding {
    solve_with_imports(path, ssa, &HashMap::new())
}

/// v5.W2.D2b: solve variant aware of length-bounding wrappers.
/// `imports` is consulted only to build a per-SSA set of VarIds
/// returned from `strlen` / `snprintf` / etc.; LengthArg sinks
/// reject lineages that pass through one of those wrappers.
#[cfg(feature = "smt")]
pub fn solve_with_imports(
    path: &TaintPath,
    ssa: &crate::ir::SsaCfg,
    imports: &HashMap<u64, String>,
) -> SmtFinding {
    solve_diag(path, ssa, imports, &mut Vec::new())
}

/// v7.W1: same as `solve_with_imports` but appends a
/// human-readable filter-reason string for each precision check
/// the solver applied. Empty `reason_log` ⇒ Reachable verdict
/// hit no filter; non-empty ⇒ at least one filter classified the
/// path as bounded / out-of-scope. Used by `--smt-candidates` to
/// dump the analyst-facing reasoning trail per path.
#[cfg(feature = "smt")]
pub fn solve_diag(
    path: &TaintPath,
    ssa: &crate::ir::SsaCfg,
    imports: &HashMap<u64, String>,
    reason_log: &mut Vec<String>,
) -> SmtFinding {
    use z3::ast::{Ast, BV};

    let source_event = &path.events[path.source_event];
    let sink_event = &path.events[path.sink_event];

    let source_var = match (&source_event.kind, path.source.tainted) {
        (TaintEventKind::SourceCall { args, .. }, AbiSlot::Arg(n)) => {
            args.get(n as usize).copied()
        }
        (TaintEventKind::SourceCall { out, .. }, AbiSlot::Ret) => *out,
        _ => None,
    };
    let sink_var = match (&sink_event.kind, path.sink.watched) {
        (TaintEventKind::SinkCall { args, .. }, AbiSlot::Arg(n)) => {
            args.get(n as usize).copied()
        }
        (TaintEventKind::SinkCall { out, .. }, AbiSlot::Ret) => *out,
        _ => None,
    };

    let (Some(src), Some(snk)) = (source_var, sink_var) else {
        reason_log.push("source/sink slot missing".into());
        return SmtFinding::Unsupported("source/sink slot missing");
    };
    let regions = crate::region::infer_regions(ssa);
    let mem = build_mem_map(&path.events, &ssa.vars, &regions);
    let calls = build_call_return_map(ssa);
    let lineage_ok = if path.source.name == "argv" {
        // v13: argv source taints the entire `argv` region. Any
        // VarId whose SSA chain reaches the Region(Param(1), *)
        // matches, ignoring OffsetClass — `argv[N]` and `argv` share
        // a region in v4 inference.
        let src_region = regions.region_of(src);
        let chain_snk = chain_varnodes(snk, &ssa.vars, &mem, &calls, &regions);
        chain_snk.iter().any(|k| matches!(k, AliasKey::Region(r, _) if *r == src_region))
            || varid_lineage_eq(snk, src, &ssa.vars, &mem, &calls, &regions)
    } else {
        varid_lineage_eq(snk, src, &ssa.vars, &mem, &calls, &regions)
    };
    if !lineage_ok {
        reason_log.push("lineage_eq failed (no shared alias key)".into());
        return SmtFinding::NotReachable;
    }

    let z3_cfg = z3::Config::new();
    let ctx = z3::Context::new(&z3_cfg);
    let solver = z3::Solver::new(&ctx);

    const INPUT_LEN: usize = 32;
    let bytes: Vec<BV> = (0..INPUT_LEN)
        .map(|i| BV::new_const(&ctx, format!("in_{i}"), 8))
        .collect();

    match path.sink.kind {
        SinkKind::Command => {
            let mut acc = z3::ast::Bool::from_bool(&ctx, false);
            for b in &bytes {
                let semi = b._eq(&BV::from_u64(&ctx, b';' as u64, 8));
                let amp  = b._eq(&BV::from_u64(&ctx, b'&' as u64, 8));
                let pipe = b._eq(&BV::from_u64(&ctx, b'|' as u64, 8));
                let any = z3::ast::Bool::or(&ctx, &[&semi, &amp, &pipe]);
                acc = z3::ast::Bool::or(&ctx, &[&acc, &any]);
            }
            solver.assert(&acc);
        }
        SinkKind::FormatArg => {
            let mut acc = z3::ast::Bool::from_bool(&ctx, false);
            for b in &bytes {
                let pct = b._eq(&BV::from_u64(&ctx, b'%' as u64, 8));
                acc = z3::ast::Bool::or(&ctx, &[&acc, &pct]);
            }
            solver.assert(&acc);
        }
        SinkKind::StackBuffer => {
            for b in &bytes {
                let nz = b._eq(&BV::from_u64(&ctx, 0, 8)).not();
                solver.assert(&nz);
            }
        }
        SinkKind::TaintedStore => {
            // v10: SAT model. The lineage walker has proved
            // tainted source bytes reach the SRC pointer of a
            // Param→Param copy (per detect_tainted_store's two
            // preconditions). Reachable iff:
            //   (a) lineage_eq holds (already checked above), AND
            //   (b) all 32 input bytes can be nonzero — the loop
            //       bound is `*src != 0`, so an attacker who
            //       sends bytes with no \0 drives the copy
            //       arbitrarily long, overflowing the fixed
            //       caller-stack dst.
            // Trigger: 32 nonzero bytes (any value).
            for b in &bytes {
                let nz = b._eq(&BV::from_u64(&ctx, 0, 8)).not();
                solver.assert(&nz);
            }
        }
        SinkKind::CStringRead => {
            // SAT model for unbounded string readers. If the first
            // symbolic input window contains no NUL, libc string
            // walkers can read beyond packet/body bounds when the
            // caller failed to terminate the buffer. This is an
            // evidence generator, so candidate consumers must still
            // confirm the allocation/length boundary in context.
            for b in &bytes {
                let nz = b._eq(&BV::from_u64(&ctx, 0, 8)).not();
                solver.assert(&nz);
            }
        }
        SinkKind::LengthArg => {
            // v5.W2.D2b: Reachable iff
            //   (a) tainted lineage from src reaches the length
            //       operand WITHOUT passing through a length-
            //       bounding wrapper (strlen / snprintf / ...), AND
            //   (b) the dst arg is a stack-frame region (per v4
            //       region inference) — heap/global dsts have
            //       runtime size, not statically a stack-frame BOF.
            let bounded = build_bounded_returns_set(ssa, imports);
            let chain_a = chain_varnodes_with_bound(
                snk, &ssa.vars, &mem, &calls, &regions, Some(&bounded),
            );
            let chain_b = chain_varnodes_with_bound(
                src, &ssa.vars, &mem, &calls, &regions, Some(&bounded),
            );
            // v6.W1: Vn-key alias is the strongest signal. v7.W3:
            // Vn-strict alone is too tight on Heartbleed-shape flows
            // (`len = (buf[0] << 8) | buf[1]; memcpy(dst, buf+2,
            // len)`) where the buffer contents are attacker-
            // controlled but the SSA carries `buf` in Register
            // space (no Vn key emitted). Allow a Region match when
            // and only when the shared region is the SOURCE's
            // specific region — not a generic Param/StackFrame
            // match which over-approximates.
            let src_region = regions.region_of(src);
            let region_eq = matches!(regions.site_of(src_region),
                Some(s) if !matches!(s, crate::region::AllocSite::Unknown(_)))
                && chain_a.iter().any(|k| {
                    matches!(k, AliasKey::Region(r, _) if *r == src_region)
                })
                && chain_b.iter().any(|k| {
                    matches!(k, AliasKey::Region(r, _) if *r == src_region)
                });
            let unbounded_eq = chain_a.iter().any(|k_a| {
                matches!(k_a, AliasKey::Vn(_)) && chain_b.contains(k_a)
            }) || region_eq;
            if !unbounded_eq {
                reason_log.push(format!(
                    "LengthArg lineage bounded by wrapper return ({} bounded VarIds: {:?})",
                    bounded.len(),
                    bounded.iter().map(|v| v.0).take(8).collect::<Vec<_>>()
                ));
                return SmtFinding::NotReachable;
            }
            // dst region check (memcpy/strncpy/memmove all use Arg(0)).
            let dst_var = match &sink_event.kind {
                TaintEventKind::SinkCall { args, .. } => args.first().copied(),
                _ => None,
            };
            let dst_is_stack = dst_var
                .map(|v| {
                    let r = regions.region_of(v);
                    matches!(
                        regions.site_of(r),
                        Some(crate::region::AllocSite::StackFrame)
                    )
                })
                .unwrap_or(false);
            if !dst_is_stack {
                let region_label = dst_var
                    .map(|v| {
                        let r = regions.region_of(v);
                        format!("{:?}", regions.site_of(r))
                    })
                    .unwrap_or_else(|| "(no dst var)".into());
                reason_log.push(format!(
                    "LengthArg dst region not StackFrame: {}",
                    region_label
                ));
                return SmtFinding::NotReachable;
            }
            // Encode length as 32-bit BV from 4 input bytes (LE);
            // assert > 0xFFFF (any plausible stack buffer cap).
            let len = bytes[0]
                .concat(&bytes[1])
                .concat(&bytes[2])
                .concat(&bytes[3]);
            let threshold = BV::from_u64(&ctx, 0xFFFF, 32);
            solver.assert(&len.bvugt(&threshold));
        }
    }

    match solver.check() {
        z3::SatResult::Sat => {
            let m = match solver.get_model() {
                Some(m) => m,
                None => {
                    reason_log.push("Z3 SAT but model unavailable".into());
                    return SmtFinding::Unsupported("SAT but no model returned");
                }
            };
            let mut input_bytes = Vec::new();
            for (i, b) in bytes.iter().enumerate() {
                let evaluated = z3::Model::eval(&m, b, true);
                if let Some(v_bv) = evaluated {
                    if let Some(v) = v_bv.as_u64() {
                        input_bytes.push((i, v as u8));
                    }
                }
            }
            let call_chain = match &path.events[path.sink_event].kind {
                TaintEventKind::SinkCall { call_chain, .. } => call_chain.clone(),
                _ => Vec::new(),
            };
            SmtFinding::Reachable { input_bytes, call_chain }
        }
        z3::SatResult::Unsat => {
            reason_log.push("Z3 unsat under sink-kind constraint".into());
            SmtFinding::NotReachable
        }
        z3::SatResult::Unknown => {
            reason_log.push("Z3 returned Unknown / timeout".into());
            SmtFinding::Unsupported("solver Unknown / timeout")
        }
    }
}

/// Stub for default builds. Callers can emit a "rebuild with
/// --features smt" hint when they see this.
#[cfg(not(feature = "smt"))]
pub fn solve(_path: &TaintPath, _ssa: &crate::ir::SsaCfg) -> SmtFinding {
    SmtFinding::Unsupported("smt feature not enabled at build time")
}

#[cfg(not(feature = "smt"))]
pub fn solve_with_imports(
    _path: &TaintPath,
    _ssa: &crate::ir::SsaCfg,
    _imports: &HashMap<u64, String>,
) -> SmtFinding {
    SmtFinding::Unsupported("smt feature not enabled at build time")
}

#[cfg(not(feature = "smt"))]
pub fn solve_diag(
    _path: &TaintPath,
    _ssa: &crate::ir::SsaCfg,
    _imports: &HashMap<u64, String>,
    reason_log: &mut Vec<String>,
) -> SmtFinding {
    reason_log.push("smt feature not enabled at build time".into());
    SmtFinding::Unsupported("smt feature not enabled at build time")
}

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

    #[test]
    fn default_tables_non_empty() {
        assert!(!DEFAULT_SOURCES.is_empty());
        assert!(!DEFAULT_SINKS.is_empty());
    }

    #[test]
    fn covers_canonical_apis() {
        let src_names: Vec<_> = DEFAULT_SOURCES.iter().map(|s| s.name).collect();
        for must in &["recv", "read", "fgets", "scanf", "argv"] {
            assert!(src_names.contains(must), "missing source `{must}`");
        }
        let sink_names: Vec<_> = DEFAULT_SINKS.iter().map(|s| s.name).collect();
        for must in &["strcpy", "sprintf", "memcpy", "system", "popen", "execve", "strlen"] {
            assert!(sink_names.contains(must), "missing sink `{must}`");
        }
    }

    #[test]
    fn argument_slots_match_real_abi() {
        // recv(int sockfd, void *buf, size_t len, int flags) — buf is arg 1.
        let recv = DEFAULT_SOURCES.iter().find(|s| s.name == "recv").unwrap();
        assert_eq!(recv.tainted, AbiSlot::Arg(1));

        // gets(char *s) — fills buffer at arg 0.
        let gets = DEFAULT_SOURCES.iter().find(|s| s.name == "gets").unwrap();
        assert_eq!(gets.tainted, AbiSlot::Arg(0));

        // memcpy(void *dst, const void *src, size_t n) — n is arg 2.
        let memcpy = DEFAULT_SINKS.iter().find(|s| s.name == "memcpy").unwrap();
        assert_eq!(memcpy.watched, AbiSlot::Arg(2));
        assert_eq!(memcpy.kind, SinkKind::LengthArg);

        // system(const char *cmd) — cmd is arg 0.
        let system = DEFAULT_SINKS.iter().find(|s| s.name == "system").unwrap();
        assert_eq!(system.watched, AbiSlot::Arg(0));
        assert_eq!(system.kind, SinkKind::Command);

        // strlen(const char *s) — an unbounded NUL scan over arg 0.
        let strlen = DEFAULT_SINKS.iter().find(|s| s.name == "strlen").unwrap();
        assert_eq!(strlen.watched, AbiSlot::Arg(0));
        assert_eq!(strlen.kind, SinkKind::CStringRead);
    }

    #[test]
    fn resolves_plain_libc_name() {
        let mut imports = HashMap::new();
        imports.insert(0x1000, "recv".to_string());
        let r = resolve_call(0x1000, &imports).expect("recv resolved");
        match r {
            SpecRef::Source(s) => assert_eq!(s.name, "recv"),
            _ => panic!("expected source"),
        }
    }

    #[test]
    fn strips_plt_suffix() {
        let mut imports = HashMap::new();
        imports.insert(0x2000, "strcpy@plt".to_string());
        let r = resolve_call(0x2000, &imports).expect("strcpy@plt resolved");
        match r {
            SpecRef::Sink(s) => assert_eq!(s.name, "strcpy"),
            _ => panic!("expected sink"),
        }
    }

    #[test]
    fn strips_macho_underscore() {
        let mut imports = HashMap::new();
        imports.insert(0x3000, "_system".to_string());
        let r = resolve_call(0x3000, &imports).expect("_system resolved");
        match r {
            SpecRef::Sink(s) => assert_eq!(s.name, "system"),
            _ => panic!("expected sink"),
        }
    }

    #[test]
    fn strips_versioned_suffix() {
        let mut imports = HashMap::new();
        imports.insert(0x4000, "memcpy@@GLIBC_2.14".to_string());
        let r = resolve_call(0x4000, &imports).expect("versioned memcpy");
        match r {
            SpecRef::Sink(s) => {
                assert_eq!(s.name, "memcpy");
                assert_eq!(s.kind, SinkKind::LengthArg);
            }
            _ => panic!("expected sink"),
        }
    }

    #[test]
    fn unknown_name_is_none() {
        let mut imports = HashMap::new();
        imports.insert(0x5000, "fancy_app_helper".to_string());
        assert!(resolve_call(0x5000, &imports).is_none());
    }

    #[test]
    fn missing_addr_is_none() {
        let imports: HashMap<u64, String> = HashMap::new();
        assert!(resolve_call(0xdead_beef, &imports).is_none());
    }

    // ---- path collector ----

    use crate::ir::{
        BlockId, Diagnostic, Expr, InferredType, SsaBlock, SsaCfg, SsaTerminator,
        Stmt, VarDef,
    };
    use pcode_ir::Varnode;

    fn mk_var(id: u32, expr: Expr) -> VarDef {
        VarDef {
            id: VarId(id),
            varnode: Varnode::constant(id as u64, 8),
            expr,
            size: 8,
            use_count: 1,
            param_name: None,
            call_return: false,
            inferred_type: InferredType::Unknown,
            display_type: None,
        }
    }

    fn block_with_term(stmts: Vec<Stmt>, term: SsaTerminator) -> SsaBlock {
        SsaBlock {
            id: BlockId(0),
            addr: 0,
            stmts,
            terminator: term,
        }
    }

    fn cfg(vars: Vec<VarDef>, block: SsaBlock) -> SsaCfg {
        SsaCfg {
            blocks: vec![block],
            vars,
            entry: BlockId(0),
            diagnostics: Vec::<Diagnostic>::new(),
        }
    }

    fn imports_with(entries: &[(u64, &str)]) -> HashMap<u64, String> {
        entries
            .iter()
            .map(|(a, n)| (*a, n.to_string()))
            .collect()
    }

    #[test]
    fn accepts_recv_then_strcpy_in_same_block() {
        // Two direct calls, recv (source) then strcpy (sink), both
        // resolved via the import map, terminator = Return.
        let vars = vec![
            mk_var(0, Expr::Const(0, 8)),       // sock fd
            mk_var(1, Expr::Const(0x4000, 8)),  // buf
            mk_var(2, Expr::Const(0x100, 8)),   // len
            mk_var(3, Expr::Const(0, 8)),       // flags
            mk_var(4, Expr::Const(0x5000, 8)),  // dst
        ];
        let stmts = vec![
            Stmt::Call {
                target: CallTarget::Direct(0x1000),
                args: vec![VarId(0), VarId(1), VarId(2), VarId(3)],
                out: None,
            },
            Stmt::Call {
                target: CallTarget::Direct(0x2000),
                args: vec![VarId(4), VarId(1)],
                out: None,
            },
        ];
        let block = block_with_term(stmts, SsaTerminator::Return(None));
        let ssa = cfg(vars, block);
        let imports = imports_with(&[(0x1000, "recv"), (0x2000, "strcpy")]);

        let paths = collect_paths(&ssa, &imports).expect("should accept");
        assert_eq!(paths.len(), 1);
        assert_eq!(paths[0].source.name, "recv");
        assert_eq!(paths[0].sink.name, "strcpy");
        assert!(paths[0].source_event < paths[0].sink_event);
    }

    #[test]
    fn cbranch_with_no_arm_blocks_falls_through_to_dangling() {
        // v1 collector explores BOTH arms of a CBranch. With only a
        // single block in the CFG and dangling block ids on the
        // CBranch terminator, both arms hit "dangling block id" and
        // the walk returns NoSinkFound (or the dangling rejection).
        // v0 rejected up front with UnsupportedTerminator(CBranch);
        // v1 attempts the arms and bails when blocks don't exist.
        let vars = vec![mk_var(0, Expr::Const(0, 1))];
        let block = block_with_term(
            vec![],
            SsaTerminator::CBranch {
                cond: VarId(0),
                taken: BlockId(1),
                fallthrough: BlockId(2),
            },
        );
        let ssa = cfg(vars, block);
        let imports: HashMap<u64, String> = HashMap::new();

        match collect_paths(&ssa, &imports) {
            Err(PathRejection::UnsupportedTerminator(reason)) => {
                // Either dangling-block rejection (the most accurate
                // outcome on this fixture) or NoSinkFound — both
                // signal "no v1 path collected".
                assert!(
                    reason == "dangling block id" || reason == "Branch",
                    "unexpected rejection reason: {reason}"
                );
            }
            Err(PathRejection::NoSinkFound) => {}
            other => panic!("expected dangling/NoSinkFound, got {other:?}"),
        }
    }

    #[test]
    fn cbranch_explores_both_arms_for_source_sink_pair() {
        // v1 hallmark: a CBranch that gates a sink in one arm and
        // not the other should produce ONE path through the
        // sink-bearing arm, with branch_decisions recording the
        // taken edge.
        //
        //   block 0: recv(...)         (Source in entry block stmts)
        //   block 0 terminator: CBranch cond → block 1 (sink) / block 2 (return)
        //   block 1 terminator: Call strcpy(...) → block 3
        //   block 2 terminator: Return
        //   block 3 terminator: Return
        let vars = vec![
            mk_var(0, Expr::Const(0, 1)),    // CBranch cond
            mk_var(1, Expr::Const(0, 8)),    // sock fd
            mk_var(2, Expr::Const(0x4000, 8)), // buf
            mk_var(3, Expr::Const(0x100, 8)),
            mk_var(4, Expr::Const(0, 8)),
            mk_var(5, Expr::Const(0x5000, 8)), // dst
        ];
        let block0 = SsaBlock {
            id: BlockId(0),
            addr: 0x1000,
            stmts: vec![Stmt::Call {
                target: CallTarget::Direct(0x10),
                args: vec![VarId(1), VarId(2), VarId(3), VarId(4)],
                out: None,
            }],
            terminator: SsaTerminator::CBranch {
                cond: VarId(0),
                taken: BlockId(1),
                fallthrough: BlockId(2),
            },
        };
        let block1 = SsaBlock {
            id: BlockId(1),
            addr: 0x1010,
            stmts: vec![],
            terminator: SsaTerminator::Call {
                target: CallTarget::Direct(0x20),
                args: vec![VarId(5), VarId(2)],
                out: None,
                fallthrough: BlockId(3),
            },
        };
        let block2 = SsaBlock {
            id: BlockId(2),
            addr: 0x1020,
            stmts: vec![],
            terminator: SsaTerminator::Return(None),
        };
        let block3 = SsaBlock {
            id: BlockId(3),
            addr: 0x1030,
            stmts: vec![],
            terminator: SsaTerminator::Return(None),
        };
        let ssa = SsaCfg {
            blocks: vec![block0, block1, block2, block3],
            vars,
            entry: BlockId(0),
            diagnostics: Vec::<Diagnostic>::new(),
        };
        let imports = imports_with(&[(0x10, "recv"), (0x20, "strcpy")]);

        let paths =
            collect_paths(&ssa, &imports).expect("v1 should explore CBranch arms");
        assert_eq!(paths.len(), 1, "expected single recv→strcpy path, got {}", paths.len());
        assert_eq!(paths[0].source.name, "recv");
        assert_eq!(paths[0].sink.name, "strcpy");
        assert_eq!(paths[0].branch_decisions.len(), 1);
        assert_eq!(paths[0].branch_decisions[0].block_addr, 0x1000);
        assert!(paths[0].branch_decisions[0].taken, "should have taken the sink-bearing arm");
    }

    #[test]
    fn cbranch_depth_limit_caps_walks() {
        // Construct a chain of CBranches deeper than MAX_BRANCH_DEPTH.
        // The walker must reject the over-budget walks but still
        // surface paths from the within-budget arms (none here, so
        // the result is a depth-limit rejection).
        //
        // Just chain k+1 CBranches where every fallthrough goes to
        // the next CBranch — this hits the depth cap on the
        // taken-arm walks specifically.
        let mut vars = Vec::new();
        let mut blocks = Vec::new();
        let depth = (MAX_BRANCH_DEPTH + 2) as usize;
        vars.push(mk_var(0, Expr::Const(0, 1))); // cond, reused
        for i in 0..depth {
            blocks.push(SsaBlock {
                id: BlockId(i),
                addr: 0x1000 + i as u64 * 0x10,
                stmts: vec![],
                terminator: SsaTerminator::CBranch {
                    cond: VarId(0),
                    taken: BlockId(i + 1),
                    fallthrough: BlockId(depth + 1),
                },
            });
        }
        // Terminal blocks at the bottom of the chain
        blocks.push(SsaBlock {
            id: BlockId(depth),
            addr: 0x2000,
            stmts: vec![],
            terminator: SsaTerminator::Return(None),
        });
        blocks.push(SsaBlock {
            id: BlockId(depth + 1),
            addr: 0x2010,
            stmts: vec![],
            terminator: SsaTerminator::Return(None),
        });
        let ssa = SsaCfg {
            blocks,
            vars,
            entry: BlockId(0),
            diagnostics: Vec::<Diagnostic>::new(),
        };
        let imports: HashMap<u64, String> = HashMap::new();

        let result = collect_paths(&ssa, &imports);
        // No source/sink configured; result should be an error,
        // and the depth limit must have been triggered for at
        // least the deepest arm.
        match result {
            Err(PathRejection::UnsupportedTerminator("depth limit"))
            | Err(PathRejection::NoSinkFound)
            | Err(PathRejection::UnsupportedTerminator("Branch")) => {}
            other => panic!("expected depth-limit/NoSink rejection, got {other:?}"),
        }
    }

    #[test]
    fn phi_assignment_is_skipped_not_rejected() {
        // v0 hard-rejected any Phi in entry block. v1 skips the
        // Phi assignment (recording no event for it) and keeps
        // walking — necessary to reach Source/Sink pairs in real
        // CFGs where every reconvergence point introduces a Phi.
        // Without source/sink configured, walk completes with
        // no paths -> NoSinkFound (NOT PhiInPath).
        let vars = vec![
            mk_var(0, Expr::Const(0, 8)),
            mk_var(1, Expr::Const(0, 8)),
            mk_var(2, Expr::Phi(vec![VarId(0), VarId(1)])),
        ];
        let block = block_with_term(
            vec![Stmt::Assign(VarId(2))],
            SsaTerminator::Return(None),
        );
        let ssa = cfg(vars, block);
        let imports: HashMap<u64, String> = HashMap::new();

        match collect_paths(&ssa, &imports) {
            Err(PathRejection::NoSinkFound) => {}
            other => panic!("expected NoSinkFound (Phi skipped), got {other:?}"),
        }
    }

    #[test]
    fn rejects_indirect_call() {
        let vars = vec![mk_var(0, Expr::Const(0, 8))];
        let block = block_with_term(
            vec![Stmt::Call {
                target: CallTarget::Indirect(Varnode::constant(0, 8)),
                args: vec![],
                out: None,
            }],
            SsaTerminator::Return(None),
        );
        let ssa = cfg(vars, block);
        let imports: HashMap<u64, String> = HashMap::new();

        assert_eq!(collect_paths(&ssa, &imports).unwrap_err(), PathRejection::IndirectCall);
    }

    #[test]
    fn no_sink_found() {
        // recv but no sink anywhere.
        let vars = vec![mk_var(0, Expr::Const(0, 8))];
        let block = block_with_term(
            vec![Stmt::Call {
                target: CallTarget::Direct(0x1000),
                args: vec![],
                out: None,
            }],
            SsaTerminator::Return(None),
        );
        let ssa = cfg(vars, block);
        let imports = imports_with(&[(0x1000, "recv")]);

        assert_eq!(collect_paths(&ssa, &imports).unwrap_err(), PathRejection::NoSinkFound);
    }

    #[test]
    fn source_after_sink_yields_no_path() {
        // Sink fires before any source — no taint flow possible.
        let vars = vec![mk_var(0, Expr::Const(0, 8))];
        let block = block_with_term(
            vec![
                Stmt::Call {
                    target: CallTarget::Direct(0x2000),
                    args: vec![],
                    out: None,
                },
                Stmt::Call {
                    target: CallTarget::Direct(0x1000),
                    args: vec![],
                    out: None,
                },
            ],
            SsaTerminator::Return(None),
        );
        let ssa = cfg(vars, block);
        let imports = imports_with(&[(0x1000, "recv"), (0x2000, "strcpy")]);

        assert_eq!(collect_paths(&ssa, &imports).unwrap_err(), PathRejection::NoSinkFound);
    }

    // ---- v0 SAT prover (gated on `smt` feature) ----

    #[cfg(feature = "smt")]
    fn one_call_pair_cfg(
        source_addr: u64, source_args: Vec<VarId>,
        sink_addr:   u64, sink_args:   Vec<VarId>,
        vars: Vec<VarDef>,
    ) -> SsaCfg {
        let stmts = vec![
            Stmt::Call {
                target: CallTarget::Direct(source_addr),
                args: source_args,
                out: None,
            },
            Stmt::Call {
                target: CallTarget::Direct(sink_addr),
                args: sink_args,
                out: None,
            },
        ];
        cfg(vars, block_with_term(stmts, SsaTerminator::Return(None)))
    }

    #[cfg(feature = "smt")]
    #[test]
    fn sat_recv_to_strcpy_is_reachable() {
        let vars = vec![
            mk_var(0, Expr::Const(0, 8)),       // sock fd
            mk_var(1, Expr::Const(0x4000, 8)),  // buf  (shared between recv arg1 and strcpy arg1)
            mk_var(2, Expr::Const(0x100, 8)),
            mk_var(3, Expr::Const(0, 8)),
            mk_var(4, Expr::Const(0x5000, 8)),  // dst
        ];
        let ssa = one_call_pair_cfg(
            0x1000, vec![VarId(0), VarId(1), VarId(2), VarId(3)],
            0x2000, vec![VarId(4), VarId(1)],
            vars,
        );
        let imports = imports_with(&[(0x1000, "recv"), (0x2000, "strcpy")]);
        let paths = collect_paths(&ssa, &imports).expect("v0 path collection");
        match solve(&paths[0], &ssa) {
            SmtFinding::Reachable { input_bytes, .. } => {
                assert_eq!(input_bytes.len(), 32);
                assert!(input_bytes.iter().all(|(_, b)| *b != 0));
            }
            other => panic!("expected Reachable, got {other:?}"),
        }
    }

    #[cfg(feature = "smt")]
    #[test]
    fn sat_recv_to_printf_is_reachable() {
        let vars = vec![
            mk_var(0, Expr::Const(0, 8)),
            mk_var(1, Expr::Const(0x4000, 8)),
            mk_var(2, Expr::Const(0x100, 8)),
            mk_var(3, Expr::Const(0, 8)),
        ];
        let ssa = one_call_pair_cfg(
            0x1000, vec![VarId(0), VarId(1), VarId(2), VarId(3)],
            0x2000, vec![VarId(1)],
            vars,
        );
        let imports = imports_with(&[(0x1000, "recv"), (0x2000, "printf")]);
        let paths = collect_paths(&ssa, &imports).expect("v0 path collection");
        match solve(&paths[0], &ssa) {
            SmtFinding::Reachable { input_bytes, .. } => {
                assert!(input_bytes.iter().any(|(_, b)| *b == b'%'));
            }
            other => panic!("expected Reachable with `%`, got {other:?}"),
        }
    }

    #[cfg(feature = "smt")]
    #[test]
    fn sat_argv_to_system_is_reachable() {
        let vars = vec![
            mk_var(0, Expr::Const(0, 8)),       // argc
            mk_var(1, Expr::Const(0x4000, 8)),  // argv (becomes argv[*] approx)
        ];
        let ssa = one_call_pair_cfg(
            0x1000, vec![VarId(0), VarId(1)],
            0x2000, vec![VarId(1)],
            vars,
        );
        let imports = imports_with(&[(0x1000, "argv"), (0x2000, "system")]);
        let paths = collect_paths(&ssa, &imports).expect("v0 path collection");
        match solve(&paths[0], &ssa) {
            SmtFinding::Reachable { input_bytes, .. } => {
                assert!(input_bytes
                    .iter()
                    .any(|(_, b)| matches!(*b, b';' | b'&' | b'|')));
            }
            other => panic!("expected Reachable with shell metachar, got {other:?}"),
        }
    }

    #[cfg(feature = "smt")]
    #[test]
    fn v8_inter_procedural_summary_synthesizes_reachable_path() {
        // outer(buf) → helper(buf). helper's summary records that
        // its arg 0 receives recv()'s output AND feeds strcpy()'s
        // watched slot. The walker must synthesize SourceCall +
        // SinkCall events at the outer→helper site so SAT can prove
        // taint reaches the strcpy without the helper body present.
        use crate::callgraph::FuncId;
        use crate::function_summary::{FunctionSummary, SinkInvocation, SourceEmission};

        let vars = vec![
            mk_var(0, Expr::Const(0x4000, 8)), // buf — outer's arg 0
        ];
        // outer body: a single Stmt::Call to helper(VarId 0).
        let outer = SsaCfg {
            blocks: vec![SsaBlock {
                id: BlockId(0),
                addr: 0x1000,
                stmts: vec![Stmt::Call {
                    target: CallTarget::Direct(0xBEEF),
                    args: vec![VarId(0)],
                    out: None,
                }],
                terminator: SsaTerminator::Return(None),
            }],
            vars,
            entry: BlockId(0),
            diagnostics: Vec::<Diagnostic>::new(),
        };

        // Imports: NO entry for 0xBEEF — that's the helper FuncId.
        let imports: HashMap<u64, String> = HashMap::new();

        // helper's pre-built summary (V6 would have produced this).
        let recv_spec = DEFAULT_SOURCES.iter().find(|s| s.name == "recv").copied().unwrap();
        let strcpy_spec = DEFAULT_SINKS.iter().find(|s| s.name == "strcpy").copied().unwrap();
        let helper_summary = FunctionSummary {
            func: FuncId(0xBEEF),
            sources: vec![SourceEmission {
                source: recv_spec,
                call_site: 0xBEEF + 4,
                tainted_caller_slots: vec![AbiSlot::Arg(0)],
            }],
            sinks: vec![SinkInvocation {
                sink: strcpy_spec,
                call_site: 0xBEEF + 8,
                tainted_caller_slots: vec![AbiSlot::Arg(0)],
            }],
        };
        let mut summaries = HashMap::new();
        summaries.insert(FuncId(0xBEEF), helper_summary);

        let paths = collect_paths_with_summaries(&outer, &imports, &summaries)
            .expect("V8 should synthesize Source/Sink events from helper's summary");
        assert_eq!(paths.len(), 1);
        let path = &paths[0];
        assert_eq!(path.source.name, "recv");
        assert_eq!(path.sink.name, "strcpy");
        // Synthesized events must carry the call chain.
        match &path.events[path.sink_event].kind {
            TaintEventKind::SinkCall { call_chain, .. } => {
                assert!(!call_chain.is_empty(), "sink call_chain should be populated");
            }
            other => panic!("expected SinkCall, got {other:?}"),
        }
        match solve(path, &outer) {
            SmtFinding::Reachable { call_chain, .. } => {
                // v2.V9: chain must surface on the SmtFinding so the
                // CLI can render `via [0x... -> 0x...]` traces.
                assert!(
                    !call_chain.is_empty(),
                    "Reachable.call_chain should propagate from synthesized event"
                );
            }
            other => panic!("expected Reachable via summary synthesis, got {other:?}"),
        }
    }

    #[cfg(feature = "smt")]
    #[test]
    fn unsat_recv_into_unrelated_strcpy_dst() {
        // recv fills buf (VarId 1), strcpy copies UNRELATED VarId 9
        // — no taint lineage. Must NotReachable.
        let vars = vec![
            mk_var(0, Expr::Const(0, 8)),
            mk_var(1, Expr::Const(0x4000, 8)),
            mk_var(2, Expr::Const(0x100, 8)),
            mk_var(3, Expr::Const(0, 8)),
            mk_var(4, Expr::Const(0x5000, 8)),
            mk_var(5, Expr::Const(0, 8)),
            mk_var(6, Expr::Const(0, 8)),
            mk_var(7, Expr::Const(0, 8)),
            mk_var(8, Expr::Const(0, 8)),
            mk_var(9, Expr::Const(0x6000, 8)),  // unrelated buffer
        ];
        let ssa = one_call_pair_cfg(
            0x1000, vec![VarId(0), VarId(1), VarId(2), VarId(3)],
            0x2000, vec![VarId(4), VarId(9)],
            vars,
        );
        let imports = imports_with(&[(0x1000, "recv"), (0x2000, "strcpy")]);
        let paths = collect_paths(&ssa, &imports).expect("v0 path collection");
        assert_eq!(solve(&paths[0], &ssa), SmtFinding::NotReachable);
    }

    #[cfg(feature = "smt")]
    #[test]
    fn lineage_eq_follows_var_chain() {
        // VarId 5 -> Var(4) -> Var(3) -> Var(2). lineage_eq(5, 2) = true.
        let vars = vec![
            mk_var(0, Expr::Const(0, 8)),
            mk_var(1, Expr::Const(0, 8)),
            mk_var(2, Expr::Const(0x4000, 8)),
            mk_var(3, Expr::Var(VarId(2))),
            mk_var(4, Expr::Var(VarId(3))),
            mk_var(5, Expr::Var(VarId(4))),
        ];
        let mem = MemMap::new();
        let calls = CallReturnMap::new();
        let regions = crate::region::RegionMap::default();
        assert!(varid_lineage_eq(VarId(5), VarId(2), &vars, &mem, &calls, &regions));
        assert!(!varid_lineage_eq(VarId(5), VarId(0), &vars, &mem, &calls, &regions));
    }

    #[cfg(feature = "smt")]
    #[test]
    fn lineage_eq_follows_store_then_load() {
        // Store v1 -> mem[addr=v0]; Load(v0) → should resolve to v1.
        // lineage_eq(load_var, v1) must be true via the memory map.
        let vars = vec![
            mk_var(0, Expr::Const(0x1000, 8)),     // addr
            mk_var(1, Expr::Const(0xdeadbeef, 8)), // stored value
            mk_var(2, Expr::Load(VarId(0))),       // load from same addr
        ];
        let regions = crate::region::RegionMap::default();
        let mut mem = MemMap::new();
        let key = mem_key(VarId(0), &vars, &regions);
        mem.insert(key, VarId(1));
        let calls = CallReturnMap::new();
        // Without memmap entry, lineage fails.
        assert!(!varid_lineage_eq(
            VarId(2),
            VarId(1),
            &vars,
            &MemMap::new(),
            &calls,
            &regions,
        ));
        // With memmap entry, lineage holds.
        assert!(varid_lineage_eq(VarId(2), VarId(1), &vars, &mem, &calls, &regions));
    }

    #[cfg(feature = "smt")]
    #[test]
    fn lineage_eq_follows_call_return_pass_through() {
        // v2.V5: out = strdup(arg). Sink reads `out`. Lineage from
        // `out` (VarId 2) must reach the source-tainted `arg`
        // (VarId 1) through the call's argument list.
        let vars = vec![
            mk_var(0, Expr::Const(0x1000, 8)),
            mk_var(1, Expr::Const(0xdead, 8)), // tainted source value
            mk_var(2, Expr::Const(0xbeef, 8)), // out of strdup; opaque expr
        ];
        let mem = MemMap::new();
        let mut calls = CallReturnMap::new();
        let regions = crate::region::RegionMap::default();
        // Without the call-return map: lineage misses (out is opaque).
        assert!(!varid_lineage_eq(VarId(2), VarId(1), &vars, &mem, &calls, &regions));
        // With the map: out=2 → args=[1], lineage holds.
        calls.insert(VarId(2), vec![VarId(1)]);
        assert!(varid_lineage_eq(VarId(2), VarId(1), &vars, &mem, &calls, &regions));
        // Argument that wasn't passed must still miss.
        assert!(!varid_lineage_eq(VarId(2), VarId(0), &vars, &mem, &calls, &regions));
    }

    #[cfg(feature = "smt")]
    #[test]
    fn region_keyed_mem_map_collides_distinct_unique_addrs_on_same_offset() {
        // v4.W7: two address VarIds computed via DISTINCT expression
        // shapes that nonetheless evaluate to the same logical
        // location must collide on the same MemMap key.
        // Simulated by giving both addr VarIds the same Region+
        // offset via classify_offset returning ConstOffset(8) for
        // both.
        let vars = vec![
            mk_var(0, Expr::Const(8, 8)),                // const offset 8
            mk_var(1, Expr::Const(8, 8)),                // distinct VarId, same const
            mk_var(2, Expr::Const(0xDEAD, 8)),           // stored value A
            mk_var(3, Expr::Const(0xBEEF, 8)),           // stored value B (later)
        ];
        let regions = crate::region::RegionMap::default();
        let mut mem = MemMap::new();
        let key0 = mem_key(VarId(0), &vars, &regions);
        let key1 = mem_key(VarId(1), &vars, &regions);
        assert_eq!(key0, key1, "same const-offset addrs must share MemMap key");
        mem.insert(key0.clone(), VarId(2));
        // Second store via distinct addr VarId overwrites — verifies
        // the alias relation, not just two equal keys.
        mem.insert(key1, VarId(3));
        assert_eq!(mem.get(&key0).copied(), Some(VarId(3)));
        assert_eq!(mem.len(), 1);
    }

    #[cfg(feature = "smt")]
    #[test]
    fn build_call_return_map_captures_stmt_and_terminator_calls() {
        let vars = vec![
            mk_var(0, Expr::Const(0, 8)),
            mk_var(1, Expr::Const(0, 8)),
            mk_var(2, Expr::Const(0, 8)),
            mk_var(3, Expr::Const(0, 8)),
        ];
        let block = SsaBlock {
            id: BlockId(0),
            addr: 0,
            stmts: vec![Stmt::Call {
                target: CallTarget::Direct(0x1000),
                args: vec![VarId(0)],
                out: Some(VarId(2)),
            }],
            terminator: SsaTerminator::Call {
                target: CallTarget::Direct(0x2000),
                args: vec![VarId(1)],
                out: Some(VarId(3)),
                fallthrough: BlockId(1),
            },
        };
        let block1 = SsaBlock {
            id: BlockId(1),
            addr: 4,
            stmts: vec![],
            terminator: SsaTerminator::Return(None),
        };
        let ssa = SsaCfg {
            blocks: vec![block, block1],
            vars,
            entry: BlockId(0),
            diagnostics: Vec::<Diagnostic>::new(),
        };
        let calls = build_call_return_map(&ssa);
        assert_eq!(calls.get(&VarId(2)).map(|a| a.as_slice()), Some(&[VarId(0)][..]));
        assert_eq!(calls.get(&VarId(3)).map(|a| a.as_slice()), Some(&[VarId(1)][..]));
    }

    #[test]
    fn sink_in_terminator_call_slot() {
        // strcpy lives in the SsaTerminator::Call slot. Path
        // collector must walk the Call terminator and continue to
        // the fallthrough block (which here just returns).
        let vars = vec![
            mk_var(0, Expr::Const(0, 8)),
            mk_var(1, Expr::Const(0x4000, 8)),
            mk_var(2, Expr::Const(0x5000, 8)),
        ];
        let block0 = SsaBlock {
            id: BlockId(0),
            addr: 0,
            stmts: vec![Stmt::Call {
                target: CallTarget::Direct(0x1000),
                args: vec![VarId(0), VarId(1), VarId(0), VarId(0)],
                out: None,
            }],
            terminator: SsaTerminator::Call {
                target: CallTarget::Direct(0x2000),
                args: vec![VarId(2), VarId(1)],
                out: None,
                fallthrough: BlockId(1),
            },
        };
        let block1 = SsaBlock {
            id: BlockId(1),
            addr: 0x10,
            stmts: vec![],
            terminator: SsaTerminator::Return(None),
        };
        let ssa = SsaCfg {
            blocks: vec![block0, block1],
            vars,
            entry: BlockId(0),
            diagnostics: Vec::<Diagnostic>::new(),
        };
        let imports = imports_with(&[(0x1000, "recv"), (0x2000, "strcpy")]);

        let paths = collect_paths(&ssa, &imports).expect("should accept terminator-Call sink");
        assert_eq!(paths.len(), 1);
        assert_eq!(paths[0].sink.name, "strcpy");
    }
}