1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
use super::super::{CertRule, RuleViolation};
use crate::analyze::cfg::FunctionCfg;
use crate::analyze::const_eval::{self, MacroConstantMap, VarRangeMap};
use crate::analyze::context::ProjectContext;
use crate::analyze::function_summary::FunctionSummary;
use crate::analyze::value_range::RangeAnalysisResult;
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils::{self, get_node_text};
use crate::utility::cert_c::std_functions;
use std::cell::RefCell;
use std::collections::HashMap;
use tree_sitter::Node;
pub struct Int32C {
project_macros: RefCell<MacroConstantMap>,
current_macros: RefCell<MacroConstantMap>,
struct_field_types: RefCell<HashMap<String, HashMap<String, String>>>,
function_cfgs: RefCell<HashMap<usize, FunctionCfg>>,
vra_results: RefCell<HashMap<usize, RangeAnalysisResult>>,
function_summaries: RefCell<HashMap<String, FunctionSummary>>,
}
impl Int32C {
pub fn new() -> Self {
Self {
project_macros: RefCell::new(MacroConstantMap::new()),
current_macros: RefCell::new(MacroConstantMap::new()),
struct_field_types: RefCell::new(HashMap::new()),
function_cfgs: RefCell::new(HashMap::new()),
vra_results: RefCell::new(HashMap::new()),
function_summaries: RefCell::new(HashMap::new()),
}
}
/// Get VRA-derived variable ranges at a specific expression node.
/// Uses the block entry ranges as a conservative approximation.
fn vra_var_ranges_at(&self, expr_node: &Node) -> Option<VarRangeMap> {
let vra_results = self.vra_results.borrow();
let cfgs = self.function_cfgs.borrow();
if vra_results.is_empty() || cfgs.is_empty() {
return None;
}
let func = ast_utils::find_containing_function(expr_node)?;
let start_byte = func.start_byte();
let cfg = cfgs.get(&start_byte)?;
let vra = vra_results.get(&start_byte)?;
let byte_offset = expr_node.start_byte();
// Find containing block
let block = cfg
.blocks
.iter()
.find(|b| {
b.statements
.iter()
.any(|&(s, e)| byte_offset >= s && byte_offset < e)
})
.or_else(|| {
cfg.blocks.iter().find(|b| {
b.byte_range.0 > 0
&& byte_offset >= b.byte_range.0
&& byte_offset < b.byte_range.1
})
})?;
let entry = vra.block_entry_ranges.get(&block.id)?;
let var_ranges: VarRangeMap = entry
.iter()
.map(|(name, typed)| (name.clone(), typed.range))
.collect();
if var_ranges.is_empty() {
None
} else {
Some(var_ranges)
}
}
}
impl CertRule for Int32C {
fn rule_id(&self) -> &'static str {
"INT32-C"
}
fn description(&self) -> &'static str {
"Ensure that operations on signed integers do not result in overflow"
}
fn severity(&self) -> Severity {
Severity::High
}
fn category(&self) -> RuleCategory {
RuleCategory::Rule
}
fn cert_id(&self) -> &'static str {
"INT32-C"
}
fn set_project_context(&self, context: &ProjectContext) {
*self.project_macros.borrow_mut() = context.macro_constants.clone();
*self.struct_field_types.borrow_mut() = context.struct_field_types.clone();
*self.function_summaries.borrow_mut() = context.function_summaries.clone();
}
fn set_function_cfgs(&self, cfgs: &HashMap<usize, FunctionCfg>) {
*self.function_cfgs.borrow_mut() = cfgs.clone();
}
fn set_vra_results(&self, results: &HashMap<usize, RangeAnalysisResult>) {
let mut stored = HashMap::new();
for (&key, result) in results {
stored.insert(
key,
RangeAnalysisResult {
block_entry_ranges: result.block_entry_ranges.clone(),
block_exit_ranges: result.block_exit_ranges.clone(),
return_ranges: result.return_ranges.clone(),
},
);
}
*self.vra_results.borrow_mut() = stored;
}
fn needs_vra(&self) -> bool {
true
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
let type_map = self.collect_variable_types(node, source);
// Merge project-level macros with per-file macros
let mut macros = self.project_macros.borrow().clone();
macros.extend(const_eval::collect_macro_constants(node, source));
*self.current_macros.borrow_mut() = macros;
self.check_node(node, source, &mut violations, &type_map);
violations
}
}
impl Int32C {
fn check_node(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
type_map: &HashMap<String, String>,
) {
// Skip nodes inside compile-time contexts (cannot overflow at runtime)
if self.is_in_compile_time_context(node) {
return;
}
match node.kind() {
"binary_expression" => {
self.check_binary_operation(node, source, violations, type_map);
}
"assignment_expression" => {
self.check_assignment_operation(node, source, violations, type_map);
}
"unary_expression" => {
self.check_unary_operation(node, source, violations, type_map);
}
"update_expression" => {
self.check_increment_decrement(node, source, violations, type_map);
}
"call_expression" => {
self.check_function_call(node, source, violations);
}
_ => {}
}
// Recursively check child nodes
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
// Scope type_map per function to avoid cross-function name collisions
// (e.g., float X_pred in one function vs int32_t X_pred in another)
if child.kind() == "function_definition" {
let fn_type_map = self.collect_variable_types(&child, source);
self.check_node(&child, source, violations, &fn_type_map);
} else {
self.check_node(&child, source, violations, type_map);
}
}
}
}
/// Check if this node is inside a compile-time context where overflow cannot occur at runtime.
/// Covers: sizeof(), _Static_assert, enum value definitions, array size declarators.
fn is_in_compile_time_context(&self, node: &Node) -> bool {
let mut current = node.parent();
while let Some(parent) = current {
match parent.kind() {
"sizeof_expression" => return true,
"static_assert_declaration" => return true,
"enumerator" => return true,
"array_declarator" => {
// Array size expressions like int arr[N + 1] are compile-time
return true;
}
"function_definition" => break,
_ => {}
}
current = parent.parent();
}
false
}
/// For compound assignments (`x op= y`), check if `x op y` provably fits
/// in a signed integer of `bits` width using constant evaluation.
/// Note: only resolves the RHS — the LHS is the mutation target and its
/// initial assignment doesn't reflect its current value (especially in loops).
fn compound_expr_fits_signed(&self, node: &Node, source: &str, op: &str, bits: u32) -> bool {
let macros = self.current_macros.borrow();
if let (Some(left), Some(right)) = (
node.child_by_field_name("left"),
node.child_by_field_name("right"),
) {
let loop_ranges = const_eval::extract_loop_var_ranges(node, source, ¯os);
let mut var_ranges = loop_ranges.clone();
// Only resolve RHS identifiers — LHS is the mutation target
const_eval::resolve_identifiers_in_expr(
&right,
source,
¯os,
&loop_ranges,
&mut var_ranges,
);
// LHS: only use loop ranges and macros (not local assignments)
let lr = const_eval::try_evaluate_range(&left, source, ¯os, &loop_ranges);
let rr = const_eval::try_evaluate_range(&right, source, ¯os, &var_ranges);
if let (Some(lr), Some(rr)) = (lr, rr) {
let result = match op {
"+" => lr.add(&rr),
"-" => lr.sub(&rr),
"*" => lr.mul(&rr),
"<<" => lr.shl(&rr),
_ => None,
};
if let Some(range) = result {
return range.fits_in_signed(bits);
}
}
}
false
}
fn check_binary_operation(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
type_map: &HashMap<String, String>,
) {
if let Some(operator) = self.get_operator(node, source) {
match operator.as_str() {
"+" => self.check_addition(node, source, violations, type_map),
"-" => self.check_subtraction(node, source, violations, type_map),
"*" => self.check_multiplication(node, source, violations, type_map),
"/" => self.check_division(node, source, violations, type_map),
"%" => self.check_modulo(node, source, violations, type_map),
"<<" => self.check_left_shift(node, source, violations, type_map),
_ => {}
}
}
}
fn check_assignment_operation(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
type_map: &HashMap<String, String>,
) {
if let Some(operator) = self.get_assignment_operator(node, source) {
match operator.as_str() {
"+=" => self.check_compound_addition(node, source, violations, type_map),
"-=" => self.check_compound_subtraction(node, source, violations, type_map),
"*=" => self.check_compound_multiplication(node, source, violations, type_map),
"/=" => self.check_compound_division(node, source, violations),
"%=" => self.check_compound_modulo(node, source, violations),
"<<=" => self.check_compound_left_shift(node, source, violations, type_map),
_ => {}
}
}
}
fn check_unary_operation(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
type_map: &HashMap<String, String>,
) {
if let Some(operator) = self.get_unary_operator(node, source) {
if operator == "-" {
self.check_negation(node, source, violations, type_map);
}
}
}
fn check_addition(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
type_map: &HashMap<String, String>,
) {
if let (Some(left), Some(right)) = (
node.child_by_field_name("left"),
node.child_by_field_name("right"),
) {
let left_type = self.infer_type(&left, source, type_map);
let right_type = self.infer_type(&right, source, type_map);
// Skip if any operand is a non-integer type (char, float, pointer, etc.)
if left_type == "not_applicable" || right_type == "not_applicable" {
return;
}
// Skip if either operand is unsigned — unsigned wrap is INT30-C, not INT32-C
if left_type == "unsigned" || right_type == "unsigned" {
return;
}
if self.is_signed_type(&left_type) || self.is_signed_type(&right_type) {
// Skip if this operation is part of an overflow check comparison
if self.is_part_of_comparison(node, source) {
return;
}
// Skip if using wider type (cast to long long before addition)
let left_text = get_node_text(&left, source);
let right_text = get_node_text(&right, source);
if self.has_wider_cast(left_text, right_text) {
return;
}
// Skip if inside a block guarded by a type-limit bounds check
let op_names = self.extract_operand_names(node, source);
if self.is_inside_bounds_checked_block(node, source, &op_names) {
return;
}
// Skip if constant evaluation proves the result fits in 32-bit signed
if const_eval::expression_fits_in_signed_vra(
node,
source,
&self.current_macros.borrow(),
32,
self.vra_var_ranges_at(node).as_ref(),
) {
return;
}
// Skip opaque_value + small_literal (e.g. strlen() + 1)
// but NOT for known full-range functions (atoi, rand, etc.)
if Self::is_small_increment_of_opaque(
node,
source,
&self.function_summaries.borrow(),
) {
return;
}
if !self.has_overflow_check_addition(node, source) {
let start_point = node.start_position();
let expr_text = get_node_text(node, source);
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::High,
message: format!(
"Signed integer addition '{}' may overflow without proper checking",
expr_text
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some("Add overflow check: if ((b > 0 && a > INT_MAX - b) || (b < 0 && a < INT_MIN - b)) { /* handle error */ }".to_string()),
..Default::default()
});
}
}
}
}
fn check_subtraction(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
type_map: &HashMap<String, String>,
) {
if let (Some(left), Some(right)) = (
node.child_by_field_name("left"),
node.child_by_field_name("right"),
) {
let left_type = self.infer_type(&left, source, type_map);
let right_type = self.infer_type(&right, source, type_map);
// Skip if any operand is a non-integer type (char, float, pointer, etc.)
if left_type == "not_applicable" || right_type == "not_applicable" {
return;
}
// Skip if either operand is unsigned — unsigned wrap is INT30-C, not INT32-C
if left_type == "unsigned" || right_type == "unsigned" {
return;
}
if self.is_signed_type(&left_type) || self.is_signed_type(&right_type) {
// Skip if this operation is part of an overflow check comparison
if self.is_part_of_comparison(node, source) {
return;
}
// Skip if both operands are constants (compiler handles these)
let left_text = get_node_text(&left, source);
let right_text = get_node_text(&right, source);
if self.is_constant_expression(left_text) && self.is_constant_expression(right_text)
{
return; // Safe - constant expression
}
// Skip if using wider type (cast to long long before subtraction)
if self.has_wider_cast(left_text, right_text) {
return;
}
// Skip if inside a block guarded by a type-limit bounds check
let op_names = self.extract_operand_names(node, source);
if self.is_inside_bounds_checked_block(node, source, &op_names) {
return;
}
// Skip if constant evaluation proves the result fits in 32-bit signed
if const_eval::expression_fits_in_signed_vra(
node,
source,
&self.current_macros.borrow(),
32,
self.vra_var_ranges_at(node).as_ref(),
) {
return;
}
if !self.has_overflow_check_subtraction(node, source) {
let start_point = node.start_position();
let expr_text = get_node_text(node, source);
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::High,
message: format!(
"Signed integer subtraction '{}' may overflow without proper checking",
expr_text
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some("Add overflow check: if ((b < 0 && a > INT_MAX + b) || (b > 0 && a < INT_MIN + b)) { /* handle error */ }".to_string()),
..Default::default()
});
}
}
}
}
fn check_multiplication(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
type_map: &HashMap<String, String>,
) {
if let (Some(left), Some(right)) = (
node.child_by_field_name("left"),
node.child_by_field_name("right"),
) {
let left_type = self.infer_type(&left, source, type_map);
let right_type = self.infer_type(&right, source, type_map);
// Skip if any operand is a non-integer type (char, float, pointer, etc.)
if left_type == "not_applicable" || right_type == "not_applicable" {
return;
}
// Skip if either operand is unsigned — unsigned wrap is INT30-C, not INT32-C
if left_type == "unsigned" || right_type == "unsigned" {
return;
}
if self.is_signed_type(&left_type) || self.is_signed_type(&right_type) {
// Skip if this operation is part of an overflow check comparison
if self.is_part_of_comparison(node, source) {
return;
}
// Skip if using wider type (cast to long long before multiplication)
let left_text = get_node_text(&left, source);
let right_text = get_node_text(&right, source);
if self.has_wider_cast(left_text, right_text) {
return; // Safe - using wider type
}
// Skip if operands are bounded for-loop variables
if self.is_in_bounded_for_loop(node, source) {
return;
}
// Skip if inside a block guarded by a type-limit bounds check
let op_names = self.extract_operand_names(node, source);
if self.is_inside_bounds_checked_block(node, source, &op_names) {
return;
}
// Skip if constant evaluation proves the result fits in 32-bit signed
if const_eval::expression_fits_in_signed_vra(
node,
source,
&self.current_macros.borrow(),
32,
self.vra_var_ranges_at(node).as_ref(),
) {
return;
}
if !self.has_overflow_check_multiplication(node, source) {
let start_point = node.start_position();
let expr_text = get_node_text(node, source);
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::High,
message: format!(
"Signed integer multiplication '{}' may overflow without proper checking",
expr_text
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some("Add overflow check using complex multiplication overflow detection".to_string()),
..Default::default()
});
}
}
}
}
fn check_division(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
type_map: &HashMap<String, String>,
) {
if let (Some(left), Some(right)) = (
node.child_by_field_name("left"),
node.child_by_field_name("right"),
) {
let left_text = get_node_text(&left, source);
let right_text = get_node_text(&right, source);
let left_type = self.infer_type(&left, source, type_map);
let right_type = self.infer_type(&right, source, type_map);
// Skip if any operand is a non-integer type (char, float, pointer, etc.)
if left_type == "not_applicable" || right_type == "not_applicable" {
return;
}
// Skip if either operand is unsigned — unsigned wrap is INT30-C, not INT32-C
if left_type == "unsigned" || right_type == "unsigned" {
return;
}
// Check for signed integer division
// INT_MIN / -1 causes overflow because -INT_MIN cannot be represented
if self.is_signed_type(&left_type) || self.is_signed_type(&right_type) {
// Skip if this division is part of an overflow check comparison
if self.is_part_of_comparison(node, source) {
return;
}
// Check if there's explicit INT_MIN/-1 pattern OR generic signed division without checks
let has_explicit_risk = right_text.trim() == "-1"
|| right_text.contains("-1")
|| left_text.contains("INT_MIN")
|| left_text.contains("LONG_MIN")
|| self.could_be_int_min(&left, source);
// Also flag generic signed division of variables (could be INT_MIN / -1 at runtime)
// but skip if the right operand (divisor) is unsigned — can't be -1
let is_variable_division = left.kind() == "identifier"
&& right.kind() == "identifier"
&& !self.is_unsigned_type(&right_type);
if (has_explicit_risk || is_variable_division)
&& !self.has_division_overflow_check(node, source)
{
let start_point = node.start_position();
let expr_text = get_node_text(node, source);
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::High,
message: format!(
"Signed integer division '{}' may overflow (INT_MIN / -1)",
expr_text
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some("Add check: if (dividend == INT_MIN && divisor == -1) { /* handle error */ }".to_string()),
..Default::default()
});
}
}
}
}
fn check_modulo(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
type_map: &HashMap<String, String>,
) {
if let (Some(left), Some(right)) = (
node.child_by_field_name("left"),
node.child_by_field_name("right"),
) {
let left_text = get_node_text(&left, source);
let right_text = get_node_text(&right, source);
let left_type = self.infer_type(&left, source, type_map);
let right_type = self.infer_type(&right, source, type_map);
// Skip if any operand is a non-integer type (char, float, pointer, etc.)
if left_type == "not_applicable" || right_type == "not_applicable" {
return;
}
// Skip if either operand is unsigned — unsigned wrap is INT30-C, not INT32-C
if left_type == "unsigned" || right_type == "unsigned" {
return;
}
// Check for signed integer modulo
// INT_MIN % -1 causes overflow
if self.is_signed_type(&left_type) || self.is_signed_type(&right_type) {
let has_explicit_risk = (left_text.contains("INT_MIN")
|| left_text.contains("LONG_MIN")
|| self.could_be_int_min(&left, source))
&& (right_text == "-1" || right_text.contains("-1"));
// Also flag generic signed modulo of variables (could be INT_MIN % -1 at runtime)
// but skip if the right operand (divisor) is unsigned — can't be -1
let is_variable_modulo = left.kind() == "identifier"
&& right.kind() == "identifier"
&& !self.is_unsigned_type(&right_type);
if (has_explicit_risk || is_variable_modulo)
&& !self.has_modulo_overflow_check(node, source)
{
let start_point = node.start_position();
let expr_text = get_node_text(node, source);
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::High,
message: format!(
"Signed integer modulo '{}' may overflow (INT_MIN % -1)",
expr_text
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some("Add check: if (dividend == INT_MIN && divisor == -1) { /* handle error */ }".to_string()),
..Default::default()
});
}
}
}
}
fn check_negation(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
type_map: &HashMap<String, String>,
) {
if let Some(argument) = node.child_by_field_name("argument") {
let _arg_text = get_node_text(&argument, source);
let arg_type = self.infer_type(&argument, source, type_map);
// Skip if operand is a non-integer type (char, float, pointer, etc.)
if arg_type == "not_applicable" {
return;
}
// Check for negation of signed integers, especially -INT_MIN which causes overflow
if self.is_signed_type(&arg_type) && !self.has_negation_overflow_check(node, source) {
let start_point = node.start_position();
let expr_text = get_node_text(node, source);
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::High,
message: format!(
"Signed integer negation '{}' may overflow (-INT_MIN)",
expr_text
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some(
"Add check: if (value == INT_MIN) { /* handle error */ }".to_string(),
),
..Default::default()
});
}
}
}
fn check_left_shift(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
type_map: &HashMap<String, String>,
) {
if let (Some(left), Some(_right)) = (
node.child_by_field_name("left"),
node.child_by_field_name("right"),
) {
let left_type = self.infer_type(&left, source, type_map);
// Skip if operand is a non-integer type (char, float, pointer, etc.)
if left_type == "not_applicable" {
return;
}
if self.is_signed_type(&left_type) {
// Skip if inside a block guarded by a type-limit bounds check
let op_names = self.extract_operand_names(node, source);
if self.is_inside_bounds_checked_block(node, source, &op_names) {
return;
}
// Skip if constant evaluation proves the result fits in 32-bit signed
if const_eval::expression_fits_in_signed_vra(
node,
source,
&self.current_macros.borrow(),
32,
self.vra_var_ranges_at(node).as_ref(),
) {
return;
}
if !self.has_shift_overflow_check(node, source) {
let start_point = node.start_position();
let expr_text = get_node_text(node, source);
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::High,
message: format!(
"Signed integer left shift '{}' may overflow or exhibit undefined behavior",
expr_text
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some("Validate shift amount and check for overflow before shifting".to_string()),
..Default::default()
});
}
}
}
}
fn check_compound_addition(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
type_map: &HashMap<String, String>,
) {
if let Some(left) = node.child_by_field_name("left") {
let left_type = self.infer_type(&left, source, type_map);
// Skip if operand is a non-integer type (char, float, pointer, etc.)
if left_type == "not_applicable" {
return;
}
if self.is_signed_type(&left_type) {
// Skip if inside a block guarded by a type-limit bounds check
let op_names = self.extract_operand_names(node, source);
if self.is_inside_bounds_checked_block(node, source, &op_names) {
return;
}
// Skip if constant evaluation proves the result fits in 32-bit signed
if self.compound_expr_fits_signed(node, source, "+", 32) {
return;
}
if !self.has_overflow_check_compound(node, source) {
let start_point = node.start_position();
let expr_text = get_node_text(node, source);
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::High,
message: format!(
"Signed integer compound addition '{}' may overflow without checking",
expr_text
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some(
"Add overflow check before compound assignment".to_string(),
),
..Default::default()
});
}
}
}
}
fn check_compound_subtraction(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
type_map: &HashMap<String, String>,
) {
if let Some(left) = node.child_by_field_name("left") {
let left_type = self.infer_type(&left, source, type_map);
// Skip if operand is a non-integer type (char, float, pointer, etc.)
if left_type == "not_applicable" {
return;
}
if self.is_signed_type(&left_type) {
// Skip if inside a block guarded by a type-limit bounds check
let op_names = self.extract_operand_names(node, source);
if self.is_inside_bounds_checked_block(node, source, &op_names) {
return;
}
// Skip if constant evaluation proves the result fits in 32-bit signed
if self.compound_expr_fits_signed(node, source, "-", 32) {
return;
}
if !self.has_overflow_check_compound(node, source) {
let start_point = node.start_position();
let expr_text = get_node_text(node, source);
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::High,
message: format!(
"Signed integer compound subtraction '{}' may overflow without checking",
expr_text
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some("Add overflow check before compound assignment".to_string()),
..Default::default()
});
}
}
}
}
fn check_compound_multiplication(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
type_map: &HashMap<String, String>,
) {
if let Some(left) = node.child_by_field_name("left") {
let left_type = self.infer_type(&left, source, type_map);
// Skip if operand is a non-integer type (char, float, pointer, etc.)
if left_type == "not_applicable" {
return;
}
if self.is_signed_type(&left_type) {
// Skip if inside a block guarded by a type-limit bounds check
let op_names = self.extract_operand_names(node, source);
if self.is_inside_bounds_checked_block(node, source, &op_names) {
return;
}
// Skip if constant evaluation proves the result fits in 32-bit signed
if self.compound_expr_fits_signed(node, source, "*", 32) {
return;
}
if !self.has_overflow_check_compound(node, source) {
let start_point = node.start_position();
let expr_text = get_node_text(node, source);
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::High,
message: format!(
"Signed integer compound multiplication '{}' may overflow without checking",
expr_text
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some("Add overflow check before compound assignment".to_string()),
..Default::default()
});
}
}
}
}
fn check_compound_division(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
) {
if let (Some(left), Some(right)) = (
node.child_by_field_name("left"),
node.child_by_field_name("right"),
) {
let left_text = get_node_text(&left, source);
let right_text = get_node_text(&right, source);
if (left_text.contains("INT_MIN") || self.could_be_int_min(&left, source))
&& (right_text == "-1" || right_text.contains("-1"))
&& !self.has_overflow_check_compound(node, source)
{
let start_point = node.start_position();
let expr_text = get_node_text(node, source);
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::High,
message: format!(
"Signed integer compound division '{}' may overflow (INT_MIN /= -1)",
expr_text
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some("Add check before assignment: if (left == INT_MIN && right == -1) { /* handle error */ }".to_string()),
..Default::default()
});
}
}
}
fn check_compound_modulo(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
) {
if let (Some(left), Some(right)) = (
node.child_by_field_name("left"),
node.child_by_field_name("right"),
) {
let left_text = get_node_text(&left, source);
let right_text = get_node_text(&right, source);
if (left_text.contains("INT_MIN") || self.could_be_int_min(&left, source))
&& (right_text == "-1" || right_text.contains("-1"))
&& !self.has_overflow_check_compound(node, source)
{
let start_point = node.start_position();
let expr_text = get_node_text(node, source);
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::High,
message: format!(
"Signed integer compound modulo '{}' may overflow (INT_MIN %= -1)",
expr_text
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some("Add check before assignment: if (left == INT_MIN && right == -1) { /* handle error */ }".to_string()),
..Default::default()
});
}
}
}
fn check_compound_left_shift(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
type_map: &HashMap<String, String>,
) {
if let Some(left) = node.child_by_field_name("left") {
let left_type = self.infer_type(&left, source, type_map);
// Skip if operand is a non-integer type (char, float, pointer, etc.)
if left_type == "not_applicable" {
return;
}
if self.is_signed_type(&left_type) {
// Skip if constant evaluation proves the result fits in 32-bit signed
if self.compound_expr_fits_signed(node, source, "<<", 32) {
return;
}
if !self.has_overflow_check_compound(node, source) {
let start_point = node.start_position();
let expr_text = get_node_text(node, source);
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::High,
message: format!(
"Signed integer compound left shift '{}' may overflow or exhibit undefined behavior",
expr_text
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some("Validate shift amount and check for overflow before assignment".to_string()),
..Default::default()
});
}
}
}
}
fn check_increment_decrement(
&self,
node: &Node,
source: &str,
violations: &mut Vec<RuleViolation>,
type_map: &HashMap<String, String>,
) {
if let Some(argument) = node.child_by_field_name("argument") {
let arg_type = self.infer_type(&argument, source, type_map);
// Skip if operand is a non-integer type (char, float, pointer, etc.)
if arg_type == "not_applicable" {
return;
}
if self.is_signed_type(&arg_type) {
// Skip if this is part of a safe for loop (bounded, starting from small values)
if self.is_in_safe_for_loop(node, source) {
return;
}
// Skip if inside a block guarded by a type-limit bounds check
let op_names = self.extract_operand_names(node, source);
if self.is_inside_bounds_checked_block(node, source, &op_names) {
return;
}
// Skip if VRA proves the result fits in 32-bit signed
if const_eval::expression_fits_in_signed_vra(
node,
source,
&self.current_macros.borrow(),
32,
self.vra_var_ranges_at(node).as_ref(),
) {
return;
}
let operator = self.get_update_operator(node, source);
if (operator == "++" || operator == "--")
&& !self.has_overflow_check_update(node, source)
{
let start_point = node.start_position();
let expr_text = get_node_text(node, source);
let message = if operator == "++" {
format!(
"Signed integer increment '{}' may overflow at INT_MAX",
expr_text
)
} else {
format!(
"Signed integer decrement '{}' may overflow at INT_MIN",
expr_text
)
};
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::Medium,
message,
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some(
"Add bounds checking before increment/decrement".to_string(),
),
..Default::default()
});
}
}
}
}
fn check_function_call(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
if let Some(function_node) = node.child_by_field_name("function") {
let function_name = get_node_text(&function_node, source);
// Check for functions that commonly receive arithmetic expressions that might overflow
match function_name {
"malloc" | "calloc" | "realloc" => {
self.check_allocation_overflow(node, source, function_name, violations);
}
"memcpy" | "memmove" | "memset" => {
self.check_memory_function_overflow(node, source, function_name, violations);
}
"abs" | "labs" | "llabs" => {
self.check_abs_overflow(node, source, function_name, violations);
}
_ => {}
}
}
}
fn check_allocation_overflow(
&self,
node: &Node,
source: &str,
function_name: &str,
violations: &mut Vec<RuleViolation>,
) {
if let Some(arguments) = node.child_by_field_name("arguments") {
let mut arg_idx = 0;
for i in 0..arguments.child_count() {
if let Some(arg_node) = arguments.child(i) {
let kind = arg_node.kind();
if kind == "(" || kind == ")" || kind == "," {
continue;
}
let arg_text = get_node_text(&arg_node, source);
if self.contains_arithmetic(arg_text) {
// Use const_eval to check if the arithmetic provably fits
let macros = self.current_macros.borrow();
let vra_ranges = self.vra_var_ranges_at(&arg_node);
if const_eval::expression_fits_in_signed_vra(
&arg_node,
source,
¯os,
64,
vra_ranges.as_ref(),
) {
arg_idx += 1;
continue;
}
drop(macros);
if !self.has_allocation_overflow_check(node, source) {
let start_point = node.start_position();
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::High,
message: format!(
"{}() argument {} contains arithmetic that may overflow: '{}'",
function_name,
arg_idx + 1,
arg_text
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some(
"Validate arithmetic operations before passing to allocation functions"
.to_string(),
),
..Default::default()
});
}
}
arg_idx += 1;
}
}
}
}
fn check_memory_function_overflow(
&self,
node: &Node,
source: &str,
function_name: &str,
violations: &mut Vec<RuleViolation>,
) {
// Check size arguments for arithmetic that might overflow
let size_arg_idx: usize = match function_name {
"memcpy" | "memmove" | "memset" => 2, // Third argument is size
_ => return,
};
if let Some(arguments) = node.child_by_field_name("arguments") {
let mut arg_idx = 0;
for i in 0..arguments.child_count() {
if let Some(arg_node) = arguments.child(i) {
let kind = arg_node.kind();
if kind == "(" || kind == ")" || kind == "," {
continue;
}
if arg_idx == size_arg_idx {
// Simple field access (e.g., struct->field) is not arithmetic.
// contains_arithmetic() text match hits '->' as '-'.
if arg_node.kind() == "field_expression" {
return;
}
// sizeof(...) always yields size_t, no signed overflow.
// contains_arithmetic() false-matches the `*` in `sizeof(*ctx)`.
if arg_node.kind() == "sizeof_expression" {
return;
}
let arg_text = get_node_text(&arg_node, source);
if self.contains_arithmetic(arg_text) {
// Use const_eval to check if the arithmetic provably fits
let macros = self.current_macros.borrow();
let vra_ranges = self.vra_var_ranges_at(&arg_node);
if const_eval::expression_fits_in_signed_vra(
&arg_node,
source,
¯os,
64,
vra_ranges.as_ref(),
) {
return;
}
drop(macros);
if !self.has_memory_function_overflow_check(node, source) {
let start_point = node.start_position();
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::High,
message: format!(
"{}() size argument contains arithmetic that may overflow: '{}'",
function_name, arg_text
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some(
"Validate size calculations before passing to memory functions"
.to_string(),
),
..Default::default()
});
}
}
return;
}
arg_idx += 1;
}
}
}
}
fn check_abs_overflow(
&self,
node: &Node,
source: &str,
function_name: &str,
violations: &mut Vec<RuleViolation>,
) {
// abs(INT_MIN), labs(LONG_MIN), llabs(LLONG_MIN) all cause overflow
// because the absolute value of the minimum signed integer cannot be represented
// Skip if the abs() argument is cast to a wider type (e.g., abs((long)data)).
// Widening cast means the minimum value of the original type is representable
// in the wider type's abs range, so overflow can't occur.
if self.abs_arg_has_widening_cast(node, source, function_name) {
return;
}
// Skip if abs() call is part of a comparison condition (it IS a bounds check).
// Pattern: if (abs(x) <= limit) { ... } — the abs() is the safety check itself.
if self.is_inside_comparison_condition(node) {
return;
}
if !self.has_abs_overflow_check(node, source) {
let start_point = node.start_position();
let expr_text = get_node_text(node, source);
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: Severity::High,
message: format!(
"{}() may overflow when called with most negative value (e.g., INT_MIN): '{}'",
function_name, expr_text
),
file_path: String::new(),
line: start_point.row + 1,
column: start_point.column + 1,
suggestion: Some("Check if argument equals INT_MIN/LONG_MIN/LLONG_MIN before calling abs/labs/llabs".to_string()),
..Default::default()
});
}
}
/// Check if the abs() argument contains a widening cast (e.g., `abs((long)data)`).
/// When abs() gets `int` but is called as `abs((long)data)`, the long range
/// means INT_MIN cast to long is representable and abs() won't overflow.
fn abs_arg_has_widening_cast(&self, node: &Node, source: &str, function_name: &str) -> bool {
if let Some(arguments) = node.child_by_field_name("arguments") {
for i in 0..arguments.child_count() {
if let Some(arg) = arguments.child(i) {
if arg.kind() == "cast_expression" {
let cast_text = get_node_text(&arg, source);
// For abs(): widening to long or long long
if function_name == "abs"
&& (cast_text.contains("(long)") || cast_text.contains("(long long)"))
{
return true;
}
// For labs(): widening to long long
if function_name == "labs" && cast_text.contains("(long long)") {
return true;
}
}
}
}
}
false
}
/// Check if this node is inside a comparison that's part of a condition
/// (e.g., `if (abs(x) <= limit)`).
fn is_inside_comparison_condition(&self, node: &Node) -> bool {
let mut current = node.parent();
let mut depth = 0;
while let Some(parent) = current {
if depth > 10 {
break;
}
match parent.kind() {
"binary_expression" => {
// Check if this is a comparison operator
for i in 0..parent.child_count() {
if let Some(c) = parent.child(i) {
if matches!(c.kind(), "<" | "<=" | ">" | ">=" | "==" | "!=") {
// Now check if the comparison is part of an if/while condition
if let Some(grandparent) = parent.parent() {
if grandparent.kind() == "parenthesized_expression" {
if let Some(ggp) = grandparent.parent() {
if matches!(
ggp.kind(),
"if_statement" | "while_statement"
) {
return true;
}
}
}
// Also handle: if (abs(x) <= y && ...)
if matches!(grandparent.kind(), "binary_expression") {
if let Some(ggp) = grandparent.parent() {
if ggp.kind() == "parenthesized_expression" {
if let Some(gggp) = ggp.parent() {
if matches!(
gggp.kind(),
"if_statement" | "while_statement"
) {
return true;
}
}
}
}
}
}
return false;
}
}
}
}
"function_definition" | "translation_unit" => break,
_ => {}
}
current = parent.parent();
depth += 1;
}
false
}
/// Collect variable types from function parameters and local declarations.
/// Walks the entire AST to find all function_definition nodes and collects
/// types from their parameters and body declarations.
fn collect_variable_types(&self, node: &Node, source: &str) -> HashMap<String, String> {
let mut type_map = HashMap::new();
if node.kind() == "function_definition" {
// Collect from function parameters
if let Some(declarator) = node.child_by_field_name("declarator") {
self.collect_params_from_declarator(&declarator, source, &mut type_map);
}
// Collect from local declarations in the function body
if let Some(body) = node.child_by_field_name("body") {
self.collect_local_declarations(&body, source, &mut type_map);
}
}
// Recurse into children to find nested function_definitions
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
let child_map = self.collect_variable_types(&child, source);
type_map.extend(child_map);
}
}
type_map
}
fn collect_params_from_declarator(
&self,
node: &Node,
source: &str,
type_map: &mut HashMap<String, String>,
) {
if node.kind() == "function_declarator" {
if let Some(params) = node.child_by_field_name("parameters") {
for i in 0..params.child_count() {
if let Some(param) = params.child(i) {
if param.kind() == "parameter_declaration" {
self.extract_type_and_name(¶m, source, type_map);
}
}
}
}
}
// Recurse to find nested function_declarator (e.g. pointer declarators)
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.collect_params_from_declarator(&child, source, type_map);
}
}
}
fn collect_local_declarations(
&self,
node: &Node,
source: &str,
type_map: &mut HashMap<String, String>,
) {
if node.kind() == "declaration" {
self.extract_type_and_name(node, source, type_map);
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
self.collect_local_declarations(&child, source, type_map);
}
}
}
fn extract_type_and_name(
&self,
node: &Node,
source: &str,
type_map: &mut HashMap<String, String>,
) {
let mut type_text = String::new();
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
match child.kind() {
"primitive_type" | "sized_type_specifier" | "type_identifier" => {
type_text = get_node_text(&child, source).to_string();
}
"struct_specifier" => {
type_text = get_node_text(&child, source).to_string();
}
_ => {}
}
}
}
if type_text.is_empty() {
return;
}
// Extract variable names from declarators, tracking pointer indirection
if let Some(declarator) = node.child_by_field_name("declarator") {
let is_pointer = declarator.kind() == "pointer_declarator";
if let Some(name) = Self::extract_identifier_name(&declarator, source) {
let full_type = if is_pointer {
format!("{} *", type_text)
} else {
type_text.clone()
};
type_map.insert(name, full_type);
}
}
// Handle init_declarator lists (e.g. `int a, b;`)
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if child.kind() == "init_declarator" {
if let Some(decl) = child.child_by_field_name("declarator") {
let is_pointer = decl.kind() == "pointer_declarator";
if let Some(name) = Self::extract_identifier_name(&decl, source) {
let full_type = if is_pointer {
format!("{} *", type_text)
} else {
type_text.clone()
};
type_map.insert(name, full_type);
}
}
}
}
}
}
fn extract_identifier_name(node: &Node, source: &str) -> Option<String> {
match node.kind() {
"identifier" => Some(get_node_text(node, source).to_string()),
"pointer_declarator" | "array_declarator" | "parenthesized_declarator" => {
if let Some(inner) = node.child_by_field_name("declarator") {
Self::extract_identifier_name(&inner, source)
} else {
None
}
}
_ => {
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if child.kind() == "identifier" {
return Some(get_node_text(&child, source).to_string());
}
}
}
None
}
}
}
fn infer_type(&self, node: &Node, source: &str, type_map: &HashMap<String, String>) -> String {
let text = get_node_text(node, source);
// Check the type map FIRST — most reliable source of type info.
// Must come before text heuristics because variable names like "index"
// contain "int" as a substring, causing false signed classification.
if node.kind() == "identifier" {
if let Some(declared_type) = type_map.get(text) {
if self.is_unsigned_type(declared_type) {
return "unsigned".to_string();
}
// Only return signed if the type is clearly an integer type
if declared_type.contains("int")
|| declared_type.contains("short")
|| declared_type.contains("long")
|| declared_type == "signed"
{
return "signed".to_string();
}
// Non-integer types (float, double, char, pointers, structs) — not applicable to INT32-C
return "not_applicable".to_string();
}
}
// Look for explicit unsigned type indicators
if text.contains("unsigned") || text.contains("size_t") || text.contains("uint") {
return "unsigned".to_string();
}
// Look for unsigned literals
if text.ends_with("u") || text.ends_with("U") {
return "unsigned".to_string();
}
// Look for unsigned constants
if text.contains("UINT_MAX") || text.contains("SIZE_MAX") {
return "unsigned".to_string();
}
// Field expressions (e.g., s->count): try to resolve via struct field type database
if node.kind() == "field_expression" {
let sft = self.struct_field_types.borrow();
if let Some(field_type) =
crate::utility::cert_c::ast_utils::resolve_field_expression_type(
node, source, type_map, &sft,
)
{
if self.is_unsigned_type(&field_type) {
return "unsigned".to_string();
}
if field_type.contains("int")
|| field_type.contains("short")
|| field_type.contains("long")
|| field_type == "signed"
{
return "signed".to_string();
}
return "not_applicable".to_string();
}
return "not_applicable".to_string();
}
// Binary expressions: propagate unsigned/not_applicable from sub-operands.
// If any operand in the chain is unsigned, the whole expression should be
// treated as unsigned (matching C integer promotion rules for unsigned types).
if node.kind() == "binary_expression" {
if let (Some(left), Some(right)) = (
node.child_by_field_name("left"),
node.child_by_field_name("right"),
) {
let lt = self.infer_type(&left, source, type_map);
let rt = self.infer_type(&right, source, type_map);
if lt == "unsigned" || rt == "unsigned" {
return "unsigned".to_string();
}
if lt == "not_applicable" || rt == "not_applicable" {
return "not_applicable".to_string();
}
if lt == "signed" || rt == "signed" {
return "signed".to_string();
}
return "unknown".to_string();
}
}
// Look for explicit signed type indicators (only for non-identifier nodes
// like type specifiers in casts/declarations — identifiers checked above)
if node.kind() != "identifier"
&& (text.contains("signed")
|| text.contains("int")
|| text.contains("short")
|| text.contains("long"))
{
return "signed".to_string();
}
// Look for signed integer constants
if text.contains("INT_MAX") || text.contains("INT_MIN") {
return "signed".to_string();
}
// Plain numbers without unsigned suffix are typically signed
if text.chars().all(|c| c.is_ascii_digit() || c == '-') {
return "signed".to_string();
}
// Fall back to old heuristic for variable names not in the type map
if text.chars().all(|c| c.is_ascii_alphabetic() || c == '_') {
if let Some(declared_type) = self.find_variable_declaration(node, source, text) {
return declared_type;
}
}
// ALL_CAPS identifiers (including those with digits/underscores) are macros whose
// type cannot be determined without macro expansion. Hardware register addresses
// (e.g., AFE_INT_EN) look like signed integer literals to the type inference but
// are actually pointer-width constants. Treat as not_applicable to avoid FPs.
if !text.is_empty()
&& text
.chars()
.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
{
return "not_applicable".to_string();
}
// Variable names that suggest unsigned integers
if text.starts_with("u") || text.contains("size") || text.contains("len") {
return "unsigned".to_string();
}
// Variable names that suggest signed integers
if text.starts_with("i")
|| text.contains("signed")
|| text.contains("count")
|| text.contains("index")
{
return "signed".to_string();
}
// For variables NOT in the type map, default to unknown instead of signed
// This prevents false positives on variables whose type we can't determine
"unknown".to_string()
}
fn find_variable_declaration(
&self,
node: &Node,
source: &str,
var_name: &str,
) -> Option<String> {
// Look for the function that contains this node
let mut current = node.parent();
while let Some(parent) = current {
if parent.kind() == "function_definition" {
// Look in function parameters
if let Some(params) = parent.child_by_field_name("parameters") {
let params_text = get_node_text(¶ms, source);
if params_text.contains("unsigned") && params_text.contains(var_name) {
return Some("unsigned".to_string());
}
if (params_text.contains("signed") || params_text.contains("int"))
&& params_text.contains(var_name)
&& !params_text.contains("unsigned")
{
return Some("signed".to_string());
}
}
break;
}
current = parent.parent();
}
// Look in local declarations (simplified)
current = node.parent();
while let Some(parent) = current {
if parent.kind() == "declaration" {
let decl_text = get_node_text(&parent, source);
if decl_text.contains(var_name) {
if decl_text.contains("unsigned") {
return Some("unsigned".to_string());
}
if decl_text.contains("signed") || decl_text.contains("int") {
return Some("signed".to_string());
}
}
}
current = parent.parent();
}
None
}
fn is_signed_type(&self, type_str: &str) -> bool {
type_str == "signed" || type_str == "int"
}
fn is_unsigned_type(&self, type_str: &str) -> bool {
type_str == "unsigned"
|| type_str == "size_t"
|| type_str.contains("uint")
|| type_str.starts_with("unsigned ")
|| type_str == "SIZE_MAX"
|| is_short_unsigned_typedef(type_str)
}
fn could_be_int_min(&self, node: &Node, source: &str) -> bool {
let text = get_node_text(node, source);
text.contains("INT_MIN")
|| (text.starts_with("min") && (text.contains("val") || text.contains("num")))
}
/// Check if either operand has a wider-type cast (long long), making overflow impossible.
fn has_wider_cast(&self, left_text: &str, right_text: &str) -> bool {
let has_ll = |text: &str| {
text.contains("long long")
|| text.starts_with("(signed long long)")
|| text.starts_with("(long long)")
|| text.starts_with("(int64_t)")
|| text.starts_with("(int_least64_t)")
};
has_ll(left_text) || has_ll(right_text)
}
/// Extract operand identifier names from a binary expression node.
/// Returns a vec of variable names found in the left/right operands.
fn extract_operand_names(&self, node: &Node, source: &str) -> Vec<String> {
let mut names = Vec::new();
if let Some(left) = node.child_by_field_name("left") {
Self::collect_identifiers(&left, source, &mut names);
}
if let Some(right) = node.child_by_field_name("right") {
Self::collect_identifiers(&right, source, &mut names);
}
// For unary/update expressions, check argument
if let Some(arg) = node.child_by_field_name("argument") {
Self::collect_identifiers(&arg, source, &mut names);
}
names
}
fn collect_identifiers(node: &Node, source: &str, names: &mut Vec<String>) {
if node.kind() == "identifier" {
let name = get_node_text(node, source).to_string();
if !names.contains(&name) {
names.push(name);
}
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
Self::collect_identifiers(&child, source, names);
}
}
}
/// Returns true if this binary_expression is `opaque + small_literal` or
/// `small_literal + opaque`, where "opaque" is a call_expression or an
/// identifier whose value comes from a call_expression, AND the callee is
/// not known to return full-range values.
///
/// Functions like `strlen()` return bounded values where +1 is safe.
/// Functions like `atoi()` or `rand()` can return any value in the type
/// range, so their result + small literal is a genuine overflow risk.
fn is_small_increment_of_opaque(
node: &Node,
source: &str,
summaries: &HashMap<String, FunctionSummary>,
) -> bool {
if node.kind() != "binary_expression" {
return false;
}
let (left, right) = match (
node.child_by_field_name("left"),
node.child_by_field_name("right"),
) {
(Some(l), Some(r)) => (l, r),
_ => return false,
};
let is_small_literal = |n: &Node| -> bool {
if n.kind() != "number_literal" {
return false;
}
let text = get_node_text(n, source).trim().to_string();
text.parse::<u64>().is_ok_and(|v| v <= 10)
};
// Resolve the callee function name from a call_expression or an
// identifier initialized from a call_expression. Returns None if
// the node is not call-derived.
let resolve_callee = |n: &Node| -> Option<String> {
if n.kind() == "call_expression" {
return n
.child_by_field_name("function")
.and_then(|f| f.utf8_text(source.as_bytes()).ok())
.map(|s| s.trim().to_string());
}
if n.kind() == "identifier" {
let var_name = get_node_text(n, source);
if let Some(func) = ast_utils::find_containing_function(n) {
if let Some(body) = func.child_by_field_name("body") {
return Self::resolve_identifier_call_name(&body, var_name, source, n);
}
}
}
None
};
// Check if either operand is opaque + small literal
let callee = if is_small_literal(&right) {
resolve_callee(&left)
} else if is_small_literal(&left) {
resolve_callee(&right)
} else {
return false; // Neither side is a small literal
};
let callee = match callee {
Some(name) => name,
None => return false, // Not call-derived, not opaque
};
// Known full-range functions: never suppress (atoi, rand, strtol, etc.)
if std_functions::is_full_range_return_function(&callee) {
return false;
}
// Local function with proven wide return range: don't suppress
if let Some(summary) = summaries.get(&callee) {
if let Some(ref return_range) = summary.return_range {
let signed_danger = i32::MAX as i64 - 10;
if return_range.max >= signed_danger {
return false;
}
}
}
// Default: suppress (safe for strlen, wcslen, unknown helpers)
true
}
/// Resolve the callee function name for an identifier that was initialized
/// name instead of just a boolean.
fn resolve_identifier_call_name(
scope: &Node,
var_name: &str,
source: &str,
usage_node: &Node,
) -> Option<String> {
let usage_row = usage_node.start_position().row;
for i in 0..scope.named_child_count() {
if let Some(child) = scope.named_child(i) {
if child.start_position().row >= usage_row {
break;
}
// declaration: type var = call();
if child.kind() == "declaration" {
if let Some(declarator) = child.child_by_field_name("declarator") {
if declarator.kind() == "init_declarator" {
let decl_name = declarator
.child_by_field_name("declarator")
.map(|d| get_node_text(&d, source));
let init = declarator.child_by_field_name("value");
if decl_name == Some(var_name) {
if let Some(init_node) = init {
if init_node.kind() == "call_expression" {
return init_node
.child_by_field_name("function")
.and_then(|f| f.utf8_text(source.as_bytes()).ok())
.map(|s| s.trim().to_string());
}
}
}
}
}
}
// assignment: var = call();
if child.kind() == "expression_statement" {
if let Some(expr) = child.named_child(0) {
if expr.kind() == "assignment_expression" {
let lhs = expr.child_by_field_name("left");
let rhs = expr.child_by_field_name("right");
if let (Some(l), Some(r)) = (lhs, rhs) {
if get_node_text(&l, source) == var_name
&& r.kind() == "call_expression"
{
return r
.child_by_field_name("function")
.and_then(|f| f.utf8_text(source.as_bytes()).ok())
.map(|s| s.trim().to_string());
}
}
}
}
}
// Recurse into preproc blocks and nested scopes
if child.kind().starts_with("preproc_")
|| child.kind() == "compound_statement"
|| child.kind() == "if_statement"
|| child.kind() == "switch_statement"
|| child.kind() == "case_statement"
|| child.kind() == "for_statement"
|| child.kind() == "while_statement"
{
if let Some(name) =
Self::resolve_identifier_call_name(&child, var_name, source, usage_node)
{
return Some(name);
}
}
}
}
None
}
fn contains_arithmetic(&self, expr: &str) -> bool {
expr.contains('+') || expr.contains('-') || expr.contains('*') || expr.contains('/')
}
fn is_constant_expression(&self, expr: &str) -> bool {
// Check if expression is a constant (literal number or named constant like INT_MAX)
let trimmed = expr.trim();
// Numeric literals
if trimmed
.chars()
.all(|c| c.is_ascii_digit() || c == '-' || c == '+')
{
return true;
}
// Named constants
if trimmed.contains("INT_MAX")
|| trimmed.contains("INT_MIN")
|| trimmed.contains("LONG_MAX")
|| trimmed.contains("LONG_MIN")
|| trimmed.contains("LLONG_MAX")
|| trimmed.contains("LLONG_MIN")
|| trimmed.contains("UINT_MAX")
|| trimmed.contains("SIZE_MAX")
{
return true;
}
false
}
/// Check if a binary expression is inside a for-loop with a small constant bound,
/// making overflow impossible (e.g., `i * i` where `i < 100`).
fn is_in_bounded_for_loop(&self, node: &Node, source: &str) -> bool {
let mut current = node.parent();
while let Some(parent) = current {
if parent.kind() == "for_statement" {
let for_text = get_node_text(&parent, source);
// Check that the loop doesn't involve near-limit values
if for_text.contains("INT_MAX")
|| for_text.contains("LONG_MAX")
|| for_text.contains("INT_MIN")
|| for_text.contains("LONG_MIN")
{
return false;
}
// Heuristic: if the for-loop condition contains a small numeric bound
// (< 4 digits), the loop variable won't overflow in typical arithmetic
if let Some(condition) = parent.child_by_field_name("condition") {
let cond_text = get_node_text(&condition, source);
// Look for patterns like "i < 100" or "i <= 999"
let bound_re = cond_text
.split(|c: char| !c.is_ascii_digit())
.filter(|s| !s.is_empty())
.any(|num| {
num.len() <= 4
&& num.parse::<i64>().is_ok_and(|n| (0..=10000).contains(&n))
});
if bound_re {
return true;
}
}
return false;
}
if parent.kind() == "function_definition" {
break;
}
current = parent.parent();
}
false
}
fn is_in_safe_for_loop(&self, node: &Node, source: &str) -> bool {
// Walk up the tree to see if this node is in a for_statement
// Only consider it safe if the loop has clear small bounds
let mut current = node.parent();
while let Some(parent) = current {
if parent.kind() == "for_statement" {
// Check if this is a typical safe for loop (starting from 0 or small value)
// by looking at the initializer
if let Some(initializer) = parent.child_by_field_name("initializer") {
// Convert initializer to text and check if it's safe
// Safe patterns: i = 0, i = 1, etc. (small constants)
// Unsafe patterns: i = INT_MAX - 2, etc.
let init_text = get_node_text(&initializer, source);
if init_text.contains("INT_MAX")
|| init_text.contains("LONG_MAX")
|| init_text.contains("INT_MIN")
|| init_text.contains("LONG_MIN")
{
return false; // Unsafe - loop starts near limits
}
return true; // Safe - typical for loop
}
}
// Stop at function boundary
if parent.kind() == "function_definition" {
break;
}
current = parent.parent();
}
false
}
fn has_overflow_check_addition(&self, node: &Node, source: &str) -> bool {
// First check the immediate surrounding context (parent/grandparent) — strict pattern
if self.has_surrounding_check(node, source, &["INT_MAX", "INT_MIN", " - ", " > ", " < "]) {
return true;
}
// Check for any signed limit macro with a comparison operator in the function.
// Relaxed from requiring ALL of [INT_MAX, INT_MIN, " - ", " > ", " < "] to
// requiring any limit macro + comparison — handles CHAR_MAX, SHRT_MAX, etc.
// The scoped check (guard_keywords + operand match) ensures precision.
self.has_function_level_overflow_check(node, source, &[" > "])
|| self.has_function_level_overflow_check(node, source, &[" < "])
|| self.has_function_level_overflow_check(node, source, &[" >= "])
|| self.has_function_level_overflow_check(node, source, &[" <= "])
}
fn has_overflow_check_subtraction(&self, node: &Node, source: &str) -> bool {
// First check the immediate surrounding context (parent/grandparent)
if self.has_surrounding_check(node, source, &["INT_MAX", "INT_MIN", " + ", " > ", " < "]) {
return true;
}
// Then check the broader function context for overflow checks
self.has_function_level_overflow_check(
node,
source,
&["INT_MAX", "INT_MIN", " + ", " > ", " < "],
)
}
fn has_overflow_check_multiplication(&self, node: &Node, source: &str) -> bool {
// Check for multiplication overflow patterns:
// 1. if (a > INT_MAX / b) - division-based check
// 2. Complex checks with INT_MAX/INT_MIN and division
if self.has_surrounding_check(node, source, &["INT_MAX", " / "])
|| self.has_surrounding_check(node, source, &["INT_MIN", " / "])
|| self.has_surrounding_check(node, source, &["LONG_MAX", " / "])
|| self.has_surrounding_check(node, source, &["LONG_MIN", " / "])
{
return true;
}
// Function-level checks
if self.has_function_level_patterns_any(node, source, &["INT_MAX", " / "])
|| self.has_function_level_patterns_any(node, source, &["INT_MIN", " / "])
|| self.has_function_level_patterns_any(node, source, &["LONG_MAX", " / "])
|| self.has_function_level_patterns_any(node, source, &["LONG_MIN", " / "])
{
return true;
}
false
}
fn has_division_overflow_check(&self, node: &Node, source: &str) -> bool {
// Check for INT_MIN/-1 or LONG_MIN/-1 or LLONG_MIN/-1 division overflow checks
if self.has_surrounding_check(node, source, &["INT_MIN", " == ", " -1"])
|| self.has_surrounding_check(node, source, &["LONG_MIN", " == ", " -1"])
|| self.has_surrounding_check(node, source, &["LLONG_MIN", " == ", " -1"])
{
return true;
}
self.has_function_level_patterns_any(node, source, &["INT_MIN", " == ", " -1"])
|| self.has_function_level_patterns_any(node, source, &["LONG_MIN", " == ", " -1"])
|| self.has_function_level_patterns_any(node, source, &["LLONG_MIN", " == ", " -1"])
}
fn has_modulo_overflow_check(&self, node: &Node, source: &str) -> bool {
// Check for INT_MIN%- 1 or LONG_MIN%-1 or LLONG_MIN%-1 modulo overflow checks
if self.has_surrounding_check(node, source, &["INT_MIN", " == ", " -1"])
|| self.has_surrounding_check(node, source, &["LONG_MIN", " == ", " -1"])
|| self.has_surrounding_check(node, source, &["LLONG_MIN", " == ", " -1"])
{
return true;
}
self.has_function_level_patterns_any(node, source, &["INT_MIN", " == ", " -1"])
|| self.has_function_level_patterns_any(node, source, &["LONG_MIN", " == ", " -1"])
|| self.has_function_level_patterns_any(node, source, &["LLONG_MIN", " == ", " -1"])
}
fn has_negation_overflow_check(&self, node: &Node, source: &str) -> bool {
// Check for negation of INT_MIN, LONG_MIN, or LLONG_MIN
if self.has_surrounding_check(node, source, &["INT_MIN", " == "])
|| self.has_surrounding_check(node, source, &["LONG_MIN", " == "])
|| self.has_surrounding_check(node, source, &["LLONG_MIN", " == "])
{
return true;
}
self.has_function_level_patterns_any(node, source, &["INT_MIN", " == "])
|| self.has_function_level_patterns_any(node, source, &["LONG_MIN", " == "])
|| self.has_function_level_patterns_any(node, source, &["LLONG_MIN", " == "])
}
fn has_shift_overflow_check(&self, node: &Node, source: &str) -> bool {
// Check for left shift overflow patterns:
// Complete check requires BOTH:
// 1. Shift amount validation AND value range check
// 2. Value range check: a > (INT_MAX >> b) or similar with LONG_MAX
// Check for value range pattern (most comprehensive)
if self.has_surrounding_check(node, source, &["LONG_MAX", " >> "])
|| self.has_surrounding_check(node, source, &["INT_MAX", " >> "])
{
return true;
}
if self.has_function_level_patterns_any(node, source, &["LONG_MAX", " >> "])
|| self.has_function_level_patterns_any(node, source, &["INT_MAX", " >> "])
{
return true;
}
// Only accept PRECISION if it's combined with value range checks
// (PRECISION alone is insufficient - see wiki_noncompliant_6)
if (self.has_surrounding_check(node, source, &["PRECISION"])
|| self.has_function_level_patterns_any(node, source, &["PRECISION"]))
&& (self.has_function_level_patterns_any(node, source, &[" >> "])
|| self.has_function_level_patterns_any(node, source, &[" < ", "sizeof"]))
{
return false; // PRECISION + shift amount check only is insufficient
}
// sizeof-based complete checks
self.has_surrounding_check(node, source, &[" < ", "sizeof", "* 8"])
}
fn has_overflow_check_compound(&self, node: &Node, source: &str) -> bool {
if self.has_surrounding_check(node, source, &["if", "INT_MAX", "INT_MIN"]) {
return true;
}
self.has_function_level_overflow_check(node, source, &["if", "INT_MAX", "INT_MIN"])
}
fn has_overflow_check_update(&self, node: &Node, source: &str) -> bool {
// For increment: check if value == INT_MAX
// For decrement: check if value == INT_MIN
// We need to detect EITHER check, not both
if self.has_surrounding_check(node, source, &["if", "INT_MAX", " == "])
|| self.has_surrounding_check(node, source, &["if", "INT_MIN", " == "])
{
return true;
}
self.has_function_level_patterns_any(node, source, &["if", "INT_MAX", " == "])
|| self.has_function_level_patterns_any(node, source, &["if", "INT_MIN", " == "])
}
fn has_allocation_overflow_check(&self, node: &Node, source: &str) -> bool {
self.has_surrounding_check(node, source, &["SIZE_MAX", " / ", " > ", "if"])
}
fn has_memory_function_overflow_check(&self, node: &Node, source: &str) -> bool {
self.has_surrounding_check(node, source, &["SIZE_MAX", " > ", "if"])
}
fn has_abs_overflow_check(&self, node: &Node, source: &str) -> bool {
// Check if there's a check for INT_MIN/LONG_MIN/LLONG_MIN before the abs call
if self.has_surrounding_check(node, source, &["INT_MIN", "if"])
|| self.has_surrounding_check(node, source, &["LONG_MIN", "if"])
|| self.has_surrounding_check(node, source, &["LLONG_MIN", "if"])
{
return true;
}
self.has_function_level_overflow_check(node, source, &["INT_MIN", "if"])
|| self.has_function_level_overflow_check(node, source, &["LONG_MIN", "if"])
|| self.has_function_level_overflow_check(node, source, &["LLONG_MIN", "if"])
}
/// Check if a binary operation is part of a comparison expression (used in overflow checking)
fn is_part_of_comparison(&self, node: &Node, source: &str) -> bool {
let mut current = node.parent();
while let Some(parent) = current {
// If we find a binary_expression parent, check if it's a comparison operator
if parent.kind() == "binary_expression" {
// Get the operator
for i in 0..parent.child_count() {
if let Some(child) = parent.child(i) {
let text = get_node_text(&child, source);
// Check if this is a comparison operator
if matches!(text, ">" | "<" | ">=" | "<=" | "==" | "!=") {
return true;
}
}
}
}
// Stop at statement boundaries to avoid going too far up the tree
if matches!(
parent.kind(),
"expression_statement"
| "return_statement"
| "declaration"
| "function_definition"
| "compound_statement"
) {
break;
}
current = parent.parent();
}
false
}
/// Check if the function containing this node has overflow checking code (all patterns must match).
/// Scoped to operands: requires at least one operand name from the flagged expression to appear
/// near the overflow guard pattern, preventing one variable's check from suppressing another's.
fn has_function_level_overflow_check(
&self,
node: &Node,
source: &str,
patterns: &[&str],
) -> bool {
let operand_names = self.extract_operand_names(node, source);
self.has_function_level_overflow_check_scoped(node, source, patterns, &operand_names)
}
/// Check if the function containing this node has overflow checking code (all patterns must match).
/// Variant used when operand names are not applicable (e.g., compound assignments).
fn has_function_level_patterns_any(
&self,
node: &Node,
source: &str,
patterns: &[&str],
) -> bool {
let operand_names = self.extract_operand_names(node, source);
self.has_function_level_overflow_check_scoped(node, source, patterns, &operand_names)
}
/// Core operand-scoped function-level overflow check.
/// Checks that:
/// 1. All the given patterns exist in the function (e.g., "INT_MAX", " - ")
/// 2. At least one operand from the flagged expression appears in a line that
/// also contains at least one of the overflow-guard keywords (INT_MAX, INT_MIN, etc.)
fn has_function_level_overflow_check_scoped(
&self,
node: &Node,
source: &str,
patterns: &[&str],
operand_names: &[String],
) -> bool {
// Find the containing function
let mut current = node.parent();
while let Some(parent) = current {
if parent.kind() == "function_definition" {
let func_text = get_node_text(&parent, source);
// First: do the patterns even exist in this function?
if !patterns.iter().all(|p| func_text.contains(p)) {
return false;
}
// If we have no operand names to scope against, fall back to
// the old behavior (patterns found anywhere in the function)
if operand_names.is_empty() {
return true;
}
// The overflow-guard keywords we look for near operand names
let guard_keywords = [
"INT_MAX",
"INT_MIN",
"LONG_MAX",
"LONG_MIN",
"LLONG_MAX",
"LLONG_MIN",
"UINT_MAX",
"SIZE_MAX",
"CHAR_MAX",
"CHAR_MIN",
"SCHAR_MAX",
"SCHAR_MIN",
"SHRT_MAX",
"SHRT_MIN",
];
// Search for lines that contain an overflow guard keyword AND
// at least one operand name from the flagged expression.
for line in func_text.lines() {
let trimmed = line.trim();
let has_guard = guard_keywords.iter().any(|kw| trimmed.contains(kw));
if !has_guard {
continue;
}
if operand_names
.iter()
.any(|name| self.contains_word(trimmed, name))
{
return true;
}
}
return false;
}
current = parent.parent();
}
false
}
/// Check if `text` contains `word` as a whole word (not a substring of another identifier).
fn contains_word(&self, text: &str, word: &str) -> bool {
if word.is_empty() {
return false;
}
let mut start = 0;
while let Some(pos) = text[start..].find(word) {
let abs_pos = start + pos;
let before_ok = abs_pos == 0
|| !text.as_bytes()[abs_pos - 1].is_ascii_alphanumeric()
&& text.as_bytes()[abs_pos - 1] != b'_';
let after_pos = abs_pos + word.len();
let after_ok = after_pos >= text.len()
|| !text.as_bytes()[after_pos].is_ascii_alphanumeric()
&& text.as_bytes()[after_pos] != b'_';
if before_ok && after_ok {
return true;
}
start = abs_pos + 1;
}
false
}
/// Check if the arithmetic node is inside a block guarded by a type-limit bounds check.
/// Walks up ancestors (up to 15 levels) looking for an `if_statement` whose condition
/// references a signed type-limit macro AND at least one operand of the arithmetic.
fn is_inside_bounds_checked_block(
&self,
node: &Node,
source: &str,
op_names: &[String],
) -> bool {
const SIGNED_LIMIT_MACROS: &[&str] = &[
"INT_MAX",
"INT_MIN",
"LONG_MAX",
"LONG_MIN",
"LLONG_MAX",
"LLONG_MIN",
"CHAR_MAX",
"CHAR_MIN",
"SCHAR_MAX",
"SCHAR_MIN",
"SHRT_MAX",
"SHRT_MIN",
];
let mut current = *node;
let mut depth = 0;
while let Some(parent) = current.parent() {
depth += 1;
if depth > 15 {
break;
}
if parent.kind() == "function_definition" {
break;
}
if matches!(
parent.kind(),
"if_statement" | "while_statement" | "for_statement"
) {
if let Some(condition) = parent.child_by_field_name("condition") {
let cond_text = get_node_text(&condition, source);
let has_limit = SIGNED_LIMIT_MACROS
.iter()
.any(|m| self.contains_word(cond_text, m));
if has_limit {
if op_names.is_empty() {
return true;
}
if op_names
.iter()
.any(|name| self.contains_word(cond_text, name))
{
return true;
}
}
// For while/for: check if the loop-bounded variable is the
// same as the operation's target variable. E.g., `while (attempts < MAX)`
// bounds `attempts`, so `attempts++` is safe, but `sum += x` is not.
if matches!(parent.kind(), "while_statement" | "for_statement") {
let bounded_vars = self.extract_loop_bounded_vars(&condition, source);
if let Some(target) = self.extract_mutation_target(node, source) {
if bounded_vars.contains(&target) {
return true;
}
}
}
}
}
current = parent;
}
false
}
/// Extract the target variable of a mutation operation.
/// For `x += y` → "x", for `x++` → "x", for `a * b` → None (not a mutation).
fn extract_mutation_target(&self, node: &Node, source: &str) -> Option<String> {
match node.kind() {
"augmented_assignment_expression" | "assignment_expression" => {
if let Some(left) = node.child_by_field_name("left") {
if left.kind() == "identifier" {
let name = get_node_text(&left, source);
if !name.is_empty() {
return Some(name.to_string());
}
}
}
None
}
"update_expression" => {
if let Some(arg) = node.child_by_field_name("argument") {
if arg.kind() == "identifier" {
let name = get_node_text(&arg, source);
if !name.is_empty() {
return Some(name.to_string());
}
}
}
None
}
_ => None,
}
}
/// Extract variable names that are bounded by comparison operators in a
/// loop condition. E.g., `i < N` → ["i"], `attempts < MAX && ret != 0` → ["attempts"].
fn extract_loop_bounded_vars(&self, condition: &Node, source: &str) -> Vec<String> {
let cond_text = get_node_text(condition, source);
// Strip outer parens
let cond_text = cond_text
.strip_prefix('(')
.and_then(|s| s.strip_suffix(')'))
.unwrap_or(cond_text);
let mut vars = Vec::new();
// Split on && to handle compound conditions
for part in cond_text.split("&&") {
let part = part.trim();
// Look for `var < expr`, `var <= expr`, `var > expr`, `var >= expr`
for op in &["<=", ">=", "<", ">"] {
if let Some(pos) = part.find(op) {
let left = part[..pos].trim();
let right = part[pos + op.len()..].trim();
// Left-side bounded: `var < BOUND`
if matches!(*op, "<" | "<=") && is_simple_c_identifier(left) {
vars.push(left.to_string());
}
// Right-side bounded: `BOUND > var`
if matches!(*op, ">" | ">=") && is_simple_c_identifier(right) {
vars.push(right.to_string());
}
break; // Only match first operator per sub-expression
}
}
}
vars
}
fn has_surrounding_check(&self, node: &Node, source: &str, patterns: &[&str]) -> bool {
if let Some(parent) = node.parent() {
if let Some(grandparent) = parent.parent() {
let context = get_node_text(&grandparent, source);
return patterns.iter().all(|pattern| context.contains(pattern));
}
}
false
}
fn get_operator(&self, node: &Node, source: &str) -> Option<String> {
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
let text = get_node_text(&child, source);
if matches!(text, "+" | "-" | "*" | "/" | "%" | "<<" | ">>") {
return Some(text.to_string());
}
}
}
None
}
fn get_assignment_operator(&self, node: &Node, source: &str) -> Option<String> {
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
let text = get_node_text(&child, source);
if matches!(text, "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=") {
return Some(text.to_string());
}
}
}
None
}
fn get_unary_operator(&self, node: &Node, source: &str) -> Option<String> {
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
let text = get_node_text(&child, source);
if matches!(text, "-" | "+" | "!" | "~") {
return Some(text.to_string());
}
}
}
None
}
fn get_update_operator(&self, node: &Node, source: &str) -> String {
let text = get_node_text(node, source);
if text.contains("++") {
"++".to_string()
} else if text.contains("--") {
"--".to_string()
} else {
"unknown".to_string()
}
}
}
fn is_simple_c_identifier(s: &str) -> bool {
!s.is_empty()
&& s.chars()
.next()
.is_some_and(|c| c.is_alphabetic() || c == '_')
&& s.chars().all(|c| c.is_alphanumeric() || c == '_')
}
/// Recognizes common short unsigned typedef names: u8, u16, u32, u64, u128.
/// These are MCU/embedded typedefs not caught by the "uint" substring check.
fn is_short_unsigned_typedef(s: &str) -> bool {
matches!(s, "u8" | "u16" | "u32" | "u64" | "u128")
}