1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
|
==================
Available Checkers
==================
The analyzer performs checks that are categorized into families or "checkers".
The default set of checkers covers a variety of checks targeted at finding security and API usage bugs,
dead code, and other logic errors. See the :ref:`default-checkers` checkers list below.
In addition to these, the analyzer contains a number of :ref:`alpha-checkers` (aka *alpha* checkers).
These checkers are under development and are switched off by default. They may crash or emit a higher number of false positives.
The :ref:`debug-checkers` package contains checkers for analyzer developers for debugging purposes.
.. contents:: Table of Contents
:depth: 4
.. _default-checkers:
Default Checkers
----------------
.. _core-checkers:
core
^^^^
Models core language features and contains general-purpose checkers such as division by zero,
null pointer dereference, usage of uninitialized values, etc.
*These checkers must be always switched on as other checker rely on them.*
.. _core-BitwiseShift:
core.BitwiseShift (C, C++)
""""""""""""""""""""""""""
Finds undefined behavior caused by the bitwise left- and right-shift operator
operating on integer types.
By default, this checker only reports situations when the right operand is
either negative or larger than the bit width of the type of the left operand;
these are logically unsound.
Moreover, if the pedantic mode is activated by
``-analyzer-config core.BitwiseShift:Pedantic=true``, then this checker also
reports situations where the _left_ operand of a shift operator is negative or
overflow occurs during the right shift of a signed value. (Most compilers
handle these predictably, but the C standard and the C++ standards before C++20
say that they're undefined behavior. In the C++20 standard these constructs are
well-defined, so activating pedantic mode in C++20 has no effect.)
**Examples**
.. code-block:: cpp
static_assert(sizeof(int) == 4, "assuming 32-bit int")
void basic_examples(int a, int b) {
if (b < 0) {
b = a << b; // warn: right operand is negative in left shift
} else if (b >= 32) {
b = a >> b; // warn: right shift overflows the capacity of 'int'
}
}
int pedantic_examples(int a, int b) {
if (a < 0) {
return a >> b; // warn: left operand is negative in right shift
}
a = 1000u << 31; // OK, overflow of unsigned value is well-defined, a == 0
if (b > 10) {
a = b << 31; // this is undefined before C++20, but the checker doesn't
// warn because it doesn't know the exact value of b
}
return 1000 << 31; // warn: this overflows the capacity of 'int'
}
**Solution**
Ensure the shift operands are in proper range before shifting.
.. _core-CallAndMessage:
core.CallAndMessage (C, C++, ObjC)
""""""""""""""""""""""""""""""""""
Check for logical errors for function calls and Objective-C message expressions (e.g., uninitialized arguments, null function pointers).
.. literalinclude:: checkers/callandmessage_example.c
:language: objc
.. _core-DivideZero:
core.DivideZero (C, C++, ObjC)
""""""""""""""""""""""""""""""
Check for division by zero.
.. literalinclude:: checkers/dividezero_example.c
:language: c
.. _core-FixedAddressDereference:
core.FixedAddressDereference (C, C++, ObjC)
"""""""""""""""""""""""""""""""""""""""""""
Check for dereferences of fixed addresses.
A pointer contains a fixed address if it was set to a hard-coded value or it
becomes otherwise obvious that at that point it can have only a single fixed
numerical value.
.. code-block:: c
void test1() {
int *p = (int *)0x020;
int x = p[0]; // warn
}
void test2(int *p) {
if (p == (int *)-1)
*p = 0; // warn
}
void test3() {
int (*p_function)(char, char);
p_function = (int (*)(char, char))0x04080;
int x = (*p_function)('x', 'y'); // NO warning yet at functon pointer calls
}
If the analyzer option ``suppress-dereferences-from-any-address-space`` is set
to true (the default value), then this checker never reports dereference of
pointers with a specified address space. If the option is set to false, then
reports from the specific x86 address spaces 256, 257 and 258 are still
suppressed, but fixed address dereferences from other address spaces are
reported.
.. _core-NonNullParamChecker:
core.NonNullParamChecker (C, C++, ObjC)
"""""""""""""""""""""""""""""""""""""""
Check for null pointers passed as arguments to a function whose arguments are references or marked with the 'nonnull' attribute.
.. code-block:: cpp
int f(int *p) __attribute__((nonnull));
void test(int *p) {
if (!p)
f(p); // warn
}
.. _core-NullDereference:
core.NullDereference (C, C++, ObjC)
"""""""""""""""""""""""""""""""""""
Check for dereferences of null pointers.
.. code-block:: objc
// C
void test(int *p) {
if (p)
return;
int x = p[0]; // warn
}
// C
void test(int *p) {
if (!p)
*p = 0; // warn
}
// C++
class C {
public:
int x;
};
void test() {
C *pc = 0;
int k = pc->x; // warn
}
// Objective-C
@interface MyClass {
@public
int x;
}
@end
void test() {
MyClass *obj = 0;
obj->x = 1; // warn
}
Null pointer dereferences of pointers with address spaces are not always defined
as error. Specifically on x86/x86-64 target if the pointer address space is
256 (x86 GS Segment), 257 (x86 FS Segment), or 258 (x86 SS Segment), a null
dereference is not defined as error. See `X86/X86-64 Language Extensions
<https://clang.llvm.org/docs/LanguageExtensions.html#memory-references-to-specified-segments>`__
for reference.
If the analyzer option ``suppress-dereferences-from-any-address-space`` is set
to true (the default value), then this checker never reports dereference of
pointers with a specified address space. If the option is set to false, then
reports from the specific x86 address spaces 256, 257 and 258 are still
suppressed, but null dereferences from other address spaces are reported.
.. _core-StackAddressEscape:
core.StackAddressEscape (C)
"""""""""""""""""""""""""""
Check that addresses to stack memory do not escape the function.
.. code-block:: c
char const *p;
void test() {
char const str[] = "string";
p = str; // warn
}
void* test() {
return __builtin_alloca(12); // warn
}
void test() {
static int *x;
int y;
x = &y; // warn
}
.. _core-UndefinedBinaryOperatorResult:
core.UndefinedBinaryOperatorResult (C)
""""""""""""""""""""""""""""""""""""""
Check for undefined results of binary operators.
.. code-block:: c
void test() {
int x;
int y = x + 1; // warn: left operand is garbage
}
.. _core-VLASize:
core.VLASize (C)
""""""""""""""""
Check for declarations of Variable Length Arrays (VLA) of undefined, zero or negative
size.
.. code-block:: c
void test() {
int x;
int vla1[x]; // warn: garbage as size
}
void test() {
int x = 0;
int vla2[x]; // warn: zero size
}
The checker also gives warning if the `TaintPropagation` checker is switched on
and an unbound, attacker controlled (tainted) value is used to define
the size of the VLA.
.. code-block:: c
void taintedVLA(void) {
int x;
scanf("%d", &x);
int vla[x]; // Declared variable-length array (VLA) has tainted (attacker controlled) size, that can be 0 or negative
}
void taintedVerfieidVLA(void) {
int x;
scanf("%d", &x);
if (x<1)
return;
int vla[x]; // no-warning. The analyzer can prove that x must be positive.
}
.. _core-uninitialized-ArraySubscript:
core.uninitialized.ArraySubscript (C)
"""""""""""""""""""""""""""""""""""""
Check for uninitialized values used as array subscripts.
.. code-block:: c
void test() {
int i, a[10];
int x = a[i]; // warn: array subscript is undefined
}
.. _core-uninitialized-Assign:
core.uninitialized.Assign (C)
"""""""""""""""""""""""""""""
Check for assigning uninitialized values.
.. code-block:: c
void test() {
int x;
x |= 1; // warn: left expression is uninitialized
}
.. _core-uninitialized-Branch:
core.uninitialized.Branch (C)
"""""""""""""""""""""""""""""
Check for uninitialized values used as branch conditions.
.. code-block:: c
void test() {
int x;
if (x) // warn
return;
}
.. _core-uninitialized-CapturedBlockVariable:
core.uninitialized.CapturedBlockVariable (C)
""""""""""""""""""""""""""""""""""""""""""""
Check for blocks that capture uninitialized values.
.. code-block:: c
void test() {
int x;
^{ int y = x; }(); // warn
}
.. _core-uninitialized-UndefReturn:
core.uninitialized.UndefReturn (C)
""""""""""""""""""""""""""""""""""
Check for uninitialized values being returned to the caller.
.. code-block:: c
int test() {
int x;
return x; // warn
}
.. _core-uninitialized-NewArraySize:
core.uninitialized.NewArraySize (C++)
"""""""""""""""""""""""""""""""""""""
Check if the element count in new[] is garbage or undefined.
.. code-block:: cpp
void test() {
int n;
int *arr = new int[n]; // warn: Element count in new[] is a garbage value
delete[] arr;
}
.. _cplusplus-checkers:
cplusplus
^^^^^^^^^
C++ Checkers.
.. _cplusplus-ArrayDelete:
cplusplus.ArrayDelete (C++)
"""""""""""""""""""""""""""
Reports destructions of arrays of polymorphic objects that are destructed as
their base class. If the dynamic type of the array is different from its static
type, calling `delete[]` is undefined.
This checker corresponds to the SEI CERT rule `EXP51-CPP: Do not delete an array through a pointer of the incorrect type <https://wiki.sei.cmu.edu/confluence/display/cplusplus/EXP51-CPP.+Do+not+delete+an+array+through+a+pointer+of+the+incorrect+type>`_.
.. code-block:: cpp
class Base {
public:
virtual ~Base() {}
};
class Derived : public Base {};
Base *create() {
Base *x = new Derived[10]; // note: Casting from 'Derived' to 'Base' here
return x;
}
void foo() {
Base *x = create();
delete[] x; // warn: Deleting an array of 'Derived' objects as their base class 'Base' is undefined
}
**Limitations**
The checker does not emit note tags when casting to and from reference types,
even though the pointer values are tracked across references.
.. code-block:: cpp
void foo() {
Derived *d = new Derived[10];
Derived &dref = *d;
Base &bref = static_cast<Base&>(dref); // no note
Base *b = &bref;
delete[] b; // warn: Deleting an array of 'Derived' objects as their base class 'Base' is undefined
}
.. _cplusplus-InnerPointer:
cplusplus.InnerPointer (C++)
""""""""""""""""""""""""""""
Check for inner pointers of C++ containers used after re/deallocation.
Many container methods in the C++ standard library are known to invalidate
"references" (including actual references, iterators and raw pointers) to
elements of the container. Using such references after they are invalidated
causes undefined behavior, which is a common source of memory errors in C++ that
this checker is capable of finding.
The checker is currently limited to ``std::string`` objects and doesn't
recognize some of the more sophisticated approaches to passing unowned pointers
around, such as ``std::string_view``.
.. code-block:: cpp
void deref_after_assignment() {
std::string s = "llvm";
const char *c = s.data(); // note: pointer to inner buffer of 'std::string' obtained here
s = "clang"; // note: inner buffer of 'std::string' reallocated by call to 'operator='
consume(c); // warn: inner pointer of container used after re/deallocation
}
const char *return_temp(int x) {
return std::to_string(x).c_str(); // warn: inner pointer of container used after re/deallocation
// note: pointer to inner buffer of 'std::string' obtained here
// note: inner buffer of 'std::string' deallocated by call to destructor
}
.. _cplusplus-Move:
cplusplus.Move (C++)
""""""""""""""""""""
Find use-after-move bugs in C++. This includes method calls on moved-from
objects, assignment of a moved-from object, and repeated move of a moved-from
object.
.. code-block:: cpp
struct A {
void foo() {}
};
void f1() {
A a;
A b = std::move(a); // note: 'a' became 'moved-from' here
a.foo(); // warn: method call on a 'moved-from' object 'a'
}
void f2() {
A a;
A b = std::move(a);
A c(std::move(a)); // warn: move of an already moved-from object
}
void f3() {
A a;
A b = std::move(a);
b = a; // warn: copy of moved-from object
}
The checker option ``WarnOn`` controls on what objects the use-after-move is
checked:
* The most strict value is ``KnownsOnly``, in this mode only objects are
checked whose type is known to be move-unsafe. These include most STL objects
(but excluding move-safe ones) and smart pointers.
* With option value ``KnownsAndLocals`` local variables (of any type) are
additionally checked. The idea behind this is that local variables are
usually not tempting to be re-used so an use after move is more likely a bug
than with member variables.
* With option value ``All`` any use-after move condition is checked on all
kinds of variables, excluding global variables and known move-safe cases.
Default value is ``KnownsAndLocals``.
Calls of methods named ``empty()`` or ``isEmpty()`` are allowed on moved-from
objects because these methods are considered as move-safe. Functions called
``reset()``, ``destroy()``, ``clear()``, ``assign``, ``resize``, ``shrink`` are
treated as state-reset functions and are allowed on moved-from objects, these
make the object valid again. This applies to any type of object (not only STL
ones).
.. _cplusplus-NewDelete:
cplusplus.NewDelete (C++)
"""""""""""""""""""""""""
Check for double-free and use-after-free problems. Traces memory managed by new/delete.
Custom allocation/deallocation functions can be defined using
:ref:`ownership attributes<analyzer-ownership-attrs>`.
.. literalinclude:: checkers/newdelete_example.cpp
:language: cpp
.. _cplusplus-NewDeleteLeaks:
cplusplus.NewDeleteLeaks (C++)
""""""""""""""""""""""""""""""
Check for memory leaks. Traces memory managed by new/delete.
Custom allocation/deallocation functions can be defined using
:ref:`ownership attributes<analyzer-ownership-attrs>`.
.. code-block:: cpp
void test() {
int *p = new int;
} // warn
.. _cplusplus-PlacementNew:
cplusplus.PlacementNew (C++)
""""""""""""""""""""""""""""
Check if default placement new is provided with pointers to sufficient storage capacity.
.. code-block:: cpp
#include <new>
void f() {
short s;
long *lp = ::new (&s) long; // warn
}
.. _cplusplus-SelfAssignment:
cplusplus.SelfAssignment (C++)
""""""""""""""""""""""""""""""
Checks C++ copy and move assignment operators for self assignment.
.. _cplusplus-StringChecker:
cplusplus.StringChecker (C++)
"""""""""""""""""""""""""""""
Checks std::string operations.
Checks if the cstring pointer from which the ``std::string`` object is
constructed is ``NULL`` or not.
If the checker cannot reason about the nullness of the pointer it will assume
that it was non-null to satisfy the precondition of the constructor.
This checker is capable of checking the `SEI CERT C++ coding rule STR51-CPP.
Do not attempt to create a std::string from a null pointer
<https://wiki.sei.cmu.edu/confluence/x/E3s-BQ>`__.
.. code-block:: cpp
#include <string>
void f(const char *p) {
if (!p) {
std::string msg(p); // warn: The parameter must not be null
}
}
.. _cplusplus-PureVirtualCall:
cplusplus.PureVirtualCall (C++)
"""""""""""""""""""""""""""""""
When `virtual methods are called during construction and destruction
<https://en.cppreference.com/w/cpp/language/virtual#During_construction_and_destruction>`__
the polymorphism is restricted to the class that's being constructed or
destructed because the more derived contexts are either not yet initialized or
already destructed.
This checker reports situations where this restricted polymorphism causes a
call to a pure virtual method, which is undefined behavior. (See also the
related checker :ref:`optin-cplusplus-VirtualCall` which reports situations
where the restricted polymorphism affects a call and the called method is not
pure virtual – but may be still surprising for the programmer.)
.. code-block:: cpp
struct A {
virtual int getKind() = 0;
A() {
// warn: This calls the pure virtual method A::getKind().
log << "Constructing " << getKind();
}
virtual ~A() {
releaseResources();
}
void releaseResources() {
// warn: This can call the pure virtual method A::getKind() when this is
// called from the destructor.
callSomeFunction(getKind());
}
};
.. _deadcode-checkers:
deadcode
^^^^^^^^
Dead Code Checkers.
.. _deadcode-DeadStores:
deadcode.DeadStores (C)
"""""""""""""""""""""""
Check for values stored to variables that are never read afterwards.
.. code-block:: c
void test() {
int x;
x = 1; // warn
}
The ``WarnForDeadNestedAssignments`` option enables the checker to emit
warnings for nested dead assignments. You can disable with the
``-analyzer-config deadcode.DeadStores:WarnForDeadNestedAssignments=false``.
*Defaults to true*.
Would warn for this e.g.:
if ((y = make_int())) {
}
.. _nullability-checkers:
nullability
^^^^^^^^^^^
Checkers (mostly Objective C) that warn for null pointer passing and dereferencing errors.
.. _nullability-NullPassedToNonnull:
nullability.NullPassedToNonnull (ObjC)
""""""""""""""""""""""""""""""""""""""
Warns when a null pointer is passed to a pointer which has a _Nonnull type.
.. code-block:: objc
if (name != nil)
return;
// Warning: nil passed to a callee that requires a non-null 1st parameter
NSString *greeting = [@"Hello " stringByAppendingString:name];
.. _nullability-NullReturnedFromNonnull:
nullability.NullReturnedFromNonnull (C, C++, ObjC)
""""""""""""""""""""""""""""""""""""""""""""""""""
Warns when a null pointer is returned from a function that has _Nonnull return type.
.. code-block:: objc
- (nonnull id)firstChild {
id result = nil;
if ([_children count] > 0)
result = _children[0];
// Warning: nil returned from a method that is expected
// to return a non-null value
return result;
}
Warns when a null pointer is returned from a function annotated with ``__attribute__((returns_nonnull))``
.. code-block:: cpp
int global;
__attribute__((returns_nonnull)) void* getPtr(void* p);
void* getPtr(void* p) {
if (p) { // forgot to negate the condition
return &global;
}
// Warning: nullptr returned from a function that is expected
// to return a non-null value
return p;
}
.. _nullability-NullableDereferenced:
nullability.NullableDereferenced (ObjC)
"""""""""""""""""""""""""""""""""""""""
Warns when a nullable pointer is dereferenced.
.. code-block:: objc
struct LinkedList {
int data;
struct LinkedList *next;
};
struct LinkedList * _Nullable getNext(struct LinkedList *l);
void updateNextData(struct LinkedList *list, int newData) {
struct LinkedList *next = getNext(list);
// Warning: Nullable pointer is dereferenced
next->data = 7;
}
.. _nullability-NullablePassedToNonnull:
nullability.NullablePassedToNonnull (ObjC)
""""""""""""""""""""""""""""""""""""""""""
Warns when a nullable pointer is passed to a pointer which has a _Nonnull type.
.. code-block:: objc
typedef struct Dummy { int val; } Dummy;
Dummy *_Nullable returnsNullable();
void takesNonnull(Dummy *_Nonnull);
void test() {
Dummy *p = returnsNullable();
takesNonnull(p); // warn
}
.. _nullability-NullableReturnedFromNonnull:
nullability.NullableReturnedFromNonnull (ObjC)
""""""""""""""""""""""""""""""""""""""""""""""
Warns when a nullable pointer is returned from a function that has _Nonnull return type.
.. _optin-checkers:
optin
^^^^^
Checkers for portability, performance, optional security and coding style specific rules.
.. _optin-core-EnumCastOutOfRange:
optin.core.EnumCastOutOfRange (C, C++)
""""""""""""""""""""""""""""""""""""""
Check for integer to enumeration casts that would produce a value with no
corresponding enumerator. This is not necessarily undefined behavior, but can
lead to nasty surprises, so projects may decide to use a coding standard that
disallows these "unusual" conversions.
Note that no warnings are produced when the enum type (e.g. `std::byte`) has no
enumerators at all.
.. code-block:: cpp
enum WidgetKind { A=1, B, C, X=99 };
void foo() {
WidgetKind c = static_cast<WidgetKind>(3); // OK
WidgetKind x = static_cast<WidgetKind>(99); // OK
WidgetKind d = static_cast<WidgetKind>(4); // warn
}
**Limitations**
This checker does not accept the coding pattern where an enum type is used to
store combinations of flag values.
Such enums should be annotated with the `__attribute__((flag_enum))` or by the
`[[clang::flag_enum]]` attribute to signal this intent. Refer to the
`documentation <https://clang.llvm.org/docs/AttributeReference.html#flag-enum>`_
of this Clang attribute.
.. code-block:: cpp
enum AnimalFlags
{
HasClaws = 1,
CanFly = 2,
EatsFish = 4,
Endangered = 8
};
AnimalFlags operator|(AnimalFlags a, AnimalFlags b)
{
return static_cast<AnimalFlags>(static_cast<int>(a) | static_cast<int>(b));
}
auto flags = HasClaws | CanFly;
Projects that use this pattern should not enable this optin checker.
.. _optin-cplusplus-UninitializedObject:
optin.cplusplus.UninitializedObject (C++)
"""""""""""""""""""""""""""""""""""""""""
This checker reports uninitialized fields in objects created after a constructor
call. It doesn't only find direct uninitialized fields, but rather makes a deep
inspection of the object, analyzing all of its fields' subfields.
The checker regards inherited fields as direct fields, so one will receive
warnings for uninitialized inherited data members as well.
.. code-block:: cpp
// With Pedantic and CheckPointeeInitialization set to true
struct A {
struct B {
int x; // note: uninitialized field 'this->b.x'
// note: uninitialized field 'this->bptr->x'
int y; // note: uninitialized field 'this->b.y'
// note: uninitialized field 'this->bptr->y'
};
int *iptr; // note: uninitialized pointer 'this->iptr'
B b;
B *bptr;
char *cptr; // note: uninitialized pointee 'this->cptr'
A (B *bptr, char *cptr) : bptr(bptr), cptr(cptr) {}
};
void f() {
A::B b;
char c;
A a(&b, &c); // warning: 6 uninitialized fields
// after the constructor call
}
// With Pedantic set to false and
// CheckPointeeInitialization set to true
// (every field is uninitialized)
struct A {
struct B {
int x;
int y;
};
int *iptr;
B b;
B *bptr;
char *cptr;
A (B *bptr, char *cptr) : bptr(bptr), cptr(cptr) {}
};
void f() {
A::B b;
char c;
A a(&b, &c); // no warning
}
// With Pedantic set to true and
// CheckPointeeInitialization set to false
// (pointees are regarded as initialized)
struct A {
struct B {
int x; // note: uninitialized field 'this->b.x'
int y; // note: uninitialized field 'this->b.y'
};
int *iptr; // note: uninitialized pointer 'this->iptr'
B b;
B *bptr;
char *cptr;
A (B *bptr, char *cptr) : bptr(bptr), cptr(cptr) {}
};
void f() {
A::B b;
char c;
A a(&b, &c); // warning: 3 uninitialized fields
// after the constructor call
}
**Options**
This checker has several options which can be set from command line (e.g.
``-analyzer-config optin.cplusplus.UninitializedObject:Pedantic=true``):
* ``Pedantic`` (boolean). If to false, the checker won't emit warnings for
objects that don't have at least one initialized field. Defaults to false.
* ``NotesAsWarnings`` (boolean). If set to true, the checker will emit a
warning for each uninitialized field, as opposed to emitting one warning per
constructor call, and listing the uninitialized fields that belongs to it in
notes. *Defaults to false*.
* ``CheckPointeeInitialization`` (boolean). If set to false, the checker will
not analyze the pointee of pointer/reference fields, and will only check
whether the object itself is initialized. *Defaults to false*.
* ``IgnoreRecordsWithField`` (string). If supplied, the checker will not analyze
structures that have a field with a name or type name that matches the given
pattern. *Defaults to ""*.
.. _optin-cplusplus-VirtualCall:
optin.cplusplus.VirtualCall (C++)
"""""""""""""""""""""""""""""""""
When `virtual methods are called during construction and destruction
<https://en.cppreference.com/w/cpp/language/virtual#During_construction_and_destruction>`__
the polymorphism is restricted to the class that's being constructed or
destructed because the more derived contexts are either not yet initialized or
already destructed.
Although this behavior is well-defined, it can surprise the programmer and
cause unintended behavior, so this checker reports calls that appear to be
virtual calls but can be affected by this restricted polymorphism.
Note that situations where this restricted polymorphism causes a call to a pure
virtual method (which is definitely invalid, triggers undefined behavior) are
**reported by another checker:** :ref:`cplusplus-PureVirtualCall` and **this
checker does not report them**.
.. code-block:: cpp
struct A {
virtual int getKind();
A() {
// warn: This calls A::getKind() even if we are constructing an instance
// of a different class that is derived from A.
log << "Constructing " << getKind();
}
virtual ~A() {
releaseResources();
}
void releaseResources() {
// warn: This can be called within ~A() and calls A::getKind() even if
// we are destructing a class that is derived from A.
callSomeFunction(getKind());
}
};
.. _optin-mpi-MPI-Checker:
optin.mpi.MPI-Checker (C)
"""""""""""""""""""""""""
Checks MPI code.
.. code-block:: c
void test() {
double buf = 0;
MPI_Request sendReq1;
MPI_Ireduce(MPI_IN_PLACE, &buf, 1, MPI_DOUBLE, MPI_SUM,
0, MPI_COMM_WORLD, &sendReq1);
} // warn: request 'sendReq1' has no matching wait.
void test() {
double buf = 0;
MPI_Request sendReq;
MPI_Isend(&buf, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &sendReq);
MPI_Irecv(&buf, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &sendReq); // warn
MPI_Isend(&buf, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &sendReq); // warn
MPI_Wait(&sendReq, MPI_STATUS_IGNORE);
}
void missingNonBlocking() {
int rank = 0;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Request sendReq1[10][10][10];
MPI_Wait(&sendReq1[1][7][9], MPI_STATUS_IGNORE); // warn
}
.. _optin-osx-cocoa-localizability-EmptyLocalizationContextChecker:
optin.osx.cocoa.localizability.EmptyLocalizationContextChecker (ObjC)
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Check that NSLocalizedString macros include a comment for context.
.. code-block:: objc
- (void)test {
NSString *string = NSLocalizedString(@"LocalizedString", nil); // warn
NSString *string2 = NSLocalizedString(@"LocalizedString", @" "); // warn
NSString *string3 = NSLocalizedStringWithDefaultValue(
@"LocalizedString", nil, [[NSBundle alloc] init], nil,@""); // warn
}
.. _optin-osx-cocoa-localizability-NonLocalizedStringChecker:
optin.osx.cocoa.localizability.NonLocalizedStringChecker (ObjC)
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Warns about uses of non-localized NSStrings passed to UI methods expecting localized NSStrings.
.. code-block:: objc
NSString *alarmText =
NSLocalizedString(@"Enabled", @"Indicates alarm is turned on");
if (!isEnabled) {
alarmText = @"Disabled";
}
UILabel *alarmStateLabel = [[UILabel alloc] init];
// Warning: User-facing text should use localized string macro
[alarmStateLabel setText:alarmText];
.. _optin-performance-GCDAntipattern:
optin.performance.GCDAntipattern
""""""""""""""""""""""""""""""""
Check for performance anti-patterns when using Grand Central Dispatch.
.. _optin-performance-Padding:
optin.performance.Padding (C, C++, ObjC)
""""""""""""""""""""""""""""""""""""""""
Check for excessively padded structs.
This checker detects structs with excessive padding, which can lead to wasted
memory thus decreased performance by reducing the effectiveness of the
processor cache. Padding bytes are added by compilers to align data accesses
as some processors require data to be aligned to certain boundaries. On others,
unaligned data access are possible, but impose significantly larger latencies.
To avoid padding bytes, the fields of a struct should be ordered by decreasing
by alignment. Usually, its easier to think of the ``sizeof`` of the fields, and
ordering the fields by ``sizeof`` would usually also lead to the same optimal
layout.
In rare cases, one can use the ``#pragma pack(1)`` directive to enforce a packed
layout too, but it can significantly increase the access times, so reordering the
fields is usually a better solution.
.. code-block:: cpp
// warn: Excessive padding in 'struct NonOptimal' (35 padding bytes, where 3 is optimal)
struct NonOptimal {
char c1;
// 7 bytes of padding
std::int64_t big1; // 8 bytes
char c2;
// 7 bytes of padding
std::int64_t big2; // 8 bytes
char c3;
// 7 bytes of padding
std::int64_t big3; // 8 bytes
char c4;
// 7 bytes of padding
std::int64_t big4; // 8 bytes
char c5;
// 7 bytes of padding
};
static_assert(sizeof(NonOptimal) == 4*8+5+5*7);
// no-warning: The fields are nicely aligned to have the minimal amount of padding bytes.
struct Optimal {
std::int64_t big1; // 8 bytes
std::int64_t big2; // 8 bytes
std::int64_t big3; // 8 bytes
std::int64_t big4; // 8 bytes
char c1;
char c2;
char c3;
char c4;
char c5;
// 3 bytes of padding
};
static_assert(sizeof(Optimal) == 4*8+5+3);
// no-warning: Bit packing representation is also accepted by this checker, but
// it can significantly increase access times, so prefer reordering the fields.
#pragma pack(1)
struct BitPacked {
char c1;
std::int64_t big1; // 8 bytes
char c2;
std::int64_t big2; // 8 bytes
char c3;
std::int64_t big3; // 8 bytes
char c4;
std::int64_t big4; // 8 bytes
char c5;
};
static_assert(sizeof(BitPacked) == 4*8+5);
The ``AllowedPad`` option can be used to specify a threshold for the number
padding bytes raising the warning. If the number of padding bytes of the struct
and the optimal number of padding bytes differ by more than the threshold value,
a warning will be raised.
By default, the ``AllowedPad`` threshold is 24 bytes.
To override this threshold to e.g. 4 bytes, use the
``-analyzer-config optin.performance.Padding:AllowedPad=4`` option.
.. _optin-portability-UnixAPI:
optin.portability.UnixAPI
"""""""""""""""""""""""""
Reports situations where 0 is passed as the "size" argument of various
allocation functions ( ``calloc``, ``malloc``, ``realloc``, ``reallocf``,
``alloca``, ``__builtin_alloca``, ``__builtin_alloca_with_align``, ``valloc``).
Note that similar functionality is also supported by :ref:`unix-Malloc` which
reports code that *uses* memory allocated with size zero.
(The name of this checker is motivated by the fact that it was originally
introduced with the vague goal that it "Finds implementation-defined behavior
in UNIX/Posix functions.")
optin.taint
^^^^^^^^^^^
Checkers implementing
`taint analysis <https://en.wikipedia.org/wiki/Taint_checking>`_.
.. _optin-taint-GenericTaint:
optin.taint.GenericTaint (C, C++)
"""""""""""""""""""""""""""""""""
Taint analysis identifies potential security vulnerabilities where the
attacker can inject malicious data to the program to execute an attack
(privilege escalation, command injection, SQL injection etc.).
The malicious data is injected at the taint source (e.g. ``getenv()`` call)
which is then propagated through function calls and being used as arguments of
sensitive operations, also called as taint sinks (e.g. ``system()`` call).
One can defend against this type of vulnerability by always checking and
sanitizing the potentially malicious, untrusted user input.
The goal of the checker is to discover and show to the user these potential
taint source-sink pairs and the propagation call chain.
The most notable examples of taint sources are:
- data from network
- files or standard input
- environment variables
- data from databases
Let us examine a practical example of a Command Injection attack.
.. code-block:: c
// Command Injection Vulnerability Example
int main(int argc, char** argv) {
char cmd[2048] = "/bin/cat ";
char filename[1024];
printf("Filename:");
scanf (" %1023[^\n]", filename); // The attacker can inject a shell escape here
strcat(cmd, filename);
system(cmd); // Warning: Untrusted data is passed to a system call
}
The program prints the content of any user specified file.
Unfortunately the attacker can execute arbitrary commands
with shell escapes. For example with the following input the `ls` command is also
executed after the contents of `/etc/shadow` is printed.
`Input: /etc/shadow ; ls /`
The analysis implemented in this checker points out this problem.
One can protect against such attack by for example checking if the provided
input refers to a valid file and removing any invalid user input.
.. code-block:: c
// No vulnerability anymore, but we still get the warning
void sanitizeFileName(char* filename){
if (access(filename,F_OK)){// Verifying user input
printf("File does not exist\n");
filename[0]='\0';
}
}
int main(int argc, char** argv) {
char cmd[2048] = "/bin/cat ";
char filename[1024];
printf("Filename:");
scanf (" %1023[^\n]", filename); // The attacker can inject a shell escape here
sanitizeFileName(filename);// filename is safe after this point
if (!filename[0])
return -1;
strcat(cmd, filename);
system(cmd); // Superfluous Warning: Untrusted data is passed to a system call
}
Unfortunately, the checker cannot discover automatically that the programmer
have performed data sanitation, so it still emits the warning.
One can get rid of this superfluous warning by telling by specifying the
sanitation functions in the taint configuration file (see
:doc:`user-docs/TaintAnalysisConfiguration`).
.. code-block:: YAML
Filters:
- Name: sanitizeFileName
Args: [0]
The clang invocation to pass the configuration file location:
.. code-block:: bash
clang --analyze -Xclang -analyzer-config -Xclang optin.taint.TaintPropagation:Config=`pwd`/taint_config.yml ...
If you are validating your inputs instead of sanitizing them, or don't want to
mention each sanitizing function in our configuration,
you can use a more generic approach.
Introduce a generic no-op `csa_mark_sanitized(..)` function to
tell the Clang Static Analyzer
that the variable is safe to be used on that analysis path.
.. code-block:: c
// Marking sanitized variables safe.
// No vulnerability anymore, no warning.
// User csa_mark_sanitize function is for the analyzer only
#ifdef __clang_analyzer__
void csa_mark_sanitized(const void *);
#endif
int main(int argc, char** argv) {
char cmd[2048] = "/bin/cat ";
char filename[1024];
printf("Filename:");
scanf (" %1023[^\n]", filename);
if (access(filename,F_OK)){// Verifying user input
printf("File does not exist\n");
return -1;
}
#ifdef __clang_analyzer__
csa_mark_sanitized(filename); // Indicating to CSA that filename variable is safe to be used after this point
#endif
strcat(cmd, filename);
system(cmd); // No warning
}
Similarly to the previous example, you need to
define a `Filter` function in a `YAML` configuration file
and add the `csa_mark_sanitized` function.
.. code-block:: YAML
Filters:
- Name: csa_mark_sanitized
Args: [0]
Then calling `csa_mark_sanitized(X)` will tell the analyzer that `X` is safe to
be used after this point, because its contents are verified. It is the
responsibility of the programmer to ensure that this verification was indeed
correct. Please note that `csa_mark_sanitized` function is only declared and
used during Clang Static Analysis and skipped in (production) builds.
Further examples of injection vulnerabilities this checker can find.
.. code-block:: c
void test() {
char x = getchar(); // 'x' marked as tainted
system(&x); // warn: untrusted data is passed to a system call
}
// note: compiler internally checks if the second param to
// sprintf is a string literal or not.
// Use -Wno-format-security to suppress compiler warning.
void test() {
char s[10], buf[10];
fscanf(stdin, "%s", s); // 's' marked as tainted
sprintf(buf, s); // warn: untrusted data used as a format string
}
There are built-in sources, propagations and sinks even if no external taint
configuration is provided.
Default sources:
``_IO_getc``, ``fdopen``, ``fopen``, ``freopen``, ``get_current_dir_name``,
``getch``, ``getchar``, ``getchar_unlocked``, ``getwd``, ``getcwd``,
``getgroups``, ``gethostname``, ``getlogin``, ``getlogin_r``, ``getnameinfo``,
``gets``, ``gets_s``, ``getseuserbyname``, ``readlink``, ``readlinkat``,
``scanf``, ``scanf_s``, ``socket``, ``wgetch``
Default propagations rules:
``atoi``, ``atol``, ``atoll``, ``basename``, ``dirname``, ``fgetc``,
``fgetln``, ``fgets``, ``fnmatch``, ``fread``, ``fscanf``, ``fscanf_s``,
``index``, ``inflate``, ``isalnum``, ``isalpha``, ``isascii``, ``isblank``,
``iscntrl``, ``isdigit``, ``isgraph``, ``islower``, ``isprint``, ``ispunct``,
``isspace``, ``isupper``, ``isxdigit``, ``memchr``, ``memrchr``, ``sscanf``,
``getc``, ``getc_unlocked``, ``getdelim``, ``getline``, ``getw``, ``memcmp``,
``memcpy``, ``memmem``, ``memmove``, ``mbtowc``, ``pread``, ``qsort``,
``qsort_r``, ``rawmemchr``, ``read``, ``recv``, ``recvfrom``, ``rindex``,
``strcasestr``, ``strchr``, ``strchrnul``, ``strcasecmp``, ``strcmp``,
``strcspn``, ``strncasecmp``, ``strncmp``, ``strndup``,
``strndupa``, ``strpbrk``, ``strrchr``, ``strsep``, ``strspn``,
``strstr``, ``strtol``, ``strtoll``, ``strtoul``, ``strtoull``, ``tolower``,
``toupper``, ``ttyname``, ``ttyname_r``, ``wctomb``, ``wcwidth``
Default sinks:
``printf``, ``setproctitle``, ``system``, ``popen``, ``execl``, ``execle``,
``execlp``, ``execv``, ``execvp``, ``execvP``, ``execve``, ``dlopen``
Please note that there are no built-in filter functions.
One can configure their own taint sources, sinks, and propagation rules by
providing a configuration file via checker option
``optin.taint.TaintPropagation:Config``. The configuration file is in
`YAML <http://llvm.org/docs/YamlIO.html#introduction-to-yaml>`_ format. The
taint-related options defined in the config file extend but do not override the
built-in sources, rules, sinks. The format of the external taint configuration
file is not stable, and could change without any notice even in a non-backward
compatible way.
For a more detailed description of configuration options, please see the
:doc:`user-docs/TaintAnalysisConfiguration`. For an example see
:ref:`clangsa-taint-configuration-example`.
**Configuration**
* `Config` Specifies the name of the YAML configuration file. The user can
define their own taint sources and sinks.
**Related Guidelines**
* `CWE Data Neutralization Issues
<https://cwe.mitre.org/data/definitions/137.html>`_
* `SEI Cert STR02-C. Sanitize data passed to complex subsystems
<https://wiki.sei.cmu.edu/confluence/display/c/STR02-C.+Sanitize+data+passed+to+complex+subsystems>`_
* `SEI Cert ENV33-C. Do not call system()
<https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152177>`_
* `ENV03-C. Sanitize the environment when invoking external programs
<https://wiki.sei.cmu.edu/confluence/display/c/ENV03-C.+Sanitize+the+environment+when+invoking+external+programs>`_
**Limitations**
* The taintedness property is not propagated through function calls which are
unknown (or too complex) to the analyzer, unless there is a specific
propagation rule built-in to the checker or given in the YAML configuration
file. This causes potential true positive findings to be lost.
.. _optin-taint-TaintedAlloc:
optin.taint.TaintedAlloc (C, C++)
"""""""""""""""""""""""""""""""""
This checker warns for cases when the ``size`` parameter of the ``malloc`` ,
``calloc``, ``realloc``, ``alloca`` or the size parameter of the
array new C++ operator is tainted (potentially attacker controlled).
If an attacker can inject a large value as the size parameter, memory exhaustion
denial of service attack can be carried out.
The analyzer emits warning only if it cannot prove that the size parameter is
within reasonable bounds (``<= SIZE_MAX/4``). This functionality partially
covers the SEI Cert coding standard rule `INT04-C
<https://wiki.sei.cmu.edu/confluence/display/c/INT04-C.+Enforce+limits+on+integer+values+originating+from+tainted+sources>`_.
You can silence this warning either by bound checking the ``size`` parameter, or
by explicitly marking the ``size`` parameter as sanitized. See the
:ref:`optin-taint-GenericTaint` checker for an example.
Custom allocation/deallocation functions can be defined using
:ref:`ownership attributes<analyzer-ownership-attrs>`.
.. code-block:: c
void vulnerable(void) {
size_t size = 0;
scanf("%zu", &size);
int *p = malloc(size); // warn: malloc is called with a tainted (potentially attacker controlled) value
free(p);
}
void not_vulnerable(void) {
size_t size = 0;
scanf("%zu", &size);
if (1024 < size)
return;
int *p = malloc(size); // No warning expected as the the user input is bound
free(p);
}
void vulnerable_cpp(void) {
size_t size = 0;
scanf("%zu", &size);
int *ptr = new int[size];// warn: Memory allocation function is called with a tainted (potentially attacker controlled) value
delete[] ptr;
}
.. _optin-taint-TaintedDiv:
optin.taint.TaintedDiv (C, C++, ObjC)
"""""""""""""""""""""""""""""""""""""
This checker warns when the denominator in a division
operation is a tainted (potentially attacker controlled) value.
If the attacker can set the denominator to 0, a runtime error can
be triggered. The checker warns when the denominator is a tainted
value and the analyzer cannot prove that it is not 0. This warning
is more pessimistic than the :ref:`core-DivideZero` checker
which warns only when it can prove that the denominator is 0.
.. code-block:: c
int vulnerable(int n) {
size_t size = 0;
scanf("%zu", &size);
return n / size; // warn: Division by a tainted value, possibly zero
}
int not_vulnerable(int n) {
size_t size = 0;
scanf("%zu", &size);
if (!size)
return 0;
return n / size; // no warning
}
.. _security-checkers:
security
^^^^^^^^
Security related checkers.
.. _security-ArrayBound:
security.ArrayBound (C, C++)
""""""""""""""""""""""""""""
Report out of bounds access to memory that is before the start or after the end
of the accessed region (array, heap-allocated region, string literal etc.).
This usually means incorrect indexing, but the checker also detects access via
the operators ``*`` and ``->``.
.. code-block:: c
void test_underflow(int x) {
int buf[100][100];
if (x < 0)
buf[0][x] = 1; // warn
}
void test_overflow() {
int buf[100];
int *p = buf + 100;
*p = 1; // warn
}
If checkers like :ref:`unix-Malloc` or :ref:`cplusplus-NewDelete` are enabled
to model the behavior of ``malloc()``, ``operator new`` and similar
allocators), then this checker can also reports out of bounds access to
dynamically allocated memory:
.. code-block:: cpp
int *test_dynamic() {
int *mem = new int[100];
mem[-1] = 42; // warn
return mem;
}
In uncertain situations (when the checker can neither prove nor disprove that
overflow occurs), the checker assumes that the the index (more precisely, the
memory offeset) is within bounds.
However, if :ref:`optin-taint-GenericTaint` is enabled and the index/offset is
tainted (i.e. it is influenced by an untrusted source), then this checker
reports the potential out of bounds access:
.. code-block:: c
void test_with_tainted_index() {
char s[] = "abc";
int x = getchar();
char c = s[x]; // warn: potential out of bounds access with tainted index
}
.. note::
This checker is an improved and renamed version of the checker that was
previously known as ``alpha.security.ArrayBoundV2``. The old checker
``alpha.security.ArrayBound`` was removed when the (previously
"experimental") V2 variant became stable enough for regular use.
.. _security-cert-env-InvalidPtr:
security.cert.env.InvalidPtr
""""""""""""""""""""""""""""
Corresponds to SEI CERT Rules `ENV31-C <https://wiki.sei.cmu.edu/confluence/display/c/ENV31-C.+Do+not+rely+on+an+environment+pointer+following+an+operation+that+may+invalidate+it>`_ and `ENV34-C <https://wiki.sei.cmu.edu/confluence/display/c/ENV34-C.+Do+not+store+pointers+returned+by+certain+functions>`_.
* **ENV31-C**:
Rule is about the possible problem with ``main`` function's third argument, environment pointer,
"envp". When environment array is modified using some modification function
such as ``putenv``, ``setenv`` or others, It may happen that memory is reallocated,
however "envp" is not updated to reflect the changes and points to old memory
region.
* **ENV34-C**:
Some functions return a pointer to a statically allocated buffer.
Consequently, subsequent call of these functions will invalidate previous
pointer. These functions include: ``getenv``, ``localeconv``, ``asctime``, ``setlocale``, ``strerror``
.. code-block:: c
int main(int argc, const char *argv[], const char *envp[]) {
if (setenv("MY_NEW_VAR", "new_value", 1) != 0) {
// setenv call may invalidate 'envp'
/* Handle error */
}
if (envp != NULL) {
for (size_t i = 0; envp[i] != NULL; ++i) {
puts(envp[i]);
// envp may no longer point to the current environment
// this program has unanticipated behavior, since envp
// does not reflect changes made by setenv function.
}
}
return 0;
}
void previous_call_invalidation() {
char *p, *pp;
p = getenv("VAR");
setenv("SOMEVAR", "VALUE", /*overwrite = */1);
// call to 'setenv' may invalidate p
*p;
// dereferencing invalid pointer
}
The ``InvalidatingGetEnv`` option is available for treating ``getenv`` calls as
invalidating. When enabled, the checker issues a warning if ``getenv`` is called
multiple times and their results are used without first creating a copy.
This level of strictness might be considered overly pedantic for the commonly
used ``getenv`` implementations.
To enable this option, use:
``-analyzer-config security.cert.env.InvalidPtr:InvalidatingGetEnv=true``.
By default, this option is set to *false*.
When this option is enabled, warnings will be generated for scenarios like the
following:
.. code-block:: c
char* p = getenv("VAR");
char* pp = getenv("VAR2"); // assumes this call can invalidate `env`
strlen(p); // warns about accessing invalid ptr
.. _security-FloatLoopCounter:
security.FloatLoopCounter (C)
"""""""""""""""""""""""""""""
Warn on using a floating point value as a loop counter (CERT: FLP30-C, FLP30-CPP).
.. code-block:: c
void test() {
for (float x = 0.1f; x <= 1.0f; x += 0.1f) {} // warn
}
.. _security-insecureAPI-UncheckedReturn:
security.insecureAPI.UncheckedReturn (C)
""""""""""""""""""""""""""""""""""""""""
Warn on uses of functions whose return values must be always checked.
.. code-block:: c
void test() {
setuid(1); // warn
}
.. _security-insecureAPI-bcmp:
security.insecureAPI.bcmp (C)
"""""""""""""""""""""""""""""
Warn on uses of the 'bcmp' function.
.. code-block:: c
void test() {
bcmp(ptr0, ptr1, n); // warn
}
.. _security-insecureAPI-bcopy:
security.insecureAPI.bcopy (C)
""""""""""""""""""""""""""""""
Warn on uses of the 'bcopy' function.
.. code-block:: c
void test() {
bcopy(src, dst, n); // warn
}
.. _security-insecureAPI-bzero:
security.insecureAPI.bzero (C)
""""""""""""""""""""""""""""""
Warn on uses of the 'bzero' function.
.. code-block:: c
void test() {
bzero(ptr, n); // warn
}
.. _security-insecureAPI-getpw:
security.insecureAPI.getpw (C)
""""""""""""""""""""""""""""""
Warn on uses of the 'getpw' function.
.. code-block:: c
void test() {
char buff[1024];
getpw(2, buff); // warn
}
.. _security-insecureAPI-gets:
security.insecureAPI.gets (C)
"""""""""""""""""""""""""""""
Warn on uses of the 'gets' function.
.. code-block:: c
void test() {
char buff[1024];
gets(buff); // warn
}
.. _security-insecureAPI-mkstemp:
security.insecureAPI.mkstemp (C)
""""""""""""""""""""""""""""""""
Warn when 'mkstemp' is passed fewer than 6 X's in the format string.
.. code-block:: c
void test() {
mkstemp("XX"); // warn
}
.. _security-insecureAPI-mktemp:
security.insecureAPI.mktemp (C)
"""""""""""""""""""""""""""""""
Warn on uses of the ``mktemp`` function.
.. code-block:: c
void test() {
char *x = mktemp("/tmp/zxcv"); // warn: insecure, use mkstemp
}
.. _security-insecureAPI-rand:
security.insecureAPI.rand (C)
"""""""""""""""""""""""""""""
Warn on uses of inferior random number generating functions (only if arc4random function is available):
``drand48, erand48, jrand48, lcong48, lrand48, mrand48, nrand48, random, rand_r``.
.. code-block:: c
void test() {
random(); // warn
}
.. _security-insecureAPI-strcpy:
security.insecureAPI.strcpy (C)
"""""""""""""""""""""""""""""""
Warn on uses of the ``strcpy`` and ``strcat`` functions.
.. code-block:: c
void test() {
char x[4];
char *y = "abcd";
strcpy(x, y); // warn
}
.. _security-insecureAPI-vfork:
security.insecureAPI.vfork (C)
""""""""""""""""""""""""""""""
Warn on uses of the 'vfork' function.
.. code-block:: c
void test() {
vfork(); // warn
}
.. _security-insecureAPI-DeprecatedOrUnsafeBufferHandling:
security.insecureAPI.DeprecatedOrUnsafeBufferHandling (C)
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Warn on occurrences of unsafe or deprecated buffer handling functions, which now have a secure variant: ``sprintf, fprintf, vsprintf, scanf, wscanf, fscanf, fwscanf, vscanf, vwscanf, vfscanf, vfwscanf, sscanf, swscanf, vsscanf, vswscanf, swprintf, snprintf, vswprintf, vsnprintf, memcpy, memmove, strncpy, strncat, memset``
.. code-block:: c
void test() {
char buf [5];
strncpy(buf, "a", 1); // warn
}
.. _security-MmapWriteExec:
security.MmapWriteExec (C)
""""""""""""""""""""""""""
Warn on ``mmap()`` calls with both writable and executable access.
.. code-block:: c
void test(int n) {
void *c = mmap(NULL, 32, PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANON, -1, 0);
// warn: Both PROT_WRITE and PROT_EXEC flags are set. This can lead to
// exploitable memory regions, which could be overwritten with malicious
// code
}
.. _security-PointerSub:
security.PointerSub (C)
"""""""""""""""""""""""
Check for pointer subtractions on two pointers pointing to different memory
chunks. According to the C standard §6.5.6 only subtraction of pointers that
point into (or one past the end) the same array object is valid (for this
purpose non-array variables are like arrays of size 1). This checker only
searches for different memory objects at subtraction, but does not check if the
array index is correct. Furthermore, only cases are reported where
stack-allocated objects are involved (no warnings on pointers to memory
allocated by `malloc`).
.. code-block:: c
void test() {
int a, b, c[10], d[10];
int x = &c[3] - &c[1];
x = &d[4] - &c[1]; // warn: 'c' and 'd' are different arrays
x = (&a + 1) - &a;
x = &b - &a; // warn: 'a' and 'b' are different variables
}
struct S {
int x[10];
int y[10];
};
void test1() {
struct S a[10];
struct S b;
int d = &a[4] - &a[6];
d = &a[0].x[3] - &a[0].x[1];
d = a[0].y - a[0].x; // warn: 'S.b' and 'S.a' are different objects
d = (char *)&b.y - (char *)&b.x; // warn: different members of the same object
d = (char *)&b.y - (char *)&b; // warn: object of type S is not the same array as a member of it
}
There may be existing applications that use code like above for calculating
offsets of members in a structure, using pointer subtractions. This is still
undefined behavior according to the standard and code like this can be replaced
with the `offsetof` macro.
.. _security-putenv-stack-array:
security.PutenvStackArray (C)
"""""""""""""""""""""""""""""
Finds calls to the ``putenv`` function which pass a pointer to a stack-allocated
(automatic) array as the argument. Function ``putenv`` does not copy the passed
string, only a pointer to the data is stored and this data can be read even by
other threads. Content of a stack-allocated array is likely to be overwritten
after exiting from the function.
The problem can be solved by using a static array variable or dynamically
allocated memory. Even better is to avoid using ``putenv`` (it has other
problems related to memory leaks) and use ``setenv`` instead.
The check corresponds to CERT rule
`POS34-C. Do not call putenv() with a pointer to an automatic variable as the argument
<https://wiki.sei.cmu.edu/confluence/display/c/POS34-C.+Do+not+call+putenv%28%29+with+a+pointer+to+an+automatic+variable+as+the+argument>`_.
.. code-block:: c
int f() {
char env[] = "NAME=value";
return putenv(env); // putenv function should not be called with stack-allocated string
}
There is one case where the checker can report a false positive. This is when
the stack-allocated array is used at `putenv` in a function or code branch that
does not return (process is terminated on all execution paths).
Another special case is if the `putenv` is called from function `main`. Here
the stack is deallocated at the end of the program and it should be no problem
to use the stack-allocated string (a multi-threaded program may require more
attention). The checker does not warn for cases when stack space of `main` is
used at the `putenv` call.
security.SetgidSetuidOrder (C)
""""""""""""""""""""""""""""""
When dropping user-level and group-level privileges in a program by using
``setuid`` and ``setgid`` calls, it is important to reset the group-level
privileges (with ``setgid``) first. Function ``setgid`` will likely fail if
the superuser privileges are already dropped.
The checker checks for sequences of ``setuid(getuid())`` and
``setgid(getgid())`` calls (in this order). If such a sequence is found and
there is no other privilege-changing function call (``seteuid``, ``setreuid``,
``setresuid`` and the GID versions of these) in between, a warning is
generated. The checker finds only exactly ``setuid(getuid())`` calls (and the
GID versions), not for example if the result of ``getuid()`` is stored in a
variable.
.. code-block:: c
void test1() {
// ...
// end of section with elevated privileges
// reset privileges (user and group) to normal user
if (setuid(getuid()) != 0) {
handle_error();
return;
}
if (setgid(getgid()) != 0) { // warning: A 'setgid(getgid())' call following a 'setuid(getuid())' call is likely to fail
handle_error();
return;
}
// user-ID and group-ID are reset to normal user now
// ...
}
In the code above the problem is that ``setuid(getuid())`` removes superuser
privileges before ``setgid(getgid())`` is called. To fix the problem the
``setgid(getgid())`` should be called first. Further attention is needed to
avoid code like ``setgid(getuid())`` (this checker does not detect bugs like
this) and always check the return value of these calls.
This check corresponds to SEI CERT Rule `POS36-C <https://wiki.sei.cmu.edu/confluence/display/c/POS36-C.+Observe+correct+revocation+order+while+relinquishing+privileges>`_.
.. _unix-checkers:
unix
^^^^
POSIX/Unix checkers.
.. _unix-API:
unix.API (C)
""""""""""""
Check calls to various UNIX/Posix functions: ``open, pthread_once, calloc, malloc, realloc, alloca``.
.. literalinclude:: checkers/unix_api_example.c
:language: c
.. _unix-BlockInCriticalSection:
unix.BlockInCriticalSection (C, C++)
""""""""""""""""""""""""""""""""""""
Check for calls to blocking functions inside a critical section.
Blocking functions detected by this checker: ``sleep, getc, fgets, read, recv``.
Critical section handling functions modeled by this checker:
``lock, unlock, pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock, mtx_lock, mtx_timedlock, mtx_trylock, mtx_unlock, lock_guard, unique_lock``.
.. code-block:: c
void pthread_lock_example(pthread_mutex_t *m) {
pthread_mutex_lock(m); // note: entering critical section here
sleep(10); // warn: Call to blocking function 'sleep' inside of critical section
pthread_mutex_unlock(m);
}
.. code-block:: cpp
void overlapping_critical_sections(mtx_t *m1, std::mutex &m2) {
std::lock_guard lg{m2}; // note: entering critical section here
mtx_lock(m1); // note: entering critical section here
sleep(10); // warn: Call to blocking function 'sleep' inside of critical section
mtx_unlock(m1);
sleep(10); // warn: Call to blocking function 'sleep' inside of critical section
// still inside of the critical section of the std::lock_guard
}
**Limitations**
* The ``trylock`` and ``timedlock`` versions of acquiring locks are currently assumed to always succeed.
This can lead to false positives.
.. code-block:: c
void trylock_example(pthread_mutex_t *m) {
if (pthread_mutex_trylock(m) == 0) { // assume trylock always succeeds
sleep(10); // warn: Call to blocking function 'sleep' inside of critical section
pthread_mutex_unlock(m);
} else {
sleep(10); // false positive: Incorrect warning about blocking function inside critical section.
}
}
.. _unix-Chroot:
unix.Chroot (C)
"""""""""""""""
Check improper use of chroot described by SEI Cert C recommendation `POS05-C.
Limit access to files by creating a jail
<https://wiki.sei.cmu.edu/confluence/display/c/POS05-C.+Limit+access+to+files+by+creating+a+jail>`_.
The checker finds usage patterns where ``chdir("/")`` is not called immediately
after a call to ``chroot(path)``.
.. code-block:: c
void f();
void test_bad() {
chroot("/usr/local");
f(); // warn: no call of chdir("/") immediately after chroot
}
void test_bad_path() {
chroot("/usr/local");
chdir("/usr"); // warn: no call of chdir("/") immediately after chroot
f();
}
void test_good() {
chroot("/usr/local");
chdir("/"); // no warning
f();
}
.. _unix-Errno:
unix.Errno (C)
""""""""""""""
Check for improper use of ``errno``.
This checker implements partially CERT rule
`ERR30-C. Set errno to zero before calling a library function known to set errno,
and check errno only after the function returns a value indicating failure
<https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152351>`_.
The checker can find the first read of ``errno`` after successful standard
function calls.
The C and POSIX standards often do not define if a standard library function
may change value of ``errno`` if the call does not fail.
Therefore, ``errno`` should only be used if it is known from the return value
of a function that the call has failed.
There are exceptions to this rule (for example ``strtol``) but the affected
functions are not yet supported by the checker.
The return values for the failure cases are documented in the standard Linux man
pages of the functions and in the `POSIX standard <https://pubs.opengroup.org/onlinepubs/9699919799/>`_.
.. code-block:: c
int unsafe_errno_read(int sock, void *data, int data_size) {
if (send(sock, data, data_size, 0) != data_size) {
// 'send' can be successful even if not all data was sent
if (errno == 1) { // An undefined value may be read from 'errno'
return 0;
}
}
return 1;
}
The checker :ref:`unix-StdCLibraryFunctions` must be turned on to get the
warnings from this checker. The supported functions are the same as by
:ref:`unix-StdCLibraryFunctions`. The ``ModelPOSIX`` option of that
checker affects the set of checked functions.
**Parameters**
The ``AllowErrnoReadOutsideConditionExpressions`` option allows read of the
errno value if the value is not used in a condition (in ``if`` statements,
loops, conditional expressions, ``switch`` statements). For example ``errno``
can be stored into a variable without getting a warning by the checker.
.. code-block:: c
int unsafe_errno_read(int sock, void *data, int data_size) {
if (send(sock, data, data_size, 0) != data_size) {
int err = errno;
// warning if 'AllowErrnoReadOutsideConditionExpressions' is false
// no warning if 'AllowErrnoReadOutsideConditionExpressions' is true
}
return 1;
}
Default value of this option is ``true``. This allows save of the errno value
for possible later error handling.
**Limitations**
- Only the very first usage of ``errno`` is checked after an affected function
call. Value of ``errno`` is not followed when it is stored into a variable
or returned from a function.
- Documentation of function ``lseek`` is not clear about what happens if the
function returns different value than the expected file position but not -1.
To avoid possible false-positives ``errno`` is allowed to be used in this
case.
.. _unix-Malloc:
unix.Malloc (C)
"""""""""""""""
Check for memory leaks, double free, and use-after-free problems. Traces memory managed by malloc()/free().
Custom allocation/deallocation functions can be defined using
:ref:`ownership attributes<analyzer-ownership-attrs>`.
.. literalinclude:: checkers/unix_malloc_example.c
:language: c
.. _unix-MallocSizeof:
unix.MallocSizeof (C)
"""""""""""""""""""""
Check for dubious ``malloc`` arguments involving ``sizeof``.
Custom allocation/deallocation functions can be defined using
:ref:`ownership attributes<analyzer-ownership-attrs>`.
.. code-block:: c
void test() {
long *p = malloc(sizeof(short));
// warn: result is converted to 'long *', which is
// incompatible with operand type 'short'
free(p);
}
.. _unix-MismatchedDeallocator:
unix.MismatchedDeallocator (C, C++)
"""""""""""""""""""""""""""""""""""
Check for mismatched deallocators.
Custom allocation/deallocation functions can be defined using
:ref:`ownership attributes<analyzer-ownership-attrs>`.
.. literalinclude:: checkers/mismatched_deallocator_example.cpp
:language: c
.. _unix-Vfork:
unix.Vfork (C)
""""""""""""""
Check for proper usage of ``vfork``.
.. code-block:: c
int test(int x) {
pid_t pid = vfork(); // warn
if (pid != 0)
return 0;
switch (x) {
case 0:
pid = 1;
execl("", "", 0);
_exit(1);
break;
case 1:
x = 0; // warn: this assignment is prohibited
break;
case 2:
foo(); // warn: this function call is prohibited
break;
default:
return 0; // warn: return is prohibited
}
while(1);
}
.. _unix-cstring-BadSizeArg:
unix.cstring.BadSizeArg (C)
"""""""""""""""""""""""""""
Check the size argument passed into C string functions for common erroneous patterns. Use ``-Wno-strncat-size`` compiler option to mute other ``strncat``-related compiler warnings.
.. code-block:: c
void test() {
char dest[3];
strncat(dest, """""""""""""""""""""""""*", sizeof(dest));
// warn: potential buffer overflow
}
.. _unix-cstring-NotNullTerminated:
unix.cstring.NotNullTerminated (C)
""""""""""""""""""""""""""""""""""
Check for arguments which are not null-terminated strings;
applies to the ``strlen``, ``strcpy``, ``strcat``, ``strcmp`` family of functions.
Only very fundamental cases are detected where the passed memory block is
absolutely different from a null-terminated string. This checker does not
find if a memory buffer is passed where the terminating zero character
is missing.
.. code-block:: c
void test1() {
int l = strlen((char *)&test1); // warn
}
void test2() {
label:
int l = strlen((char *)&&label); // warn
}
.. _unix-cstring-NullArg:
unix.cstring.NullArg (C)
""""""""""""""""""""""""
Check for null pointers being passed as arguments to C string functions:
``strlen, strnlen, strcpy, strncpy, strcat, strncat, strcmp, strncmp, strcasecmp, strncasecmp, wcslen, wcsnlen``.
.. code-block:: c
int test() {
return strlen(0); // warn
}
.. _unix-StdCLibraryFunctions:
unix.StdCLibraryFunctions (C)
"""""""""""""""""""""""""""""
Check for calls of standard library functions that violate predefined argument
constraints. For example, according to the C standard the behavior of function
``int isalnum(int ch)`` is undefined if the value of ``ch`` is not representable
as ``unsigned char`` and is not equal to ``EOF``.
You can think of this checker as defining restrictions (pre- and postconditions)
on standard library functions. Preconditions are checked, and when they are
violated, a warning is emitted. Postconditions are added to the analysis, e.g.
that the return value of a function is not greater than 255. Preconditions are
added to the analysis too, in the case when the affected values are not known
before the call.
For example, if an argument to a function must be in between 0 and 255, but the
value of the argument is unknown, the analyzer will assume that it is in this
interval. Similarly, if a function mustn't be called with a null pointer and the
analyzer cannot prove that it is null, then it will assume that it is non-null.
These are the possible checks on the values passed as function arguments:
- The argument has an allowed range (or multiple ranges) of values. The checker
can detect if a passed value is outside of the allowed range and show the
actual and allowed values.
- The argument has pointer type and is not allowed to be null pointer. Many
(but not all) standard functions can produce undefined behavior if a null
pointer is passed, these cases can be detected by the checker.
- The argument is a pointer to a memory block and the minimal size of this
buffer is determined by another argument to the function, or by
multiplication of two arguments (like at function ``fread``), or is a fixed
value (for example ``asctime_r`` requires at least a buffer of size 26). The
checker can detect if the buffer size is too small and in optimal case show
the size of the buffer and the values of the corresponding arguments.
.. code-block:: c
#define EOF -1
void test_alnum_concrete(int v) {
int ret = isalnum(256); // \
// warning: Function argument outside of allowed range
(void)ret;
}
void buffer_size_violation(FILE *file) {
enum { BUFFER_SIZE = 1024 };
wchar_t wbuf[BUFFER_SIZE];
const size_t size = sizeof(*wbuf); // 4
const size_t nitems = sizeof(wbuf); // 4096
// Below we receive a warning because the 3rd parameter should be the
// number of elements to read, not the size in bytes. This case is a known
// vulnerability described by the ARR38-C SEI-CERT rule.
fread(wbuf, size, nitems, file);
}
int test_alnum_symbolic(int x) {
int ret = isalnum(x);
// after the call, ret is assumed to be in the range [-1, 255]
if (ret > 255) // impossible (infeasible branch)
if (x == 0)
return ret / x; // division by zero is not reported
return ret;
}
Additionally to the argument and return value conditions, this checker also adds
state of the value ``errno`` if applicable to the analysis. Many system
functions set the ``errno`` value only if an error occurs (together with a
specific return value of the function), otherwise it becomes undefined. This
checker changes the analysis state to contain such information. This data is
used by other checkers, for example :ref:`unix-Errno`.
**Limitations**
The checker can not always provide notes about the values of the arguments.
Without this information it is hard to confirm if the constraint is indeed
violated. The argument values are shown if they are known constants or the value
is determined by previous (not too complicated) assumptions.
The checker can produce false positives in cases such as if the program has
invariants not known to the analyzer engine or the bug report path contains
calls to unknown functions. In these cases the analyzer fails to detect the real
range of the argument.
**Parameters**
The ``ModelPOSIX`` option controls if functions from the POSIX standard are
recognized by the checker.
With ``ModelPOSIX=true``, many POSIX functions are modeled according to the
`POSIX standard`_. This includes ranges of parameters and possible return
values. Furthermore the behavior related to ``errno`` in the POSIX case is
often that ``errno`` is set only if a function call fails, and it becomes
undefined after a successful function call.
With ``ModelPOSIX=false``, this checker follows the C99 language standard and
only models the functions that are described there. It is possible that the
same functions are modeled differently in the two cases because differences in
the standards. The C standard specifies less aspects of the functions, for
example exact ``errno`` behavior is often unspecified (and not modeled by the
checker).
Default value of the option is ``true``.
.. _unix-Stream:
unix.Stream (C)
"""""""""""""""
Check C stream handling functions:
``fopen, fdopen, freopen, tmpfile, fclose, fread, fwrite, fgetc, fgets, fputc, fputs, fprintf, fscanf, ungetc, getdelim, getline, fseek, fseeko, ftell, ftello, fflush, rewind, fgetpos, fsetpos, clearerr, feof, ferror, fileno``.
The checker maintains information about the C stream objects (``FILE *``) and
can detect error conditions related to use of streams. The following conditions
are detected:
* The ``FILE *`` pointer passed to the function is NULL (the single exception is
``fflush`` where NULL is allowed).
* Use of stream after close.
* Opened stream is not closed.
* Read from a stream after end-of-file. (This is not a fatal error but reported
by the checker. Stream remains in EOF state and the read operation fails.)
* Use of stream when the file position is indeterminate after a previous failed
operation. Some functions (like ``ferror``, ``clearerr``, ``fseek``) are
allowed in this state.
* Invalid 3rd ("``whence``") argument to ``fseek``.
The stream operations are by this checker usually split into two cases, a success
and a failure case.
On the success case it also assumes that the current value of ``stdout``,
``stderr``, or ``stdin`` can't be equal to the file pointer returned by ``fopen``.
Operations performed on ``stdout``, ``stderr``, or ``stdin`` are not checked by
this checker in contrast to the streams opened by ``fopen``.
In the case of write operations (like ``fwrite``,
``fprintf`` and even ``fsetpos``) this behavior could produce a large amount of
unwanted reports on projects that don't have error checks around the write
operations, so by default the checker assumes that write operations always succeed.
This behavior can be controlled by the ``Pedantic`` flag: With
``-analyzer-config unix.Stream:Pedantic=true`` the checker will model the
cases where a write operation fails and report situations where this leads to
erroneous behavior. (The default is ``Pedantic=false``, where write operations
are assumed to succeed.)
.. code-block:: c
void test1() {
FILE *p = fopen("foo", "r");
} // warn: opened file is never closed
void test2() {
FILE *p = fopen("foo", "r");
fseek(p, 1, SEEK_SET); // warn: stream pointer might be NULL
fclose(p);
}
void test3() {
FILE *p = fopen("foo", "r");
if (p) {
fseek(p, 1, 3); // warn: third arg should be SEEK_SET, SEEK_END, or SEEK_CUR
fclose(p);
}
}
void test4() {
FILE *p = fopen("foo", "r");
if (!p)
return;
fclose(p);
fclose(p); // warn: stream already closed
}
void test5() {
FILE *p = fopen("foo", "r");
if (!p)
return;
fgetc(p);
if (!ferror(p))
fgetc(p); // warn: possible read after end-of-file
fclose(p);
}
void test6() {
FILE *p = fopen("foo", "r");
if (!p)
return;
fgetc(p);
if (!feof(p))
fgetc(p); // warn: file position may be indeterminate after I/O error
fclose(p);
}
**Limitations**
The checker does not track the correspondence between integer file descriptors
and ``FILE *`` pointers.
.. _osx-checkers:
osx
^^^
macOS checkers.
.. _osx-API:
osx.API (C)
"""""""""""
Check for proper uses of various Apple APIs.
.. code-block:: objc
void test() {
dispatch_once_t pred = 0;
dispatch_once(&pred, ^(){}); // warn: dispatch_once uses local
}
.. _osx-NumberObjectConversion:
osx.NumberObjectConversion (C, C++, ObjC)
"""""""""""""""""""""""""""""""""""""""""
Check for erroneous conversions of objects representing numbers into numbers.
.. code-block:: objc
NSNumber *photoCount = [albumDescriptor objectForKey:@"PhotoCount"];
// Warning: Comparing a pointer value of type 'NSNumber *'
// to a scalar integer value
if (photoCount > 0) {
[self displayPhotos];
}
.. _osx-ObjCProperty:
osx.ObjCProperty (ObjC)
"""""""""""""""""""""""
Check for proper uses of Objective-C properties.
.. code-block:: objc
NSNumber *photoCount = [albumDescriptor objectForKey:@"PhotoCount"];
// Warning: Comparing a pointer value of type 'NSNumber *'
// to a scalar integer value
if (photoCount > 0) {
[self displayPhotos];
}
.. _osx-SecKeychainAPI:
osx.SecKeychainAPI (C)
""""""""""""""""""""""
Check for proper uses of Secure Keychain APIs.
.. literalinclude:: checkers/seckeychainapi_example.m
:language: objc
.. _osx-cocoa-AtSync:
osx.cocoa.AtSync (ObjC)
"""""""""""""""""""""""
Check for nil pointers used as mutexes for @synchronized.
.. code-block:: objc
void test(id x) {
if (!x)
@synchronized(x) {} // warn: nil value used as mutex
}
void test() {
id y;
@synchronized(y) {} // warn: uninitialized value used as mutex
}
.. _osx-cocoa-AutoreleaseWrite:
osx.cocoa.AutoreleaseWrite
""""""""""""""""""""""""""
Warn about potentially crashing writes to autoreleasing objects from different autoreleasing pools in Objective-C.
.. _osx-cocoa-ClassRelease:
osx.cocoa.ClassRelease (ObjC)
"""""""""""""""""""""""""""""
Check for sending 'retain', 'release', or 'autorelease' directly to a Class.
.. code-block:: objc
@interface MyClass : NSObject
@end
void test(void) {
[MyClass release]; // warn
}
.. _osx-cocoa-Dealloc:
osx.cocoa.Dealloc (ObjC)
""""""""""""""""""""""""
Warn about Objective-C classes that lack a correct implementation of -dealloc
.. literalinclude:: checkers/dealloc_example.m
:language: objc
.. _osx-cocoa-IncompatibleMethodTypes:
osx.cocoa.IncompatibleMethodTypes (ObjC)
""""""""""""""""""""""""""""""""""""""""
Warn about Objective-C method signatures with type incompatibilities.
.. code-block:: objc
@interface MyClass1 : NSObject
- (int)foo;
@end
@implementation MyClass1
- (int)foo { return 1; }
@end
@interface MyClass2 : MyClass1
- (float)foo;
@end
@implementation MyClass2
- (float)foo { return 1.0; } // warn
@end
.. _osx-cocoa-Loops:
osx.cocoa.Loops
"""""""""""""""
Improved modeling of loops using Cocoa collection types.
.. _osx-cocoa-MissingSuperCall:
osx.cocoa.MissingSuperCall (ObjC)
"""""""""""""""""""""""""""""""""
Warn about Objective-C methods that lack a necessary call to super.
.. code-block:: objc
@interface Test : UIViewController
@end
@implementation test
- (void)viewDidLoad {} // warn
@end
.. _osx-cocoa-NSAutoreleasePool:
osx.cocoa.NSAutoreleasePool (ObjC)
""""""""""""""""""""""""""""""""""
Warn for suboptimal uses of NSAutoreleasePool in Objective-C GC mode.
.. code-block:: objc
void test() {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[pool release]; // warn
}
.. _osx-cocoa-NSError:
osx.cocoa.NSError (ObjC)
""""""""""""""""""""""""
Check usage of NSError parameters.
.. code-block:: objc
@interface A : NSObject
- (void)foo:(NSError """""""""""""""""""""""")error;
@end
@implementation A
- (void)foo:(NSError """""""""""""""""""""""")error {
// warn: method accepting NSError"""""""""""""""""""""""" should have a non-void
// return value
}
@end
@interface A : NSObject
- (BOOL)foo:(NSError """""""""""""""""""""""")error;
@end
@implementation A
- (BOOL)foo:(NSError """""""""""""""""""""""")error {
*error = 0; // warn: potential null dereference
return 0;
}
@end
.. _osx-cocoa-NilArg:
osx.cocoa.NilArg (ObjC)
"""""""""""""""""""""""
Check for prohibited nil arguments to ObjC method calls.
- caseInsensitiveCompare:
- compare:
- compare:options:
- compare:options:range:
- compare:options:range:locale:
- componentsSeparatedByCharactersInSet:
- initWithFormat:
.. code-block:: objc
NSComparisonResult test(NSString *s) {
NSString *aString = nil;
return [s caseInsensitiveCompare:aString];
// warn: argument to 'NSString' method
// 'caseInsensitiveCompare:' cannot be nil
}
.. _osx-cocoa-NonNilReturnValue:
osx.cocoa.NonNilReturnValue
"""""""""""""""""""""""""""
Models the APIs that are guaranteed to return a non-nil value.
.. _osx-cocoa-ObjCGenerics:
osx.cocoa.ObjCGenerics (ObjC)
"""""""""""""""""""""""""""""
Check for type errors when using Objective-C generics.
.. code-block:: objc
NSMutableArray *names = [NSMutableArray array];
NSMutableArray *birthDates = names;
// Warning: Conversion from value of type 'NSDate *'
// to incompatible type 'NSString *'
[birthDates addObject: [NSDate date]];
.. _osx-cocoa-RetainCount:
osx.cocoa.RetainCount (ObjC)
""""""""""""""""""""""""""""
Check for leaks and improper reference count management
.. code-block:: objc
void test() {
NSString *s = [[NSString alloc] init]; // warn
}
CFStringRef test(char *bytes) {
return CFStringCreateWithCStringNoCopy(
0, bytes, NSNEXTSTEPStringEncoding, 0); // warn
}
.. _osx-cocoa-RunLoopAutoreleaseLeak:
osx.cocoa.RunLoopAutoreleaseLeak
""""""""""""""""""""""""""""""""
Check for leaked memory in autorelease pools that will never be drained.
.. _osx-cocoa-SelfInit:
osx.cocoa.SelfInit (ObjC)
"""""""""""""""""""""""""
Check that 'self' is properly initialized inside an initializer method.
.. code-block:: objc
@interface MyObj : NSObject {
id x;
}
- (id)init;
@end
@implementation MyObj
- (id)init {
[super init];
x = 0; // warn: instance variable used while 'self' is not
// initialized
return 0;
}
@end
@interface MyObj : NSObject
- (id)init;
@end
@implementation MyObj
- (id)init {
[super init];
return self; // warn: returning uninitialized 'self'
}
@end
.. _osx-cocoa-SuperDealloc:
osx.cocoa.SuperDealloc (ObjC)
"""""""""""""""""""""""""""""
Warn about improper use of '[super dealloc]' in Objective-C.
.. code-block:: objc
@interface SuperDeallocThenReleaseIvarClass : NSObject {
NSObject *_ivar;
}
@end
@implementation SuperDeallocThenReleaseIvarClass
- (void)dealloc {
[super dealloc];
[_ivar release]; // warn
}
@end
.. _osx-cocoa-UnusedIvars:
osx.cocoa.UnusedIvars (ObjC)
""""""""""""""""""""""""""""
Warn about private ivars that are never used.
.. code-block:: objc
@interface MyObj : NSObject {
@private
id x; // warn
}
@end
@implementation MyObj
@end
.. _osx-cocoa-VariadicMethodTypes:
osx.cocoa.VariadicMethodTypes (ObjC)
""""""""""""""""""""""""""""""""""""
Check for passing non-Objective-C types to variadic collection
initialization methods that expect only Objective-C types.
.. code-block:: objc
void test() {
[NSSet setWithObjects:@"Foo", "Bar", nil];
// warn: argument should be an ObjC pointer type, not 'char *'
}
.. _osx-coreFoundation-CFError:
osx.coreFoundation.CFError (C)
""""""""""""""""""""""""""""""
Check usage of CFErrorRef* parameters
.. code-block:: c
void test(CFErrorRef *error) {
// warn: function accepting CFErrorRef* should have a
// non-void return
}
int foo(CFErrorRef *error) {
*error = 0; // warn: potential null dereference
return 0;
}
.. _osx-coreFoundation-CFNumber:
osx.coreFoundation.CFNumber (C)
"""""""""""""""""""""""""""""""
Check for proper uses of CFNumber APIs.
.. code-block:: c
CFNumberRef test(unsigned char x) {
return CFNumberCreate(0, kCFNumberSInt16Type, &x);
// warn: 8-bit integer is used to initialize a 16-bit integer
}
.. _osx-coreFoundation-CFRetainRelease:
osx.coreFoundation.CFRetainRelease (C)
""""""""""""""""""""""""""""""""""""""
Check for null arguments to CFRetain/CFRelease/CFMakeCollectable.
.. code-block:: c
void test(CFTypeRef p) {
if (!p)
CFRetain(p); // warn
}
void test(int x, CFTypeRef p) {
if (p)
return;
CFRelease(p); // warn
}
.. _osx-coreFoundation-containers-OutOfBounds:
osx.coreFoundation.containers.OutOfBounds (C)
"""""""""""""""""""""""""""""""""""""""""""""
Checks for index out-of-bounds when using 'CFArray' API.
.. code-block:: c
void test() {
CFArrayRef A = CFArrayCreate(0, 0, 0, &kCFTypeArrayCallBacks);
CFArrayGetValueAtIndex(A, 0); // warn
}
.. _osx-coreFoundation-containers-PointerSizedValues:
osx.coreFoundation.containers.PointerSizedValues (C)
""""""""""""""""""""""""""""""""""""""""""""""""""""
Warns if 'CFArray', 'CFDictionary', 'CFSet' are created with non-pointer-size values.
.. code-block:: c
void test() {
int x[] = { 1 };
CFArrayRef A = CFArrayCreate(0, (const void """""""""""""""""""""""")x, 1,
&kCFTypeArrayCallBacks); // warn
}
Fuchsia
^^^^^^^
Fuchsia is an open source capability-based operating system currently being
developed by Google. This section describes checkers that can find various
misuses of Fuchsia APIs.
.. _fuchsia-HandleChecker:
fuchsia.HandleChecker
""""""""""""""""""""""""""""
Handles identify resources. Similar to pointers they can be leaked,
double freed, or use after freed. This check attempts to find such problems.
.. code-block:: cpp
void checkLeak08(int tag) {
zx_handle_t sa, sb;
zx_channel_create(0, &sa, &sb);
if (tag)
zx_handle_close(sa);
use(sb); // Warn: Potential leak of handle
zx_handle_close(sb);
}
WebKit
^^^^^^
WebKit is an open-source web browser engine available for macOS, iOS and Linux.
This section describes checkers that can find issues in WebKit codebase.
Most of the checkers focus on memory management for which WebKit uses custom implementation of reference counted smartpointers.
Checkers are formulated in terms related to ref-counting:
- *Ref-counted type* is either ``Ref<T>`` or ``RefPtr<T>``.
- *Ref-countable type* is any type that implements ``ref()`` and ``deref()`` methods as ``RefPtr<>`` is a template (i. e. relies on duck typing).
- *Uncounted type* is ref-countable but not ref-counted type.
.. _webkit-RefCntblBaseVirtualDtor:
webkit.RefCntblBaseVirtualDtor
""""""""""""""""""""""""""""""""""""
All uncounted types used as base classes must have a virtual destructor.
Ref-counted types hold their ref-countable data by a raw pointer and allow implicit upcasting from ref-counted pointer to derived type to ref-counted pointer to base type. This might lead to an object of (dynamic) derived type being deleted via pointer to the base class type which C++ standard defines as UB in case the base class doesn't have virtual destructor ``[expr.delete]``.
.. code-block:: cpp
struct RefCntblBase {
void ref() {}
void deref() {}
};
struct Derived : RefCntblBase { }; // warn
.. _webkit-NoUncountedMemberChecker:
webkit.NoUncountedMemberChecker
"""""""""""""""""""""""""""""""""""""
Raw pointers and references to uncounted types can't be used as class members. Only ref-counted types are allowed.
.. code-block:: cpp
struct RefCntbl {
void ref() {}
void deref() {}
};
struct Foo {
RefCntbl * ptr; // warn
RefCntbl & ptr; // warn
// ...
};
.. _webkit-UncountedLambdaCapturesChecker:
webkit.UncountedLambdaCapturesChecker
"""""""""""""""""""""""""""""""""""""
Raw pointers and references to uncounted types can't be captured in lambdas. Only ref-counted types are allowed.
.. code-block:: cpp
struct RefCntbl {
void ref() {}
void deref() {}
};
void foo(RefCntbl* a, RefCntbl& b) {
[&, a](){ // warn about 'a'
do_something(b); // warn about 'b'
};
};
.. _alpha-checkers:
Experimental Checkers
---------------------
*These are checkers with known issues or limitations that keep them from being on by default. They are likely to have false positives. Bug reports and especially patches are welcome.*
alpha.clone
^^^^^^^^^^^
.. _alpha-clone-CloneChecker:
alpha.clone.CloneChecker (C, C++, ObjC)
"""""""""""""""""""""""""""""""""""""""
Reports similar pieces of code.
.. code-block:: c
void log();
int max(int a, int b) { // warn
log();
if (a > b)
return a;
return b;
}
int maxClone(int x, int y) { // similar code here
log();
if (x > y)
return x;
return y;
}
alpha.core
^^^^^^^^^^
.. _alpha-core-BoolAssignment:
alpha.core.BoolAssignment (ObjC)
""""""""""""""""""""""""""""""""
Warn about assigning non-{0,1} values to boolean variables.
.. code-block:: objc
void test() {
BOOL b = -1; // warn
}
.. _alpha-core-C11Lock:
alpha.core.C11Lock
""""""""""""""""""
Similarly to :ref:`alpha.unix.PthreadLock <alpha-unix-PthreadLock>`, checks for
the locking/unlocking of ``mtx_t`` mutexes.
.. code-block:: cpp
mtx_t mtx1;
void bad1(void)
{
mtx_lock(&mtx1);
mtx_lock(&mtx1); // warn: This lock has already been acquired
}
.. _alpha-core-CastSize:
alpha.core.CastSize (C)
"""""""""""""""""""""""
Check when casting a malloc'ed type ``T``, whether the size is a multiple of the size of ``T``.
.. code-block:: c
void test() {
int *x = (int *) malloc(11); // warn
}
.. _alpha-core-CastToStruct:
alpha.core.CastToStruct (C, C++)
""""""""""""""""""""""""""""""""
Check for cast from non-struct pointer to struct pointer.
.. code-block:: cpp
// C
struct s {};
void test(int *p) {
struct s *ps = (struct s *) p; // warn
}
// C++
class c {};
void test(int *p) {
c *pc = (c *) p; // warn
}
.. _alpha-core-Conversion:
alpha.core.Conversion (C, C++, ObjC)
""""""""""""""""""""""""""""""""""""
Loss of sign/precision in implicit conversions.
.. code-block:: c
void test(unsigned U, signed S) {
if (S > 10) {
if (U < S) {
}
}
if (S < -10) {
if (U < S) { // warn (loss of sign)
}
}
}
void test() {
long long A = 1LL << 60;
short X = A; // warn (loss of precision)
}
.. _alpha-core-DynamicTypeChecker:
alpha.core.DynamicTypeChecker (ObjC)
""""""""""""""""""""""""""""""""""""
Check for cases where the dynamic and the static type of an object are unrelated.
.. code-block:: objc
id date = [NSDate date];
// Warning: Object has a dynamic type 'NSDate *' which is
// incompatible with static type 'NSNumber *'"
NSNumber *number = date;
[number doubleValue];
.. _alpha-core-FixedAddr:
alpha.core.FixedAddr (C)
""""""""""""""""""""""""
Check for assignment of a fixed address to a pointer.
.. code-block:: c
void test() {
int *p;
p = (int *) 0x10000; // warn
}
.. _alpha-core-PointerArithm:
alpha.core.PointerArithm (C)
""""""""""""""""""""""""""""
Check for pointer arithmetic on locations other than array elements.
.. code-block:: c
void test() {
int x;
int *p;
p = &x + 1; // warn
}
.. _alpha-core-StackAddressAsyncEscape:
alpha.core.StackAddressAsyncEscape (ObjC)
"""""""""""""""""""""""""""""""""""""""""
Check that addresses to stack memory do not escape the function that involves dispatch_after or dispatch_async.
This checker is a part of ``core.StackAddressEscape``, but is temporarily disabled until some false positives are fixed.
.. code-block:: c
dispatch_block_t test_block_inside_block_async_leak() {
int x = 123;
void (^inner)(void) = ^void(void) {
int y = x;
++y;
};
void (^outer)(void) = ^void(void) {
int z = x;
++z;
inner();
};
return outer; // warn: address of stack-allocated block is captured by a
// returned block
}
.. _alpha-core-StdVariant:
alpha.core.StdVariant (C++)
"""""""""""""""""""""""""""
Check if a value of active type is retrieved from an ``std::variant`` instance with ``std::get``.
In case of bad variant type access (the accessed type differs from the active type)
a warning is emitted. Currently, this checker does not take exception handling into account.
.. code-block:: cpp
void test() {
std::variant<int, char> v = 25;
char c = stg::get<char>(v); // warn: "int" is the active alternative
}
.. _alpha-core-TestAfterDivZero:
alpha.core.TestAfterDivZero (C)
"""""""""""""""""""""""""""""""
Check for division by variable that is later compared against 0.
Either the comparison is useless or there is division by zero.
.. code-block:: c
void test(int x) {
var = 77 / x;
if (x == 0) { } // warn
}
alpha.cplusplus
^^^^^^^^^^^^^^^
.. _alpha-cplusplus-DeleteWithNonVirtualDtor:
alpha.cplusplus.DeleteWithNonVirtualDtor (C++)
""""""""""""""""""""""""""""""""""""""""""""""
Reports destructions of polymorphic objects with a non-virtual destructor in their base class.
.. code-block:: cpp
class NonVirtual {};
class NVDerived : public NonVirtual {};
NonVirtual *create() {
NonVirtual *x = new NVDerived(); // note: Casting from 'NVDerived' to
// 'NonVirtual' here
return x;
}
void foo() {
NonVirtual *x = create();
delete x; // warn: destruction of a polymorphic object with no virtual
// destructor
}
.. _alpha-cplusplus-InvalidatedIterator:
alpha.cplusplus.InvalidatedIterator (C++)
"""""""""""""""""""""""""""""""""""""""""
Check for use of invalidated iterators.
.. code-block:: cpp
void bad_copy_assign_operator_list1(std::list &L1,
const std::list &L2) {
auto i0 = L1.cbegin();
L1 = L2;
*i0; // warn: invalidated iterator accessed
}
.. _alpha-cplusplus-IteratorRange:
alpha.cplusplus.IteratorRange (C++)
"""""""""""""""""""""""""""""""""""
Check for iterators used outside their valid ranges.
.. code-block:: cpp
void simple_bad_end(const std::vector &v) {
auto i = v.end();
*i; // warn: iterator accessed outside of its range
}
.. _alpha-cplusplus-MismatchedIterator:
alpha.cplusplus.MismatchedIterator (C++)
""""""""""""""""""""""""""""""""""""""""
Check for use of iterators of different containers where iterators of the same container are expected.
.. code-block:: cpp
void bad_insert3(std::vector &v1, std::vector &v2) {
v2.insert(v1.cbegin(), v2.cbegin(), v2.cend()); // warn: container accessed
// using foreign
// iterator argument
v1.insert(v1.cbegin(), v1.cbegin(), v2.cend()); // warn: iterators of
// different containers
// used where the same
// container is
// expected
v1.insert(v1.cbegin(), v2.cbegin(), v1.cend()); // warn: iterators of
// different containers
// used where the same
// container is
// expected
}
.. _alpha-cplusplus-SmartPtr:
alpha.cplusplus.SmartPtr (C++)
""""""""""""""""""""""""""""""
Check for dereference of null smart pointers.
.. code-block:: cpp
void deref_smart_ptr() {
std::unique_ptr<int> P;
*P; // warn: dereference of a default constructed smart unique_ptr
}
alpha.deadcode
^^^^^^^^^^^^^^
.. _alpha-deadcode-UnreachableCode:
alpha.deadcode.UnreachableCode (C, C++)
"""""""""""""""""""""""""""""""""""""""
Check unreachable code.
.. code-block:: cpp
// C
int test() {
int x = 1;
while(x);
return x; // warn
}
// C++
void test() {
int a = 2;
while (a > 1)
a--;
if (a > 1)
a++; // warn
}
// Objective-C
void test(id x) {
return;
[x retain]; // warn
}
alpha.fuchsia
^^^^^^^^^^^^^
.. _alpha-fuchsia-lock:
alpha.fuchsia.Lock
""""""""""""""""""
Similarly to :ref:`alpha.unix.PthreadLock <alpha-unix-PthreadLock>`, checks for
the locking/unlocking of fuchsia mutexes.
.. code-block:: cpp
spin_lock_t mtx1;
void bad1(void)
{
spin_lock(&mtx1);
spin_lock(&mtx1); // warn: This lock has already been acquired
}
alpha.llvm
^^^^^^^^^^
.. _alpha-llvm-Conventions:
alpha.llvm.Conventions
""""""""""""""""""""""
Check code for LLVM codebase conventions:
* A StringRef should not be bound to a temporary std::string whose lifetime is shorter than the StringRef's.
* Clang AST nodes should not have fields that can allocate memory.
alpha.osx
^^^^^^^^^
.. _alpha-osx-cocoa-DirectIvarAssignment:
alpha.osx.cocoa.DirectIvarAssignment (ObjC)
"""""""""""""""""""""""""""""""""""""""""""
Check for direct assignments to instance variables.
.. code-block:: objc
@interface MyClass : NSObject {}
@property (readonly) id A;
- (void) foo;
@end
@implementation MyClass
- (void) foo {
_A = 0; // warn
}
@end
.. _alpha-osx-cocoa-DirectIvarAssignmentForAnnotatedFunctions:
alpha.osx.cocoa.DirectIvarAssignmentForAnnotatedFunctions (ObjC)
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Check for direct assignments to instance variables in
the methods annotated with ``objc_no_direct_instance_variable_assignment``.
.. code-block:: objc
@interface MyClass : NSObject {}
@property (readonly) id A;
- (void) fAnnotated __attribute__((
annotate("objc_no_direct_instance_variable_assignment")));
- (void) fNotAnnotated;
@end
@implementation MyClass
- (void) fAnnotated {
_A = 0; // warn
}
- (void) fNotAnnotated {
_A = 0; // no warn
}
@end
.. _alpha-osx-cocoa-InstanceVariableInvalidation:
alpha.osx.cocoa.InstanceVariableInvalidation (ObjC)
"""""""""""""""""""""""""""""""""""""""""""""""""""
Check that the invalidatable instance variables are
invalidated in the methods annotated with objc_instance_variable_invalidator.
.. code-block:: objc
@protocol Invalidation <NSObject>
- (void) invalidate
__attribute__((annotate("objc_instance_variable_invalidator")));
@end
@interface InvalidationImpObj : NSObject <Invalidation>
@end
@interface SubclassInvalidationImpObj : InvalidationImpObj {
InvalidationImpObj *var;
}
- (void)invalidate;
@end
@implementation SubclassInvalidationImpObj
- (void) invalidate {}
@end
// warn: var needs to be invalidated or set to nil
.. _alpha-osx-cocoa-MissingInvalidationMethod:
alpha.osx.cocoa.MissingInvalidationMethod (ObjC)
""""""""""""""""""""""""""""""""""""""""""""""""
Check that the invalidation methods are present in classes that contain invalidatable instance variables.
.. code-block:: objc
@protocol Invalidation <NSObject>
- (void)invalidate
__attribute__((annotate("objc_instance_variable_invalidator")));
@end
@interface NeedInvalidation : NSObject <Invalidation>
@end
@interface MissingInvalidationMethodDecl : NSObject {
NeedInvalidation *Var; // warn
}
@end
@implementation MissingInvalidationMethodDecl
@end
.. _alpha-osx-cocoa-localizability-PluralMisuseChecker:
alpha.osx.cocoa.localizability.PluralMisuseChecker (ObjC)
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Warns against using one vs. many plural pattern in code when generating localized strings.
.. code-block:: objc
NSString *reminderText =
NSLocalizedString(@"None", @"Indicates no reminders");
if (reminderCount == 1) {
// Warning: Plural cases are not supported across all languages.
// Use a .stringsdict file instead
reminderText =
NSLocalizedString(@"1 Reminder", @"Indicates single reminder");
} else if (reminderCount >= 2) {
// Warning: Plural cases are not supported across all languages.
// Use a .stringsdict file instead
reminderText =
[NSString stringWithFormat:
NSLocalizedString(@"%@ Reminders", @"Indicates multiple reminders"),
reminderCount];
}
alpha.security
^^^^^^^^^^^^^^
.. _alpha-security-ReturnPtrRange:
alpha.security.ReturnPtrRange (C)
"""""""""""""""""""""""""""""""""
Check for an out-of-bound pointer being returned to callers.
.. code-block:: c
static int A[10];
int *test() {
int *p = A + 10;
return p; // warn
}
int test(void) {
int x;
return x; // warn: undefined or garbage returned
}
alpha.security.cert
^^^^^^^^^^^^^^^^^^^
SEI CERT checkers which tries to find errors based on their `C coding rules <https://wiki.sei.cmu.edu/confluence/display/c/2+Rules>`_.
alpha.unix
^^^^^^^^^^
.. _alpha-unix-PthreadLock:
alpha.unix.PthreadLock (C)
""""""""""""""""""""""""""
Simple lock -> unlock checker.
Applies to: ``pthread_mutex_lock, pthread_rwlock_rdlock, pthread_rwlock_wrlock, lck_mtx_lock, lck_rw_lock_exclusive``
``lck_rw_lock_shared, pthread_mutex_trylock, pthread_rwlock_tryrdlock, pthread_rwlock_tryrwlock, lck_mtx_try_lock,
lck_rw_try_lock_exclusive, lck_rw_try_lock_shared, pthread_mutex_unlock, pthread_rwlock_unlock, lck_mtx_unlock, lck_rw_done``.
.. code-block:: c
pthread_mutex_t mtx;
void test() {
pthread_mutex_lock(&mtx);
pthread_mutex_lock(&mtx);
// warn: this lock has already been acquired
}
lck_mtx_t lck1, lck2;
void test() {
lck_mtx_lock(&lck1);
lck_mtx_lock(&lck2);
lck_mtx_unlock(&lck1);
// warn: this was not the most recently acquired lock
}
lck_mtx_t lck1, lck2;
void test() {
if (lck_mtx_try_lock(&lck1) == 0)
return;
lck_mtx_lock(&lck2);
lck_mtx_unlock(&lck1);
// warn: this was not the most recently acquired lock
}
.. _alpha-unix-SimpleStream:
alpha.unix.SimpleStream (C)
"""""""""""""""""""""""""""
Check for misuses of stream APIs. Check for misuses of stream APIs: ``fopen, fclose``
(demo checker, the subject of the demo (`Slides <https://llvm.org/devmtg/2012-11/Zaks-Rose-Checker24Hours.pdf>`_ ,
`Video <https://youtu.be/kdxlsP5QVPw>`_) by Anna Zaks and Jordan Rose presented at the
`2012 LLVM Developers' Meeting <https://llvm.org/devmtg/2012-11/>`_).
.. code-block:: c
void test() {
FILE *F = fopen("myfile.txt", "w");
} // warn: opened file is never closed
void test() {
FILE *F = fopen("myfile.txt", "w");
if (F)
fclose(F);
fclose(F); // warn: closing a previously closed file stream
}
.. _alpha-unix-cstring-BufferOverlap:
alpha.unix.cstring.BufferOverlap (C)
""""""""""""""""""""""""""""""""""""
Checks for overlap in two buffer arguments. Applies to: ``memcpy, mempcpy, wmemcpy, wmempcpy``.
.. code-block:: c
void test() {
int a[4] = {0};
memcpy(a + 2, a + 1, 8); // warn
}
.. _alpha-unix-cstring-OutOfBounds:
alpha.unix.cstring.OutOfBounds (C)
""""""""""""""""""""""""""""""""""
Check for out-of-bounds access in string functions, such as:
``memcpy, bcopy, strcpy, strncpy, strcat, strncat, memmove, memcmp, memset`` and more.
This check also works with string literals, except there is a known bug in that
the analyzer cannot detect embedded NULL characters when determining the string length.
.. code-block:: c
void test1() {
const char str[] = "Hello world";
char buffer[] = "Hello world";
memcpy(buffer, str, sizeof(str) + 1); // warn
}
void test2() {
const char str[] = "Hello world";
char buffer[] = "Helloworld";
memcpy(buffer, str, sizeof(str)); // warn
}
.. _alpha-unix-cstring-UninitializedRead:
alpha.unix.cstring.UninitializedRead (C)
""""""""""""""""""""""""""""""""""""""""
Check for uninitialized reads from common memory copy/manipulation functions such as:
``memcpy, mempcpy, memmove, memcmp, strcmp, strncmp, strcpy, strlen, strsep`` and many more.
.. code-block:: c
void test() {
char src[10];
char dst[5];
memcpy(dst,src,sizeof(dst)); // warn: Bytes string function accesses uninitialized/garbage values
}
Limitations:
- Due to limitations of the memory modeling in the analyzer, one can likely
observe a lot of false-positive reports like this:
.. code-block:: c
void false_positive() {
int src[] = {1, 2, 3, 4};
int dst[5] = {0};
memcpy(dst, src, 4 * sizeof(int)); // false-positive:
// The 'src' buffer was correctly initialized, yet we cannot conclude
// that since the analyzer could not see a direct initialization of the
// very last byte of the source buffer.
}
More details at the corresponding `GitHub issue <https://github.com/llvm/llvm-project/issues/43459>`_.
alpha.WebKit
^^^^^^^^^^^^
alpha.webkit.ForwardDeclChecker
"""""""""""""""""""""""""""""""
Check for local variables, member variables, and function arguments that are forward declared.
.. code-block:: cpp
struct Obj;
Obj* provide();
struct Foo {
Obj* ptr; // warn
};
void foo() {
Obj* obj = provide(); // warn
consume(obj); // warn
}
.. _alpha-webkit-NoUncheckedPtrMemberChecker:
alpha.webkit.MemoryUnsafeCastChecker
""""""""""""""""""""""""""""""""""""""
Check for all casts from a base type to its derived type as these might be memory-unsafe.
Example:
.. code-block:: cpp
class Base { };
class Derived : public Base { };
void f(Base* base) {
Derived* derived = static_cast<Derived*>(base); // ERROR
}
For all cast operations (C-style casts, static_cast, reinterpret_cast, dynamic_cast), if the source type a `Base*` and the destination type is `Derived*`, where `Derived` inherits from `Base`, the static analyzer should signal an error.
This applies to:
- C structs, C++ structs and classes, and Objective-C classes and protocols.
- Pointers and references.
- Inside template instantiations and macro expansions that are visible to the compiler.
For types like this, instead of using built in casts, the programmer will use helper functions that internally perform the appropriate type check and disable static analysis.
alpha.webkit.NoUncheckedPtrMemberChecker
""""""""""""""""""""""""""""""""""""""""
Raw pointers and references to an object which supports CheckedPtr or CheckedRef can't be used as class members. Only CheckedPtr, CheckedRef, RefPtr, or Ref are allowed.
.. code-block:: cpp
struct CheckableObj {
void incrementCheckedPtrCount() {}
void decrementCheckedPtrCount() {}
};
struct Foo {
CheckableObj* ptr; // warn
CheckableObj& ptr; // warn
// ...
};
See `WebKit Guidelines for Safer C++ Programming <https://github.com/WebKit/WebKit/wiki/Safer-CPP-Guidelines>`_ for details.
alpha.webkit.NoUnretainedMemberChecker
""""""""""""""""""""""""""""""""""""""""
Raw pointers and references to a NS or CF object can't be used as class members or ivars. Only RetainPtr is allowed for CF types regardless of whether ARC is enabled or disabled. Only RetainPtr is allowed for NS types when ARC is disabled.
.. code-block:: cpp
struct Foo {
NSObject *ptr; // warn
// ...
};
See `WebKit Guidelines for Safer C++ Programming <https://github.com/WebKit/WebKit/wiki/Safer-CPP-Guidelines>`_ for details.
alpha.webkit.UnretainedLambdaCapturesChecker
""""""""""""""""""""""""""""""""""""""""""""
Raw pointers and references to NS or CF types can't be captured in lambdas. Only RetainPtr is allowed for CF types regardless of whether ARC is enabled or disabled, and only RetainPtr is allowed for NS types when ARC is disabled.
.. code-block:: cpp
void foo(NSObject *a, NSObject *b) {
[&, a](){ // warn about 'a'
do_something(b); // warn about 'b'
};
};
.. _alpha-webkit-UncountedCallArgsChecker:
alpha.webkit.UncountedCallArgsChecker
"""""""""""""""""""""""""""""""""""""
The goal of this rule is to make sure that lifetime of any dynamically allocated ref-countable object passed as a call argument spans past the end of the call. This applies to call to any function, method, lambda, function pointer or functor. Ref-countable types aren't supposed to be allocated on stack so we check arguments for parameters of raw pointers and references to uncounted types.
Here are some examples of situations that we warn about as they *might* be potentially unsafe. The logic is that either we're able to guarantee that an argument is safe or it's considered if not a bug then bug-prone.
.. code-block:: cpp
RefCountable* provide_uncounted();
void consume(RefCountable*);
// In these cases we can't make sure callee won't directly or indirectly call `deref()` on the argument which could make it unsafe from such point until the end of the call.
void foo1() {
consume(provide_uncounted()); // warn
}
void foo2() {
RefCountable* uncounted = provide_uncounted();
consume(uncounted); // warn
}
Although we are enforcing member variables to be ref-counted by `webkit.NoUncountedMemberChecker` any method of the same class still has unrestricted access to these. Since from a caller's perspective we can't guarantee a particular member won't get modified by callee (directly or indirectly) we don't consider values obtained from members safe.
Note: It's likely this heuristic could be made more precise with fewer false positives - for example calls to free functions that don't have any parameter other than the pointer should be safe as the callee won't be able to tamper with the member unless it's a global variable.
.. code-block:: cpp
struct Foo {
RefPtr<RefCountable> member;
void consume(RefCountable*) { /* ... */ }
void bugprone() {
consume(member.get()); // warn
}
};
The implementation of this rule is a heuristic - we define a whitelist of kinds of values that are considered safe to be passed as arguments. If we can't prove an argument is safe it's considered an error.
Allowed kinds of arguments:
- values obtained from ref-counted objects (including temporaries as those survive the call too)
.. code-block:: cpp
RefCountable* provide_uncounted();
void consume(RefCountable*);
void foo() {
RefPtr<RefCountable> rc = makeRef(provide_uncounted());
consume(rc.get()); // ok
consume(makeRef(provide_uncounted()).get()); // ok
}
- forwarding uncounted arguments from caller to callee
.. code-block:: cpp
void foo(RefCountable& a) {
bar(a); // ok
}
Caller of ``foo()`` is responsible for ``a``'s lifetime.
- ``this`` pointer
.. code-block:: cpp
void Foo::foo() {
baz(this); // ok
}
Caller of ``foo()`` is responsible for keeping the memory pointed to by ``this`` pointer safe.
- constants
.. code-block:: cpp
foo(nullptr, NULL, 0); // ok
We also define a set of safe transformations which if passed a safe value as an input provide (usually it's the return value) a safe value (or an object that provides safe values). This is also a heuristic.
- constructors of ref-counted types (including factory methods)
- getters of ref-counted types
- member overloaded operators
- casts
- unary operators like ``&`` or ``*``
alpha.webkit.UncheckedCallArgsChecker
"""""""""""""""""""""""""""""""""""""
The goal of this rule is to make sure that lifetime of any dynamically allocated CheckedPtr capable object passed as a call argument keeps its memory region past the end of the call. This applies to call to any function, method, lambda, function pointer or functor. CheckedPtr capable objects aren't supposed to be allocated on stack so we check arguments for parameters of raw pointers and references to unchecked types.
The rules of when to use and not to use CheckedPtr / CheckedRef are same as alpha.webkit.UncountedCallArgsChecker for ref-counted objects.
alpha.webkit.UnretainedCallArgsChecker
""""""""""""""""""""""""""""""""""""""
The goal of this rule is to make sure that lifetime of any dynamically allocated NS or CF objects passed as a call argument keeps its memory region past the end of the call. This applies to call to any function, method, lambda, function pointer or functor. NS or CF objects aren't supposed to be allocated on stack so we check arguments for parameters of raw pointers and references to unretained types.
The rules of when to use and not to use RetainPtr are same as alpha.webkit.UncountedCallArgsChecker for ref-counted objects.
alpha.webkit.UncountedLocalVarsChecker
""""""""""""""""""""""""""""""""""""""
The goal of this rule is to make sure that any uncounted local variable is backed by a ref-counted object with lifetime that is strictly larger than the scope of the uncounted local variable. To be on the safe side we require the scope of an uncounted variable to be embedded in the scope of ref-counted object that backs it.
These are examples of cases that we consider safe:
.. code-block:: cpp
void foo1() {
RefPtr<RefCountable> counted;
// The scope of uncounted is EMBEDDED in the scope of counted.
{
RefCountable* uncounted = counted.get(); // ok
}
}
void foo2(RefPtr<RefCountable> counted_param) {
RefCountable* uncounted = counted_param.get(); // ok
}
void FooClass::foo_method() {
RefCountable* uncounted = this; // ok
}
Here are some examples of situations that we warn about as they *might* be potentially unsafe. The logic is that either we're able to guarantee that a local variable is safe or it's considered unsafe.
.. code-block:: cpp
void foo1() {
RefCountable* uncounted = new RefCountable; // warn
}
RefCountable* global_uncounted;
void foo2() {
RefCountable* uncounted = global_uncounted; // warn
}
void foo3() {
RefPtr<RefCountable> counted;
// The scope of uncounted is not EMBEDDED in the scope of counted.
RefCountable* uncounted = counted.get(); // warn
}
alpha.webkit.UncheckedLocalVarsChecker
""""""""""""""""""""""""""""""""""""""
The goal of this rule is to make sure that any unchecked local variable is backed by a CheckedPtr or CheckedRef with lifetime that is strictly larger than the scope of the unchecked local variable. To be on the safe side we require the scope of an unchecked variable to be embedded in the scope of CheckedPtr/CheckRef object that backs it.
These are examples of cases that we consider safe:
.. code-block:: cpp
void foo1() {
CheckedPtr<RefCountable> counted;
// The scope of uncounted is EMBEDDED in the scope of counted.
{
RefCountable* uncounted = counted.get(); // ok
}
}
void foo2(CheckedPtr<RefCountable> counted_param) {
RefCountable* uncounted = counted_param.get(); // ok
}
void FooClass::foo_method() {
RefCountable* uncounted = this; // ok
}
Here are some examples of situations that we warn about as they *might* be potentially unsafe. The logic is that either we're able to guarantee that a local variable is safe or it's considered unsafe.
.. code-block:: cpp
void foo1() {
RefCountable* uncounted = new RefCountable; // warn
}
RefCountable* global_uncounted;
void foo2() {
RefCountable* uncounted = global_uncounted; // warn
}
void foo3() {
RefPtr<RefCountable> counted;
// The scope of uncounted is not EMBEDDED in the scope of counted.
RefCountable* uncounted = counted.get(); // warn
}
alpha.webkit.UnretainedLocalVarsChecker
"""""""""""""""""""""""""""""""""""""""
The goal of this rule is to make sure that any NS or CF local variable is backed by a RetainPtr with lifetime that is strictly larger than the scope of the unretained local variable. To be on the safe side we require the scope of an unretained variable to be embedded in the scope of Retainptr object that backs it.
The rules of when to use and not to use RetainPtr are same as alpha.webkit.UncountedCallArgsChecker for ref-counted objects.
These are examples of cases that we consider safe:
.. code-block:: cpp
void foo1() {
RetainPtr<NSObject> retained;
// The scope of unretained is EMBEDDED in the scope of retained.
{
NSObject* unretained = retained.get(); // ok
}
}
void foo2(RetainPtr<NSObject> retained_param) {
NSObject* unretained = retained_param.get(); // ok
}
void FooClass::foo_method() {
NSObject* unretained = this; // ok
}
Here are some examples of situations that we warn about as they *might* be potentially unsafe. The logic is that either we're able to guarantee that a local variable is safe or it's considered unsafe.
.. code-block:: cpp
void foo1() {
NSObject* unretained = [[NSObject alloc] init]; // warn
}
NSObject* global_unretained;
void foo2() {
NSObject* unretained = global_unretained; // warn
}
void foo3() {
RetainPtr<NSObject> retained;
// The scope of unretained is not EMBEDDED in the scope of retained.
NSObject* unretained = retained.get(); // warn
}
webkit.RetainPtrCtorAdoptChecker
""""""""""""""""""""""""""""""""
The goal of this rule is to make sure the constructor of RetainPtr as well as adoptNS and adoptCF are used correctly.
When creating a RetainPtr with +1 semantics, adoptNS or adoptCF should be used, and in +0 semantics, RetainPtr constructor should be used.
Warn otherwise.
These are examples of cases that we consider correct:
.. code-block:: cpp
RetainPtr ptr = adoptNS([[NSObject alloc] init]); // ok
RetainPtr ptr = CGImageGetColorSpace(image); // ok
Here are some examples of cases that we consider incorrect use of RetainPtr constructor and adoptCF
.. code-block:: cpp
RetainPtr ptr = [[NSObject alloc] init]; // warn
auto ptr = adoptCF(CGImageGetColorSpace(image)); // warn
Debug Checkers
---------------
.. _debug-checkers:
debug
^^^^^
Checkers used for debugging the analyzer.
:doc:`developer-docs/DebugChecks` page contains a detailed description.
.. _debug-AnalysisOrder:
debug.AnalysisOrder
"""""""""""""""""""
Print callbacks that are called during analysis in order.
.. _debug-ConfigDumper:
debug.ConfigDumper
""""""""""""""""""
Dump config table.
.. _debug-DumpCFG Display:
debug.DumpCFG Display
"""""""""""""""""""""
Control-Flow Graphs.
.. _debug-DumpCallGraph:
debug.DumpCallGraph
"""""""""""""""""""
Display Call Graph.
.. _debug-DumpCalls:
debug.DumpCalls
"""""""""""""""
Print calls as they are traversed by the engine.
.. _debug-DumpDominators:
debug.DumpDominators
""""""""""""""""""""
Print the dominance tree for a given CFG.
.. _debug-DumpLiveVars:
debug.DumpLiveVars
""""""""""""""""""
Print results of live variable analysis.
.. _debug-DumpTraversal:
debug.DumpTraversal
"""""""""""""""""""
Print branch conditions as they are traversed by the engine.
.. _debug-ExprInspection:
debug.ExprInspection
""""""""""""""""""""
Check the analyzer's understanding of expressions.
.. _debug-Stats:
debug.Stats
"""""""""""
Emit warnings with analyzer statistics.
.. _debug-TaintTest:
debug.TaintTest
"""""""""""""""
Mark tainted symbols as such.
.. _debug-ViewCFG:
debug.ViewCFG
"""""""""""""
View Control-Flow Graphs using GraphViz.
.. _debug-ViewCallGraph:
debug.ViewCallGraph
"""""""""""""""""""
View Call Graph using GraphViz.
.. _debug-ViewExplodedGraph:
debug.ViewExplodedGraph
"""""""""""""""""""""""
View Exploded Graphs using GraphViz.
|