aboutsummaryrefslogtreecommitdiff
path: root/gcc/analyzer/sm-fd.cc
blob: d107390bc0058e807def257c1ba5c2a3d48de0a4 (plain)
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
/* A state machine for detecting misuses of POSIX file descriptor APIs.
   Copyright (C) 2019-2023 Free Software Foundation, Inc.
   Contributed by Immad Mir <mir@sourceware.org>.

This file is part of GCC.

GCC is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.

GCC is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3.  If not see
<http://www.gnu.org/licenses/>.  */

#include "config.h"
#define INCLUDE_MEMORY
#include "system.h"
#include "coretypes.h"
#include "make-unique.h"
#include "tree.h"
#include "function.h"
#include "basic-block.h"
#include "gimple.h"
#include "options.h"
#include "diagnostic-path.h"
#include "diagnostic-metadata.h"
#include "analyzer/analyzer.h"
#include "diagnostic-event-id.h"
#include "analyzer/analyzer-logging.h"
#include "analyzer/sm.h"
#include "analyzer/pending-diagnostic.h"
#include "analyzer/function-set.h"
#include "analyzer/analyzer-selftests.h"
#include "stringpool.h"
#include "attribs.h"
#include "analyzer/call-string.h"
#include "analyzer/program-point.h"
#include "analyzer/store.h"
#include "analyzer/region-model.h"
#include "bitmap.h"
#include "analyzer/program-state.h"
#include "analyzer/supergraph.h"
#include "analyzer/analyzer-language.h"
#include "analyzer/call-details.h"
#include "analyzer/call-info.h"

#if ENABLE_ANALYZER

namespace ana {

namespace {

/* An enum for distinguishing between three different access modes.  */

enum access_mode
{
  READ_WRITE,
  READ_ONLY,
  WRITE_ONLY
};

enum access_directions
{
  DIRS_READ_WRITE,
  DIRS_READ,
  DIRS_WRITE
};

/* An enum for distinguishing between dup, dup2 and dup3.  */
enum dup
{
  DUP_1,
  DUP_2,
  DUP_3
};

/* Enum for use by -Wanalyzer-fd-phase-mismatch.  */

enum expected_phase
{
  EXPECTED_PHASE_CAN_TRANSFER, /* can "read"/"write".  */
  EXPECTED_PHASE_CAN_BIND,
  EXPECTED_PHASE_CAN_LISTEN,
  EXPECTED_PHASE_CAN_ACCEPT,
  EXPECTED_PHASE_CAN_CONNECT
};

class fd_state_machine : public state_machine
{
public:
  fd_state_machine (logger *logger);

  bool
  inherited_state_p () const final override
  {
    return false;
  }

  state_machine::state_t
  get_default_state (const svalue *sval) const final override
  {
    if (tree cst = sval->maybe_get_constant ())
      {
	if (TREE_CODE (cst) == INTEGER_CST)
	  {
	    int val = TREE_INT_CST_LOW (cst);
	    if (val >= 0)
	      return m_constant_fd;
	    else
	      return m_invalid;
	  }
      }
    return m_start;
  }

  bool on_stmt (sm_context *sm_ctxt, const supernode *node,
		const gimple *stmt) const final override;

  void on_condition (sm_context *sm_ctxt, const supernode *node,
		     const gimple *stmt, const svalue *lhs, const tree_code op,
		     const svalue *rhs) const final override;

  bool can_purge_p (state_t s) const final override;
  std::unique_ptr<pending_diagnostic> on_leak (tree var) const final override;

  bool is_unchecked_fd_p (state_t s) const;
  bool is_valid_fd_p (state_t s) const;
  bool is_socket_fd_p (state_t s) const;
  bool is_datagram_socket_fd_p (state_t s) const;
  bool is_stream_socket_fd_p (state_t s) const;
  bool is_closed_fd_p (state_t s) const;
  bool is_constant_fd_p (state_t s) const;
  bool is_readonly_fd_p (state_t s) const;
  bool is_writeonly_fd_p (state_t s) const;
  enum access_mode get_access_mode_from_flag (int flag) const;
  /* Function for one-to-one correspondence between valid
     and unchecked states.  */
  state_t valid_to_unchecked_state (state_t state) const;

  void mark_as_valid_fd (region_model *model,
			 sm_state_map *smap,
			 const svalue *fd_sval,
			 const extrinsic_state &ext_state) const;

  bool on_socket (const call_details &cd,
		  bool successful,
		  sm_context *sm_ctxt,
		  const extrinsic_state &ext_state) const;
  bool on_bind (const call_details &cd,
		bool successful,
		sm_context *sm_ctxt,
		const extrinsic_state &ext_state) const;
  bool on_listen (const call_details &cd,
		  bool successful,
		  sm_context *sm_ctxt,
		  const extrinsic_state &ext_state) const;
  bool on_accept (const call_details &cd,
		  bool successful,
		  sm_context *sm_ctxt,
		  const extrinsic_state &ext_state) const;
  bool on_connect (const call_details &cd,
		   bool successful,
		   sm_context *sm_ctxt,
		   const extrinsic_state &ext_state) const;

  /* State for a constant file descriptor (>= 0) */
  state_t m_constant_fd;

  /* States representing a file descriptor that hasn't yet been
    checked for validity after opening, for three different
    access modes.  */
  state_t m_unchecked_read_write;

  state_t m_unchecked_read_only;

  state_t m_unchecked_write_only;

  /* States for representing a file descriptor that is known to be valid (>=
    0), for three different access modes.  */
  state_t m_valid_read_write;

  state_t m_valid_read_only;

  state_t m_valid_write_only;

  /* State for a file descriptor that is known to be invalid (< 0). */
  state_t m_invalid;

  /* State for a file descriptor that has been closed.  */
  state_t m_closed;

  /* States for FDs relating to socket APIs.  */

  /* Result of successful "socket" with SOCK_DGRAM.  */
  state_t m_new_datagram_socket;
  /* Result of successful "socket" with SOCK_STREAM.  */
  state_t m_new_stream_socket;
  /* Result of successful "socket" with unknown type.  */
  state_t m_new_unknown_socket;

  /* The above after a successful call to "bind".  */
  state_t m_bound_datagram_socket;
  state_t m_bound_stream_socket;
  state_t m_bound_unknown_socket;

  /* A bound socket after a successful call to "listen" (stream or unknown).  */
  state_t m_listening_stream_socket;

  /* (i) the new FD as a result of a succesful call to "accept" on a
     listening socket (via a passive open), or
     (ii) an active socket after a successful call to "connect"
     (via an active open).  */
  state_t m_connected_stream_socket;

  /* State for a file descriptor that we do not want to track anymore . */
  state_t m_stop;

  /* Stashed constant values from the frontend.  These could be NULL.  */
  tree m_O_ACCMODE;
  tree m_O_RDONLY;
  tree m_O_WRONLY;
  tree m_SOCK_STREAM;
  tree m_SOCK_DGRAM;

private:
  void on_open (sm_context *sm_ctxt, const supernode *node, const gimple *stmt,
		const gcall *call) const;
  void on_creat (sm_context *sm_ctxt, const supernode *node, const gimple *stmt,
		const gcall *call) const;
  void on_close (sm_context *sm_ctxt, const supernode *node, const gimple *stmt,
		 const gcall *call) const;
  void on_read (sm_context *sm_ctxt, const supernode *node, const gimple *stmt,
		const gcall *call, const tree callee_fndecl) const;
  void on_write (sm_context *sm_ctxt, const supernode *node, const gimple *stmt,
		 const gcall *call, const tree callee_fndecl) const;
  void check_for_open_fd (sm_context *sm_ctxt, const supernode *node,
			  const gimple *stmt, const gcall *call,
			  const tree callee_fndecl,
			  enum access_directions access_fn) const;

  void make_valid_transitions_on_condition (sm_context *sm_ctxt,
					    const supernode *node,
					    const gimple *stmt,
					    const svalue *lhs) const;
  void make_invalid_transitions_on_condition (sm_context *sm_ctxt,
					      const supernode *node,
					      const gimple *stmt,
					      const svalue *lhs) const;
  void check_for_fd_attrs (sm_context *sm_ctxt, const supernode *node,
			   const gimple *stmt, const gcall *call,
			   const tree callee_fndecl, const char *attr_name,
			   access_directions fd_attr_access_dir) const;
  void check_for_dup (sm_context *sm_ctxt, const supernode *node,
       const gimple *stmt, const gcall *call, const tree callee_fndecl,
       enum dup kind) const;

  state_t get_state_for_socket_type (const svalue *socket_type_sval) const;

  bool check_for_socket_fd (const call_details &cd,
			    bool successful,
			    sm_context *sm_ctxt,
			    const svalue *fd_sval,
			    const supernode *node,
			    state_t old_state,
			    bool *complained = NULL) const;
  bool check_for_new_socket_fd (const call_details &cd,
				bool successful,
				sm_context *sm_ctxt,
				const svalue *fd_sval,
				const supernode *node,
				state_t old_state,
				enum expected_phase expected_phase) const;
};

/* Base diagnostic class relative to fd_state_machine.  */
class fd_diagnostic : public pending_diagnostic
{
public:
  fd_diagnostic (const fd_state_machine &sm, tree arg) : m_sm (sm), m_arg (arg)
  {
  }

  bool
  subclass_equal_p (const pending_diagnostic &base_other) const override
  {
    return same_tree_p (m_arg, ((const fd_diagnostic &)base_other).m_arg);
  }

  label_text
  describe_state_change (const evdesc::state_change &change) override
  {
    if (change.m_old_state == m_sm.get_start_state ())
      {
	if (change.m_new_state == m_sm.m_unchecked_read_write
	    || change.m_new_state == m_sm.m_valid_read_write)
	  return change.formatted_print ("opened here as read-write");

	if (change.m_new_state == m_sm.m_unchecked_read_only
	    || change.m_new_state == m_sm.m_valid_read_only)
	  return change.formatted_print ("opened here as read-only");

	if (change.m_new_state == m_sm.m_unchecked_write_only
	    || change.m_new_state == m_sm.m_valid_write_only)
	  return change.formatted_print ("opened here as write-only");

	if (change.m_new_state == m_sm.m_new_datagram_socket)
	  return change.formatted_print ("datagram socket created here");

	if (change.m_new_state == m_sm.m_new_stream_socket)
	  return change.formatted_print ("stream socket created here");

	if (change.m_new_state == m_sm.m_new_unknown_socket
	    || change.m_new_state == m_sm.m_connected_stream_socket)
	  return change.formatted_print ("socket created here");
      }

    if (change.m_new_state == m_sm.m_bound_datagram_socket)
      return change.formatted_print ("datagram socket bound here");

    if (change.m_new_state == m_sm.m_bound_stream_socket)
      return change.formatted_print ("stream socket bound here");

    if (change.m_new_state == m_sm.m_bound_unknown_socket
	|| change.m_new_state == m_sm.m_connected_stream_socket)
	  return change.formatted_print ("socket bound here");

    if (change.m_new_state == m_sm.m_listening_stream_socket)
      return change.formatted_print
	("stream socket marked as passive here via %qs", "listen");

    if (change.m_new_state == m_sm.m_closed)
      return change.formatted_print ("closed here");

    if (m_sm.is_unchecked_fd_p (change.m_old_state)
	&& m_sm.is_valid_fd_p (change.m_new_state))
      {
	if (change.m_expr)
	  return change.formatted_print (
	      "assuming %qE is a valid file descriptor (>= 0)", change.m_expr);
	else
	  return change.formatted_print ("assuming a valid file descriptor");
      }

    if (m_sm.is_unchecked_fd_p (change.m_old_state)
	&& change.m_new_state == m_sm.m_invalid)
      {
	if (change.m_expr)
	  return change.formatted_print (
	      "assuming %qE is an invalid file descriptor (< 0)",
	      change.m_expr);
	else
	  return change.formatted_print ("assuming an invalid file descriptor");
      }

    return label_text ();
  }

  diagnostic_event::meaning
  get_meaning_for_state_change (
      const evdesc::state_change &change) const final override
  {
    if (change.m_old_state == m_sm.get_start_state ()
	&& (m_sm.is_unchecked_fd_p (change.m_new_state)
	    || change.m_new_state == m_sm.m_new_datagram_socket
	    || change.m_new_state == m_sm.m_new_stream_socket
	    || change.m_new_state == m_sm.m_new_unknown_socket))
      return diagnostic_event::meaning (diagnostic_event::VERB_acquire,
			 diagnostic_event::NOUN_resource);
    if (change.m_new_state == m_sm.m_closed)
      return diagnostic_event::meaning (diagnostic_event::VERB_release,
			 diagnostic_event::NOUN_resource);
    return diagnostic_event::meaning ();
  }

protected:
  const fd_state_machine &m_sm;
  tree m_arg;
};

class fd_param_diagnostic : public fd_diagnostic
{
public:
  fd_param_diagnostic (const fd_state_machine &sm, tree arg, tree callee_fndecl,
		       const char *attr_name, int arg_idx)
      : fd_diagnostic (sm, arg), m_callee_fndecl (callee_fndecl),
	m_attr_name (attr_name), m_arg_idx (arg_idx)
  {
  }

  fd_param_diagnostic (const fd_state_machine &sm, tree arg, tree callee_fndecl)
      : fd_diagnostic (sm, arg), m_callee_fndecl (callee_fndecl),
	m_attr_name (NULL), m_arg_idx (-1)
  {
  }

  bool
  subclass_equal_p (const pending_diagnostic &base_other) const override
  {
    const fd_param_diagnostic &sub_other
	= (const fd_param_diagnostic &)base_other;
    return (same_tree_p (m_arg, sub_other.m_arg)
	    && same_tree_p (m_callee_fndecl, sub_other.m_callee_fndecl)
	    && m_arg_idx == sub_other.m_arg_idx
	    && ((m_attr_name)
		    ? (strcmp (m_attr_name, sub_other.m_attr_name) == 0)
		    : true));
  }

  void
  inform_filedescriptor_attribute (access_directions fd_dir)
  {

    if (m_attr_name)
      switch (fd_dir)
	{
	case DIRS_READ_WRITE:
	  inform (DECL_SOURCE_LOCATION (m_callee_fndecl),
		  "argument %d of %qD must be an open file descriptor, due to "
		  "%<__attribute__((%s(%d)))%>",
		  m_arg_idx + 1, m_callee_fndecl, m_attr_name, m_arg_idx + 1);
	  break;
	case DIRS_WRITE:
	  inform (DECL_SOURCE_LOCATION (m_callee_fndecl),
		  "argument %d of %qD must be a readable file descriptor, due "
		  "to %<__attribute__((%s(%d)))%>",
		  m_arg_idx + 1, m_callee_fndecl, m_attr_name, m_arg_idx + 1);
	  break;
	case DIRS_READ:
	  inform (DECL_SOURCE_LOCATION (m_callee_fndecl),
		  "argument %d of %qD must be a writable file descriptor, due "
		  "to %<__attribute__((%s(%d)))%>",
		  m_arg_idx + 1, m_callee_fndecl, m_attr_name, m_arg_idx + 1);
	  break;
	}
  }

protected:
  tree m_callee_fndecl;
  const char *m_attr_name;
  /* ARG_IDX is 0-based.  */
  int m_arg_idx;
};

class fd_leak : public fd_diagnostic
{
public:
  fd_leak (const fd_state_machine &sm, tree arg) : fd_diagnostic (sm, arg) {}

  const char *
  get_kind () const final override
  {
    return "fd_leak";
  }

  int
  get_controlling_option () const final override
  {
    return OPT_Wanalyzer_fd_leak;
  }

  bool
  emit (rich_location *rich_loc) final override
  {
    /*CWE-775: Missing Release of File Descriptor or Handle after Effective
      Lifetime
     */
    diagnostic_metadata m;
    m.add_cwe (775);
    if (m_arg)
      return warning_meta (rich_loc, m, get_controlling_option (),
			   "leak of file descriptor %qE", m_arg);
    else
      return warning_meta (rich_loc, m, get_controlling_option (),
			   "leak of file descriptor");
  }

  label_text
  describe_state_change (const evdesc::state_change &change) final override
  {
    if (m_sm.is_unchecked_fd_p (change.m_new_state))
      {
	m_open_event = change.m_event_id;
	return label_text::borrow ("opened here");
      }

    return fd_diagnostic::describe_state_change (change);
  }

  label_text
  describe_final_event (const evdesc::final_event &ev) final override
  {
    if (m_open_event.known_p ())
      {
	if (ev.m_expr)
	  return ev.formatted_print ("%qE leaks here; was opened at %@",
				     ev.m_expr, &m_open_event);
	else
	  return ev.formatted_print ("leaks here; was opened at %@",
				     &m_open_event);
      }
    else
      {
	if (ev.m_expr)
	  return ev.formatted_print ("%qE leaks here", ev.m_expr);
	else
	  return ev.formatted_print ("leaks here");
      }
  }

private:
  diagnostic_event_id_t m_open_event;
};

class fd_access_mode_mismatch : public fd_param_diagnostic
{
public:
  fd_access_mode_mismatch (const fd_state_machine &sm, tree arg,
			   enum access_directions fd_dir,
			   const tree callee_fndecl, const char *attr_name,
			   int arg_idx)
      : fd_param_diagnostic (sm, arg, callee_fndecl, attr_name, arg_idx),
	m_fd_dir (fd_dir)

  {
  }

  fd_access_mode_mismatch (const fd_state_machine &sm, tree arg,
			   enum access_directions fd_dir,
			   const tree callee_fndecl)
      : fd_param_diagnostic (sm, arg, callee_fndecl), m_fd_dir (fd_dir)
  {
  }

  const char *
  get_kind () const final override
  {
    return "fd_access_mode_mismatch";
  }

  int
  get_controlling_option () const final override
  {
    return OPT_Wanalyzer_fd_access_mode_mismatch;
  }

  bool
  emit (rich_location *rich_loc) final override
  {
    bool warned;
    switch (m_fd_dir)
      {
      case DIRS_READ:
	warned =  warning_at (rich_loc, get_controlling_option (),
			   "%qE on read-only file descriptor %qE",
			   m_callee_fndecl, m_arg);
	break;
      case DIRS_WRITE:
	warned = warning_at (rich_loc, get_controlling_option (),
			   "%qE on write-only file descriptor %qE",
			   m_callee_fndecl, m_arg);
	break;
      default:
	gcc_unreachable ();
      }
      if (warned)
	inform_filedescriptor_attribute (m_fd_dir);
      return warned;
  }

  label_text
  describe_final_event (const evdesc::final_event &ev) final override
  {
    switch (m_fd_dir)
      {
      case DIRS_READ:
	return ev.formatted_print ("%qE on read-only file descriptor %qE",
				   m_callee_fndecl, m_arg);
      case DIRS_WRITE:
	return ev.formatted_print ("%qE on write-only file descriptor %qE",
				   m_callee_fndecl, m_arg);
      default:
	gcc_unreachable ();
      }
  }

private:
  enum access_directions m_fd_dir;
};

class fd_double_close : public fd_diagnostic
{
public:
  fd_double_close (const fd_state_machine &sm, tree arg) : fd_diagnostic (sm, arg)
  {
  }

  const char *
  get_kind () const final override
  {
    return "fd_double_close";
  }

  int
  get_controlling_option () const final override
  {
    return OPT_Wanalyzer_fd_double_close;
  }
  bool
  emit (rich_location *rich_loc) final override
  {
    diagnostic_metadata m;
    // CWE-1341: Multiple Releases of Same Resource or Handle
    m.add_cwe (1341);
    return warning_meta (rich_loc, m, get_controlling_option (),
			 "double %<close%> of file descriptor %qE", m_arg);
  }

  label_text
  describe_state_change (const evdesc::state_change &change) override
  {
    if (m_sm.is_unchecked_fd_p (change.m_new_state))
      return label_text::borrow ("opened here");

    if (change.m_new_state == m_sm.m_closed)
      {
	m_first_close_event = change.m_event_id;
	return change.formatted_print ("first %qs here", "close");
      }
    return fd_diagnostic::describe_state_change (change);
  }

  label_text
  describe_final_event (const evdesc::final_event &ev) final override
  {
    if (m_first_close_event.known_p ())
      return ev.formatted_print ("second %qs here; first %qs was at %@",
				 "close", "close", &m_first_close_event);
    return ev.formatted_print ("second %qs here", "close");
  }

private:
  diagnostic_event_id_t m_first_close_event;
};

class fd_use_after_close : public fd_param_diagnostic
{
public:
  fd_use_after_close (const fd_state_machine &sm, tree arg,
		      const tree callee_fndecl, const char *attr_name,
		      int arg_idx)
      : fd_param_diagnostic (sm, arg, callee_fndecl, attr_name, arg_idx)
  {
  }

  fd_use_after_close (const fd_state_machine &sm, tree arg,
		      const tree callee_fndecl)
      : fd_param_diagnostic (sm, arg, callee_fndecl)
  {
  }

  const char *
  get_kind () const final override
  {
    return "fd_use_after_close";
  }

  int
  get_controlling_option () const final override
  {
    return OPT_Wanalyzer_fd_use_after_close;
  }

  bool
  emit (rich_location *rich_loc) final override
  {
    bool warned;
    warned = warning_at (rich_loc, get_controlling_option (),
		       "%qE on closed file descriptor %qE", m_callee_fndecl,
		       m_arg);
    if (warned)
      inform_filedescriptor_attribute (DIRS_READ_WRITE);
    return warned;
  }

  label_text
  describe_state_change (const evdesc::state_change &change) override
  {
    if (m_sm.is_unchecked_fd_p (change.m_new_state))
      return label_text::borrow ("opened here");

    if (change.m_new_state == m_sm.m_closed)
      {
	m_first_close_event = change.m_event_id;
	return change.formatted_print ("closed here");
      }

    return fd_diagnostic::describe_state_change (change);
  }

  label_text
  describe_final_event (const evdesc::final_event &ev) final override
  {
    if (m_first_close_event.known_p ())
	return ev.formatted_print (
	    "%qE on closed file descriptor %qE; %qs was at %@", m_callee_fndecl,
	    m_arg, "close", &m_first_close_event);
      else
	return ev.formatted_print ("%qE on closed file descriptor %qE",
				  m_callee_fndecl, m_arg);
  }

private:
  diagnostic_event_id_t m_first_close_event;
};

class fd_use_without_check : public fd_param_diagnostic
{
public:
  fd_use_without_check (const fd_state_machine &sm, tree arg,
			const tree callee_fndecl, const char *attr_name,
			int arg_idx)
      : fd_param_diagnostic (sm, arg, callee_fndecl, attr_name, arg_idx)
  {
  }

  fd_use_without_check (const fd_state_machine &sm, tree arg,
			const tree callee_fndecl)
      : fd_param_diagnostic (sm, arg, callee_fndecl)
  {
  }

  const char *
  get_kind () const final override
  {
    return "fd_use_without_check";
  }

  int
  get_controlling_option () const final override
  {
    return OPT_Wanalyzer_fd_use_without_check;
  }

  bool
  emit (rich_location *rich_loc) final override
  {
    bool warned;
    warned = warning_at (rich_loc, get_controlling_option (),
			"%qE on possibly invalid file descriptor %qE",
			m_callee_fndecl, m_arg);
    if (warned)
     inform_filedescriptor_attribute (DIRS_READ_WRITE);
    return warned;
  }

  label_text
  describe_state_change (const evdesc::state_change &change) override
  {
    if (m_sm.is_unchecked_fd_p (change.m_new_state))
      {
	m_first_open_event = change.m_event_id;
	return label_text::borrow ("opened here");
      }

    return fd_diagnostic::describe_state_change (change);
  }

  label_text
  describe_final_event (const evdesc::final_event &ev) final override
  {
    if (m_first_open_event.known_p ())
      return ev.formatted_print (
	  "%qE could be invalid: unchecked value from %@", m_arg,
	  &m_first_open_event);
    else
      return ev.formatted_print ("%qE could be invalid", m_arg);
  }

private:
  diagnostic_event_id_t m_first_open_event;
};

/* Concrete pending_diagnostic subclass for -Wanalyzer-fd-phase-mismatch.  */

class fd_phase_mismatch : public fd_param_diagnostic
{
public:
  fd_phase_mismatch (const fd_state_machine &sm, tree arg,
		     const tree callee_fndecl,
		     state_machine::state_t actual_state,
		     enum expected_phase expected_phase)
  : fd_param_diagnostic (sm, arg, callee_fndecl),
    m_actual_state (actual_state),
    m_expected_phase (expected_phase)
  {
    gcc_assert (m_sm.is_socket_fd_p (actual_state));
    switch (expected_phase)
      {
      case EXPECTED_PHASE_CAN_TRANSFER:
	gcc_assert (actual_state == m_sm.m_new_stream_socket
		    || actual_state == m_sm.m_bound_stream_socket
		    || actual_state == m_sm.m_listening_stream_socket);
	break;
      case EXPECTED_PHASE_CAN_BIND:
	gcc_assert (actual_state == m_sm.m_bound_datagram_socket
		    || actual_state == m_sm.m_bound_stream_socket
		    || actual_state == m_sm.m_bound_unknown_socket
		    || actual_state == m_sm.m_connected_stream_socket
		    || actual_state == m_sm.m_listening_stream_socket);
	break;
      case EXPECTED_PHASE_CAN_LISTEN:
	gcc_assert (actual_state == m_sm.m_new_stream_socket
		    || actual_state == m_sm.m_new_unknown_socket
		    || actual_state == m_sm.m_connected_stream_socket);
	break;
      case EXPECTED_PHASE_CAN_ACCEPT:
	gcc_assert (actual_state == m_sm.m_new_stream_socket
		    || actual_state == m_sm.m_new_unknown_socket
		    || actual_state == m_sm.m_bound_stream_socket
		    || actual_state == m_sm.m_bound_unknown_socket
		    || actual_state == m_sm.m_connected_stream_socket);
	break;
      case EXPECTED_PHASE_CAN_CONNECT:
	gcc_assert (actual_state == m_sm.m_bound_datagram_socket
		    || actual_state == m_sm.m_bound_stream_socket
		    || actual_state == m_sm.m_bound_unknown_socket
		    || actual_state == m_sm.m_listening_stream_socket
		    || actual_state == m_sm.m_connected_stream_socket);
	break;
      }
  }

  const char *
  get_kind () const final override
  {
    return "fd_phase_mismatch";
  }

  bool
  subclass_equal_p (const pending_diagnostic &base_other) const final override
  {
    const fd_phase_mismatch &sub_other = (const fd_phase_mismatch &)base_other;
    if (!fd_param_diagnostic ::subclass_equal_p (sub_other))
      return false;
    return (m_actual_state == sub_other.m_actual_state
	    && m_expected_phase == sub_other.m_expected_phase);
  }

  int
  get_controlling_option () const final override
  {
    return OPT_Wanalyzer_fd_phase_mismatch;
  }

  bool
  emit (rich_location *rich_loc) final override
  {
    /* CWE-666: Operation on Resource in Wrong Phase of Lifetime.  */
    diagnostic_metadata m;
    m.add_cwe (666);
    return warning_at (rich_loc, get_controlling_option (),
		       "%qE on file descriptor %qE in wrong phase",
		       m_callee_fndecl, m_arg);
  }

  label_text
  describe_final_event (const evdesc::final_event &ev) final override
  {
    switch (m_expected_phase)
      {
      case EXPECTED_PHASE_CAN_TRANSFER:
	{
	  if (m_actual_state == m_sm.m_new_stream_socket)
	    return ev.formatted_print
	      ("%qE expects a stream socket to be connected via %qs"
	       " but %qE has not yet been bound",
	       m_callee_fndecl, "accept", m_arg);
	  if (m_actual_state == m_sm.m_bound_stream_socket)
	    return ev.formatted_print
	      ("%qE expects a stream socket to be connected via %qs"
	       " but %qE is not yet listening",
	       m_callee_fndecl, "accept", m_arg);
	  if (m_actual_state == m_sm.m_listening_stream_socket)
	    return ev.formatted_print
	      ("%qE expects a stream socket to be connected via"
	       " the return value of %qs"
	       " but %qE is listening; wrong file descriptor?",
	       m_callee_fndecl, "accept", m_arg);
	}
	break;
      case EXPECTED_PHASE_CAN_BIND:
	{
	  if (m_actual_state == m_sm.m_bound_datagram_socket
	      || m_actual_state == m_sm.m_bound_stream_socket
	      || m_actual_state == m_sm.m_bound_unknown_socket)
	    return ev.formatted_print
	      ("%qE expects a new socket file descriptor"
	       " but %qE has already been bound",
	       m_callee_fndecl, m_arg);
	  if (m_actual_state == m_sm.m_connected_stream_socket)
	    return ev.formatted_print
	      ("%qE expects a new socket file descriptor"
	       " but %qE is already connected",
	       m_callee_fndecl, m_arg);
	  if (m_actual_state == m_sm.m_listening_stream_socket)
	    return ev.formatted_print
	      ("%qE expects a new socket file descriptor"
	       " but %qE is already listening",
	       m_callee_fndecl, m_arg);
	}
	break;
      case EXPECTED_PHASE_CAN_LISTEN:
	{
	  if (m_actual_state == m_sm.m_new_stream_socket
	      || m_actual_state == m_sm.m_new_unknown_socket)
	    return ev.formatted_print
	      ("%qE expects a bound stream socket file descriptor"
	       " but %qE has not yet been bound",
	       m_callee_fndecl, m_arg);
	  if (m_actual_state == m_sm.m_connected_stream_socket)
	    return ev.formatted_print
	      ("%qE expects a bound stream socket file descriptor"
	       " but %qE is connected",
	       m_callee_fndecl, m_arg);
	}
	break;
      case EXPECTED_PHASE_CAN_ACCEPT:
	{
	  if (m_actual_state == m_sm.m_new_stream_socket
	      || m_actual_state == m_sm.m_new_unknown_socket)
	    return ev.formatted_print
	      ("%qE expects a listening stream socket file descriptor"
	       " but %qE has not yet been bound",
	       m_callee_fndecl, m_arg);
	  if (m_actual_state == m_sm.m_bound_stream_socket
	      || m_actual_state == m_sm.m_bound_unknown_socket)
	    return ev.formatted_print
	      ("%qE expects a listening stream socket file descriptor"
	       " whereas %qE is bound but not yet listening",
	       m_callee_fndecl, m_arg);
	  if (m_actual_state == m_sm.m_connected_stream_socket)
	    return ev.formatted_print
	      ("%qE expects a listening stream socket file descriptor"
	       " but %qE is connected",
	       m_callee_fndecl, m_arg);
	}
	break;
      case EXPECTED_PHASE_CAN_CONNECT:
	{
	  if (m_actual_state == m_sm.m_bound_datagram_socket
	      || m_actual_state == m_sm.m_bound_stream_socket
	      || m_actual_state == m_sm.m_bound_unknown_socket)
	    return ev.formatted_print
	      ("%qE expects a new socket file descriptor but %qE is bound",
	       m_callee_fndecl, m_arg);
	  else
	    return ev.formatted_print
	      ("%qE expects a new socket file descriptor", m_callee_fndecl);
	}
	break;
      }
    gcc_unreachable ();
  }

private:
  state_machine::state_t m_actual_state;
  enum expected_phase m_expected_phase;
};

/* Enum for use by -Wanalyzer-fd-type-mismatch.  */

enum expected_type
{
 EXPECTED_TYPE_SOCKET,
 EXPECTED_TYPE_STREAM_SOCKET
};

/* Concrete pending_diagnostic subclass for -Wanalyzer-fd-type-mismatch.  */

class fd_type_mismatch : public fd_param_diagnostic
{
public:
  fd_type_mismatch (const fd_state_machine &sm, tree arg,
		    const tree callee_fndecl,
		    state_machine::state_t actual_state,
		    enum expected_type expected_type)
  : fd_param_diagnostic (sm, arg, callee_fndecl),
    m_actual_state (actual_state),
    m_expected_type (expected_type)
  {
  }

  const char *
  get_kind () const final override
  {
    return "fd_type_mismatch";
  }

  bool
  subclass_equal_p (const pending_diagnostic &base_other) const final override
  {
    const fd_type_mismatch &sub_other = (const fd_type_mismatch &)base_other;
    if (!fd_param_diagnostic ::subclass_equal_p (sub_other))
      return false;
    return (m_actual_state == sub_other.m_actual_state
	    && m_expected_type == sub_other.m_expected_type);
  }

  int
  get_controlling_option () const final override
  {
    return OPT_Wanalyzer_fd_type_mismatch;
  }

  bool
  emit (rich_location *rich_loc) final override
  {
    switch (m_expected_type)
      {
      default:
	gcc_unreachable ();
      case EXPECTED_TYPE_SOCKET:
	return warning_at (rich_loc, get_controlling_option (),
			   "%qE on non-socket file descriptor %qE",
			   m_callee_fndecl, m_arg);
      case EXPECTED_TYPE_STREAM_SOCKET:
	if (m_sm.is_datagram_socket_fd_p (m_actual_state))
	  return warning_at (rich_loc, get_controlling_option (),
			     "%qE on datagram socket file descriptor %qE",
			     m_callee_fndecl, m_arg);
	else
	  return warning_at (rich_loc, get_controlling_option (),
			     "%qE on non-stream-socket file descriptor %qE",
			     m_callee_fndecl, m_arg);
      }
  }

  label_text
  describe_final_event (const evdesc::final_event &ev) final override
  {
    switch (m_expected_type)
      {
      default:
	break;
	gcc_unreachable ();
      case EXPECTED_TYPE_SOCKET:
      case EXPECTED_TYPE_STREAM_SOCKET:
	if (!m_sm.is_socket_fd_p (m_actual_state))
	  return ev.formatted_print ("%qE expects a socket file descriptor"
				     " but %qE is not a socket",
				     m_callee_fndecl, m_arg);
      }
    gcc_assert (m_expected_type == EXPECTED_TYPE_STREAM_SOCKET);
    gcc_assert (m_sm.is_datagram_socket_fd_p (m_actual_state));
    return ev.formatted_print
      ("%qE expects a stream socket file descriptor"
       " but %qE is a datagram socket",
       m_callee_fndecl, m_arg);
  }

private:
  state_machine::state_t m_actual_state;
  enum expected_type m_expected_type;
};

fd_state_machine::fd_state_machine (logger *logger)
    : state_machine ("file-descriptor", logger),
      m_constant_fd (add_state ("fd-constant")),
      m_unchecked_read_write (add_state ("fd-unchecked-read-write")),
      m_unchecked_read_only (add_state ("fd-unchecked-read-only")),
      m_unchecked_write_only (add_state ("fd-unchecked-write-only")),
      m_valid_read_write (add_state ("fd-valid-read-write")),
      m_valid_read_only (add_state ("fd-valid-read-only")),
      m_valid_write_only (add_state ("fd-valid-write-only")),
      m_invalid (add_state ("fd-invalid")),
      m_closed (add_state ("fd-closed")),
      m_new_datagram_socket (add_state ("fd-new-datagram-socket")),
      m_new_stream_socket (add_state ("fd-new-stream-socket")),
      m_new_unknown_socket (add_state ("fd-new-unknown-socket")),
      m_bound_datagram_socket (add_state ("fd-bound-datagram-socket")),
      m_bound_stream_socket (add_state ("fd-bound-stream-socket")),
      m_bound_unknown_socket (add_state ("fd-bound-unknown-socket")),
      m_listening_stream_socket (add_state ("fd-listening-stream-socket")),
      m_connected_stream_socket (add_state ("fd-connected-stream-socket")),
      m_stop (add_state ("fd-stop")),
      m_O_ACCMODE (get_stashed_constant_by_name ("O_ACCMODE")),
      m_O_RDONLY (get_stashed_constant_by_name ("O_RDONLY")),
      m_O_WRONLY (get_stashed_constant_by_name ("O_WRONLY")),
      m_SOCK_STREAM (get_stashed_constant_by_name ("SOCK_STREAM")),
      m_SOCK_DGRAM (get_stashed_constant_by_name ("SOCK_DGRAM"))
{
}

bool
fd_state_machine::is_unchecked_fd_p (state_t s) const
{
  return (s == m_unchecked_read_write
       || s == m_unchecked_read_only
       || s == m_unchecked_write_only);
}

bool
fd_state_machine::is_valid_fd_p (state_t s) const
{
  return (s == m_valid_read_write
       || s == m_valid_read_only
       || s == m_valid_write_only);
}

bool
fd_state_machine::is_socket_fd_p (state_t s) const
{
  return (s == m_new_datagram_socket
	  || s == m_new_stream_socket
	  || s == m_new_unknown_socket
	  || s == m_bound_datagram_socket
	  || s == m_bound_stream_socket
	  || s == m_bound_unknown_socket
	  || s == m_listening_stream_socket
	  || s == m_connected_stream_socket);
}

bool
fd_state_machine::is_datagram_socket_fd_p (state_t s) const
{
  return (s == m_new_datagram_socket
	  || s == m_new_unknown_socket
	  || s == m_bound_datagram_socket
	  || s == m_bound_unknown_socket);
}

bool
fd_state_machine::is_stream_socket_fd_p (state_t s) const
{
  return (s == m_new_stream_socket
	  || s == m_new_unknown_socket
	  || s == m_bound_stream_socket
	  || s == m_bound_unknown_socket
	  || s == m_listening_stream_socket
	  || s == m_connected_stream_socket);
}

enum access_mode
fd_state_machine::get_access_mode_from_flag (int flag) const
{
  if (m_O_ACCMODE && TREE_CODE (m_O_ACCMODE) == INTEGER_CST)
    {
      const unsigned HOST_WIDE_INT mask_val = TREE_INT_CST_LOW (m_O_ACCMODE);
      const unsigned HOST_WIDE_INT masked_flag = flag & mask_val;

      if (m_O_RDONLY && TREE_CODE (m_O_RDONLY) == INTEGER_CST)
	if (masked_flag == TREE_INT_CST_LOW (m_O_RDONLY))
	  return READ_ONLY;

      if (m_O_WRONLY && TREE_CODE (m_O_WRONLY) == INTEGER_CST)
	if (masked_flag == TREE_INT_CST_LOW (m_O_WRONLY))
	  return WRITE_ONLY;
    }
  return READ_WRITE;
}

bool
fd_state_machine::is_readonly_fd_p (state_t state) const
{
  return (state == m_unchecked_read_only || state == m_valid_read_only);
}

bool
fd_state_machine::is_writeonly_fd_p (state_t state) const
{
  return (state == m_unchecked_write_only || state == m_valid_write_only);
}

bool
fd_state_machine::is_closed_fd_p (state_t state) const
{
  return (state == m_closed);
}

bool
fd_state_machine::is_constant_fd_p (state_t state) const
{
  return (state == m_constant_fd);
}

fd_state_machine::state_t
fd_state_machine::valid_to_unchecked_state (state_t state) const
{
  if (state == m_valid_read_write)
    return m_unchecked_read_write;
  else if (state == m_valid_write_only)
    return m_unchecked_write_only;
  else if (state == m_valid_read_only)
    return m_unchecked_read_only;
  else
    gcc_unreachable ();
  return NULL;
}

void
fd_state_machine::mark_as_valid_fd (region_model *model,
				    sm_state_map *smap,
				    const svalue *fd_sval,
				    const extrinsic_state &ext_state) const
{
  smap->set_state (model, fd_sval, m_valid_read_write, NULL, ext_state);
}

bool
fd_state_machine::on_stmt (sm_context *sm_ctxt, const supernode *node,
			   const gimple *stmt) const
{
  if (const gcall *call = dyn_cast<const gcall *> (stmt))
    if (tree callee_fndecl = sm_ctxt->get_fndecl_for_call (call))
      {
	if (is_named_call_p (callee_fndecl, "open", call, 2))
	  {
	    on_open (sm_ctxt, node, stmt, call);
	    return true;
	  } //  "open"

	if (is_named_call_p (callee_fndecl, "creat", call, 2))
	  {
	    on_creat (sm_ctxt, node, stmt, call);
	    return true;
	  } // "creat"

	if (is_named_call_p (callee_fndecl, "close", call, 1))
	  {
	    on_close (sm_ctxt, node, stmt, call);
	    return true;
	  } //  "close"

	if (is_named_call_p (callee_fndecl, "write", call, 3))
	  {
	    on_write (sm_ctxt, node, stmt, call, callee_fndecl);
	    return true;
	  } // "write"

	if (is_named_call_p (callee_fndecl, "read", call, 3))
	  {
	    on_read (sm_ctxt, node, stmt, call, callee_fndecl);
	    return true;
	  } // "read"

	if (is_named_call_p (callee_fndecl, "dup", call, 1))
	  {
	    check_for_dup (sm_ctxt, node, stmt, call, callee_fndecl, DUP_1);
	    return true;
	  }

	if (is_named_call_p (callee_fndecl, "dup2", call, 2))
	  {
	    check_for_dup (sm_ctxt, node, stmt, call, callee_fndecl, DUP_2);
	    return true;
	  }

	if (is_named_call_p (callee_fndecl, "dup3", call, 3))
	  {
	    check_for_dup (sm_ctxt, node, stmt, call, callee_fndecl, DUP_3);
	    return true;
	  }

	{
	  // Handle __attribute__((fd_arg))

	  check_for_fd_attrs (sm_ctxt, node, stmt, call, callee_fndecl,
			      "fd_arg", DIRS_READ_WRITE);

	  // Handle __attribute__((fd_arg_read))

	  check_for_fd_attrs (sm_ctxt, node, stmt, call, callee_fndecl,
			      "fd_arg_read", DIRS_READ);

	  // Handle __attribute__((fd_arg_write))

	  check_for_fd_attrs (sm_ctxt, node, stmt, call, callee_fndecl,
			      "fd_arg_write", DIRS_WRITE);
	}
      }

  return false;
}

void
fd_state_machine::check_for_fd_attrs (
    sm_context *sm_ctxt, const supernode *node, const gimple *stmt,
    const gcall *call, const tree callee_fndecl, const char *attr_name,
    access_directions fd_attr_access_dir) const
{

  tree attrs = TYPE_ATTRIBUTES (TREE_TYPE (callee_fndecl));
  attrs = lookup_attribute (attr_name, attrs);
  if (!attrs)
    return;

  if (!TREE_VALUE (attrs))
    return;

  auto_bitmap argmap;

  for (tree idx = TREE_VALUE (attrs); idx; idx = TREE_CHAIN (idx))
    {
      unsigned int val = TREE_INT_CST_LOW (TREE_VALUE (idx)) - 1;
      bitmap_set_bit (argmap, val);
    }
  if (bitmap_empty_p (argmap))
    return;

  for (unsigned arg_idx = 0; arg_idx < gimple_call_num_args (call); arg_idx++)
    {
      tree arg = gimple_call_arg (call, arg_idx);
      tree diag_arg = sm_ctxt->get_diagnostic_tree (arg);
      state_t state = sm_ctxt->get_state (stmt, arg);
      bool bit_set = bitmap_bit_p (argmap, arg_idx);
      if (TREE_CODE (TREE_TYPE (arg)) != INTEGER_TYPE)
	continue;
      if (bit_set) // Check if arg_idx is marked by any of the file descriptor
		   // attributes
	{

	  if (is_closed_fd_p (state))
	    {

	      sm_ctxt->warn (node, stmt, arg,
			     make_unique<fd_use_after_close>
			       (*this, diag_arg,
				callee_fndecl, attr_name,
				arg_idx));
	      continue;
	    }

	  if (!(is_valid_fd_p (state) || (state == m_stop)))
	    {
	      if (!is_constant_fd_p (state))
		{
		  sm_ctxt->warn (node, stmt, arg,
				 make_unique<fd_use_without_check>
				 (*this, diag_arg,
				  callee_fndecl, attr_name,
				  arg_idx));
		  continue;
		}
	    }

	  switch (fd_attr_access_dir)
	    {
	    case DIRS_READ_WRITE:
	      break;
	    case DIRS_READ:

	      if (is_writeonly_fd_p (state))
		{
		  sm_ctxt->warn (
		      node, stmt, arg,
		      make_unique<fd_access_mode_mismatch> (*this, diag_arg,
							    DIRS_WRITE,
							    callee_fndecl,
							    attr_name,
							    arg_idx));
		}

	      break;
	    case DIRS_WRITE:

	      if (is_readonly_fd_p (state))
		{
		  sm_ctxt->warn (
		      node, stmt, arg,
		      make_unique<fd_access_mode_mismatch> (*this, diag_arg,
							    DIRS_READ,
							    callee_fndecl,
							    attr_name,
							    arg_idx));
		}

	      break;
	    }
	}
    }
}


void
fd_state_machine::on_open (sm_context *sm_ctxt, const supernode *node,
			   const gimple *stmt, const gcall *call) const
{
  tree lhs = gimple_call_lhs (call);
  if (lhs)
    {
      tree arg = gimple_call_arg (call, 1);
      enum access_mode mode = READ_WRITE;
      if (TREE_CODE (arg) == INTEGER_CST)
	{
	  int flag = TREE_INT_CST_LOW (arg);
	  mode = get_access_mode_from_flag (flag);
	}
      switch (mode)
	{
	case READ_ONLY:
	  sm_ctxt->on_transition (node, stmt, lhs, m_start,
				  m_unchecked_read_only);
	  break;
	case WRITE_ONLY:
	  sm_ctxt->on_transition (node, stmt, lhs, m_start,
				  m_unchecked_write_only);
	  break;
	default:
	  sm_ctxt->on_transition (node, stmt, lhs, m_start,
				  m_unchecked_read_write);
	}
    }
  else
    {
      sm_ctxt->warn (node, stmt, NULL_TREE,
		     make_unique<fd_leak> (*this, NULL_TREE));
    }
}

void
fd_state_machine::on_creat (sm_context *sm_ctxt, const supernode *node,
			    const gimple *stmt, const gcall *call) const
{
  tree lhs = gimple_call_lhs (call);
  if (lhs)
    sm_ctxt->on_transition (node, stmt, lhs, m_start, m_unchecked_write_only);
  else
    sm_ctxt->warn (node, stmt, NULL_TREE,
		   make_unique<fd_leak> (*this, NULL_TREE));
}

void
fd_state_machine::check_for_dup (sm_context *sm_ctxt, const supernode *node,
				 const gimple *stmt, const gcall *call,
				 const tree callee_fndecl, enum dup kind) const
{
  tree lhs = gimple_call_lhs (call);
  tree arg_1 = gimple_call_arg (call, 0);
  state_t state_arg_1 = sm_ctxt->get_state (stmt, arg_1);
  if (state_arg_1 == m_stop)
    return;
  if (!(is_constant_fd_p (state_arg_1) || is_valid_fd_p (state_arg_1)
	|| state_arg_1 == m_start))
    {
      check_for_open_fd (sm_ctxt, node, stmt, call, callee_fndecl,
			 DIRS_READ_WRITE);
      return;
    }
  switch (kind)
    {
    case DUP_1:
      if (lhs)
	{
	  if (is_constant_fd_p (state_arg_1) || state_arg_1 == m_start)
	    sm_ctxt->set_next_state (stmt, lhs, m_unchecked_read_write);
	  else
	    sm_ctxt->set_next_state (stmt, lhs,
				     valid_to_unchecked_state (state_arg_1));
	}
      break;

    case DUP_2:
    case DUP_3:
      tree arg_2 = gimple_call_arg (call, 1);
      state_t state_arg_2 = sm_ctxt->get_state (stmt, arg_2);
      tree diag_arg_2 = sm_ctxt->get_diagnostic_tree (arg_2);
      if (state_arg_2 == m_stop)
	return;
      /* Check if -1 was passed as second argument to dup2.  */
      if (!(is_constant_fd_p (state_arg_2) || is_valid_fd_p (state_arg_2)
	    || state_arg_2 == m_start))
	{
	  sm_ctxt->warn (
	      node, stmt, arg_2,
	      make_unique<fd_use_without_check> (*this, diag_arg_2,
						 callee_fndecl));
	  return;
	}
      /* dup2 returns value of its second argument on success.But, the
      access mode of the returned file descriptor depends on the duplicated
      file descriptor i.e the first argument.  */
      if (lhs)
	{
	  if (is_constant_fd_p (state_arg_1) || state_arg_1 == m_start)
	    sm_ctxt->set_next_state (stmt, lhs, m_unchecked_read_write);
	  else
	    sm_ctxt->set_next_state (stmt, lhs,
				     valid_to_unchecked_state (state_arg_1));
	}

      break;
    }
}

void
fd_state_machine::on_close (sm_context *sm_ctxt, const supernode *node,
			    const gimple *stmt, const gcall *call) const
{
  tree arg = gimple_call_arg (call, 0);
  state_t state = sm_ctxt->get_state (stmt, arg);
  tree diag_arg = sm_ctxt->get_diagnostic_tree (arg);

  sm_ctxt->on_transition (node, stmt, arg, m_start, m_closed);
  sm_ctxt->on_transition (node, stmt, arg, m_unchecked_read_write, m_closed);
  sm_ctxt->on_transition (node, stmt, arg, m_unchecked_read_only, m_closed);
  sm_ctxt->on_transition (node, stmt, arg, m_unchecked_write_only, m_closed);
  sm_ctxt->on_transition (node, stmt, arg, m_valid_read_write, m_closed);
  sm_ctxt->on_transition (node, stmt, arg, m_valid_read_only, m_closed);
  sm_ctxt->on_transition (node, stmt, arg, m_valid_write_only, m_closed);
  sm_ctxt->on_transition (node, stmt, arg, m_constant_fd, m_closed);
  sm_ctxt->on_transition (node, stmt, arg, m_new_datagram_socket, m_closed);
  sm_ctxt->on_transition (node, stmt, arg, m_new_stream_socket, m_closed);
  sm_ctxt->on_transition (node, stmt, arg, m_new_unknown_socket, m_closed);
  sm_ctxt->on_transition (node, stmt, arg, m_bound_datagram_socket, m_closed);
  sm_ctxt->on_transition (node, stmt, arg, m_bound_stream_socket, m_closed);
  sm_ctxt->on_transition (node, stmt, arg, m_bound_unknown_socket, m_closed);
  sm_ctxt->on_transition (node, stmt, arg, m_listening_stream_socket, m_closed);
  sm_ctxt->on_transition (node, stmt, arg, m_connected_stream_socket, m_closed);

  if (is_closed_fd_p (state))
    {
      sm_ctxt->warn (node, stmt, arg,
		     make_unique<fd_double_close> (*this, diag_arg));
      sm_ctxt->set_next_state (stmt, arg, m_stop);
    }
}
void
fd_state_machine::on_read (sm_context *sm_ctxt, const supernode *node,
			   const gimple *stmt, const gcall *call,
			   const tree callee_fndecl) const
{
  check_for_open_fd (sm_ctxt, node, stmt, call, callee_fndecl, DIRS_READ);
}
void
fd_state_machine::on_write (sm_context *sm_ctxt, const supernode *node,
			    const gimple *stmt, const gcall *call,
			    const tree callee_fndecl) const
{
  check_for_open_fd (sm_ctxt, node, stmt, call, callee_fndecl, DIRS_WRITE);
}

void
fd_state_machine::check_for_open_fd (
    sm_context *sm_ctxt, const supernode *node, const gimple *stmt,
    const gcall *call, const tree callee_fndecl,
    enum access_directions callee_fndecl_dir) const
{
  tree arg = gimple_call_arg (call, 0);
  tree diag_arg = sm_ctxt->get_diagnostic_tree (arg);
  state_t state = sm_ctxt->get_state (stmt, arg);

  if (is_closed_fd_p (state))
    {
      sm_ctxt->warn (node, stmt, arg,
		     make_unique<fd_use_after_close> (*this, diag_arg,
						      callee_fndecl));
    }

  else
    {
      if (state == m_new_stream_socket
	  || state == m_bound_stream_socket
	  || state == m_listening_stream_socket)
	/* Complain about fncall on socket in wrong phase.  */
	sm_ctxt->warn
	  (node, stmt, arg,
	   make_unique<fd_phase_mismatch> (*this, diag_arg,
					   callee_fndecl,
					   state,
					   EXPECTED_PHASE_CAN_TRANSFER));
      else if (!(is_valid_fd_p (state)
		 || state == m_new_datagram_socket
		 || state == m_bound_unknown_socket
		 || state == m_connected_stream_socket
		 || state == m_start
		 || state == m_stop))
	{
	  if (!is_constant_fd_p (state))
	    sm_ctxt->warn (
		node, stmt, arg,
		make_unique<fd_use_without_check> (*this, diag_arg,
						   callee_fndecl));
	}
      switch (callee_fndecl_dir)
	{
	case DIRS_READ_WRITE:
	  break;
	case DIRS_READ:
	  if (is_writeonly_fd_p (state))
	    {
	      tree diag_arg = sm_ctxt->get_diagnostic_tree (arg);
	      sm_ctxt->warn (node, stmt, arg,
			     make_unique<fd_access_mode_mismatch> (
				 *this, diag_arg, DIRS_WRITE, callee_fndecl));
	    }

	  break;
	case DIRS_WRITE:

	  if (is_readonly_fd_p (state))
	    {
	      tree diag_arg = sm_ctxt->get_diagnostic_tree (arg);
	      sm_ctxt->warn (node, stmt, arg,
			     make_unique<fd_access_mode_mismatch> (
				 *this, diag_arg, DIRS_READ, callee_fndecl));
	    }
	  break;
	}
    }
}

static bool
add_constraint_ge_zero (region_model *model,
			const svalue *fd_sval,
			region_model_context *ctxt)
{
  const svalue *zero
    = model->get_manager ()->get_or_create_int_cst (integer_type_node, 0);
  return model->add_constraint (fd_sval, GE_EXPR, zero, ctxt);
}

/* Get the state for a new socket type based on SOCKET_TYPE_SVAL,
   a SOCK_* value.  */

state_machine::state_t
fd_state_machine::
get_state_for_socket_type (const svalue *socket_type_sval) const
{
  if (tree socket_type_cst = socket_type_sval->maybe_get_constant ())
    {
      /* Attempt to use SOCK_* constants stashed from the frontend.  */
      if (tree_int_cst_equal (socket_type_cst, m_SOCK_STREAM))
	return m_new_stream_socket;
      if (tree_int_cst_equal (socket_type_cst, m_SOCK_DGRAM))
	return m_new_datagram_socket;
    }

  /* Unrecognized constant, or a symbolic "type" value.  */
  return m_new_unknown_socket;
}

/* Update the model and fd state for an outcome of a call to "socket",
   where SUCCESSFUL indicate which of the two outcomes.
   Return true if the outcome is feasible, or false to reject it.  */

bool
fd_state_machine::on_socket (const call_details &cd,
			     bool successful,
			     sm_context *sm_ctxt,
			     const extrinsic_state &ext_state) const
{
  const gcall *stmt = cd.get_call_stmt ();
  engine *eng = ext_state.get_engine ();
  const supergraph *sg = eng->get_supergraph ();
  const supernode *node = sg->get_supernode_for_stmt (stmt);
  region_model *model = cd.get_model ();

  if (successful)
    {
      if (gimple_call_lhs (stmt))
	{
	  conjured_purge p (model, cd.get_ctxt ());
	  region_model_manager *mgr = model->get_manager ();
	  const svalue *new_fd
	    = mgr->get_or_create_conjured_svalue (integer_type_node,
						  stmt,
						  cd.get_lhs_region (),
						  p);
	  if (!add_constraint_ge_zero (model, new_fd, cd.get_ctxt ()))
	    return false;

	  const svalue *socket_type_sval = cd.get_arg_svalue (1);
	  state_machine::state_t new_state
	    = get_state_for_socket_type (socket_type_sval);
	  sm_ctxt->on_transition (node, stmt, new_fd, m_start, new_state);
	  model->set_value (cd.get_lhs_region (), new_fd, cd.get_ctxt ());
	}
      else
	sm_ctxt->warn (node, stmt, NULL_TREE,
		       make_unique<fd_leak> (*this, NULL_TREE));
    }
  else
    {
      /* Return -1; set errno.  */
      model->update_for_int_cst_return (cd, -1, true);
      model->set_errno (cd);
    }

  return true;
}

/* Check that FD_SVAL is usable by socket APIs.
   Complain if it has been closed, if it is a non-socket,
   or is invalid.
   If COMPLAINED is non-NULL and a problem is found,
   write *COMPLAINED = true.

   If SUCCESSFUL is true, attempt to add the constraint that FD_SVAL >= 0.
   Return true if this outcome is feasible.  */

bool
fd_state_machine::check_for_socket_fd (const call_details &cd,
				       bool successful,
				       sm_context *sm_ctxt,
				       const svalue *fd_sval,
				       const supernode *node,
				       state_t old_state,
				       bool *complained) const
{
  const gcall *stmt = cd.get_call_stmt ();

  if (is_closed_fd_p (old_state))
    {
      tree diag_arg = sm_ctxt->get_diagnostic_tree (fd_sval);
      sm_ctxt->warn
	(node, stmt, fd_sval,
	 make_unique<fd_use_after_close> (*this, diag_arg,
					  cd.get_fndecl_for_call ()));
      if (complained)
	*complained = true;
      if (successful)
	return false;
    }
  else if (is_unchecked_fd_p (old_state) || is_valid_fd_p (old_state))
    {
      /* Complain about non-socket.  */
      tree diag_arg = sm_ctxt->get_diagnostic_tree (fd_sval);
      sm_ctxt->warn
	(node, stmt, fd_sval,
	 make_unique<fd_type_mismatch> (*this, diag_arg,
					cd.get_fndecl_for_call (),
					old_state,
					EXPECTED_TYPE_SOCKET));
      if (complained)
	*complained = true;
      if (successful)
	return false;
    }
  else if (old_state == m_invalid)
    {
      tree diag_arg = sm_ctxt->get_diagnostic_tree (fd_sval);
      sm_ctxt->warn
	(node, stmt, fd_sval,
	 make_unique<fd_use_without_check> (*this, diag_arg,
					    cd.get_fndecl_for_call ()));
      if (complained)
	*complained = true;
      if (successful)
	return false;
    }

  if (successful)
    if (!add_constraint_ge_zero (cd.get_model (), fd_sval, cd.get_ctxt ()))
      return false;

  return true;
}

/* For use by "bind" and "connect".
   As per fd_state_machine::check_for_socket_fd above,
   but also complain if we don't have a new socket, and check that
   we can read up to the size bytes from the address.  */

bool
fd_state_machine::check_for_new_socket_fd (const call_details &cd,
					   bool successful,
					   sm_context *sm_ctxt,
					   const svalue *fd_sval,
					   const supernode *node,
					   state_t old_state,
					   enum expected_phase expected_phase)
  const
{
  bool complained = false;

  /* Check address and len.  */
  const svalue *address_sval = cd.get_arg_svalue (1);
  const svalue *len_sval = cd.get_arg_svalue (2);

  /* Check that we can read the given number of bytes from the
     address.  */
  region_model *model = cd.get_model ();
  const region *address_reg
    = model->deref_rvalue (address_sval, cd.get_arg_tree (1),
			   cd.get_ctxt ());
  const region *sized_address_reg
    = model->get_manager ()->get_sized_region (address_reg,
					       NULL_TREE,
					       len_sval);
  model->get_store_value (sized_address_reg, cd.get_ctxt ());

  if (!check_for_socket_fd (cd, successful, sm_ctxt,
			    fd_sval, node, old_state, &complained))
    return false;
  else if (!complained
	   && !(old_state == m_new_stream_socket
		|| old_state == m_new_datagram_socket
		|| old_state == m_new_unknown_socket
		|| old_state == m_start
		|| old_state == m_stop
		|| old_state == m_constant_fd))
    {
      /* Complain about "bind" or "connect" in wrong phase.  */
      tree diag_arg = sm_ctxt->get_diagnostic_tree (fd_sval);
      sm_ctxt->warn
	(node, cd.get_call_stmt (), fd_sval,
	 make_unique<fd_phase_mismatch> (*this, diag_arg,
					 cd.get_fndecl_for_call (),
					 old_state,
					 expected_phase));
      if (successful)
	return false;
    }
  else if (!successful)
    {
      /* If we were in the start state, assume we had a new socket.  */
      if (old_state == m_start)
	sm_ctxt->set_next_state (cd.get_call_stmt (), fd_sval,
				 m_new_unknown_socket);
    }

  /* Passing NULL as the address will lead to failure.  */
  if (successful)
    if (address_sval->all_zeroes_p ())
      return false;

  return true;
}

/* Update the model and fd state for an outcome of a call to "bind",
   where SUCCESSFUL indicate which of the two outcomes.
   Return true if the outcome is feasible, or false to reject it.  */

bool
fd_state_machine::on_bind (const call_details &cd,
			   bool successful,
			   sm_context *sm_ctxt,
			   const extrinsic_state &ext_state) const
{
  const gcall *stmt = cd.get_call_stmt ();
  engine *eng = ext_state.get_engine ();
  const supergraph *sg = eng->get_supergraph ();
  const supernode *node = sg->get_supernode_for_stmt (stmt);
  const svalue *fd_sval = cd.get_arg_svalue (0);
  region_model *model = cd.get_model ();
  state_t old_state = sm_ctxt->get_state (stmt, fd_sval);

  if (!check_for_new_socket_fd (cd, successful, sm_ctxt,
				fd_sval, node, old_state,
				EXPECTED_PHASE_CAN_BIND))
    return false;

  if (successful)
    {
      state_t next_state = NULL;
      if (old_state == m_new_stream_socket)
	next_state = m_bound_stream_socket;
      else if (old_state == m_new_datagram_socket)
	next_state = m_bound_datagram_socket;
      else if (old_state == m_new_unknown_socket)
	next_state = m_bound_unknown_socket;
      else if (old_state == m_start
	       || old_state == m_constant_fd)
	next_state = m_bound_unknown_socket;
      else if (old_state == m_stop)
	next_state = m_stop;
      else
	gcc_unreachable ();
      sm_ctxt->set_next_state (cd.get_call_stmt (), fd_sval, next_state);
      model->update_for_zero_return (cd, true);
    }
  else
    {
      /* Return -1; set errno.  */
      model->update_for_int_cst_return (cd, -1, true);
      model->set_errno (cd);
    }

  return true;
}

/* Update the model and fd state for an outcome of a call to "listen",
   where SUCCESSFUL indicate which of the two outcomes.
   Return true if the outcome is feasible, or false to reject it.  */

bool
fd_state_machine::on_listen (const call_details &cd,
			     bool successful,
			     sm_context *sm_ctxt,
			     const extrinsic_state &ext_state) const
{
  const gcall *stmt = cd.get_call_stmt ();
  engine *eng = ext_state.get_engine ();
  const supergraph *sg = eng->get_supergraph ();
  const supernode *node = sg->get_supernode_for_stmt (cd.get_call_stmt ());
  const svalue *fd_sval = cd.get_arg_svalue (0);
  region_model *model = cd.get_model ();
  state_t old_state = sm_ctxt->get_state (stmt, fd_sval);

  /* We expect a stream socket that's had "bind" called on it.  */
  if (!check_for_socket_fd (cd, successful, sm_ctxt, fd_sval, node, old_state))
    return false;
  if (!(old_state == m_start
	|| old_state == m_constant_fd
	|| old_state == m_stop
	|| old_state == m_invalid
	|| old_state == m_bound_stream_socket
	|| old_state == m_bound_unknown_socket
	/* Assume it's OK to call "listen" more than once.  */
	|| old_state == m_listening_stream_socket))
    {
      /* Complain about fncall on wrong type or in wrong phase.  */
      tree diag_arg = sm_ctxt->get_diagnostic_tree (fd_sval);
      if (is_stream_socket_fd_p (old_state))
	sm_ctxt->warn
	  (node, stmt, fd_sval,
	   make_unique<fd_phase_mismatch> (*this, diag_arg,
					   cd.get_fndecl_for_call (),
					   old_state,
					   EXPECTED_PHASE_CAN_LISTEN));
      else
	sm_ctxt->warn
	  (node, stmt, fd_sval,
	   make_unique<fd_type_mismatch> (*this, diag_arg,
					  cd.get_fndecl_for_call (),
					  old_state,
					  EXPECTED_TYPE_STREAM_SOCKET));
      if (successful)
	return false;
    }

  if (successful)
    {
      model->update_for_zero_return (cd, true);
      sm_ctxt->set_next_state (cd.get_call_stmt (), fd_sval,
			       m_listening_stream_socket);
    }
  else
    {
      /* Return -1; set errno.  */
      model->update_for_int_cst_return (cd, -1, true);
      model->set_errno (cd);
      if (old_state == m_start)
	sm_ctxt->set_next_state (cd.get_call_stmt (), fd_sval,
				 m_bound_stream_socket);
    }

  return true;
}

/* Update the model and fd state for an outcome of a call to "accept",
   where SUCCESSFUL indicate which of the two outcomes.
   Return true if the outcome is feasible, or false to reject it.  */

bool
fd_state_machine::on_accept (const call_details &cd,
			     bool successful,
			     sm_context *sm_ctxt,
			     const extrinsic_state &ext_state) const
{
  const gcall *stmt = cd.get_call_stmt ();
  engine *eng = ext_state.get_engine ();
  const supergraph *sg = eng->get_supergraph ();
  const supernode *node = sg->get_supernode_for_stmt (stmt);
  const svalue *fd_sval = cd.get_arg_svalue (0);
  const svalue *address_sval = cd.get_arg_svalue (1);
  const svalue *len_ptr_sval = cd.get_arg_svalue (2);
  region_model *model = cd.get_model ();
  state_t old_state = sm_ctxt->get_state (stmt, fd_sval);

  if (!address_sval->all_zeroes_p ())
    {
      region_model_manager *mgr = model->get_manager ();

      /* We might have a union of various pointer types, rather than a
	 pointer type; cast to (void *) before dereferencing.  */
      address_sval = mgr->get_or_create_cast (ptr_type_node, address_sval);

      const region *address_reg
	= model->deref_rvalue (address_sval, cd.get_arg_tree (1),
			       cd.get_ctxt ());
      const region *len_reg
	= model->deref_rvalue (len_ptr_sval, cd.get_arg_tree (2),
			       cd.get_ctxt ());
      const svalue *old_len_sval
	= model->get_store_value (len_reg, cd.get_ctxt ());
      tree len_ptr = cd.get_arg_tree (2);
      tree star_len_ptr = build2 (MEM_REF, TREE_TYPE (TREE_TYPE (len_ptr)),
				  len_ptr,
				  build_int_cst (TREE_TYPE (len_ptr), 0));
      old_len_sval = model->check_for_poison (old_len_sval,
					      star_len_ptr,
					      len_reg,
					      cd.get_ctxt ());
      if (successful)
	{
	  conjured_purge p (model, cd.get_ctxt ());
	  const region *old_sized_address_reg
	    = mgr->get_sized_region (address_reg,
				     NULL_TREE,
				     old_len_sval);
	  const svalue *new_addr_sval
	    = mgr->get_or_create_conjured_svalue (NULL_TREE,
						  stmt,
						  old_sized_address_reg,
						  p);
	  model->set_value (old_sized_address_reg, new_addr_sval,
			    cd.get_ctxt ());
	  const svalue *new_addr_len
	    = mgr->get_or_create_conjured_svalue (NULL_TREE,
						  stmt,
						  len_reg,
						  p);
	  model->set_value (len_reg, new_addr_len, cd.get_ctxt ());
	}
    }

  /* We expect a stream socket in the "listening" state.  */
  if (!check_for_socket_fd (cd, successful, sm_ctxt, fd_sval, node, old_state))
    return false;

  if (old_state == m_start || old_state == m_constant_fd)
    /* If we were in the start state (or a constant), assume we had the
       expected state.  */
    sm_ctxt->set_next_state (cd.get_call_stmt (), fd_sval,
			     m_listening_stream_socket);
  else if (old_state == m_stop)
    {
      /* No further complaints.  */
    }
  else if (old_state != m_listening_stream_socket)
    {
      /* Complain about fncall on wrong type or in wrong phase.  */
      tree diag_arg = sm_ctxt->get_diagnostic_tree (fd_sval);
      if (is_stream_socket_fd_p (old_state))
	sm_ctxt->warn
	  (node, stmt, fd_sval,
	   make_unique<fd_phase_mismatch> (*this, diag_arg,
					   cd.get_fndecl_for_call (),
					   old_state,
					   EXPECTED_PHASE_CAN_ACCEPT));
      else
	sm_ctxt->warn
	  (node, stmt, fd_sval,
	   make_unique<fd_type_mismatch> (*this, diag_arg,
					  cd.get_fndecl_for_call (),
					  old_state,
					  EXPECTED_TYPE_STREAM_SOCKET));
      if (successful)
	return false;
    }

  if (successful)
    {
      /* Return new conjured FD in "connected" state.  */
      if (gimple_call_lhs (stmt))
	{
	  conjured_purge p (model, cd.get_ctxt ());
	  region_model_manager *mgr = model->get_manager ();
	  const svalue *new_fd
	    = mgr->get_or_create_conjured_svalue (integer_type_node,
						  stmt,
						  cd.get_lhs_region (),
						  p);
	  if (!add_constraint_ge_zero (model, new_fd, cd.get_ctxt ()))
	    return false;
	  sm_ctxt->on_transition (node, stmt, new_fd,
				  m_start, m_connected_stream_socket);
	  model->set_value (cd.get_lhs_region (), new_fd, cd.get_ctxt ());
	}
      else
	sm_ctxt->warn (node, stmt, NULL_TREE,
		       make_unique<fd_leak> (*this, NULL_TREE));
    }
  else
    {
      /* Return -1; set errno.  */
      model->update_for_int_cst_return (cd, -1, true);
      model->set_errno (cd);
    }

  return true;
}

/* Update the model and fd state for an outcome of a call to "connect",
   where SUCCESSFUL indicate which of the two outcomes.
   Return true if the outcome is feasible, or false to reject it.  */

bool
fd_state_machine::on_connect (const call_details &cd,
			      bool successful,
			      sm_context *sm_ctxt,
			      const extrinsic_state &ext_state) const
{
  const gcall *stmt = cd.get_call_stmt ();
  engine *eng = ext_state.get_engine ();
  const supergraph *sg = eng->get_supergraph ();
  const supernode *node = sg->get_supernode_for_stmt (stmt);
  const svalue *fd_sval = cd.get_arg_svalue (0);
  region_model *model = cd.get_model ();
  state_t old_state = sm_ctxt->get_state (stmt, fd_sval);

  if (!check_for_new_socket_fd (cd, successful, sm_ctxt,
				fd_sval, node, old_state,
				EXPECTED_PHASE_CAN_CONNECT))
    return false;

  if (successful)
    {
      model->update_for_zero_return (cd, true);
      state_t next_state = NULL;
      if (old_state == m_new_stream_socket)
	next_state = m_connected_stream_socket;
      else if (old_state == m_new_datagram_socket)
	/* It's legal to call connect on a datagram socket, potentially
	   more than once.  We don't transition states for this.  */
	next_state = m_new_datagram_socket;
      else if (old_state == m_new_unknown_socket)
	next_state = m_stop;
      else if (old_state == m_start
	       || old_state == m_constant_fd)
	next_state = m_stop;
      else if (old_state == m_stop)
	next_state = m_stop;
      else
	gcc_unreachable ();
      sm_ctxt->set_next_state (cd.get_call_stmt (), fd_sval, next_state);
    }
  else
    {
      /* Return -1; set errno.  */
      model->update_for_int_cst_return (cd, -1, true);
      model->set_errno (cd);
      /* TODO: perhaps transition to a failed state, since the
	 portable way to handle a failed "connect" is to close
	 the socket and try again with a new socket.  */
    }

  return true;
}

void
fd_state_machine::on_condition (sm_context *sm_ctxt, const supernode *node,
				const gimple *stmt, const svalue *lhs,
				enum tree_code op, const svalue *rhs) const
{
  if (tree cst = rhs->maybe_get_constant ())
    {
      if (TREE_CODE (cst) == INTEGER_CST)
	{
	  int val = TREE_INT_CST_LOW (cst);
	  if (val == -1)
	    {
	      if (op == NE_EXPR)
		make_valid_transitions_on_condition (sm_ctxt, node, stmt, lhs);

	      else if (op == EQ_EXPR)
		make_invalid_transitions_on_condition (sm_ctxt, node, stmt,
						       lhs);
	    }
	}
    }

  if (rhs->all_zeroes_p ())
    {
      if (op == GE_EXPR)
	make_valid_transitions_on_condition (sm_ctxt, node, stmt, lhs);
      else if (op == LT_EXPR)
	make_invalid_transitions_on_condition (sm_ctxt, node, stmt, lhs);
    }
}

void
fd_state_machine::make_valid_transitions_on_condition (sm_context *sm_ctxt,
						       const supernode *node,
						       const gimple *stmt,
						       const svalue *lhs) const
{
  sm_ctxt->on_transition (node, stmt, lhs, m_unchecked_read_write,
			  m_valid_read_write);
  sm_ctxt->on_transition (node, stmt, lhs, m_unchecked_read_only,
			  m_valid_read_only);
  sm_ctxt->on_transition (node, stmt, lhs, m_unchecked_write_only,
			  m_valid_write_only);
}

void
fd_state_machine::make_invalid_transitions_on_condition (
    sm_context *sm_ctxt, const supernode *node, const gimple *stmt,
    const svalue *lhs) const
{
  sm_ctxt->on_transition (node, stmt, lhs, m_unchecked_read_write, m_invalid);
  sm_ctxt->on_transition (node, stmt, lhs, m_unchecked_read_only, m_invalid);
  sm_ctxt->on_transition (node, stmt, lhs, m_unchecked_write_only, m_invalid);
}

bool
fd_state_machine::can_purge_p (state_t s) const
{
  if (is_unchecked_fd_p (s)
      || is_valid_fd_p (s)
      || is_socket_fd_p (s))
    return false;
  else
    return true;
}

std::unique_ptr<pending_diagnostic>
fd_state_machine::on_leak (tree var) const
{
  return make_unique<fd_leak> (*this, var);
}
} // namespace

state_machine *
make_fd_state_machine (logger *logger)
{
  return new fd_state_machine (logger);
}

static bool
get_fd_state (region_model_context *ctxt,
	      sm_state_map **out_smap,
	      const fd_state_machine **out_sm,
	      unsigned *out_sm_idx,
	      std::unique_ptr<sm_context> *out_sm_context)
{
  if (!ctxt)
    return false;

  const state_machine *sm;
  if (!ctxt->get_fd_map (out_smap, &sm, out_sm_idx, out_sm_context))
    return false;

  gcc_assert (sm);

  *out_sm = (const fd_state_machine *)sm;
  return true;
}

/* Specialcase hook for handling pipe, for use by
   kf_pipe::success::update_model.  */

void
region_model::mark_as_valid_fd (const svalue *sval, region_model_context *ctxt)
{
  sm_state_map *smap;
  const fd_state_machine *fd_sm;
  if (!get_fd_state (ctxt, &smap, &fd_sm, NULL, NULL))
    return;
  const extrinsic_state *ext_state = ctxt->get_ext_state ();
  if (!ext_state)
    return;
  fd_sm->mark_as_valid_fd (this, smap, sval, *ext_state);
}

/* Handle calls to "socket".
   See e.g. https://man7.org/linux/man-pages/man3/socket.3p.html  */

class kf_socket : public known_function
{
public:
  class outcome_of_socket : public succeed_or_fail_call_info
  {
  public:
    outcome_of_socket (const call_details &cd, bool success)
    : succeed_or_fail_call_info (cd, success)
    {}

    bool update_model (region_model *model,
		       const exploded_edge *,
		       region_model_context *ctxt) const final override
    {
      const call_details cd (get_call_details (model, ctxt));
      sm_state_map *smap;
      const fd_state_machine *fd_sm;
      std::unique_ptr<sm_context> sm_ctxt;
      if (!get_fd_state (ctxt, &smap, &fd_sm, NULL, &sm_ctxt))
	return true;
      const extrinsic_state *ext_state = ctxt->get_ext_state ();
      if (!ext_state)
	return true;

      return fd_sm->on_socket (cd, m_success, sm_ctxt.get (), *ext_state);
    }
  };

  bool matches_call_types_p (const call_details &cd) const final override
  {
    return cd.num_args () == 3;
  }

  void impl_call_post (const call_details &cd) const final override
  {
    if (cd.get_ctxt ())
      {
	cd.get_ctxt ()->bifurcate (make_unique<outcome_of_socket> (cd, false));
	cd.get_ctxt ()->bifurcate (make_unique<outcome_of_socket> (cd, true));
	cd.get_ctxt ()->terminate_path ();
      }
  }
};

/* Handle calls to "bind".
   See e.g. https://man7.org/linux/man-pages/man3/bind.3p.html  */

class kf_bind : public known_function
{
public:
  class outcome_of_bind : public succeed_or_fail_call_info
  {
  public:
    outcome_of_bind (const call_details &cd, bool success)
    : succeed_or_fail_call_info (cd, success)
    {}

    bool update_model (region_model *model,
		       const exploded_edge *,
		       region_model_context *ctxt) const final override
    {
      const call_details cd (get_call_details (model, ctxt));
      sm_state_map *smap;
      const fd_state_machine *fd_sm;
      std::unique_ptr<sm_context> sm_ctxt;
      if (!get_fd_state (ctxt, &smap, &fd_sm, NULL, &sm_ctxt))
	return true;
      const extrinsic_state *ext_state = ctxt->get_ext_state ();
      if (!ext_state)
	return true;
      return fd_sm->on_bind (cd, m_success, sm_ctxt.get (), *ext_state);
    }
  };

  bool matches_call_types_p (const call_details &cd) const final override
  {
    return (cd.num_args () == 3 && cd.arg_is_pointer_p (1));
  }

  void impl_call_post (const call_details &cd) const final override
  {
    if (cd.get_ctxt ())
      {
	cd.get_ctxt ()->bifurcate (make_unique<outcome_of_bind> (cd, false));
	cd.get_ctxt ()->bifurcate (make_unique<outcome_of_bind> (cd, true));
	cd.get_ctxt ()->terminate_path ();
      }
  }
};

/* Handle calls to "listen".
   See e.g. https://man7.org/linux/man-pages/man3/listen.3p.html  */

class kf_listen : public known_function
{
  class outcome_of_listen : public succeed_or_fail_call_info
  {
  public:
    outcome_of_listen (const call_details &cd, bool success)
    : succeed_or_fail_call_info (cd, success)
    {}

    bool update_model (region_model *model,
		       const exploded_edge *,
		       region_model_context *ctxt) const final override
    {
      const call_details cd (get_call_details (model, ctxt));
      sm_state_map *smap;
      const fd_state_machine *fd_sm;
      std::unique_ptr<sm_context> sm_ctxt;
      if (!get_fd_state (ctxt, &smap, &fd_sm, NULL, &sm_ctxt))
	return true;
      const extrinsic_state *ext_state = ctxt->get_ext_state ();
      if (!ext_state)
	return true;

      return fd_sm->on_listen (cd, m_success, sm_ctxt.get (), *ext_state);
    }
  };

  bool matches_call_types_p (const call_details &cd) const final override
  {
    return cd.num_args () == 2;
  }

  void impl_call_post (const call_details &cd) const final override
  {
    if (cd.get_ctxt ())
      {
	cd.get_ctxt ()->bifurcate (make_unique<outcome_of_listen> (cd, false));
	cd.get_ctxt ()->bifurcate (make_unique<outcome_of_listen> (cd, true));
	cd.get_ctxt ()->terminate_path ();
      }
  }
};

/* Handle calls to "accept".
   See e.g. https://man7.org/linux/man-pages/man3/accept.3p.html  */

class kf_accept : public known_function
{
  class outcome_of_accept : public succeed_or_fail_call_info
  {
  public:
    outcome_of_accept (const call_details &cd, bool success)
    : succeed_or_fail_call_info (cd, success)
    {}

    bool update_model (region_model *model,
		       const exploded_edge *,
		       region_model_context *ctxt) const final override
    {
      const call_details cd (get_call_details (model, ctxt));
      sm_state_map *smap;
      const fd_state_machine *fd_sm;
      std::unique_ptr<sm_context> sm_ctxt;
      if (!get_fd_state (ctxt, &smap, &fd_sm, NULL, &sm_ctxt))
	return true;
      const extrinsic_state *ext_state = ctxt->get_ext_state ();
      if (!ext_state)
	return true;

      return fd_sm->on_accept (cd, m_success, sm_ctxt.get (), *ext_state);
    }
  };

  bool matches_call_types_p (const call_details &cd) const final override
  {
    return (cd.num_args () == 3
	    && cd.arg_is_pointer_p (1)
	    && cd.arg_is_pointer_p (2));
  }

  void impl_call_post (const call_details &cd) const final override
  {
    if (cd.get_ctxt ())
      {
	cd.get_ctxt ()->bifurcate (make_unique<outcome_of_accept> (cd, false));
	cd.get_ctxt ()->bifurcate (make_unique<outcome_of_accept> (cd, true));
	cd.get_ctxt ()->terminate_path ();
      }
  }
};

/* Handle calls to "connect".
   See e.g. https://man7.org/linux/man-pages/man3/connect.3p.html  */

class kf_connect : public known_function
{
public:
  class outcome_of_connect : public succeed_or_fail_call_info
  {
  public:
    outcome_of_connect (const call_details &cd, bool success)
    : succeed_or_fail_call_info (cd, success)
    {}

    bool update_model (region_model *model,
		       const exploded_edge *,
		       region_model_context *ctxt) const final override
    {
      const call_details cd (get_call_details (model, ctxt));
      sm_state_map *smap;
      const fd_state_machine *fd_sm;
      std::unique_ptr<sm_context> sm_ctxt;
      if (!get_fd_state (ctxt, &smap, &fd_sm, NULL, &sm_ctxt))
	return true;
      const extrinsic_state *ext_state = ctxt->get_ext_state ();
      if (!ext_state)
	return true;

      return fd_sm->on_connect (cd, m_success, sm_ctxt.get (), *ext_state);
    }
  };

  bool matches_call_types_p (const call_details &cd) const final override
  {
    return (cd.num_args () == 3
	    && cd.arg_is_pointer_p (1));
  }

  void impl_call_post (const call_details &cd) const final override
  {
    if (cd.get_ctxt ())
      {
	cd.get_ctxt ()->bifurcate (make_unique<outcome_of_connect> (cd, false));
	cd.get_ctxt ()->bifurcate (make_unique<outcome_of_connect> (cd, true));
	cd.get_ctxt ()->terminate_path ();
      }
  }
};

/* Handler for "isatty"".
   See e.g. https://man7.org/linux/man-pages/man3/isatty.3.html  */

class kf_isatty : public known_function
{
  class outcome_of_isatty : public succeed_or_fail_call_info
  {
  public:
    outcome_of_isatty (const call_details &cd, bool success)
    : succeed_or_fail_call_info (cd, success)
    {}

    bool update_model (region_model *model,
		       const exploded_edge *,
		       region_model_context *ctxt) const final override
    {
      const call_details cd (get_call_details (model, ctxt));

      if (m_success)
	{
	  /* Return 1.  */
	  model->update_for_int_cst_return (cd, 1, true);
	}
      else
	{
	  /* Return 0; set errno.  */
	  model->update_for_int_cst_return (cd, 0, true);
	  model->set_errno (cd);
	}

      return feasible_p (cd, ctxt);
    }

  private:
    bool feasible_p (const call_details &cd,
		     region_model_context *ctxt) const
    {
      if (m_success)
	{
	  /* Can't be "success" on a closed/invalid fd.  */
	  sm_state_map *smap;
	  const fd_state_machine *fd_sm;
	  std::unique_ptr<sm_context> sm_ctxt;
	  if (!get_fd_state (ctxt, &smap, &fd_sm, NULL, &sm_ctxt))
	    return true;
	  const extrinsic_state *ext_state = ctxt->get_ext_state ();
	  if (!ext_state)
	    return true;

	  const svalue *fd_sval = cd.get_arg_svalue (0);
	  state_machine::state_t old_state
	    = sm_ctxt->get_state (cd.get_call_stmt (), fd_sval);

	  if (fd_sm->is_closed_fd_p (old_state)
	      || old_state == fd_sm->m_invalid)
	    return false;
	}
      return true;
    }
  }; // class outcome_of_isatty

public:
  bool matches_call_types_p (const call_details &cd) const final override
  {
    return cd.num_args () == 1;
  }

  void impl_call_post (const call_details &cd) const final override
  {
    if (cd.get_ctxt ())
      {
	cd.get_ctxt ()->bifurcate (make_unique<outcome_of_isatty> (cd, false));
	cd.get_ctxt ()->bifurcate (make_unique<outcome_of_isatty> (cd, true));
	cd.get_ctxt ()->terminate_path ();
      }
  }
};

/* Handler for calls to "pipe" and "pipe2".
   See e.g. https://www.man7.org/linux/man-pages/man2/pipe.2.html  */

class kf_pipe : public known_function
{
  class failure : public failed_call_info
  {
  public:
    failure (const call_details &cd) : failed_call_info (cd) {}

    bool update_model (region_model *model,
		       const exploded_edge *,
		       region_model_context *ctxt) const final override
    {
      /* Return -1; everything else is unchanged.  */
      const call_details cd (get_call_details (model, ctxt));
      model->update_for_int_cst_return (cd, -1, true);
      return true;
    }
  };

  class success : public success_call_info
  {
  public:
    success (const call_details &cd) : success_call_info (cd) {}

    bool update_model (region_model *model,
		       const exploded_edge *,
		       region_model_context *ctxt) const final override
    {
      const call_details cd (get_call_details (model, ctxt));

      /* Return 0.  */
      model->update_for_zero_return (cd, true);

      /* Update fd array.  */
      region_model_manager *mgr = cd.get_manager ();
      tree arr_tree = cd.get_arg_tree (0);
      const svalue *arr_sval = cd.get_arg_svalue (0);
      for (int idx = 0; idx < 2; idx++)
	{
	  const region *arr_reg
	    = model->deref_rvalue (arr_sval, arr_tree, cd.get_ctxt ());
	  const svalue *idx_sval
	    = mgr->get_or_create_int_cst (integer_type_node, idx);
	  const region *element_reg
	    = mgr->get_element_region (arr_reg, integer_type_node, idx_sval);
	  conjured_purge p (model, cd.get_ctxt ());
	  const svalue *fd_sval
	    = mgr->get_or_create_conjured_svalue (integer_type_node,
						  cd.get_call_stmt (),
						  element_reg,
						  p);
	  model->set_value (element_reg, fd_sval, cd.get_ctxt ());
	  model->mark_as_valid_fd (fd_sval, cd.get_ctxt ());
	}
      return true;
    }
  };

public:
  kf_pipe (unsigned num_args)
  : m_num_args (num_args)
  {
    gcc_assert (num_args > 0);
  }

  bool matches_call_types_p (const call_details &cd) const final override
  {
    return (cd.num_args () == m_num_args && cd.arg_is_pointer_p (0));
  }

  void impl_call_post (const call_details &cd) const final override
  {
    if (cd.get_ctxt ())
      {
	cd.get_ctxt ()->bifurcate (make_unique<failure> (cd));
	cd.get_ctxt ()->bifurcate (make_unique<success> (cd));
	cd.get_ctxt ()->terminate_path ();
      }
  }

private:
  unsigned m_num_args;
};

/* Handler for "read".
     ssize_t read(int fildes, void *buf, size_t nbyte);
   See e.g. https://man7.org/linux/man-pages/man2/read.2.html   */

class kf_read : public known_function
{
public:
  bool matches_call_types_p (const call_details &cd) const final override
  {
    return (cd.num_args () == 3
	    && cd.arg_is_pointer_p (1)
	    && cd.arg_is_size_p (2));
  }

  /* For now, assume that any call to "read" fully clobbers the buffer
     passed in.  This isn't quite correct (e.g. errors, partial reads;
     see PR analyzer/108689), but at least stops us falsely complaining
     about the buffer being uninitialized.  */
  void impl_call_pre (const call_details &cd) const final override
  {
    region_model *model = cd.get_model ();
    const svalue *ptr_sval = cd.get_arg_svalue (1);
    if (const region *reg = ptr_sval->maybe_get_region ())
      {
	const region *base_reg = reg->get_base_region ();
	const svalue *new_sval = cd.get_or_create_conjured_svalue (base_reg);
	model->set_value (base_reg, new_sval, cd.get_ctxt ());
      }
  }
};


/* Populate KFM with instances of known functions relating to
   file descriptors.  */

void
register_known_fd_functions (known_function_manager &kfm)
{
  kfm.add ("accept", make_unique<kf_accept> ());
  kfm.add ("bind", make_unique<kf_bind> ());
  kfm.add ("connect", make_unique<kf_connect> ());
  kfm.add ("isatty", make_unique<kf_isatty> ());
  kfm.add ("listen", make_unique<kf_listen> ());
  kfm.add ("pipe", make_unique<kf_pipe> (1));
  kfm.add ("pipe2", make_unique<kf_pipe> (2));
  kfm.add ("read", make_unique<kf_read> ());
  kfm.add ("socket", make_unique<kf_socket> ());
}

} // namespace ana

#endif // ENABLE_ANALYZER