summaryrefslogtreecommitdiff
path: root/libc-test/build.rs
blob: f568affc7d4fcb57b2bf1ed4cde82aeb8314c7c4 (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
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
#![deny(warnings)]

extern crate cc;
extern crate ctest2 as ctest;

use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::{env, io};

fn do_cc() {
    let target = env::var("TARGET").unwrap();
    if cfg!(unix) {
        let exclude = ["redox", "wasi"];
        if !exclude.iter().any(|x| target.contains(x)) {
            let mut cmsg = cc::Build::new();

            cmsg.file("src/cmsg.c");

            if target.contains("solaris") || target.contains("illumos") {
                cmsg.define("_XOPEN_SOURCE", "700");
            }
            cmsg.compile("cmsg");
        }
    }
    if target.contains("android") || target.contains("linux") {
        cc::Build::new().file("src/errqueue.c").compile("errqueue");
    }
    if target.contains("linux")
        || target.contains("l4re")
        || target.contains("android")
        || target.contains("emscripten")
    {
        cc::Build::new().file("src/sigrt.c").compile("sigrt");
    }
}

fn do_ctest() {
    match &env::var("TARGET").unwrap() {
        t if t.contains("android") => return test_android(t),
        t if t.contains("apple") => return test_apple(t),
        t if t.contains("dragonfly") => return test_dragonflybsd(t),
        t if t.contains("emscripten") => return test_emscripten(t),
        t if t.contains("freebsd") => return test_freebsd(t),
        t if t.contains("haiku") => return test_haiku(t),
        t if t.contains("linux") => return test_linux(t),
        t if t.contains("netbsd") => return test_netbsd(t),
        t if t.contains("openbsd") => return test_openbsd(t),
        t if t.contains("redox") => return test_redox(t),
        t if t.contains("solaris") => return test_solarish(t),
        t if t.contains("illumos") => return test_solarish(t),
        t if t.contains("wasi") => return test_wasi(t),
        t if t.contains("windows") => return test_windows(t),
        t if t.contains("vxworks") => return test_vxworks(t),
        t => panic!("unknown target {}", t),
    }
}

fn ctest_cfg() -> ctest::TestGenerator {
    let mut cfg = ctest::TestGenerator::new();
    let libc_cfgs = [
        "libc_priv_mod_use",
        "libc_union",
        "libc_const_size_of",
        "libc_align",
        "libc_core_cvoid",
        "libc_packedN",
        "libc_thread_local",
    ];
    for f in &libc_cfgs {
        cfg.cfg(f, None);
    }
    cfg
}

fn do_semver() {
    let mut out = PathBuf::from(env::var("OUT_DIR").unwrap());
    out.push("semver.rs");
    let mut output = BufWriter::new(File::create(&out).unwrap());

    let family = env::var("CARGO_CFG_TARGET_FAMILY").unwrap();
    let vendor = env::var("CARGO_CFG_TARGET_VENDOR").unwrap();
    let os = env::var("CARGO_CFG_TARGET_OS").unwrap();
    let arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
    let target_env = env::var("CARGO_CFG_TARGET_ENV").unwrap();

    // `libc-test/semver` dir.
    let mut semver_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
    semver_root.push("semver");

    // NOTE: Windows has the same `family` as `os`, no point in including it
    // twice.
    // NOTE: Android doesn't include the unix file (or the Linux file) because
    // there are some many definitions missing it's actually easier just to
    // maintain a file for Android.
    if family != os && os != "android" {
        process_semver_file(&mut output, &mut semver_root, &family);
    }
    process_semver_file(&mut output, &mut semver_root, &vendor);
    process_semver_file(&mut output, &mut semver_root, &os);
    let os_arch = format!("{}-{}", os, arch);
    process_semver_file(&mut output, &mut semver_root, &os_arch);
    if target_env != "" {
        let os_env = format!("{}-{}", os, target_env);
        process_semver_file(&mut output, &mut semver_root, &os_env);

        let os_env_arch = format!("{}-{}-{}", os, target_env, arch);
        process_semver_file(&mut output, &mut semver_root, &os_env_arch);
    }
}

fn process_semver_file<W: Write, P: AsRef<Path>>(output: &mut W, path: &mut PathBuf, file: P) {
    // NOTE: `path` is reused between calls, so always remove the file again.
    path.push(file);
    path.set_extension("txt");

    println!("cargo:rerun-if-changed={}", path.display());
    let input_file = match File::open(&*path) {
        Ok(file) => file,
        Err(ref err) if err.kind() == io::ErrorKind::NotFound => {
            path.pop();
            return;
        }
        Err(err) => panic!("unexpected error opening file: {}", err),
    };
    let input = BufReader::new(input_file);

    write!(output, "// Source: {}.\n", path.display()).unwrap();
    output.write(b"use libc::{\n").unwrap();
    for line in input.lines() {
        let line = line.unwrap().into_bytes();
        match line.first() {
            // Ignore comments and empty lines.
            Some(b'#') | None => continue,
            _ => {
                output.write(b"    ").unwrap();
                output.write(&line).unwrap();
                output.write(b",\n").unwrap();
            }
        }
    }
    output.write(b"};\n\n").unwrap();
    path.pop();
}

fn main() {
    do_cc();
    do_ctest();
    do_semver();
}

macro_rules! headers {
    ($cfg:ident: [$m:expr]: $header:literal) => {
        if $m {
            $cfg.header($header);
        }
    };
    ($cfg:ident: $header:literal) => {
        $cfg.header($header);
    };
    ($($cfg:ident: $([$c:expr]:)* $header:literal,)*) => {
        $(headers!($cfg: $([$c]:)* $header);)*
    };
    ($cfg:ident: $( $([$c:expr]:)* $header:literal,)*) => {
        headers!($($cfg: $([$c]:)* $header,)*);
    };
    ($cfg:ident: $( $([$c:expr]:)* $header:literal),*) => {
        headers!($($cfg: $([$c]:)* $header,)*);
    };
}

fn test_apple(target: &str) {
    assert!(target.contains("apple"));
    let x86_64 = target.contains("x86_64");
    let i686 = target.contains("i686");

    let mut cfg = ctest_cfg();
    cfg.flag("-Wno-deprecated-declarations");
    cfg.define("__APPLE_USE_RFC_3542", None);

    headers! { cfg:
        "aio.h",
        "CommonCrypto/CommonCrypto.h",
        "CommonCrypto/CommonRandom.h",
        "crt_externs.h",
        "ctype.h",
        "dirent.h",
        "dlfcn.h",
        "errno.h",
        "execinfo.h",
        "fcntl.h",
        "glob.h",
        "grp.h",
        "iconv.h",
        "ifaddrs.h",
        "langinfo.h",
        "libproc.h",
        "limits.h",
        "locale.h",
        "mach-o/dyld.h",
        "mach/mach_init.h",
        "mach/mach.h",
        "mach/mach_time.h",
        "mach/mach_types.h",
        "mach/mach_vm.h",
        "mach/thread_act.h",
        "mach/thread_policy.h",
        "malloc/malloc.h",
        "net/bpf.h",
        "net/if.h",
        "net/if_arp.h",
        "net/if_dl.h",
        "net/if_utun.h",
        "net/route.h",
        "net/route.h",
        "netdb.h",
        "netinet/if_ether.h",
        "netinet/in.h",
        "netinet/in.h",
        "netinet/ip.h",
        "netinet/tcp.h",
        "netinet/udp.h",
        "poll.h",
        "pthread.h",
        "pwd.h",
        "regex.h",
        "resolv.h",
        "sched.h",
        "semaphore.h",
        "signal.h",
        "spawn.h",
        "stddef.h",
        "stdint.h",
        "stdio.h",
        "stdlib.h",
        "string.h",
        "sysdir.h",
        "sys/attr.h",
        "sys/clonefile.h",
        "sys/event.h",
        "sys/file.h",
        "sys/ioctl.h",
        "sys/ipc.h",
        "sys/kern_control.h",
        "sys/mman.h",
        "sys/mount.h",
        "sys/proc_info.h",
        "sys/ptrace.h",
        "sys/quota.h",
        "sys/resource.h",
        "sys/sem.h",
        "sys/shm.h",
        "sys/socket.h",
        "sys/stat.h",
        "sys/statvfs.h",
        "sys/sys_domain.h",
        "sys/sysctl.h",
        "sys/time.h",
        "sys/times.h",
        "sys/timex.h",
        "sys/types.h",
        "sys/uio.h",
        "sys/un.h",
        "sys/utsname.h",
        "sys/wait.h",
        "sys/xattr.h",
        "syslog.h",
        "termios.h",
        "time.h",
        "unistd.h",
        "util.h",
        "utime.h",
        "utmpx.h",
        "wchar.h",
        "xlocale.h",
        [x86_64]: "crt_externs.h",
    }

    cfg.skip_struct(move |ty| {
        match ty {
            // FIXME: actually a union
            "sigval" => true,

            _ => false,
        }
    });

    cfg.skip_const(move |name| {
        // They're declared via `deprecated_mach` and we don't support it anymore.
        if name.starts_with("VM_FLAGS_") {
            return true;
        }
        match name {
            // These OSX constants are removed in Sierra.
            // https://developer.apple.com/library/content/releasenotes/General/APIDiffsMacOS10_12/Swift/Darwin.html
            "KERN_KDENABLE_BG_TRACE" | "KERN_KDDISABLE_BG_TRACE" => true,
            // FIXME: the value has been changed since Catalina (0xffff0000 -> 0x3fff0000).
            "SF_SETTABLE" => true,
            // FIXME: the values have been changed since Big Sur
            "HW_TARGET" | "HW_PRODUCT" | "HW_MAXID" => true,
            _ => false,
        }
    });

    cfg.skip_fn(move |name| {
        // skip those that are manually verified
        match name {
            // FIXME: https://github.com/rust-lang/libc/issues/1272
            "execv" | "execve" | "execvp" => true,

            // close calls the close_nocancel system call
            "close" => true,

            // these calls require macOS 11.0 or higher
            "preadv" | "pwritev" => true,

            _ => false,
        }
    });

    cfg.skip_field(move |struct_, field| {
        match (struct_, field) {
            // FIXME: the array size has been changed since macOS 10.15 ([8] -> [7]).
            ("statfs", "f_reserved") => true,
            ("__darwin_arm_neon_state64", "__v") => true,
            // MAXPATHLEN is too big for auto-derive traits on arrays.
            ("vnode_info_path", "vip_path") => true,
            _ => false,
        }
    });

    cfg.skip_field_type(move |struct_, field| {
        match (struct_, field) {
            // FIXME: actually a union
            ("sigevent", "sigev_value") => true,
            _ => false,
        }
    });

    cfg.volatile_item(|i| {
        use ctest::VolatileItemKind::*;
        match i {
            StructField(ref n, ref f) if n == "aiocb" && f == "aio_buf" => true,
            _ => false,
        }
    });

    cfg.type_name(move |ty, is_struct, is_union| {
        match ty {
            // Just pass all these through, no need for a "struct" prefix
            "FILE" | "DIR" | "Dl_info" => ty.to_string(),

            // OSX calls this something else
            "sighandler_t" => "sig_t".to_string(),

            t if is_union => format!("union {}", t),
            t if t.ends_with("_t") => t.to_string(),
            t if is_struct => format!("struct {}", t),
            t => t.to_string(),
        }
    });

    cfg.field_name(move |struct_, field| {
        match field {
            s if s.ends_with("_nsec") && struct_.starts_with("stat") => {
                s.replace("e_nsec", "espec.tv_nsec")
            }
            // FIXME: sigaction actually contains a union with two variants:
            // a sa_sigaction with type: (*)(int, struct __siginfo *, void *)
            // a sa_handler with type sig_t
            "sa_sigaction" if struct_ == "sigaction" => "sa_handler".to_string(),
            s => s.to_string(),
        }
    });

    cfg.skip_roundtrip(move |s| match s {
        // FIXME: this type has the wrong ABI
        "max_align_t" if i686 => true,
        // Can't return an array from a C function.
        "uuid_t" => true,
        _ => false,
    });
    cfg.generate("../src/lib.rs", "main.rs");
}

fn test_openbsd(target: &str) {
    assert!(target.contains("openbsd"));

    let mut cfg = ctest_cfg();
    cfg.flag("-Wno-deprecated-declarations");

    let x86_64 = target.contains("x86_64");

    headers! { cfg:
        "elf.h",
        "errno.h",
        "fcntl.h",
        "limits.h",
        "link.h",
        "locale.h",
        "stddef.h",
        "stdint.h",
        "stdio.h",
        "stdlib.h",
        "sys/stat.h",
        "sys/types.h",
        "time.h",
        "wchar.h",
        "ctype.h",
        "dirent.h",
        "sys/socket.h",
        [x86_64]:"machine/fpu.h",
        "net/if.h",
        "net/route.h",
        "net/if_arp.h",
        "netdb.h",
        "netinet/in.h",
        "netinet/ip.h",
        "netinet/tcp.h",
        "netinet/udp.h",
        "net/bpf.h",
        "regex.h",
        "resolv.h",
        "pthread.h",
        "dlfcn.h",
        "signal.h",
        "string.h",
        "sys/file.h",
        "sys/ioctl.h",
        "sys/mman.h",
        "sys/resource.h",
        "sys/shm.h",
        "sys/socket.h",
        "sys/time.h",
        "sys/un.h",
        "sys/wait.h",
        "unistd.h",
        "utime.h",
        "pwd.h",
        "grp.h",
        "sys/utsname.h",
        "sys/ptrace.h",
        "sys/mount.h",
        "sys/uio.h",
        "sched.h",
        "termios.h",
        "poll.h",
        "syslog.h",
        "semaphore.h",
        "sys/statvfs.h",
        "sys/times.h",
        "glob.h",
        "ifaddrs.h",
        "langinfo.h",
        "sys/sysctl.h",
        "utmp.h",
        "sys/event.h",
        "net/if_dl.h",
        "util.h",
        "ufs/ufs/quota.h",
        "pthread_np.h",
        "sys/syscall.h",
        "sys/shm.h",
        "sys/param.h",
    }

    cfg.skip_struct(move |ty| {
        match ty {
            // FIXME: actually a union
            "sigval" => true,

            _ => false,
        }
    });

    cfg.skip_const(move |name| {
        match name {
            // Removed in OpenBSD 6.0
            "KERN_USERMOUNT" | "KERN_ARND" => true,
            _ => false,
        }
    });

    cfg.skip_fn(move |name| {
        match name {
            // FIXME: https://github.com/rust-lang/libc/issues/1272
            "execv" | "execve" | "execvp" | "execvpe" => true,

            // Removed in OpenBSD 6.5
            // https://marc.info/?l=openbsd-cvs&m=154723400730318
            "mincore" => true,

            _ => false,
        }
    });

    cfg.type_name(move |ty, is_struct, is_union| {
        match ty {
            // Just pass all these through, no need for a "struct" prefix
            "FILE" | "DIR" | "Dl_info" | "Elf32_Phdr" | "Elf64_Phdr" => ty.to_string(),

            // OSX calls this something else
            "sighandler_t" => "sig_t".to_string(),

            t if is_union => format!("union {}", t),
            t if t.ends_with("_t") => t.to_string(),
            t if is_struct => format!("struct {}", t),
            t => t.to_string(),
        }
    });

    cfg.field_name(move |struct_, field| match field {
        "st_birthtime" if struct_.starts_with("stat") => "__st_birthtime".to_string(),
        "st_birthtime_nsec" if struct_.starts_with("stat") => "__st_birthtimensec".to_string(),
        s if s.ends_with("_nsec") && struct_.starts_with("stat") => s.replace("e_nsec", ".tv_nsec"),
        "sa_sigaction" if struct_ == "sigaction" => "sa_handler".to_string(),
        s => s.to_string(),
    });

    cfg.skip_field_type(move |struct_, field| {
        // type siginfo_t.si_addr changed from OpenBSD 6.0 to 6.1
        struct_ == "siginfo_t" && field == "si_addr"
    });

    cfg.skip_field(|struct_, field| {
        match (struct_, field) {
            // conflicting with `p_type` macro from <resolve.h>.
            ("Elf32_Phdr", "p_type") => true,
            ("Elf64_Phdr", "p_type") => true,
            _ => false,
        }
    });

    cfg.generate("../src/lib.rs", "main.rs");
}

fn test_windows(target: &str) {
    assert!(target.contains("windows"));
    let gnu = target.contains("gnu");

    let mut cfg = ctest_cfg();
    cfg.define("_WIN32_WINNT", Some("0x8000"));

    headers! { cfg:
        "direct.h",
        "errno.h",
        "fcntl.h",
        "io.h",
        "limits.h",
        "locale.h",
        "process.h",
        "signal.h",
        "stddef.h",
        "stdint.h",
        "stdio.h",
        "stdlib.h",
        "sys/stat.h",
        "sys/types.h",
        "sys/utime.h",
        "time.h",
        "wchar.h",
        [gnu]: "ws2tcpip.h",
        [!gnu]: "Winsock2.h",
    }

    cfg.type_name(move |ty, is_struct, is_union| {
        match ty {
            // Just pass all these through, no need for a "struct" prefix
            "FILE" | "DIR" | "Dl_info" => ty.to_string(),

            // FIXME: these don't exist:
            "time64_t" => "__time64_t".to_string(),
            "ssize_t" => "SSIZE_T".to_string(),

            "sighandler_t" if !gnu => "_crt_signal_t".to_string(),
            "sighandler_t" if gnu => "__p_sig_fn_t".to_string(),

            t if is_union => format!("union {}", t),
            t if t.ends_with("_t") => t.to_string(),

            // Windows uppercase structs don't have `struct` in front:
            t if is_struct => {
                if ty.clone().chars().next().unwrap().is_uppercase() {
                    t.to_string()
                } else if t == "stat" {
                    "struct __stat64".to_string()
                } else if t == "utimbuf" {
                    "struct __utimbuf64".to_string()
                } else {
                    // put `struct` in front of all structs:
                    format!("struct {}", t)
                }
            }
            t => t.to_string(),
        }
    });

    cfg.fn_cname(move |name, cname| cname.unwrap_or(name).to_string());

    cfg.skip_type(move |name| match name {
        "SSIZE_T" if !gnu => true,
        "ssize_t" if !gnu => true,
        _ => false,
    });

    cfg.skip_const(move |name| {
        match name {
            // FIXME: API error:
            // SIG_ERR type is "void (*)(int)", not "int"
            "SIG_ERR" |
            // Similar for SIG_DFL/IGN/GET/SGE/ACK
            "SIG_DFL" | "SIG_IGN" | "SIG_GET" | "SIG_SGE" | "SIG_ACK" => true,
            // FIXME: newer windows-gnu environment on CI?
            "_O_OBTAIN_DIR" if gnu => true,
            _ => false,
        }
    });

    // FIXME: All functions point to the wrong addresses?
    cfg.skip_fn_ptrcheck(|_| true);

    cfg.skip_signededness(move |c| {
        match c {
            // windows-isms
            n if n.starts_with("P") => true,
            n if n.starts_with("H") => true,
            n if n.starts_with("LP") => true,
            "sighandler_t" if gnu => true,
            _ => false,
        }
    });

    cfg.skip_fn(move |name| {
        match name {
            // FIXME: https://github.com/rust-lang/libc/issues/1272
            "execv" | "execve" | "execvp" | "execvpe" => true,

            _ => false,
        }
    });

    cfg.generate("../src/lib.rs", "main.rs");
}

fn test_redox(target: &str) {
    assert!(target.contains("redox"));

    let mut cfg = ctest_cfg();
    cfg.flag("-Wno-deprecated-declarations");

    headers! {
        cfg:
        "ctype.h",
        "dirent.h",
        "dlfcn.h",
        "errno.h",
        "fcntl.h",
        "grp.h",
        "limits.h",
        "locale.h",
        "netdb.h",
        "netinet/in.h",
        "netinet/ip.h",
        "netinet/tcp.h",
        "poll.h",
        "pwd.h",
        "semaphore.h",
        "string.h",
        "strings.h",
        "sys/file.h",
        "sys/ioctl.h",
        "sys/mman.h",
        "sys/ptrace.h",
        "sys/resource.h",
        "sys/socket.h",
        "sys/stat.h",
        "sys/statvfs.h",
        "sys/time.h",
        "sys/types.h",
        "sys/uio.h",
        "sys/un.h",
        "sys/utsname.h",
        "sys/wait.h",
        "termios.h",
        "time.h",
        "unistd.h",
        "utime.h",
        "wchar.h",
    }

    cfg.generate("../src/lib.rs", "main.rs");
}

fn test_solarish(target: &str) {
    let is_solaris = target.contains("solaris");
    let is_illumos = target.contains("illumos");
    assert!(is_solaris || is_illumos);

    // ctest generates arguments supported only by clang, so make sure to run with CC=clang.
    // While debugging, "CFLAGS=-ferror-limit=<large num>" is useful to get more error output.
    let mut cfg = ctest_cfg();
    cfg.flag("-Wno-deprecated-declarations");

    cfg.define("_XOPEN_SOURCE", Some("700"));
    cfg.define("__EXTENSIONS__", None);
    cfg.define("_LCONV_C99", None);

    headers! {
        cfg:
        "ctype.h",
        "dirent.h",
        "dlfcn.h",
        "door.h",
        "errno.h",
        "execinfo.h",
        "fcntl.h",
        "glob.h",
        "grp.h",
        "ifaddrs.h",
        "langinfo.h",
        "limits.h",
        "locale.h",
        "mqueue.h",
        "net/if.h",
        "net/if_arp.h",
        "net/route.h",
        "netdb.h",
        "netinet/in.h",
        "netinet/ip.h",
        "netinet/tcp.h",
        "netinet/udp.h",
        "poll.h",
        "port.h",
        "pthread.h",
        "pwd.h",
        "resolv.h",
        "sched.h",
        "semaphore.h",
        "signal.h",
        "stddef.h",
        "stdint.h",
        "stdio.h",
        "stdlib.h",
        "string.h",
        "sys/epoll.h",
        "sys/eventfd.h",
        "sys/file.h",
        "sys/filio.h",
        "sys/ioctl.h",
        "sys/loadavg.h",
        "sys/mman.h",
        "sys/mount.h",
        "sys/pset.h",
        "sys/resource.h",
        "sys/socket.h",
        "sys/stat.h",
        "sys/statvfs.h",
        "sys/stropts.h",
        "sys/shm.h",
        "sys/time.h",
        "sys/times.h",
        "sys/timex.h",
        "sys/types.h",
        "sys/uio.h",
        "sys/un.h",
        "sys/utsname.h",
        "sys/wait.h",
        "syslog.h",
        "termios.h",
        "time.h",
        "ucontext.h",
        "unistd.h",
        "utime.h",
        "utmpx.h",
        "wchar.h",
    }

    cfg.skip_type(move |ty| {
        match ty {
            // sighandler_t is not present here
            "sighandler_t" => true,
            _ => false,
        }
    });

    cfg.type_name(move |ty, is_struct, is_union| match ty {
        "FILE" => "__FILE".to_string(),
        "DIR" | "Dl_info" => ty.to_string(),
        t if t.ends_with("_t") => t.to_string(),
        t if is_struct => format!("struct {}", t),
        t if is_union => format!("union {}", t),
        t => t.to_string(),
    });

    cfg.field_name(move |struct_, field| {
        match struct_ {
            // rust struct uses raw u64, rather than union
            "epoll_event" if field == "u64" => "data.u64".to_string(),
            // rust struct was committed with typo for Solaris
            "door_arg_t" if field == "dec_num" => "desc_num".to_string(),
            "stat" if field.ends_with("_nsec") => {
                // expose stat.Xtim.tv_nsec fields
                field.trim_end_matches("e_nsec").to_string() + ".tv_nsec"
            }
            _ => field.to_string(),
        }
    });

    cfg.skip_const(move |name| match name {
        "DT_FIFO" | "DT_CHR" | "DT_DIR" | "DT_BLK" | "DT_REG" | "DT_LNK" | "DT_SOCK"
        | "USRQUOTA" | "GRPQUOTA" | "PRIO_MIN" | "PRIO_MAX" => true,

        // skip sighandler_t assignments
        "SIG_DFL" | "SIG_ERR" | "SIG_IGN" => true,

        "DT_UNKNOWN" => true,

        "_UTX_LINESIZE" | "_UTX_USERSIZE" | "_UTX_PADSIZE" | "_UTX_IDSIZE" | "_UTX_HOSTSIZE" => {
            true
        }

        "EADI" | "EXTPROC" | "IPC_SEAT" => true,

        // This evaluates to a sysconf() call rather than a constant
        "PTHREAD_STACK_MIN" => true,

        // EPOLLEXCLUSIVE is a relatively recent addition to the epoll interface and may not be
        // defined on older systems.  It is, however, safe to use on systems which do not
        // explicitly support it. (A no-op is an acceptable implementation of EPOLLEXCLUSIVE.)
        "EPOLLEXCLUSIVE" => true,

        _ => false,
    });

    cfg.skip_struct(move |ty| {
        if ty.starts_with("__c_anonymous_") {
            return true;
        }
        // the union handling is a mess
        if ty.contains("door_desc_t_") {
            return true;
        }
        match ty {
            // union, not a struct
            "sigval" => true,
            // a bunch of solaris-only fields
            "utmpx" if is_illumos => true,
            _ => false,
        }
    });

    cfg.skip_field(move |s, field| {
        match s {
            // C99 sizing on this is tough
            "dirent" if field == "d_name" => true,
            // the union/macro makes this rough
            "sigaction" if field == "sa_sigaction" => true,
            // Missing in illumos
            "sigevent" if field == "ss_sp" => true,
            // Avoid sigval union issues
            "sigevent" if field == "sigev_value" => true,
            // const issues
            "sigevent" if field == "sigev_notify_attributes" => true,

            // Avoid const and union issues
            "door_arg" if field == "desc_ptr" => true,
            "door_desc_t" if field == "d_data" => true,
            "door_arg_t" if field.ends_with("_ptr") => true,
            "door_arg_t" if field.ends_with("rbuf") => true,

            _ => false,
        }
    });

    cfg.skip_fn(move |name| {
        // skip those that are manually verified
        match name {
            // const-ness only added recently
            "dladdr" => true,

            // Definition of those functions as changed since unified headers
            // from NDK r14b These changes imply some API breaking changes but
            // are still ABI compatible. We can wait for the next major release
            // to be compliant with the new API.
            //
            // FIXME: unskip these for next major release
            "setpriority" | "personality" => true,

            // signal is defined in terms of sighandler_t, so ignore
            "signal" => true,

            // Currently missing
            "cfmakeraw" | "cfsetspeed" => true,

            // const-ness issues
            "execv" | "execve" | "execvp" | "settimeofday" | "sethostname" => true,

            // Solaris-different
            "getpwent_r" | "getgrent_r" | "updwtmpx" if is_illumos => true,
            "madvise" | "mprotect" if is_illumos => true,
            "door_call" | "door_return" | "door_create" if is_illumos => true,

            // These functions may return int or void depending on the exact
            // configuration of the compilation environment, but the return
            // value is not useful (always 0) so we can ignore it:
            "setservent" | "endservent" if is_illumos => true,

            _ => false,
        }
    });

    cfg.generate("../src/lib.rs", "main.rs");
}

fn test_netbsd(target: &str) {
    assert!(target.contains("netbsd"));
    let rumprun = target.contains("rumprun");
    let mut cfg = ctest_cfg();

    cfg.flag("-Wno-deprecated-declarations");
    cfg.define("_NETBSD_SOURCE", Some("1"));

    headers! {
        cfg:
        "elf.h",
        "errno.h",
        "fcntl.h",
        "limits.h",
        "link.h",
        "locale.h",
        "stddef.h",
        "stdint.h",
        "stdio.h",
        "stdlib.h",
        "sys/stat.h",
        "sys/types.h",
        "time.h",
        "wchar.h",
        "aio.h",
        "ctype.h",
        "dirent.h",
        "dlfcn.h",
        "glob.h",
        "grp.h",
        "ifaddrs.h",
        "langinfo.h",
        "net/bpf.h",
        "net/if.h",
        "net/if_arp.h",
        "net/if_dl.h",
        "net/route.h",
        "netdb.h",
        "netinet/in.h",
        "netinet/ip.h",
        "netinet/tcp.h",
        "netinet/udp.h",
        "poll.h",
        "pthread.h",
        "pwd.h",
        "regex.h",
        "resolv.h",
        "sched.h",
        "semaphore.h",
        "signal.h",
        "string.h",
        "sys/endian.h",
        "sys/exec_elf.h",
        "sys/extattr.h",
        "sys/file.h",
        "sys/ioctl.h",
        "sys/ioctl_compat.h",
        "sys/mman.h",
        "sys/mount.h",
        "sys/ptrace.h",
        "sys/resource.h",
        "sys/shm.h",
        "sys/socket.h",
        "sys/statvfs.h",
        "sys/sysctl.h",
        "sys/time.h",
        "sys/times.h",
        "sys/timex.h",
        "sys/ucontext.h",
        "sys/uio.h",
        "sys/un.h",
        "sys/utsname.h",
        "sys/wait.h",
        "syslog.h",
        "termios.h",
        "ufs/ufs/quota.h",
        "ufs/ufs/quota1.h",
        "unistd.h",
        "util.h",
        "utime.h",
        "mqueue.h",
        "netinet/dccp.h",
        "sys/event.h",
        "sys/quota.h",
        "sys/shm.h",
        "iconv.h",
    }

    cfg.type_name(move |ty, is_struct, is_union| {
        match ty {
            // Just pass all these through, no need for a "struct" prefix
            "FILE" | "fd_set" | "Dl_info" | "DIR" | "Elf32_Phdr" | "Elf64_Phdr" | "Elf32_Shdr"
            | "Elf64_Shdr" | "Elf32_Sym" | "Elf64_Sym" | "Elf32_Ehdr" | "Elf64_Ehdr"
            | "Elf32_Chdr" | "Elf64_Chdr" => ty.to_string(),

            // OSX calls this something else
            "sighandler_t" => "sig_t".to_string(),

            t if is_union => format!("union {}", t),

            t if t.ends_with("_t") => t.to_string(),

            // put `struct` in front of all structs:.
            t if is_struct => format!("struct {}", t),

            t => t.to_string(),
        }
    });

    cfg.field_name(move |struct_, field| {
        match field {
            // Our stat *_nsec fields normally don't actually exist but are part
            // of a timeval struct
            s if s.ends_with("_nsec") && struct_.starts_with("stat") => {
                s.replace("e_nsec", ".tv_nsec")
            }
            "u64" if struct_ == "epoll_event" => "data.u64".to_string(),
            s => s.to_string(),
        }
    });

    cfg.skip_type(move |ty| {
        if ty.starts_with("__c_anonymous_") {
            return true;
        }
        match ty {
            // FIXME: sighandler_t is crazy across platforms
            "sighandler_t" => true,
            _ => false,
        }
    });

    cfg.skip_struct(move |ty| {
        match ty {
            // This is actually a union, not a struct
            "sigval" => true,
            // These are tested as part of the linux_fcntl tests since there are
            // header conflicts when including them with all the other structs.
            "termios2" => true,
            _ => false,
        }
    });

    cfg.skip_signededness(move |c| {
        match c {
            "LARGE_INTEGER" | "float" | "double" => true,
            n if n.starts_with("pthread") => true,
            // sem_t is a struct or pointer
            "sem_t" => true,
            _ => false,
        }
    });

    cfg.skip_const(move |name| {
        match name {
            "SIG_DFL" | "SIG_ERR" | "SIG_IGN" => true, // sighandler_t weirdness
            "SIGUNUSED" => true,                       // removed in glibc 2.26

            // weird signed extension or something like that?
            "MS_NOUSER" => true,
            "MS_RMT_MASK" => true, // updated in glibc 2.22 and musl 1.1.13
            "BOTHER" => true,

            _ => false,
        }
    });

    cfg.skip_fn(move |name| {
        match name {
            // FIXME: https://github.com/rust-lang/libc/issues/1272
            "execv" | "execve" | "execvp" => true,

            "getrlimit" | "getrlimit64" |    // non-int in 1st arg
            "setrlimit" | "setrlimit64" |    // non-int in 1st arg
            "prlimit" | "prlimit64" |        // non-int in 2nd arg

            // These functions presumably exist on netbsd but don't look like
            // they're implemented on rumprun yet, just let them slide for now.
            // Some of them look like they have headers but then don't have
            // corresponding actual definitions either...
            "shm_open" |
            "shm_unlink" |
            "syscall" |
            "mq_open" |
            "mq_close" |
            "mq_getattr" |
            "mq_notify" |
            "mq_receive" |
            "mq_send" |
            "mq_setattr" |
            "mq_timedreceive" |
            "mq_timedsend" |
            "mq_unlink" |
            "ptrace" |
            "sigaltstack" if rumprun => true,

            _ => false,
        }
    });

    cfg.skip_field_type(move |struct_, field| {
        // This is a weird union, don't check the type.
        (struct_ == "ifaddrs" && field == "ifa_ifu") ||
        // sighandler_t type is super weird
        (struct_ == "sigaction" && field == "sa_sigaction") ||
        // sigval is actually a union, but we pretend it's a struct
        (struct_ == "sigevent" && field == "sigev_value") ||
        // aio_buf is "volatile void*" and Rust doesn't understand volatile
        (struct_ == "aiocb" && field == "aio_buf")
    });

    cfg.skip_field(|struct_, field| {
        match (struct_, field) {
            // conflicting with `p_type` macro from <resolve.h>.
            ("Elf32_Phdr", "p_type") => true,
            ("Elf64_Phdr", "p_type") => true,
            // pthread_spin_t is a volatile uchar
            ("pthread_spinlock_t", "pts_spin") => true,
            _ => false,
        }
    });

    cfg.generate("../src/lib.rs", "main.rs");
}

fn test_dragonflybsd(target: &str) {
    assert!(target.contains("dragonfly"));
    let mut cfg = ctest_cfg();
    cfg.flag("-Wno-deprecated-declarations");

    headers! {
        cfg:
        "aio.h",
        "ctype.h",
        "dirent.h",
        "dlfcn.h",
        "errno.h",
        "execinfo.h",
        "fcntl.h",
        "glob.h",
        "grp.h",
        "ifaddrs.h",
        "langinfo.h",
        "limits.h",
        "locale.h",
        "mqueue.h",
        "net/if.h",
        "net/if_arp.h",
        "net/if_dl.h",
        "net/route.h",
        "netdb.h",
        "netinet/in.h",
        "netinet/ip.h",
        "netinet/tcp.h",
        "netinet/udp.h",
        "poll.h",
        "pthread.h",
        "pthread_np.h",
        "pwd.h",
        "regex.h",
        "resolv.h",
        "sched.h",
        "semaphore.h",
        "signal.h",
        "stddef.h",
        "stdint.h",
        "stdio.h",
        "stdlib.h",
        "string.h",
        "sys/event.h",
        "sys/file.h",
        "sys/ioctl.h",
        "sys/ipc.h",
        "sys/mman.h",
        "sys/mount.h",
        "sys/ptrace.h",
        "sys/resource.h",
        "sys/rtprio.h",
        "sys/sched.h",
        "sys/shm.h",
        "sys/socket.h",
        "sys/stat.h",
        "sys/statvfs.h",
        "sys/sysctl.h",
        "sys/time.h",
        "sys/times.h",
        "sys/types.h",
        "sys/uio.h",
        "sys/un.h",
        "sys/utsname.h",
        "sys/wait.h",
        "syslog.h",
        "termios.h",
        "time.h",
        "ucontext.h",
        "unistd.h",
        "util.h",
        "utime.h",
        "utmpx.h",
        "vfs/ufs/quota.h",
        "wchar.h",
        "iconv.h",
    }

    cfg.type_name(move |ty, is_struct, is_union| {
        match ty {
            // Just pass all these through, no need for a "struct" prefix
            "FILE" | "fd_set" | "Dl_info" | "DIR" | "Elf32_Phdr" | "Elf64_Phdr" | "Elf32_Shdr"
            | "Elf64_Shdr" | "Elf32_Sym" | "Elf64_Sym" | "Elf32_Ehdr" | "Elf64_Ehdr"
            | "Elf32_Chdr" | "Elf64_Chdr" => ty.to_string(),

            // FIXME: OSX calls this something else
            "sighandler_t" => "sig_t".to_string(),

            t if is_union => format!("union {}", t),

            t if t.ends_with("_t") => t.to_string(),

            // put `struct` in front of all structs:.
            t if is_struct => format!("struct {}", t),

            t => t.to_string(),
        }
    });

    cfg.field_name(move |struct_, field| {
        match field {
            // Our stat *_nsec fields normally don't actually exist but are part
            // of a timeval struct
            s if s.ends_with("_nsec") && struct_.starts_with("stat") => {
                s.replace("e_nsec", ".tv_nsec")
            }
            "u64" if struct_ == "epoll_event" => "data.u64".to_string(),
            // Field is named `type` in C but that is a Rust keyword,
            // so these fields are translated to `type_` in the bindings.
            "type_" if struct_ == "rtprio" => "type".to_string(),
            s => s.to_string(),
        }
    });

    cfg.skip_type(move |ty| {
        match ty {
            // sighandler_t is crazy across platforms
            "sighandler_t" => true,

            _ => false,
        }
    });

    cfg.skip_struct(move |ty| {
        match ty {
            // This is actually a union, not a struct
            "sigval" => true,

            // FIXME: These are tested as part of the linux_fcntl tests since
            // there are header conflicts when including them with all the other
            // structs.
            "termios2" => true,

            _ => false,
        }
    });

    cfg.skip_signededness(move |c| {
        match c {
            "LARGE_INTEGER" | "float" | "double" => true,
            // uuid_t is a struct, not an integer.
            "uuid_t" => true,
            n if n.starts_with("pthread") => true,
            // sem_t is a struct or pointer
            "sem_t" => true,
            // mqd_t is a pointer on DragonFly
            "mqd_t" => true,

            _ => false,
        }
    });

    cfg.skip_const(move |name| {
        match name {
            "SIG_DFL" | "SIG_ERR" | "SIG_IGN" => true, // sighandler_t weirdness

            // weird signed extension or something like that?
            "MS_NOUSER" => true,
            "MS_RMT_MASK" => true, // updated in glibc 2.22 and musl 1.1.13

            // These are defined for Solaris 11, but the crate is tested on
            // illumos, where they are currently not defined
            "EADI" | "PORT_SOURCE_POSTWAIT" | "PORT_SOURCE_SIGNAL" | "PTHREAD_STACK_MIN" => true,

            _ => false,
        }
    });

    cfg.skip_fn(move |name| {
        // skip those that are manually verified
        match name {
            // FIXME: https://github.com/rust-lang/libc/issues/1272
            "execv" | "execve" | "execvp" => true,

            "getrlimit" | "getrlimit64" |    // non-int in 1st arg
            "setrlimit" | "setrlimit64" |    // non-int in 1st arg
            "prlimit" | "prlimit64"        // non-int in 2nd arg
             => true,

            _ => false,
        }
    });

    cfg.skip_field_type(move |struct_, field| {
        // This is a weird union, don't check the type.
        (struct_ == "ifaddrs" && field == "ifa_ifu") ||
        // sighandler_t type is super weird
        (struct_ == "sigaction" && field == "sa_sigaction") ||
        // sigval is actually a union, but we pretend it's a struct
        (struct_ == "sigevent" && field == "sigev_value") ||
        // aio_buf is "volatile void*" and Rust doesn't understand volatile
        (struct_ == "aiocb" && field == "aio_buf")
    });

    cfg.skip_field(move |struct_, field| {
        // this is actually a union on linux, so we can't represent it well and
        // just insert some padding.
        (struct_ == "siginfo_t" && field == "_pad") ||
        // sigev_notify_thread_id is actually part of a sigev_un union
        (struct_ == "sigevent" && field == "sigev_notify_thread_id")
    });

    cfg.generate("../src/lib.rs", "main.rs");
}

fn test_wasi(target: &str) {
    assert!(target.contains("wasi"));

    let mut cfg = ctest_cfg();
    cfg.define("_GNU_SOURCE", None);

    headers! { cfg:
        "ctype.h",
        "dirent.h",
        "errno.h",
        "fcntl.h",
        "limits.h",
        "locale.h",
        "malloc.h",
        "poll.h",
        "sched.h",
        "stdbool.h",
        "stddef.h",
        "stdint.h",
        "stdio.h",
        "stdlib.h",
        "string.h",
        "sys/resource.h",
        "sys/select.h",
        "sys/socket.h",
        "sys/stat.h",
        "sys/times.h",
        "sys/types.h",
        "sys/uio.h",
        "sys/utsname.h",
        "sys/ioctl.h",
        "time.h",
        "unistd.h",
        "wasi/api.h",
        "wasi/libc.h",
        "wasi/libc-find-relpath.h",
        "wasi/libc-nocwd.h",
        "wchar.h",
    }

    cfg.type_name(move |ty, is_struct, is_union| match ty {
        "FILE" | "fd_set" | "DIR" => ty.to_string(),
        t if is_union => format!("union {}", t),
        t if t.starts_with("__wasi") && t.ends_with("_u") => format!("union {}", t),
        t if t.starts_with("__wasi") && is_struct => format!("struct {}", t),
        t if t.ends_with("_t") => t.to_string(),
        t if is_struct => format!("struct {}", t),
        t => t.to_string(),
    });

    cfg.field_name(move |_struct, field| {
        match field {
            // deal with fields as rust keywords
            "type_" => "type".to_string(),
            s => s.to_string(),
        }
    });

    // Looks like LLD doesn't merge duplicate imports, so if the Rust
    // code imports from a module and the C code also imports from a
    // module we end up with two imports of function pointers which
    // import the same thing but have different function pointers
    cfg.skip_fn_ptrcheck(|f| f.starts_with("__wasi"));

    // d_name is declared as a flexible array in WASI libc, so it
    // doesn't support sizeof.
    cfg.skip_field(|s, field| s == "dirent" && field == "d_name");

    // Currently Rust/clang disagree on function argument ABI, so skip these
    // tests. For more info see WebAssembly/tool-conventions#88
    cfg.skip_roundtrip(|_| true);

    cfg.generate("../src/lib.rs", "main.rs");
}

fn test_android(target: &str) {
    assert!(target.contains("android"));
    let target_pointer_width = match target {
        t if t.contains("aarch64") || t.contains("x86_64") => 64,
        t if t.contains("i686") || t.contains("arm") => 32,
        t => panic!("unsupported target: {}", t),
    };
    let x86 = target.contains("i686") || target.contains("x86_64");

    let mut cfg = ctest_cfg();
    cfg.define("_GNU_SOURCE", None);

    headers! { cfg:
               "arpa/inet.h",
               "ctype.h",
               "dirent.h",
               "dlfcn.h",
               "elf.h",
               "errno.h",
               "fcntl.h",
               "grp.h",
               "ifaddrs.h",
               "limits.h",
               "link.h",
               "locale.h",
               "malloc.h",
               "net/ethernet.h",
               "net/if.h",
               "net/if_arp.h",
               "net/route.h",
               "netdb.h",
               "netinet/in.h",
               "netinet/ip.h",
               "netinet/tcp.h",
               "netinet/udp.h",
               "netpacket/packet.h",
               "poll.h",
               "pthread.h",
               "pty.h",
               "pwd.h",
               "regex.h",
               "resolv.h",
               "sched.h",
               "semaphore.h",
               "signal.h",
               "stddef.h",
               "stdint.h",
               "stdio.h",
               "stdlib.h",
               "string.h",
               "sys/auxv.h",
               "sys/epoll.h",
               "sys/eventfd.h",
               "sys/file.h",
               "sys/fsuid.h",
               "sys/inotify.h",
               "sys/ioctl.h",
               "sys/mman.h",
               "sys/mount.h",
               "sys/personality.h",
               "sys/prctl.h",
               "sys/ptrace.h",
               "sys/random.h",
               "sys/reboot.h",
               "sys/resource.h",
               "sys/sendfile.h",
               "sys/signalfd.h",
               "sys/socket.h",
               "sys/stat.h",
               "sys/statvfs.h",
               "sys/swap.h",
               "sys/syscall.h",
               "sys/sysinfo.h",
               "sys/system_properties.h",
               "sys/time.h",
               "sys/timerfd.h",
               "sys/times.h",
               "sys/types.h",
               "sys/ucontext.h",
               "sys/uio.h",
               "sys/un.h",
               "sys/utsname.h",
               "sys/vfs.h",
               "sys/xattr.h",
               "sys/wait.h",
               "syslog.h",
               "termios.h",
               "time.h",
               "unistd.h",
               "utime.h",
               "utmp.h",
               "wchar.h",
               "xlocale.h",
               // time64_t is not defined for 64-bit targets If included it will
               // generate the error 'Your time_t is already 64-bit'
               [target_pointer_width == 32]: "time64.h",
               [x86]: "sys/reg.h",
    }

    // Include linux headers at the end:
    headers! { cfg:
                "asm/mman.h",
                "linux/auxvec.h",
                "linux/dccp.h",
                "linux/elf.h",
                "linux/errqueue.h",
                "linux/falloc.h",
                "linux/futex.h",
                "linux/fs.h",
                "linux/genetlink.h",
                "linux/if_alg.h",
                "linux/if_ether.h",
                "linux/if_tun.h",
                "linux/magic.h",
                "linux/memfd.h",
                "linux/module.h",
                "linux/net_tstamp.h",
                "linux/netfilter/nfnetlink.h",
                "linux/netfilter/nfnetlink_log.h",
                "linux/netfilter/nfnetlink_queue.h",
                "linux/netfilter/nf_tables.h",
                "linux/netfilter_ipv4.h",
                "linux/netfilter_ipv6.h",
                "linux/netfilter_ipv6/ip6_tables.h",
                "linux/netlink.h",
                "linux/quota.h",
                "linux/reboot.h",
                "linux/seccomp.h",
                "linux/sched.h",
                "linux/sockios.h",
                "linux/vm_sockets.h",
                "linux/wait.h",

    }

    // Include Android-specific headers:
    headers! { cfg:
                "android/set_abort_message.h"
    }

    cfg.type_name(move |ty, is_struct, is_union| {
        match ty {
            // Just pass all these through, no need for a "struct" prefix
            "FILE" | "fd_set" | "Dl_info" | "Elf32_Phdr" | "Elf64_Phdr" => ty.to_string(),

            t if is_union => format!("union {}", t),

            t if t.ends_with("_t") => t.to_string(),

            // sigval is a struct in Rust, but a union in C:
            "sigval" => format!("union sigval"),

            // put `struct` in front of all structs:.
            t if is_struct => format!("struct {}", t),

            t => t.to_string(),
        }
    });

    cfg.field_name(move |struct_, field| {
        match field {
            // Our stat *_nsec fields normally don't actually exist but are part
            // of a timeval struct
            s if s.ends_with("_nsec") && struct_.starts_with("stat") => s.to_string(),
            // FIXME: appears that `epoll_event.data` is an union
            "u64" if struct_ == "epoll_event" => "data.u64".to_string(),
            s => s.to_string(),
        }
    });

    cfg.skip_type(move |ty| {
        match ty {
            // FIXME: `sighandler_t` type is incorrect, see:
            // https://github.com/rust-lang/libc/issues/1359
            "sighandler_t" => true,
            _ => false,
        }
    });

    cfg.skip_struct(move |ty| {
        if ty.starts_with("__c_anonymous_") {
            return true;
        }
        match ty {
            // These are tested as part of the linux_fcntl tests since there are
            // header conflicts when including them with all the other structs.
            "termios2" => true,
            // uc_sigmask and uc_sigmask64 of ucontext_t are an anonymous union
            "ucontext_t" => true,
            // 'private' type
            "prop_info" => true,

            _ => false,
        }
    });

    cfg.skip_const(move |name| {
        match name {
            // FIXME: deprecated: not available in any header
            // See: https://github.com/rust-lang/libc/issues/1356
            "ENOATTR" => true,

            // FIXME: still necessary?
            "SIG_DFL" | "SIG_ERR" | "SIG_IGN" => true, // sighandler_t weirdness
            // FIXME: deprecated - removed in glibc 2.26
            "SIGUNUSED" => true,

            // Needs a newer Android SDK for the definition
            "P_PIDFD" => true,

            // Requires Linux kernel 5.6
            "VMADDR_CID_LOCAL" => true,

            _ => false,
        }
    });

    cfg.skip_fn(move |name| {
        // skip those that are manually verified
        match name {
            // FIXME: https://github.com/rust-lang/libc/issues/1272
            "execv" | "execve" | "execvp" | "execvpe" | "fexecve" => true,

            // There are two versions of the sterror_r function, see
            //
            // https://linux.die.net/man/3/strerror_r
            //
            // An XSI-compliant version provided if:
            //
            // (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE
            //
            // and a GNU specific version provided if _GNU_SOURCE is defined.
            //
            // libc provides bindings for the XSI-compliant version, which is
            // preferred for portable applications.
            //
            // We skip the test here since here _GNU_SOURCE is defined, and
            // test the XSI version below.
            "strerror_r" => true,
            "reallocarray" => true,
            "__system_property_wait" => true,

            _ => false,
        }
    });

    cfg.skip_field_type(move |struct_, field| {
        // This is a weird union, don't check the type.
        (struct_ == "ifaddrs" && field == "ifa_ifu") ||
        // sigval is actually a union, but we pretend it's a struct
        (struct_ == "sigevent" && field == "sigev_value") ||
        // FIXME: `sa_sigaction` has type `sighandler_t` but that type is
        // incorrect, see: https://github.com/rust-lang/libc/issues/1359
        (struct_ == "sigaction" && field == "sa_sigaction") ||
        // signalfd had SIGSYS fields added in Android 4.19, but CI does not have that version yet.
        (struct_ == "signalfd_siginfo" && field == "ssi_call_addr")
    });

    cfg.skip_field(move |struct_, field| {
        // this is actually a union on linux, so we can't represent it well and
        // just insert some padding.
        (struct_ == "siginfo_t" && field == "_pad") ||
        // FIXME: `sa_sigaction` has type `sighandler_t` but that type is
        // incorrect, see: https://github.com/rust-lang/libc/issues/1359
        (struct_ == "sigaction" && field == "sa_sigaction") ||
        // sigev_notify_thread_id is actually part of a sigev_un union
        (struct_ == "sigevent" && field == "sigev_notify_thread_id") ||
        // signalfd had SIGSYS fields added in Android 4.19, but CI does not have that version yet.
        (struct_ == "signalfd_siginfo" && (field == "ssi_syscall" ||
                                           field == "ssi_call_addr" ||
                                           field == "ssi_arch"))
    });

    cfg.skip_field(|struct_, field| {
        match (struct_, field) {
            // conflicting with `p_type` macro from <resolve.h>.
            ("Elf32_Phdr", "p_type") => true,
            ("Elf64_Phdr", "p_type") => true,

            // this is actually a union on linux, so we can't represent it well and
            // just insert some padding.
            ("siginfo_t", "_pad") => true,

            _ => false,
        }
    });

    cfg.generate("../src/lib.rs", "main.rs");

    test_linux_like_apis(target);
}

fn test_freebsd(target: &str) {
    assert!(target.contains("freebsd"));
    let mut cfg = ctest_cfg();

    let freebsd_ver = which_freebsd();

    match freebsd_ver {
        Some(10) => cfg.cfg("freebsd10", None),
        Some(11) => cfg.cfg("freebsd11", None),
        Some(12) => cfg.cfg("freebsd12", None),
        Some(13) => cfg.cfg("freebsd13", None),
        _ => &mut cfg,
    };

    // Required for `getline`:
    cfg.define("_WITH_GETLINE", None);
    // Required for making freebsd11_stat available in the headers
    match freebsd_ver {
        Some(10) => &mut cfg,
        _ => cfg.define("_WANT_FREEBSD11_STAT", None),
    };

    let freebsdlast = match freebsd_ver {
        Some(12) | Some(13) => true,
        _ => false,
    };

    headers! { cfg:
                "aio.h",
                "arpa/inet.h",
                "ctype.h",
                "dirent.h",
                "dlfcn.h",
                "elf.h",
                "errno.h",
                "execinfo.h",
                "fcntl.h",
                "glob.h",
                "grp.h",
                "iconv.h",
                "ifaddrs.h",
                "langinfo.h",
                "libutil.h",
                "limits.h",
                "link.h",
                "locale.h",
                "machine/elf.h",
                "machine/reg.h",
                "malloc_np.h",
                "mqueue.h",
                "net/bpf.h",
                "net/if.h",
                "net/if_arp.h",
                "net/if_dl.h",
                "net/route.h",
                "netdb.h",
                "netinet/ip.h",
                "netinet/in.h",
                "netinet/tcp.h",
                "netinet/udp.h",
                "poll.h",
                "pthread.h",
                "pthread_np.h",
                "pwd.h",
                "regex.h",
                "resolv.h",
                "sched.h",
                "semaphore.h",
                "signal.h",
                "spawn.h",
                "stddef.h",
                "stdint.h",
                "stdio.h",
                "stdlib.h",
                "string.h",
                "sys/capsicum.h",
                [freebsdlast]:"sys/auxv.h",
                "sys/cpuset.h",
                "sys/event.h",
                "sys/extattr.h",
                "sys/file.h",
                "sys/ioctl.h",
                "sys/ipc.h",
                "sys/jail.h",
                "sys/mman.h",
                "sys/mount.h",
                "sys/msg.h",
                "sys/procctl.h",
                "sys/procdesc.h",
                "sys/ptrace.h",
                "sys/queue.h",
                "sys/random.h",
                "sys/resource.h",
                "sys/rtprio.h",
                "sys/shm.h",
                "sys/socket.h",
                "sys/stat.h",
                "sys/statvfs.h",
                "sys/sysctl.h",
                "sys/time.h",
                "sys/times.h",
                "sys/timex.h",
                "sys/types.h",
                "sys/ucontext.h",
                "sys/uio.h",
                "sys/un.h",
                "sys/user.h",
                "sys/utsname.h",
                "sys/wait.h",
                "libprocstat.h",
                "syslog.h",
                "termios.h",
                "time.h",
                "ufs/ufs/quota.h",
                "unistd.h",
                "utime.h",
                "utmpx.h",
                "wchar.h",
    }

    cfg.type_name(move |ty, is_struct, is_union| {
        match ty {
            // Just pass all these through, no need for a "struct" prefix
            "FILE" | "fd_set" | "Dl_info" | "DIR" | "Elf32_Phdr" | "Elf64_Phdr"
            | "Elf32_Auxinfo" | "Elf64_Auxinfo" => ty.to_string(),

            // FIXME: https://github.com/rust-lang/libc/issues/1273
            "sighandler_t" => "sig_t".to_string(),

            t if is_union => format!("union {}", t),

            t if t.ends_with("_t") => t.to_string(),

            // sigval is a struct in Rust, but a union in C:
            "sigval" => format!("union sigval"),

            // put `struct` in front of all structs:.
            t if is_struct => format!("struct {}", t),

            t => t.to_string(),
        }
    });

    cfg.field_name(move |struct_, field| {
        match field {
            // Our stat *_nsec fields normally don't actually exist but are part
            // of a timeval struct
            s if s.ends_with("_nsec") && struct_.starts_with("stat") => {
                s.replace("e_nsec", ".tv_nsec")
            }
            // Field is named `type` in C but that is a Rust keyword,
            // so these fields are translated to `type_` in the bindings.
            "type_" if struct_ == "rtprio" => "type".to_string(),
            s => s.to_string(),
        }
    });

    cfg.skip_const(move |name| {
        match name {
            // These constants are to be introduced in yet-unreleased FreeBSD 12.2.
            "F_ADD_SEALS" | "F_GET_SEALS" | "F_SEAL_SEAL" | "F_SEAL_SHRINK" | "F_SEAL_GROW"
            | "F_SEAL_WRITE"
                if Some(12) <= freebsd_ver =>
            {
                true
            }

            // These constants were introduced in FreeBSD 12:
            "SF_USER_READAHEAD"
            | "EVFILT_EMPTY"
            | "SO_REUSEPORT_LB"
            | "IP_ORIGDSTADDR"
            | "IP_RECVORIGDSTADDR"
            | "IPV6_ORIGDSTADDR"
            | "IPV6_RECVORIGDSTADDR"
            | "NI_NUMERICSCOPE"
                if Some(11) == freebsd_ver =>
            {
                true
            }

            // These constants were introduced in FreeBSD 11:
            "SF_USER_READAHEAD"
            | "SF_NOCACHE"
            | "RLIMIT_KQUEUES"
            | "RLIMIT_UMTXP"
            | "EVFILT_PROCDESC"
            | "EVFILT_SENDFILE"
            | "EVFILT_EMPTY"
            | "SO_REUSEPORT_LB"
            | "TCP_CCALGOOPT"
            | "TCP_PCAP_OUT"
            | "TCP_PCAP_IN"
            | "IP_BINDMULTI"
            | "IP_ORIGDSTADDR"
            | "IP_RECVORIGDSTADDR"
            | "IPV6_ORIGDSTADDR"
            | "IPV6_RECVORIGDSTADDR"
            | "PD_CLOEXEC"
            | "PD_ALLOWED_AT_FORK"
            | "IP_RSS_LISTEN_BUCKET"
            | "NI_NUMERICSCOPE"
                if Some(10) == freebsd_ver =>
            {
                true
            }

            // FIXME: This constant has a different value in FreeBSD 10:
            "RLIM_NLIMITS" if Some(10) == freebsd_ver => true,

            // FIXME: There are deprecated - remove in a couple of releases.
            // These constants were removed in FreeBSD 11 (svn r273250) but will
            // still be accepted and ignored at runtime.
            "MAP_RENAME" | "MAP_NORESERVE" if Some(10) != freebsd_ver => true,

            // FIXME: There are deprecated - remove in a couple of releases.
            // These constants were removed in FreeBSD 11 (svn r262489),
            // and they've never had any legitimate use outside of the
            // base system anyway.
            "CTL_MAXID" | "KERN_MAXID" | "HW_MAXID" | "USER_MAXID" => true,

            // This constant was removed in FreeBSD 13 (svn r363622), and never
            // had any legitimate use outside of the base system anyway.
            "CTL_P1003_1B_MAXID" => true,

            // This was renamed in FreeBSD 12.2 and 13 (r352486).
            "CTL_UNSPEC" | "CTL_SYSCTL" => true,

            // These were added in FreeBSD 12.2 and 13 (r352486),
            // but they are just names for magic numbers that existed for ages.
            "CTL_SYSCTL_DEBUG"
            | "CTL_SYSCTL_NAME"
            | "CTL_SYSCTL_NEXT"
            | "CTL_SYSCTL_NAME2OID"
            | "CTL_SYSCTL_OIDFMT"
            | "CTL_SYSCTL_OIDDESCR"
            | "CTL_SYSCTL_OIDLABEL" => true,

            // This was renamed in FreeBSD 12.2 and 13 (r350749).
            "IPPROTO_SEP" | "IPPROTO_DCCP" => true,

            // This was changed to 96(0x60) in FreeBSD 13:
            // https://github.com/freebsd/freebsd/
            // commit/06b00ceaa914a3907e4e27bad924f44612bae1d7
            "MINCORE_SUPER" if Some(13) == freebsd_ver => true,

            // This was increased to 97 in FreeBSD 12.2 and 13.
            // https://github.com/freebsd/freebsd/
            // commit/72a21ba0f62da5e86a1c0b462aeb3f5ff849a1b7
            "ELAST" if Some(12) == freebsd_ver => true,

            _ => false,
        }
    });

    cfg.skip_struct(move |ty| {
        if ty.starts_with("__c_anonymous_") {
            return true;
        }
        match ty {
            // `mmsghdr` is not available in FreeBSD 10
            "mmsghdr" if Some(10) == freebsd_ver => true,

            // `max_align_t` is not available in FreeBSD 10
            "max_align_t" if Some(10) == freebsd_ver => true,

            // `procstat` is a private struct
            "procstat" => true,

            _ => false,
        }
    });

    cfg.skip_fn(move |name| {
        // skip those that are manually verified
        match name {
            // FIXME: https://github.com/rust-lang/libc/issues/1272
            "execv" | "execve" | "execvp" | "execvpe" | "fexecve" => true,

            // These functions were added in FreeBSD 11:
            "fdatasync" | "mq_getfd_np" | "sendmmsg" | "recvmmsg" if Some(10) == freebsd_ver => {
                true
            }

            // This function changed its return type from `int` in FreeBSD10 to
            // `ssize_t` in FreeBSD11:
            "aio_waitcomplete" if Some(10) == freebsd_ver => true,

            // The `uname` function in the `utsname.h` FreeBSD header is a C
            // inline function (has no symbol) that calls the `__xuname` symbol.
            // Therefore the function pointer comparison does not make sense for it.
            "uname" => true,

            // FIXME: Our API is unsound. The Rust API allows aliasing
            // pointers, but the C API requires pointers not to alias.
            // We should probably be at least using `&`/`&mut` here, see:
            // https://github.com/gnzlbg/ctest/issues/68
            "lio_listio" => true,

            _ => false,
        }
    });

    cfg.skip_signededness(move |c| {
        match c {
            // FIXME: has a different sign in FreeBSD10
            "blksize_t" if Some(10) == freebsd_ver => true,
            _ => false,
        }
    });

    cfg.volatile_item(|i| {
        use ctest::VolatileItemKind::*;
        match i {
            // aio_buf is a volatile void** but since we cannot express that in
            // Rust types, we have to explicitly tell the checker about it here:
            StructField(ref n, ref f) if n == "aiocb" && f == "aio_buf" => true,
            _ => false,
        }
    });

    cfg.skip_field(move |struct_, field| {
        match (struct_, field) {
            // FIXME: `sa_sigaction` has type `sighandler_t` but that type is
            // incorrect, see: https://github.com/rust-lang/libc/issues/1359
            ("sigaction", "sa_sigaction") => true,

            // FIXME: in FreeBSD10 this field has type `char*` instead of
            // `void*`:
            ("stack_t", "ss_sp") if Some(10) == freebsd_ver => true,

            // conflicting with `p_type` macro from <resolve.h>.
            ("Elf32_Phdr", "p_type") => true,
            ("Elf64_Phdr", "p_type") => true,

            // not available until FreeBSD 12, and is an anonymous union there.
            ("xucred", "cr_pid__c_anonymous_union") => true,

            // m_owner field is a volatile __lwpid_t
            ("umutex", "m_owner") => true,
            // c_has_waiters field is a volatile int32_t
            ("ucond", "c_has_waiters") => true,
            // is PATH_MAX long but tests can't accept multi array as equivalent.
            ("kinfo_vmentry", "kve_path") => true,

            // a_un field is a union
            ("Elf32_Auxinfo", "a_un") => true,
            ("Elf64_Auxinfo", "a_un") => true,
            _ => false,
        }
    });

    cfg.generate("../src/lib.rs", "main.rs");
}

fn test_emscripten(target: &str) {
    assert!(target.contains("emscripten"));

    let mut cfg = ctest_cfg();
    cfg.define("_GNU_SOURCE", None); // FIXME: ??

    headers! { cfg:
               "aio.h",
               "ctype.h",
               "dirent.h",
               "dlfcn.h",
               "errno.h",
               "fcntl.h",
               "glob.h",
               "grp.h",
               "ifaddrs.h",
               "langinfo.h",
               "limits.h",
               "locale.h",
               "malloc.h",
               "mntent.h",
               "mqueue.h",
               "net/ethernet.h",
               "net/if.h",
               "net/if_arp.h",
               "net/route.h",
               "netdb.h",
               "netinet/in.h",
               "netinet/ip.h",
               "netinet/tcp.h",
               "netinet/udp.h",
               "netpacket/packet.h",
               "poll.h",
               "pthread.h",
               "pty.h",
               "pwd.h",
               "resolv.h",
               "sched.h",
               "sched.h",
               "semaphore.h",
               "shadow.h",
               "signal.h",
               "stddef.h",
               "stdint.h",
               "stdio.h",
               "stdlib.h",
               "string.h",
               "sys/epoll.h",
               "sys/eventfd.h",
               "sys/file.h",
               "sys/ioctl.h",
               "sys/ipc.h",
               "sys/mman.h",
               "sys/mount.h",
               "sys/msg.h",
               "sys/personality.h",
               "sys/prctl.h",
               "sys/ptrace.h",
               "sys/quota.h",
               "sys/reboot.h",
               "sys/resource.h",
               "sys/sem.h",
               "sys/sendfile.h",
               "sys/shm.h",
               "sys/signalfd.h",
               "sys/socket.h",
               "sys/stat.h",
               "sys/statvfs.h",
               "sys/swap.h",
               "sys/syscall.h",
               "sys/sysctl.h",
               "sys/sysinfo.h",
               "sys/time.h",
               "sys/timerfd.h",
               "sys/times.h",
               "sys/types.h",
               "sys/uio.h",
               "sys/un.h",
               "sys/user.h",
               "sys/utsname.h",
               "sys/vfs.h",
               "sys/wait.h",
               "sys/xattr.h",
               "syslog.h",
               "termios.h",
               "time.h",
               "ucontext.h",
               "unistd.h",
               "utime.h",
               "utmp.h",
               "utmpx.h",
               "wchar.h",
    }

    cfg.type_name(move |ty, is_struct, is_union| {
        match ty {
            // Just pass all these through, no need for a "struct" prefix
            "FILE" | "fd_set" | "Dl_info" | "DIR" => ty.to_string(),

            t if is_union => format!("union {}", t),

            t if t.ends_with("_t") => t.to_string(),

            // put `struct` in front of all structs:.
            t if is_struct => format!("struct {}", t),

            t => t.to_string(),
        }
    });

    cfg.field_name(move |struct_, field| {
        match field {
            // Our stat *_nsec fields normally don't actually exist but are part
            // of a timeval struct
            s if s.ends_with("_nsec") && struct_.starts_with("stat") => {
                s.replace("e_nsec", ".tv_nsec")
            }
            // FIXME: appears that `epoll_event.data` is an union
            "u64" if struct_ == "epoll_event" => "data.u64".to_string(),
            s => s.to_string(),
        }
    });

    cfg.skip_type(move |ty| {
        match ty {
            // sighandler_t is crazy across platforms
            // FIXME: is this necessary?
            "sighandler_t" => true,

            _ => false,
        }
    });

    cfg.skip_struct(move |ty| {
        match ty {
            // This is actually a union, not a struct
            // FIXME: is this necessary?
            "sigval" => true,

            // FIXME: It was removed in
            // emscripten-core/emscripten@953e414
            "pthread_mutexattr_t" => true,

            // FIXME: Investigate why the test fails.
            // Skip for now to unblock CI.
            "pthread_condattr_t" => true,

            _ => false,
        }
    });

    cfg.skip_fn(move |name| {
        match name {
            // FIXME: https://github.com/rust-lang/libc/issues/1272
            "execv" | "execve" | "execvp" | "execvpe" | "fexecve" => true,

            // FIXME: Investigate why CI is missing it.
            "clearenv" => true,

            _ => false,
        }
    });

    cfg.skip_const(move |name| {
        match name {
            // FIXME: deprecated - SIGNUNUSED was removed in glibc 2.26
            // users should use SIGSYS instead
            "SIGUNUSED" => true,

            // FIXME: emscripten uses different constants to constructs these
            n if n.contains("__SIZEOF_PTHREAD") => true,

            // FIXME: `SYS_gettid` was removed in
            // emscripten-core/emscripten@6d6474e
            "SYS_gettid" => true,

            _ => false,
        }
    });

    cfg.skip_field_type(move |struct_, field| {
        // This is a weird union, don't check the type.
        // FIXME: is this necessary?
        (struct_ == "ifaddrs" && field == "ifa_ifu") ||
        // sighandler_t type is super weird
        // FIXME: is this necessary?
        (struct_ == "sigaction" && field == "sa_sigaction") ||
        // sigval is actually a union, but we pretend it's a struct
        // FIXME: is this necessary?
        (struct_ == "sigevent" && field == "sigev_value") ||
        // aio_buf is "volatile void*" and Rust doesn't understand volatile
        // FIXME: is this necessary?
        (struct_ == "aiocb" && field == "aio_buf")
    });

    cfg.skip_field(move |struct_, field| {
        // this is actually a union on linux, so we can't represent it well and
        // just insert some padding.
        // FIXME: is this necessary?
        (struct_ == "siginfo_t" && field == "_pad") ||
        // musl names this __dummy1 but it's still there
        // FIXME: is this necessary?
        (struct_ == "glob_t" && field == "gl_flags") ||
        // musl seems to define this as an *anonymous* bitfield
        // FIXME: is this necessary?
        (struct_ == "statvfs" && field == "__f_unused") ||
        // sigev_notify_thread_id is actually part of a sigev_un union
        (struct_ == "sigevent" && field == "sigev_notify_thread_id") ||
        // signalfd had SIGSYS fields added in Linux 4.18, but no libc release has them yet.
        (struct_ == "signalfd_siginfo" && (field == "ssi_addr_lsb" ||
                                           field == "_pad2" ||
                                           field == "ssi_syscall" ||
                                           field == "ssi_call_addr" ||
                                           field == "ssi_arch"))
    });

    // FIXME: test linux like
    cfg.generate("../src/lib.rs", "main.rs");
}

fn test_vxworks(target: &str) {
    assert!(target.contains("vxworks"));

    let mut cfg = ctest::TestGenerator::new();
    headers! { cfg:
               "vxWorks.h",
               "yvals.h",
               "nfs/nfsCommon.h",
               "rtpLibCommon.h",
               "randomNumGen.h",
               "taskLib.h",
               "sysLib.h",
               "ioLib.h",
               "inetLib.h",
               "socket.h",
               "errnoLib.h",
               "ctype.h",
               "dirent.h",
               "dlfcn.h",
               "elf.h",
               "fcntl.h",
               "grp.h",
               "sys/poll.h",
               "ifaddrs.h",
               "langinfo.h",
               "limits.h",
               "link.h",
               "locale.h",
               "sys/stat.h",
               "netdb.h",
               "pthread.h",
               "pwd.h",
               "sched.h",
               "semaphore.h",
               "signal.h",
               "stddef.h",
               "stdint.h",
               "stdio.h",
               "stdlib.h",
               "string.h",
               "sys/file.h",
               "sys/ioctl.h",
               "sys/socket.h",
               "sys/time.h",
               "sys/times.h",
               "sys/types.h",
               "sys/uio.h",
               "sys/un.h",
               "sys/utsname.h",
               "sys/wait.h",
               "netinet/tcp.h",
               "syslog.h",
               "termios.h",
               "time.h",
               "ucontext.h",
               "unistd.h",
               "utime.h",
               "wchar.h",
               "errno.h",
               "sys/mman.h",
               "pathLib.h",
               "mqueue.h",
    }
    // FIXME
    cfg.skip_const(move |name| match name {
        // sighandler_t weirdness
        "SIG_DFL" | "SIG_ERR" | "SIG_IGN"
        // This is not defined in vxWorks
        | "RTLD_DEFAULT"   => true,
        _ => false,
    });
    // FIXME
    cfg.skip_type(move |ty| match ty {
        "stat64" | "sighandler_t" | "off64_t" => true,
        _ => false,
    });

    cfg.skip_field_type(move |struct_, field| match (struct_, field) {
        ("siginfo_t", "si_value") | ("stat", "st_size") | ("sigaction", "sa_u") => true,
        _ => false,
    });

    cfg.skip_roundtrip(move |s| match s {
        _ => false,
    });

    cfg.type_name(move |ty, is_struct, is_union| match ty {
        "DIR" | "FILE" | "Dl_info" | "RTP_DESC" => ty.to_string(),
        t if is_union => format!("union {}", t),
        t if t.ends_with("_t") => t.to_string(),
        t if is_struct => format!("struct {}", t),
        t => t.to_string(),
    });

    // FIXME
    cfg.skip_fn(move |name| match name {
        // sigval
        "sigqueue" | "_sigqueue"
        // sighandler_t
        | "signal"
        // not used in static linking by default
        | "dlerror" => true,
        _ => false,
    });

    cfg.generate("../src/lib.rs", "main.rs");
}

fn test_linux(target: &str) {
    assert!(target.contains("linux"));

    // target_env
    let gnu = target.contains("gnu");
    let musl = target.contains("musl");
    let uclibc = target.contains("uclibc");

    match (gnu, musl, uclibc) {
        (true, false, false) => (),
        (false, true, false) => (),
        (false, false, true) => (),
        (_, _, _) => panic!(
            "linux target lib is gnu: {}, musl: {}, uclibc: {}",
            gnu, musl, uclibc
        ),
    }

    let arm = target.contains("arm");
    let i686 = target.contains("i686");
    let mips = target.contains("mips");
    let mips32 = mips && !target.contains("64");
    let mips64 = mips && target.contains("64");
    let ppc64 = target.contains("powerpc64");
    let s390x = target.contains("s390x");
    let sparc64 = target.contains("sparc64");
    let x32 = target.contains("x32");
    let x86_32 = target.contains("i686");
    let x86_64 = target.contains("x86_64");
    let aarch64_musl = target.contains("aarch64") && musl;
    let gnuabihf = target.contains("gnueabihf");
    let x86_64_gnux32 = target.contains("gnux32") && x86_64;
    let riscv64 = target.contains("riscv64");
    let uclibc = target.contains("uclibc");

    let mut cfg = ctest_cfg();
    cfg.define("_GNU_SOURCE", None);
    // This macro re-deifnes fscanf,scanf,sscanf to link to the symbols that are
    // deprecated since glibc >= 2.29. This allows Rust binaries to link against
    // glibc versions older than 2.29.
    cfg.define("__GLIBC_USE_DEPRECATED_SCANF", None);

    headers! { cfg:
               "ctype.h",
               "dirent.h",
               "dlfcn.h",
               "elf.h",
               "fcntl.h",
               "glob.h",
               "grp.h",
               "iconv.h",
               "ifaddrs.h",
               "langinfo.h",
               "limits.h",
               "link.h",
               "locale.h",
               "malloc.h",
               "mntent.h",
               "mqueue.h",
               "net/ethernet.h",
               "net/if.h",
               "net/if_arp.h",
               "net/route.h",
               "netdb.h",
               "netinet/in.h",
               "netinet/ip.h",
               "netinet/tcp.h",
               "netinet/udp.h",
               "netpacket/packet.h",
               "poll.h",
               "pthread.h",
               "pty.h",
               "pwd.h",
               "regex.h",
               "resolv.h",
               "sched.h",
               "semaphore.h",
               "shadow.h",
               "signal.h",
               "spawn.h",
               "stddef.h",
               "stdint.h",
               "stdio.h",
               "stdlib.h",
               "string.h",
               "sys/epoll.h",
               "sys/eventfd.h",
               "sys/file.h",
               "sys/fsuid.h",
               "sys/inotify.h",
               "sys/ioctl.h",
               "sys/ipc.h",
               "sys/mman.h",
               "sys/mount.h",
               "sys/msg.h",
               "sys/personality.h",
               "sys/prctl.h",
               "sys/ptrace.h",
               "sys/quota.h",
               "sys/random.h",
               "sys/reboot.h",
               "sys/resource.h",
               "sys/sem.h",
               "sys/sendfile.h",
               "sys/shm.h",
               "sys/signalfd.h",
               "sys/socket.h",
               "sys/stat.h",
               "sys/statvfs.h",
               "sys/swap.h",
               "sys/syscall.h",
               "sys/time.h",
               "sys/timerfd.h",
               "sys/times.h",
               "sys/timex.h",
               "sys/types.h",
               "sys/uio.h",
               "sys/un.h",
               "sys/user.h",
               "sys/utsname.h",
               "sys/vfs.h",
               "sys/wait.h",
               "syslog.h",
               "termios.h",
               "time.h",
               "ucontext.h",
               "unistd.h",
               "utime.h",
               "utmp.h",
               "utmpx.h",
               "wchar.h",
               "errno.h",
               // `sys/io.h` is only available on x86*, Alpha, IA64, and 32-bit
               // ARM: https://bugzilla.redhat.com/show_bug.cgi?id=1116162
               // Also unavailable on gnuabihf with glibc 2.30.
               // https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=6b33f373c7b9199e00ba5fbafd94ac9bfb4337b1
               [(x86_64 || x86_32 || arm) && !gnuabihf]: "sys/io.h",
               // `sys/reg.h` is only available on x86 and x86_64
               [x86_64 || x86_32]: "sys/reg.h",
               // sysctl system call is deprecated and not available on musl
               // It is also unsupported in x32, deprecated since glibc 2.30:
               [!(x32 || musl || gnu)]: "sys/sysctl.h",
               // <execinfo.h> is not supported by musl:
               // https://www.openwall.com/lists/musl/2015/04/09/3
               // <execinfo.h> is not present on uclibc.
               [!(musl || uclibc)]: "execinfo.h",
    }

    // Include linux headers at the end:
    headers! {
        cfg:
        "asm/mman.h",
        "linux/can.h",
        "linux/dccp.h",
        "linux/errqueue.h",
        "linux/falloc.h",
        "linux/fs.h",
        "linux/futex.h",
        "linux/genetlink.h",
        "linux/if.h",
        "linux/if_addr.h",
        "linux/if_alg.h",
        "linux/if_ether.h",
        "linux/if_tun.h",
        "linux/input.h",
        "linux/keyctl.h",
        "linux/magic.h",
        "linux/memfd.h",
        "linux/mman.h",
        "linux/module.h",
        "linux/net_tstamp.h",
        "linux/netfilter/nfnetlink.h",
        "linux/netfilter/nfnetlink_log.h",
        "linux/netfilter/nfnetlink_queue.h",
        "linux/netfilter/nf_tables.h",
        "linux/netfilter_ipv4.h",
        "linux/netfilter_ipv6.h",
        "linux/netfilter_ipv6/ip6_tables.h",
        "linux/netlink.h",
        "linux/quota.h",
        "linux/random.h",
        "linux/reboot.h",
        "linux/rtnetlink.h",
        "linux/seccomp.h",
        "linux/sockios.h",
        "linux/uinput.h",
        "linux/vm_sockets.h",
        "linux/wait.h",
        "sys/fanotify.h",
        // <sys/auxv.h> is not present on uclibc
        [!uclibc]: "sys/auxv.h",
    }

    // note: aio.h must be included before sys/mount.h
    headers! {
        cfg:
        "sys/xattr.h",
        "sys/sysinfo.h",
        // AIO is not supported by uclibc:
        [!uclibc]: "aio.h",
    }

    cfg.type_name(move |ty, is_struct, is_union| {
        match ty {
            // Just pass all these through, no need for a "struct" prefix
            "FILE" | "fd_set" | "Dl_info" | "DIR" | "Elf32_Phdr" | "Elf64_Phdr" | "Elf32_Shdr"
            | "Elf64_Shdr" | "Elf32_Sym" | "Elf64_Sym" | "Elf32_Ehdr" | "Elf64_Ehdr"
            | "Elf32_Chdr" | "Elf64_Chdr" => ty.to_string(),

            t if is_union => format!("union {}", t),

            t if t.ends_with("_t") => t.to_string(),

            // In MUSL `flock64` is a typedef to `flock`.
            "flock64" if musl => format!("struct {}", ty),

            // put `struct` in front of all structs:.
            t if is_struct => format!("struct {}", t),

            t => t.to_string(),
        }
    });

    cfg.field_name(move |struct_, field| {
        match field {
            // Our stat *_nsec fields normally don't actually exist but are part
            // of a timeval struct
            s if s.ends_with("_nsec") && struct_.starts_with("stat") => {
                s.replace("e_nsec", ".tv_nsec")
            }
            // FIXME: epoll_event.data is actually a union in C, but in Rust
            // it is only a u64 because we only expose one field
            // http://man7.org/linux/man-pages/man2/epoll_wait.2.html
            "u64" if struct_ == "epoll_event" => "data.u64".to_string(),
            // The following structs have a field called `type` in C,
            // but `type` is a Rust keyword, so these fields are translated
            // to `type_` in Rust.
            "type_"
                if struct_ == "input_event"
                    || struct_ == "input_mask"
                    || struct_ == "ff_effect" =>
            {
                "type".to_string()
            }

            s => s.to_string(),
        }
    });

    cfg.skip_type(move |ty| {
        match ty {
            // FIXME: `sighandler_t` type is incorrect, see:
            // https://github.com/rust-lang/libc/issues/1359
            "sighandler_t" => true,

            // These cannot be tested when "resolv.h" is included and are tested
            // in the `linux_elf.rs` file.
            "Elf64_Phdr" | "Elf32_Phdr" => true,

            // This type is private on Linux. It is implemented as a C `enum`
            // (`c_uint`) and this clashes with the type of the `rlimit` APIs
            // which expect a `c_int` even though both are ABI compatible.
            "__rlimit_resource_t" => true,
            // on Linux, this is a volatile int
            "pthread_spinlock_t" => true,

            _ => false,
        }
    });

    cfg.skip_struct(move |ty| {
        if ty.starts_with("__c_anonymous_") {
            return true;
        }
        // FIXME: musl CI has old headers
        if (musl || sparc64) && ty.starts_with("uinput_") {
            return true;
        }
        match ty {
            // These cannot be tested when "resolv.h" is included and are tested
            // in the `linux_elf.rs` file.
            "Elf64_Phdr" | "Elf32_Phdr" => true,

            // On Linux, the type of `ut_tv` field of `struct utmpx`
            // can be an anonymous struct, so an extra struct,
            // which is absent in glibc, has to be defined.
            "__timeval" => true,

            // FIXME: This is actually a union, not a struct
            "sigval" => true,

            // This type is tested in the `linux_termios.rs` file since there
            // are header conflicts when including them with all the other
            // structs.
            "termios2" => true,

            // FIXME: remove once we set minimum supported glibc version.
            // ucontext_t added a new field as of glibc 2.28; our struct definition is
            // conservative and omits the field, but that means the size doesn't match for newer
            // glibcs (see https://github.com/rust-lang/libc/issues/1410)
            "ucontext_t" if gnu => true,

            // FIXME: Somehow we cannot include headers correctly in glibc 2.30.
            // So let's ignore for now and re-visit later.
            // Probably related: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91085
            "statx" => true,
            "statx_timestamp" => true,

            // On Linux, the type of `ut_exit` field of struct `utmpx`
            // can be an anonymous struct, so an extra struct,
            // which is absent in musl, has to be defined.
            "__exit_status" if musl => true,

            // FIXME: CI's kernel header version is old.
            "sockaddr_can" => true,

            // Requires glibc 2.33 or newer.
            "mallinfo2" => true,

            _ => false,
        }
    });

    cfg.skip_const(move |name| {
        if !gnu {
            // Skip definitions from the kernel on non-glibc Linux targets.
            // They're libc-independent, so we only need to check them on one
            // libc. We don't want to break CI if musl or another libc doesn't
            // have the definitions yet. (We do still want to check them on
            // every glibc target, though, as some of them can vary by
            // architecture.)
            //
            // This is not an exhaustive list of kernel constants, just a list
            // of prefixes of all those that have appeared here or that get
            // updated regularly and seem likely to cause breakage.
            if name.starts_with("AF_")
                || name.starts_with("ARPHRD_")
                || name.starts_with("EPOLL")
                || name.starts_with("F_")
                || name.starts_with("FALLOC_FL_")
                || name.starts_with("IFLA_")
                || name.starts_with("MS_")
                || name.starts_with("MSG_")
                || name.starts_with("P_")
                || name.starts_with("PF_")
                || name.starts_with("RLIMIT_")
                || name.starts_with("SOL_")
                || name.starts_with("STATX_")
                || name.starts_with("SW_")
                || name.starts_with("SYS_")
                || name.starts_with("TCP_")
                || name.starts_with("UINPUT_")
                || name.starts_with("VMADDR_")
            {
                return true;
            }
        }
        match name {
            // These constants are not available if gnu headers have been included
            // and can therefore not be tested here
            //
            // The IPV6 constants are tested in the `linux_ipv6.rs` tests:
            | "IPV6_FLOWINFO"
            | "IPV6_FLOWLABEL_MGR"
            | "IPV6_FLOWINFO_SEND"
            | "IPV6_FLOWINFO_FLOWLABEL"
            | "IPV6_FLOWINFO_PRIORITY"
            // The F_ fnctl constants are tested in the `linux_fnctl.rs` tests:
            | "F_CANCELLK"
            | "F_ADD_SEALS"
            | "F_GET_SEALS"
            | "F_SEAL_SEAL"
            | "F_SEAL_SHRINK"
            | "F_SEAL_GROW"
            | "F_SEAL_WRITE" => true,
            // The `ARPHRD_CAN` is tested in the `linux_if_arp.rs` tests
            // because including `linux/if_arp.h` causes some conflicts:
            "ARPHRD_CAN" => true,

            // Require Linux kernel 5.1:
            "F_SEAL_FUTURE_WRITE" => true,

            // FIXME: deprecated: not available in any header
            // See: https://github.com/rust-lang/libc/issues/1356
            "ENOATTR" => true,

            // FIXME: SIGUNUSED was removed in glibc 2.26
            // Users should use SIGSYS instead.
            "SIGUNUSED" => true,

            // FIXME: conflicts with glibc headers and is tested in
            // `linux_termios.rs` below:
            "BOTHER" => true,

            // FIXME: on musl the pthread types are defined a little differently
            // - these constants are used by the glibc implementation.
            n if musl && n.contains("__SIZEOF_PTHREAD") => true,

            // FIXME: It was extended to 4096 since glibc 2.31 (Linux 5.4).
            // We should do so after a while.
            "SOMAXCONN" if gnu => true,

            // deprecated: not available from Linux kernel 5.6:
            "VMADDR_CID_RESERVED" => true,

            // Require Linux kernel 5.6:
            "VMADDR_CID_LOCAL" => true,

            // Requires Linux kernel 5.7:
            "MREMAP_DONTUNMAP" => true,

            // IPPROTO_MAX was increased in 5.6 for IPPROTO_MPTCP:
            | "IPPROTO_MAX"
            | "IPPROTO_MPTCP" => true,

            // FIXME: Not currently available in headers
            "P_PIDFD" if mips => true,
            "SYS_pidfd_open" if mips => true,

            // FIXME: Not currently available in headers on MIPS
            // Not yet implemented on sparc64
            "SYS_clone3" if mips | sparc64 => true,

            // FIXME: these syscalls were added in Linux 5.9 or later
            // and are currently not included in the glibc headers.
            | "SYS_close_range"
            | "SYS_openat2"
            | "SYS_pidfd_getfd"
            | "SYS_faccessat2"
            | "SYS_process_madvise"
            | "SYS_epoll_pwait2"
            | "SYS_mount_setattr" => true,

            // Requires more recent kernel headers:
            | "IFLA_PROP_LIST"
            | "IFLA_ALT_IFNAME"
            | "IFLA_PERM_ADDRESS"
            | "IFLA_PROTO_DOWN_REASON" => true,

            // FIXME: They require recent kernel header:
            | "CAN_J1939"
            | "CAN_RAW_FILTER_MAX"
            | "CAN_NPROTO" => true,

            // FIXME: Requires recent kernel headers (5.8):
            "STATX_MNT_ID" => true,

            // FIXME: requires more recent kernel headers on CI
            | "UINPUT_VERSION"
            | "SW_MAX"
            | "SW_CNT"
                if mips || ppc64 || riscv64 || sparc64 => true,

            _ => false,
        }
    });

    cfg.skip_fn(move |name| {
        // skip those that are manually verified
        match name {
            // FIXME: https://github.com/rust-lang/libc/issues/1272
            "execv" | "execve" | "execvp" | "execvpe" | "fexecve" => true,

            // There are two versions of the sterror_r function, see
            //
            // https://linux.die.net/man/3/strerror_r
            //
            // An XSI-compliant version provided if:
            //
            // (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600)
            //  && ! _GNU_SOURCE
            //
            // and a GNU specific version provided if _GNU_SOURCE is defined.
            //
            // libc provides bindings for the XSI-compliant version, which is
            // preferred for portable applications.
            //
            // We skip the test here since here _GNU_SOURCE is defined, and
            // test the XSI version below.
            "strerror_r" => true,

            // FIXME: Our API is unsound. The Rust API allows aliasing
            // pointers, but the C API requires pointers not to alias.
            // We should probably be at least using `&`/`&mut` here, see:
            // https://github.com/gnzlbg/ctest/issues/68
            "lio_listio" if musl => true,

            // FIXME: the glibc version used by the Sparc64 build jobs
            // which use Debian 10.0 is too old.
            "statx" if sparc64 => true,

            // FIXME: Deprecated since glibc 2.30. Remove fn once upstream does.
            "sysctl" if gnu => true,

            // FIXME: It now takes c_void instead of timezone since glibc 2.31.
            "gettimeofday" if gnu => true,

            // These are all implemented as static inline functions in uclibc, so
            // they cannot be linked against.
            // If implementations are required, they might need to be implemented
            // in this crate.
            "posix_spawnattr_init" if uclibc => true,
            "posix_spawnattr_destroy" if uclibc => true,
            "posix_spawnattr_getsigdefault" if uclibc => true,
            "posix_spawnattr_setsigdefault" if uclibc => true,
            "posix_spawnattr_getsigmask" if uclibc => true,
            "posix_spawnattr_setsigmask" if uclibc => true,
            "posix_spawnattr_getflags" if uclibc => true,
            "posix_spawnattr_setflags" if uclibc => true,
            "posix_spawnattr_getpgroup" if uclibc => true,
            "posix_spawnattr_setpgroup" if uclibc => true,
            "posix_spawnattr_getschedpolicy" if uclibc => true,
            "posix_spawnattr_setschedpolicy" if uclibc => true,
            "posix_spawnattr_getschedparam" if uclibc => true,
            "posix_spawnattr_setschedparam" if uclibc => true,
            "posix_spawn_file_actions_init" if uclibc => true,
            "posix_spawn_file_actions_destroy" if uclibc => true,

            // uclibc defines the flags type as a uint, but dependent crates
            // assume it's a int instead.
            "getnameinfo" if uclibc => true,

            // FIXME: This needs musl 1.2.2 or later.
            "gettid" if musl => true,

            // Needs glibc 2.33 or later.
            "mallinfo2" => true,

            "reallocarray" if musl => true,

            _ => false,
        }
    });

    cfg.skip_field_type(move |struct_, field| {
        // This is a weird union, don't check the type.
        (struct_ == "ifaddrs" && field == "ifa_ifu") ||
        // sighandler_t type is super weird
        (struct_ == "sigaction" && field == "sa_sigaction") ||
        // __timeval type is a patch which doesn't exist in glibc
        (struct_ == "utmpx" && field == "ut_tv") ||
        // sigval is actually a union, but we pretend it's a struct
        (struct_ == "sigevent" && field == "sigev_value") ||
        // this one is an anonymous union
        (struct_ == "ff_effect" && field == "u") ||
        // `__exit_status` type is a patch which is absent in musl
        (struct_ == "utmpx" && field == "ut_exit" && musl) ||
        // `can_addr` is an anonymous union
        (struct_ == "sockaddr_can" && field == "can_addr")
    });

    cfg.volatile_item(|i| {
        use ctest::VolatileItemKind::*;
        match i {
            // aio_buf is a volatile void** but since we cannot express that in
            // Rust types, we have to explicitly tell the checker about it here:
            StructField(ref n, ref f) if n == "aiocb" && f == "aio_buf" => true,
            _ => false,
        }
    });

    cfg.skip_field(move |struct_, field| {
        // this is actually a union on linux, so we can't represent it well and
        // just insert some padding.
        (struct_ == "siginfo_t" && field == "_pad") ||
        // musl names this __dummy1 but it's still there
        (musl && struct_ == "glob_t" && field == "gl_flags") ||
        // musl seems to define this as an *anonymous* bitfield
        (musl && struct_ == "statvfs" && field == "__f_unused") ||
        // sigev_notify_thread_id is actually part of a sigev_un union
        (struct_ == "sigevent" && field == "sigev_notify_thread_id") ||
        // signalfd had SIGSYS fields added in Linux 4.18, but no libc release
        // has them yet.
        (struct_ == "signalfd_siginfo" && (field == "ssi_addr_lsb" ||
                                           field == "_pad2" ||
                                           field == "ssi_syscall" ||
                                           field == "ssi_call_addr" ||
                                           field == "ssi_arch")) ||
        // FIXME: After musl 1.1.24, it have only one field `sched_priority`,
        // while other fields become reserved.
        (struct_ == "sched_param" && [
            "sched_ss_low_priority",
            "sched_ss_repl_period",
            "sched_ss_init_budget",
            "sched_ss_max_repl",
        ].contains(&field) && musl) ||
        // FIXME: After musl 1.1.24, the type becomes `int` instead of `unsigned short`.
        (struct_ == "ipc_perm" && field == "__seq" && aarch64_musl) ||
        // glibc uses unnamed fields here and Rust doesn't support that yet
        (struct_ == "timex" && field.starts_with("__unused")) ||
        // FIXME: It now takes mode_t since glibc 2.31 on some targets.
        (struct_ == "ipc_perm" && field == "mode"
            && ((x86_64 || i686 || arm || riscv64) && gnu || x86_64_gnux32)
        )
    });

    cfg.skip_roundtrip(move |s| match s {
        // FIXME:
        "utsname" if mips32 || mips64 => true,
        // FIXME:
        "mcontext_t" if s390x => true,
        // FIXME: This is actually a union.
        "fpreg_t" if s390x => true,

        "sockaddr_un" | "sembuf" | "ff_constant_effect" if mips32 && (gnu || musl) => true,
        "ipv6_mreq"
        | "ip_mreq_source"
        | "sockaddr_in6"
        | "sockaddr_ll"
        | "in_pktinfo"
        | "arpreq"
        | "arpreq_old"
        | "sockaddr_un"
        | "ff_constant_effect"
        | "ff_ramp_effect"
        | "ff_condition_effect"
        | "Elf32_Ehdr"
        | "Elf32_Chdr"
        | "ucred"
        | "in6_pktinfo"
        | "sockaddr_nl"
        | "termios"
        | "nlmsgerr"
            if (mips64 || sparc64) && gnu =>
        {
            true
        }

        // FIXME: the call ABI of max_align_t is incorrect on these platforms:
        "max_align_t" if i686 || mips64 || ppc64 => true,

        _ => false,
    });

    cfg.generate("../src/lib.rs", "main.rs");

    test_linux_like_apis(target);
}

// This function tests APIs that are incompatible to test when other APIs
// are included (e.g. because including both sets of headers clashes)
fn test_linux_like_apis(target: &str) {
    let musl = target.contains("musl");
    let linux = target.contains("linux");
    let emscripten = target.contains("emscripten");
    let android = target.contains("android");
    assert!(linux || android || emscripten);

    if linux || android || emscripten {
        // test strerror_r from the `string.h` header
        let mut cfg = ctest_cfg();
        cfg.skip_type(|_| true).skip_static(|_| true);

        headers! { cfg: "string.h" }
        cfg.skip_fn(|f| match f {
            "strerror_r" => false,
            _ => true,
        })
        .skip_const(|_| true)
        .skip_struct(|_| true);
        cfg.generate("../src/lib.rs", "linux_strerror_r.rs");
    }

    if linux || android || emscripten {
        // test fcntl - see:
        // http://man7.org/linux/man-pages/man2/fcntl.2.html
        let mut cfg = ctest_cfg();

        if musl {
            cfg.header("fcntl.h");
        } else {
            cfg.header("linux/fcntl.h");
        }

        cfg.skip_type(|_| true)
            .skip_static(|_| true)
            .skip_struct(|_| true)
            .skip_fn(|_| true)
            .skip_const(move |name| match name {
                // test fcntl constants:
                "F_CANCELLK" | "F_ADD_SEALS" | "F_GET_SEALS" | "F_SEAL_SEAL" | "F_SEAL_SHRINK"
                | "F_SEAL_GROW" | "F_SEAL_WRITE" => false,
                _ => true,
            })
            .type_name(move |ty, is_struct, is_union| match ty {
                t if is_struct => format!("struct {}", t),
                t if is_union => format!("union {}", t),
                t => t.to_string(),
            });

        cfg.generate("../src/lib.rs", "linux_fcntl.rs");
    }

    if linux || android {
        // test termios
        let mut cfg = ctest_cfg();
        cfg.header("asm/termbits.h");
        cfg.skip_type(|_| true)
            .skip_static(|_| true)
            .skip_fn(|_| true)
            .skip_const(|c| c != "BOTHER")
            .skip_struct(|s| s != "termios2")
            .type_name(move |ty, is_struct, is_union| match ty {
                t if is_struct => format!("struct {}", t),
                t if is_union => format!("union {}", t),
                t => t.to_string(),
            });
        cfg.generate("../src/lib.rs", "linux_termios.rs");
    }

    if linux || android {
        // test IPV6_ constants:
        let mut cfg = ctest_cfg();
        headers! {
            cfg:
            "linux/in6.h"
        }
        cfg.skip_type(|_| true)
            .skip_static(|_| true)
            .skip_fn(|_| true)
            .skip_const(|_| true)
            .skip_struct(|_| true)
            .skip_const(move |name| match name {
                "IPV6_FLOWINFO"
                | "IPV6_FLOWLABEL_MGR"
                | "IPV6_FLOWINFO_SEND"
                | "IPV6_FLOWINFO_FLOWLABEL"
                | "IPV6_FLOWINFO_PRIORITY" => false,
                _ => true,
            })
            .type_name(move |ty, is_struct, is_union| match ty {
                t if is_struct => format!("struct {}", t),
                t if is_union => format!("union {}", t),
                t => t.to_string(),
            });
        cfg.generate("../src/lib.rs", "linux_ipv6.rs");
    }

    if linux || android {
        // Test Elf64_Phdr and Elf32_Phdr
        // These types have a field called `p_type`, but including
        // "resolve.h" defines a `p_type` macro that expands to `__p_type`
        // making the tests for these fails when both are included.
        let mut cfg = ctest_cfg();
        cfg.header("elf.h");
        cfg.skip_fn(|_| true)
            .skip_static(|_| true)
            .skip_const(|_| true)
            .type_name(move |ty, _is_struct, _is_union| ty.to_string())
            .skip_struct(move |ty| match ty {
                "Elf64_Phdr" | "Elf32_Phdr" => false,
                _ => true,
            })
            .skip_type(move |ty| match ty {
                "Elf64_Phdr" | "Elf32_Phdr" => false,
                _ => true,
            });
        cfg.generate("../src/lib.rs", "linux_elf.rs");
    }

    if linux || android {
        // Test `ARPHRD_CAN`.
        let mut cfg = ctest_cfg();
        cfg.header("linux/if_arp.h");
        cfg.skip_fn(|_| true)
            .skip_static(|_| true)
            .skip_const(move |name| match name {
                "ARPHRD_CAN" => false,
                _ => true,
            })
            .skip_struct(|_| true)
            .skip_type(|_| true);
        cfg.generate("../src/lib.rs", "linux_if_arp.rs");
    }
}

fn which_freebsd() -> Option<i32> {
    let output = std::process::Command::new("freebsd-version")
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }

    let stdout = String::from_utf8(output.stdout).ok()?;

    match &stdout {
        s if s.starts_with("10") => Some(10),
        s if s.starts_with("11") => Some(11),
        s if s.starts_with("12") => Some(12),
        s if s.starts_with("13") => Some(13),
        _ => None,
    }
}

fn test_haiku(target: &str) {
    assert!(target.contains("haiku"));

    let mut cfg = ctest_cfg();
    cfg.flag("-Wno-deprecated-declarations");
    cfg.define("__USE_GNU", Some("1"));

    // POSIX API
    headers! { cfg:
               "alloca.h",
               "arpa/inet.h",
               "arpa/nameser.h",
               "arpa/nameser_compat.h",
               "assert.h",
               "bsd_mem.h",
               "complex.h",
               "ctype.h",
               "dirent.h",
               "div_t.h",
               "dlfcn.h",
               "endian.h",
               "errno.h",
               "fcntl.h",
               "fenv.h",
               "fnmatch.h",
               "fts.h",
               "ftw.h",
               "getopt.h",
               "glob.h",
               "grp.h",
               "inttypes.h",
               "iovec.h",
               "langinfo.h",
               "libgen.h",
               "libio.h",
               "limits.h",
               "locale.h",
               "malloc.h",
               "malloc_debug.h",
               "math.h",
               "memory.h",
               "monetary.h",
               "net/if.h",
               "net/if_dl.h",
               "net/if_media.h",
               "net/if_tun.h",
               "net/if_types.h",
               "net/route.h",
               "netdb.h",
               "netinet/icmp6.h",
               "netinet/in.h",
               "netinet/ip.h",
               "netinet/ip6.h",
               "netinet/ip_icmp.h",
               "netinet/ip_var.h",
               "netinet/tcp.h",
               "netinet/udp.h",
               "netinet6/in6.h",
               "nl_types.h",
               "null.h",
               "poll.h",
               "pthread.h",
               "pwd.h",
               "regex.h",
               "resolv.h",
               "sched.h",
               "search.h",
               "semaphore.h",
               "setjmp.h",
               "shadow.h",
               "signal.h",
               "size_t.h",
               "spawn.h",
               "stdint.h",
               "stdio.h",
               "stdlib.h",
               "string.h",
               "strings.h",
               "sys/cdefs.h",
               "sys/file.h",
               "sys/ioctl.h",
               "sys/ipc.h",
               "sys/mman.h",
               "sys/msg.h",
               "sys/param.h",
               "sys/poll.h",
               "sys/resource.h",
               "sys/select.h",
               "sys/sem.h",
               "sys/socket.h",
               "sys/sockio.h",
               "sys/stat.h",
               "sys/statvfs.h",
               "sys/time.h",
               "sys/timeb.h",
               "sys/times.h",
               "sys/types.h",
               "sys/uio.h",
               "sys/un.h",
               "sys/utsname.h",
               "sys/wait.h",
               "syslog.h",
               "tar.h",
               "termios.h",
               "time.h",
               "uchar.h",
               "unistd.h",
               "utime.h",
               "wchar.h",
               "wchar_t.h",
               "wctype.h"
    }

    // BSD Extensions
    headers! { cfg:
               "pty.h",
    }

    // Native API
    headers! { cfg:
               "kernel/OS.h",
               "kernel/fs_attr.h",
               "kernel/fs_index.h",
               "kernel/fs_info.h",
               "kernel/fs_query.h",
               "kernel/fs_volume.h",
               "kernel/image.h",
               "kernel/scheduler.h",
               "storage/FindDirectory.h",
               "storage/StorageDefs.h",
               "support/Errors.h",
               "support/SupportDefs.h",
               "support/TypeConstants.h"
    }

    cfg.skip_struct(move |ty| {
        if ty.starts_with("__c_anonymous_") {
            return true;
        }
        match ty {
            // FIXME: actually a union
            "sigval" => true,
            // FIXME: locale_t does not exist on Haiku
            "locale_t" => true,
            // FIXME: rusage has a different layout on Haiku
            "rusage" => true,
            // FIXME?: complains that rust aligns on 4 byte boundary, but
            //         Haiku does not align it at all.
            "in6_addr" => true,
            // The d_name attribute is an array of 1 on Haiku, with the
            // intention that the developer allocates a larger or smaller
            // piece of memory depending on the expected/actual size of the name.
            // Other platforms have sensible defaults. In Rust, the d_name field
            // is sized as the _POSIX_MAX_PATH, so that path names will fit in
            // newly allocated dirent objects. This breaks the automated tests.
            "dirent" => true,
            // The following structs contain function pointers, which cannot be initialized
            // with mem::zeroed(), so skip the automated test
            "image_info" | "thread_info" => true,

            _ => false,
        }
    });

    cfg.skip_type(move |ty| {
        match ty {
            // FIXME: locale_t does not exist on Haiku
            "locale_t" => true,
            // These cause errors, to be reviewed in the future
            "sighandler_t" => true,
            "pthread_t" => true,
            "pthread_condattr_t" => true,
            "pthread_mutexattr_t" => true,
            "pthread_rwlockattr_t" => true,
            _ => false,
        }
    });

    cfg.skip_fn(move |name| {
        // skip those that are manually verified
        match name {
            // FIXME: https://github.com/rust-lang/libc/issues/1272
            "execv" | "execve" | "execvp" | "execvpe" => true,
            // FIXME: does not exist on haiku
            "open_wmemstream" => true,
            "mlockall" | "munlockall" => true,
            "tcgetsid" => true,
            "cfsetspeed" => true,
            // ignore for now, will be part of Haiku R1 beta 3
            "mlock" | "munlock" => true,
            // returns const char * on Haiku
            "strsignal" => true,
            // uses an enum as a parameter argument, which is incorrectly
            // translated into a struct argument
            "find_path" => true,

            _ => false,
        }
    });

    cfg.skip_const(move |name| {
        match name {
            // FIXME: these constants do not exist on Haiku
            "DT_UNKNOWN" | "DT_FIFO" | "DT_CHR" | "DT_DIR" | "DT_BLK" | "DT_REG" | "DT_LNK"
            | "DT_SOCK" => true,
            "USRQUOTA" | "GRPQUOTA" => true,
            "SIGIOT" => true,
            "ARPOP_REQUEST" | "ARPOP_REPLY" | "ATF_COM" | "ATF_PERM" | "ATF_PUBL"
            | "ATF_USETRAILERS" => true,
            // Haiku does not have MAP_FILE, but rustc requires it
            "MAP_FILE" => true,
            // The following does not exist on Haiku but is required by
            // several crates
            "FIOCLEX" => true,
            // just skip this one, it is not defined on Haiku beta 2 but
            // since it is meant as a mask and not a parameter it can exist
            // here
            "LOG_PRIMASK" => true,
            // not defined on Haiku, but [get|set]priority is, so they are
            // useful
            "PRIO_MIN" | "PRIO_MAX" => true,
            //
            _ => false,
        }
    });

    cfg.skip_field(move |struct_, field| {
        match (struct_, field) {
            // FIXME: the stat struct actually has timespec members, whereas
            //        the current representation has these unpacked.
            ("stat", "st_atime") => true,
            ("stat", "st_atime_nsec") => true,
            ("stat", "st_mtime") => true,
            ("stat", "st_mtime_nsec") => true,
            ("stat", "st_ctime") => true,
            ("stat", "st_ctime_nsec") => true,
            ("stat", "st_crtime") => true,
            ("stat", "st_crtime_nsec") => true,

            // these are actually unions, but we cannot represent it well
            ("siginfo_t", "sigval") => true,
            ("sem_t", "named_sem_id") => true,
            ("sigaction", "sa_sigaction") => true,
            ("sigevent", "sigev_value") => true,
            ("fpu_state", "_fpreg") => true,
            // these fields have a simplified data definition in libc
            ("fpu_state", "_xmm") => true,
            ("savefpu", "_fp_ymm") => true,

            // skip these enum-type fields
            ("thread_info", "state") => true,
            ("image_info", "image_type") => true,
            _ => false,
        }
    });

    cfg.skip_roundtrip(move |s| match s {
        // FIXME: for some reason the roundtrip check fails for cpu_info
        "cpu_info" => true,
        _ => false,
    });

    cfg.type_name(move |ty, is_struct, is_union| {
        match ty {
            // Just pass all these through, no need for a "struct" prefix
            "area_info" | "port_info" | "port_message_info" | "team_info" | "sem_info"
            | "team_usage_info" | "thread_info" | "cpu_info" | "system_info"
            | "object_wait_info" | "image_info" | "attr_info" | "index_info" | "fs_info"
            | "FILE" | "DIR" | "Dl_info" => ty.to_string(),

            // is actually a union
            "sigval" => format!("union sigval"),
            t if is_union => format!("union {}", t),
            t if t.ends_with("_t") => t.to_string(),
            t if is_struct => format!("struct {}", t),
            t => t.to_string(),
        }
    });

    cfg.field_name(move |struct_, field| {
        match field {
            // Field is named `type` in C but that is a Rust keyword,
            // so these fields are translated to `type_` in the bindings.
            "type_" if struct_ == "object_wait_info" => "type".to_string(),
            "type_" if struct_ == "sem_t" => "type".to_string(),
            "type_" if struct_ == "attr_info" => "type".to_string(),
            "type_" if struct_ == "index_info" => "type".to_string(),
            "image_type" if struct_ == "image_info" => "type".to_string(),
            s => s.to_string(),
        }
    });
    cfg.generate("../src/lib.rs", "main.rs");
}