aboutsummaryrefslogtreecommitdiff
path: root/lib/std/c/darwin.zig
blob: 0a65fa52429ea9a6f23fef3e08e2d56b0cf4c9b7 (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
const std = @import("../std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const macho = std.macho;
const native_arch = builtin.target.cpu.arch;
const maxInt = std.math.maxInt;
const iovec_const = std.os.iovec_const;

pub const aarch64 = @import("darwin/aarch64.zig");
pub const x86_64 = @import("darwin/x86_64.zig");

const arch_bits = switch (native_arch) {
    .aarch64 => @import("darwin/aarch64.zig"),
    .x86_64 => @import("darwin/x86_64.zig"),
    else => struct {},
};

pub const ucontext_t = extern struct {
    onstack: c_int,
    sigmask: sigset_t,
    stack: stack_t,
    link: ?*ucontext_t,
    mcsize: u64,
    mcontext: *mcontext_t,
};

pub const mcontext_t = extern struct {
    es: arch_bits.exception_state,
    ss: arch_bits.thread_state,
};

extern "c" fn __error() *c_int;
pub extern "c" fn NSVersionOfRunTimeLibrary(library_name: [*:0]const u8) u32;
pub extern "c" fn _NSGetExecutablePath(buf: [*:0]u8, bufsize: *u32) c_int;
pub extern "c" fn _dyld_image_count() u32;
pub extern "c" fn _dyld_get_image_header(image_index: u32) ?*mach_header;
pub extern "c" fn _dyld_get_image_vmaddr_slide(image_index: u32) usize;
pub extern "c" fn _dyld_get_image_name(image_index: u32) [*:0]const u8;

pub const COPYFILE_ACL = 1 << 0;
pub const COPYFILE_STAT = 1 << 1;
pub const COPYFILE_XATTR = 1 << 2;
pub const COPYFILE_DATA = 1 << 3;

pub const copyfile_state_t = *opaque {};
pub extern "c" fn fcopyfile(from: fd_t, to: fd_t, state: ?copyfile_state_t, flags: u32) c_int;

pub extern "c" fn @"realpath$DARWIN_EXTSN"(noalias file_name: [*:0]const u8, noalias resolved_name: [*]u8) ?[*:0]u8;
pub const realpath = @"realpath$DARWIN_EXTSN";

pub extern "c" fn __getdirentries64(fd: c_int, buf_ptr: [*]u8, buf_len: usize, basep: *i64) isize;

const private = struct {
    extern "c" fn fstat(fd: fd_t, buf: *Stat) c_int;
    /// On x86_64 Darwin, fstat has to be manully linked with $INODE64 suffix to
    /// force 64bit version.
    /// Note that this is fixed on aarch64 and no longer necessary.
    extern "c" fn @"fstat$INODE64"(fd: fd_t, buf: *Stat) c_int;

    extern "c" fn fstatat(dirfd: fd_t, path: [*:0]const u8, stat_buf: *Stat, flags: u32) c_int;
    /// On x86_64 Darwin, fstatat has to be manully linked with $INODE64 suffix to
    /// force 64bit version.
    /// Note that this is fixed on aarch64 and no longer necessary.
    extern "c" fn @"fstatat$INODE64"(dirfd: fd_t, path_name: [*:0]const u8, buf: *Stat, flags: u32) c_int;

    extern "c" fn readdir(dir: *std.c.DIR) ?*dirent;
    extern "c" fn @"readdir$INODE64"(dir: *std.c.DIR) ?*dirent;
};
pub const fstat = if (native_arch == .aarch64) private.fstat else private.@"fstat$INODE64";
pub const fstatat = if (native_arch == .aarch64) private.fstatat else private.@"fstatat$INODE64";
pub const readdir = if (native_arch == .aarch64) private.readdir else private.@"readdir$INODE64";

pub extern "c" fn mach_absolute_time() u64;
pub extern "c" fn mach_continuous_time() u64;
pub extern "c" fn mach_timebase_info(tinfo: ?*mach_timebase_info_data) kern_return_t;

pub extern "c" fn malloc_size(?*const anyopaque) usize;
pub extern "c" fn posix_memalign(memptr: *?*anyopaque, alignment: usize, size: usize) c_int;

pub const posix_spawnattr_t = *opaque {};
pub const posix_spawn_file_actions_t = *opaque {};
pub extern "c" fn posix_spawnattr_init(attr: *posix_spawnattr_t) c_int;
pub extern "c" fn posix_spawnattr_destroy(attr: *posix_spawnattr_t) void;
pub extern "c" fn posix_spawnattr_setflags(attr: *posix_spawnattr_t, flags: c_short) c_int;
pub extern "c" fn posix_spawnattr_getflags(attr: *const posix_spawnattr_t, flags: *c_short) c_int;
pub extern "c" fn posix_spawn_file_actions_init(actions: *posix_spawn_file_actions_t) c_int;
pub extern "c" fn posix_spawn_file_actions_destroy(actions: *posix_spawn_file_actions_t) void;
pub extern "c" fn posix_spawn_file_actions_addclose(actions: *posix_spawn_file_actions_t, filedes: fd_t) c_int;
pub extern "c" fn posix_spawn_file_actions_addopen(
    actions: *posix_spawn_file_actions_t,
    filedes: fd_t,
    path: [*:0]const u8,
    oflag: c_int,
    mode: mode_t,
) c_int;
pub extern "c" fn posix_spawn_file_actions_adddup2(
    actions: *posix_spawn_file_actions_t,
    filedes: fd_t,
    newfiledes: fd_t,
) c_int;
pub extern "c" fn posix_spawn_file_actions_addinherit_np(actions: *posix_spawn_file_actions_t, filedes: fd_t) c_int;
pub extern "c" fn posix_spawn_file_actions_addchdir_np(actions: *posix_spawn_file_actions_t, path: [*:0]const u8) c_int;
pub extern "c" fn posix_spawn_file_actions_addfchdir_np(actions: *posix_spawn_file_actions_t, filedes: fd_t) c_int;
pub extern "c" fn posix_spawn(
    pid: *pid_t,
    path: [*:0]const u8,
    actions: ?*const posix_spawn_file_actions_t,
    attr: ?*const posix_spawnattr_t,
    argv: [*:null]?[*:0]const u8,
    env: [*:null]?[*:0]const u8,
) c_int;
pub extern "c" fn posix_spawnp(
    pid: *pid_t,
    path: [*:0]const u8,
    actions: ?*const posix_spawn_file_actions_t,
    attr: ?*const posix_spawnattr_t,
    argv: [*:null]?[*:0]const u8,
    env: [*:null]?[*:0]const u8,
) c_int;

pub extern "c" fn kevent64(
    kq: c_int,
    changelist: [*]const kevent64_s,
    nchanges: c_int,
    eventlist: [*]kevent64_s,
    nevents: c_int,
    flags: c_uint,
    timeout: ?*const timespec,
) c_int;

const mach_hdr = if (@sizeOf(usize) == 8) mach_header_64 else mach_header;

/// The value of the link editor defined symbol _MH_EXECUTE_SYM is the address
/// of the mach header in a Mach-O executable file type.  It does not appear in
/// any file type other than a MH_EXECUTE file type.  The type of the symbol is
/// absolute as the header is not part of any section.
/// This symbol is populated when linking the system's libc, which is guaranteed
/// on this operating system. However when building object files or libraries,
/// the system libc won't be linked until the final executable. So we
/// export a weak symbol here, to be overridden by the real one.
var dummy_execute_header: mach_hdr = undefined;
pub extern var _mh_execute_header: mach_hdr;
comptime {
    if (builtin.target.isDarwin()) {
        @export(dummy_execute_header, .{ .name = "_mh_execute_header", .linkage = .Weak });
    }
}

pub const mach_header_64 = macho.mach_header_64;
pub const mach_header = macho.mach_header;

pub const _errno = __error;

pub extern "c" fn @"close$NOCANCEL"(fd: fd_t) c_int;
pub extern "c" fn mach_host_self() mach_port_t;
pub extern "c" fn clock_get_time(clock_serv: clock_serv_t, cur_time: *mach_timespec_t) kern_return_t;

pub const vm_map_t = mach_port_t;
pub const vm_map_read_t = mach_port_t;
pub const vm_region_flavor_t = c_int;
pub const vm_region_info_t = *c_int;
pub const vm_region_recurse_info_t = *c_int;
pub const mach_vm_address_t = usize;
pub const vm_offset_t = usize;
pub const mach_vm_size_t = u64;
pub const mach_msg_type_number_t = natural_t;

extern "c" var mach_task_self_: mach_port_t;
pub fn mach_task_self() callconv(.C) mach_port_t {
    return mach_task_self_;
}

pub const task_read_t = mach_port_t;

pub extern "c" fn task_resume(target_task: task_read_t) kern_return_t;
pub extern "c" fn task_suspend(target_task: task_read_t) kern_return_t;

pub extern "c" fn task_for_pid(target_tport: mach_port_name_t, pid: pid_t, t: *mach_port_name_t) kern_return_t;
pub extern "c" fn mach_vm_read(
    target_task: vm_map_read_t,
    address: mach_vm_address_t,
    size: mach_vm_size_t,
    data: *vm_offset_t,
    data_cnt: *mach_msg_type_number_t,
) kern_return_t;
pub extern "c" fn mach_vm_write(
    target_task: vm_map_t,
    address: mach_vm_address_t,
    data: vm_offset_t,
    data_cnt: mach_msg_type_number_t,
) kern_return_t;
pub extern "c" fn mach_vm_region(
    target_task: vm_map_t,
    address: *mach_vm_address_t,
    size: *mach_vm_size_t,
    flavor: vm_region_flavor_t,
    info: vm_region_info_t,
    info_cnt: *mach_msg_type_number_t,
    object_name: *mach_port_t,
) kern_return_t;
pub extern "c" fn mach_vm_region_recurse(
    target_task: vm_map_t,
    address: *mach_vm_address_t,
    size: *mach_vm_size_t,
    nesting_depth: *natural_t,
    info: vm_region_recurse_info_t,
    info_cnt: *mach_msg_type_number_t,
) kern_return_t;

pub const vm_inherit_t = u32;
pub const memory_object_offset_t = u64;
pub const vm_behavior_t = i32;
pub const vm32_object_id_t = u32;
pub const vm_object_id_t = u64;

pub const VM_INHERIT_SHARE: vm_inherit_t = 0;
pub const VM_INHERIT_COPY: vm_inherit_t = 1;
pub const VM_INHERIT_NONE: vm_inherit_t = 2;
pub const VM_INHERIT_DONATE_COPY: vm_inherit_t = 3;
pub const VM_INHERIT_DEFAULT = VM_INHERIT_COPY;

pub const VM_BEHAVIOR_DEFAULT: vm_behavior_t = 0;
pub const VM_BEHAVIOR_RANDOM: vm_behavior_t = 1;
pub const VM_BEHAVIOR_SEQUENTIAL: vm_behavior_t = 2;
pub const VM_BEHAVIOR_RSEQNTL: vm_behavior_t = 3;

pub const VM_BEHAVIOR_WILLNEED: vm_behavior_t = 4;
pub const VM_BEHAVIOR_DONTNEED: vm_behavior_t = 5;
pub const VM_BEHAVIOR_FREE: vm_behavior_t = 6;
pub const VM_BEHAVIOR_ZERO_WIRED_PAGES: vm_behavior_t = 7;
pub const VM_BEHAVIOR_REUSABLE: vm_behavior_t = 8;
pub const VM_BEHAVIOR_REUSE: vm_behavior_t = 9;
pub const VM_BEHAVIOR_CAN_REUSE: vm_behavior_t = 10;
pub const VM_BEHAVIOR_PAGEOUT: vm_behavior_t = 11;

pub const VM_REGION_BASIC_INFO_64 = 9;
pub const VM_REGION_EXTENDED_INFO = 13;
pub const VM_REGION_TOP_INFO = 12;
pub const VM_REGION_SUBMAP_INFO_COUNT_64: mach_msg_type_number_t = @sizeOf(vm_region_submap_info_64) / @sizeOf(natural_t);
pub const VM_REGION_SUBMAP_SHORT_INFO_COUNT_64: mach_msg_type_number_t = @sizeOf(vm_region_submap_short_info_64) / @sizeOf(natural_t);
pub const VM_REGION_BASIC_INFO_COUNT: mach_msg_type_number_t = @sizeOf(vm_region_basic_info_64) / @sizeOf(c_int);
pub const VM_REGION_EXTENDED_INFO_COUNT: mach_msg_type_number_t = @sizeOf(vm_region_extended_info) / @sizeOf(natural_t);
pub const VM_REGION_TOP_INFO_COUNT: mach_msg_type_number_t = @sizeOf(vm_region_top_info) / @sizeOf(natural_t);

pub const vm_region_basic_info_64 = extern struct {
    protection: vm_prot_t,
    max_protection: vm_prot_t,
    inheritance: vm_inherit_t,
    shared: boolean_t,
    reserved: boolean_t,
    offset: memory_object_offset_t,
    behavior: vm_behavior_t,
    user_wired_count: u16,
};

pub const vm_region_extended_info = extern struct {
    protection: vm_prot_t,
    user_tag: u32,
    pages_resident: u32,
    pages_shared_now_private: u32,
    pages_swapped_out: u32,
    pages_dirtied: u32,
    ref_count: u32,
    shadow_depth: u16,
    external_pager: u8,
    share_mode: u8,
    pages_reusable: u32,
};

pub const vm_region_top_info = extern struct {
    obj_id: u32,
    ref_count: u32,
    private_pages_resident: u32,
    shared_pages_resident: u32,
    share_mode: u8,
};

pub const vm_region_submap_info_64 = extern struct {
    // present across protection
    protection: vm_prot_t,
    // max avail through vm_prot
    max_protection: vm_prot_t,
    // behavior of map/obj on fork
    inheritance: vm_inherit_t,
    // offset into object/map
    offset: memory_object_offset_t,
    // user tag on map entry
    user_tag: u32,
    // only valid for objects
    pages_resident: u32,
    // only for objects
    pages_shared_now_private: u32,
    // only for objects
    pages_swapped_out: u32,
    // only for objects
    pages_dirtied: u32,
    // obj/map mappers, etc.
    ref_count: u32,
    // only for obj
    shadow_depth: u16,
    // only for obj
    external_pager: u8,
    // see enumeration
    share_mode: u8,
    // submap vs obj
    is_submap: boolean_t,
    // access behavior hint
    behavior: vm_behavior_t,
    // obj/map name, not a handle
    object_id: vm32_object_id_t,
    user_wired_count: u16,
    pages_reusable: u32,
    object_id_full: vm_object_id_t,
};

pub const vm_region_submap_short_info_64 = extern struct {
    // present access protection
    protection: vm_prot_t,
    // max avail through vm_prot
    max_protection: vm_prot_t,
    // behavior of map/obj on fork
    inheritance: vm_inherit_t,
    // offset into object/map
    offset: memory_object_offset_t,
    // user tag on map entry
    user_tag: u32,
    // obj/map mappers, etc
    ref_count: u32,
    // only for obj
    shadow_depth: u16,
    // only for obj
    external_pager: u8,
    // see enumeration
    share_mode: u8,
    //  submap vs obj
    is_submap: boolean_t,
    // access behavior hint
    behavior: vm_behavior_t,
    // obj/map name, not a handle
    object_id: vm32_object_id_t,
    user_wired_count: u16,
};

pub const thread_act_t = mach_port_t;
pub const thread_state_t = *natural_t;
pub const mach_port_array_t = *mach_port_t;

pub extern "c" fn task_threads(
    target_task: mach_port_t,
    init_port_set: *mach_port_array_t,
    init_port_count: *mach_msg_type_number_t,
) kern_return_t;
pub extern "c" fn thread_get_state(
    thread: thread_act_t,
    flavor: thread_flavor_t,
    state: thread_state_t,
    count: *mach_msg_type_number_t,
) kern_return_t;
pub extern "c" fn thread_set_state(
    thread: thread_act_t,
    flavor: thread_flavor_t,
    new_state: thread_state_t,
    count: mach_msg_type_number_t,
) kern_return_t;
pub extern "c" fn thread_info(
    thread: thread_act_t,
    flavor: thread_flavor_t,
    info: thread_info_t,
    count: *mach_msg_type_number_t,
) kern_return_t;
pub extern "c" fn thread_resume(thread: thread_act_t) kern_return_t;

pub const THREAD_BASIC_INFO = 3;
pub const THREAD_BASIC_INFO_COUNT: mach_msg_type_number_t = @sizeOf(thread_basic_info) / @sizeOf(natural_t);

pub const thread_flavor_t = natural_t;
pub const thread_info_t = *integer_t;
pub const time_value_t = time_value;
pub const task_policy_flavor_t = natural_t;
pub const task_policy_t = *integer_t;
pub const policy_t = c_int;

pub const time_value = extern struct {
    seconds: integer_t,
    microseconds: integer_t,
};

pub const thread_basic_info = extern struct {
    // user run time
    user_time: time_value_t,
    // system run time
    system_time: time_value_t,
    // scaled cpu usage percentage
    cpu_usage: integer_t,
    // scheduling policy in effect
    policy: policy_t,
    // run state
    run_state: integer_t,
    // various flags
    flags: integer_t,
    // suspend count for thread
    suspend_count: integer_t,
    // number of seconds that thread has been sleeping
    sleep_time: integer_t,
};

/// Cachability
pub const MATTR_CACHE = 1;
/// Migrability
pub const MATTR_MIGRATE = 2;
/// Replicability
pub const MATTR_REPLICATE = 4;

/// (Generic) turn attribute off
pub const MATTR_VAL_OFF = 0;
/// (Generic) turn attribute on
pub const MATTR_VAL_ON = 1;
/// (Generic) return current value
pub const MATTR_VAL_GET = 2;
/// Flush from all caches
pub const MATTR_VAL_CACHE_FLUSH = 6;
/// Flush from data caches
pub const MATTR_VAL_DCACHE_FLUSH = 7;
/// Flush from instruction caches
pub const MATTR_VAL_ICACHE_FLUSH = 8;
/// Sync I+D caches
pub const MATTR_VAL_CACHE_SYNC = 9;
/// Get page info (stats)
pub const MATTR_VAL_GET_INFO = 10;

pub const TASK_VM_INFO = 22;
pub const TASK_VM_INFO_COUNT: mach_msg_type_number_t = @sizeOf(task_vm_info_data_t) / @sizeOf(natural_t);

pub const task_vm_info = extern struct {
    // virtual memory size (bytes)
    virtual_size: mach_vm_size_t,
    // number of memory regions
    region_count: integer_t,
    page_size: integer_t,
    // resident memory size (bytes)
    resident_size: mach_vm_size_t,
    // peak resident size (bytes)
    resident_size_peak: mach_vm_size_t,

    device: mach_vm_size_t,
    device_peak: mach_vm_size_t,
    internal: mach_vm_size_t,
    internal_peak: mach_vm_size_t,
    external: mach_vm_size_t,
    external_peak: mach_vm_size_t,
    reusable: mach_vm_size_t,
    reusable_peak: mach_vm_size_t,
    purgeable_volatile_pmap: mach_vm_size_t,
    purgeable_volatile_resident: mach_vm_size_t,
    purgeable_volatile_virtual: mach_vm_size_t,
    compressed: mach_vm_size_t,
    compressed_peak: mach_vm_size_t,
    compressed_lifetime: mach_vm_size_t,

    // added for rev1
    phys_footprint: mach_vm_size_t,

    // added for rev2
    min_address: mach_vm_address_t,
    max_address: mach_vm_address_t,

    // added for rev3
    ledger_phys_footprint_peak: i64,
    ledger_purgeable_nonvolatile: i64,
    ledger_purgeable_novolatile_compressed: i64,
    ledger_purgeable_volatile: i64,
    ledger_purgeable_volatile_compressed: i64,
    ledger_tag_network_nonvolatile: i64,
    ledger_tag_network_nonvolatile_compressed: i64,
    ledger_tag_network_volatile: i64,
    ledger_tag_network_volatile_compressed: i64,
    ledger_tag_media_footprint: i64,
    ledger_tag_media_footprint_compressed: i64,
    ledger_tag_media_nofootprint: i64,
    ledger_tag_media_nofootprint_compressed: i64,
    ledger_tag_graphics_footprint: i64,
    ledger_tag_graphics_footprint_compressed: i64,
    ledger_tag_graphics_nofootprint: i64,
    ledger_tag_graphics_nofootprint_compressed: i64,
    ledger_tag_neural_footprint: i64,
    ledger_tag_neural_footprint_compressed: i64,
    ledger_tag_neural_nofootprint: i64,
    ledger_tag_neural_nofootprint_compressed: i64,

    // added for rev4
    limit_bytes_remaining: u64,

    // added for rev5
    decompressions: integer_t,
};
pub const task_vm_info_data_t = task_vm_info;

pub const vm_prot_t = c_int;
pub const boolean_t = c_int;

pub extern "c" fn mach_vm_protect(
    target_task: vm_map_t,
    address: mach_vm_address_t,
    size: mach_vm_size_t,
    set_maximum: boolean_t,
    new_protection: vm_prot_t,
) kern_return_t;

pub extern "c" fn mach_port_deallocate(target_tport: mach_port_name_t, task: mach_port_name_t) kern_return_t;

pub extern "c" fn task_info(
    target_task: task_name_t,
    flavor: task_flavor_t,
    task_info_out: task_info_t,
    task_info_outCnt: *mach_msg_type_number_t,
) kern_return_t;
pub extern "c" fn _host_page_size(task: mach_port_t, size: *vm_size_t) kern_return_t;
pub extern "c" fn vm_deallocate(target_task: vm_map_t, address: vm_address_t, size: vm_size_t) kern_return_t;
pub extern "c" fn vm_machine_attribute(
    target_task: vm_map_t,
    address: vm_address_t,
    size: vm_size_t,
    attribute: vm_machine_attribute_t,
    value: *vm_machine_attribute_val_t,
) kern_return_t;

pub const sf_hdtr = extern struct {
    headers: [*]const iovec_const,
    hdr_cnt: c_int,
    trailers: [*]const iovec_const,
    trl_cnt: c_int,
};

pub extern "c" fn sendfile(
    in_fd: fd_t,
    out_fd: fd_t,
    offset: off_t,
    len: *off_t,
    sf_hdtr: ?*sf_hdtr,
    flags: u32,
) c_int;

pub fn sigaddset(set: *sigset_t, signo: u5) void {
    set.* |= @as(u32, 1) << (signo - 1);
}

pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int;

pub const IFNAMESIZE = 16;

pub const AI = struct {
    /// get address to use bind()
    pub const PASSIVE = 0x00000001;
    /// fill ai_canonname
    pub const CANONNAME = 0x00000002;
    /// prevent host name resolution
    pub const NUMERICHOST = 0x00000004;
    /// prevent service name resolution
    pub const NUMERICSERV = 0x00001000;
};

pub const EAI = enum(c_int) {
    /// address family for hostname not supported
    ADDRFAMILY = 1,

    /// temporary failure in name resolution
    AGAIN = 2,

    /// invalid value for ai_flags
    BADFLAGS = 3,

    /// non-recoverable failure in name resolution
    FAIL = 4,

    /// ai_family not supported
    FAMILY = 5,

    /// memory allocation failure
    MEMORY = 6,

    /// no address associated with hostname
    NODATA = 7,

    /// hostname nor servname provided, or not known
    NONAME = 8,

    /// servname not supported for ai_socktype
    SERVICE = 9,

    /// ai_socktype not supported
    SOCKTYPE = 10,

    /// system error returned in errno
    SYSTEM = 11,

    /// invalid value for hints
    BADHINTS = 12,

    /// resolved protocol is unknown
    PROTOCOL = 13,

    /// argument buffer overflow
    OVERFLOW = 14,

    _,
};

pub const EAI_MAX = 15;

pub const pthread_mutex_t = extern struct {
    __sig: c_long = 0x32AAABA7,
    __opaque: [__PTHREAD_MUTEX_SIZE__]u8 = [_]u8{0} ** __PTHREAD_MUTEX_SIZE__,
};
pub const pthread_cond_t = extern struct {
    __sig: c_long = 0x3CB0B1BB,
    __opaque: [__PTHREAD_COND_SIZE__]u8 = [_]u8{0} ** __PTHREAD_COND_SIZE__,
};
pub const pthread_rwlock_t = extern struct {
    __sig: c_long = 0x2DA8B3B4,
    __opaque: [192]u8 = [_]u8{0} ** 192,
};
pub const sem_t = c_int;
const __PTHREAD_MUTEX_SIZE__ = if (@sizeOf(usize) == 8) 56 else 40;
const __PTHREAD_COND_SIZE__ = if (@sizeOf(usize) == 8) 40 else 24;

pub const pthread_attr_t = extern struct {
    __sig: c_long,
    __opaque: [56]u8,
};

pub extern "c" fn pthread_threadid_np(thread: ?std.c.pthread_t, thread_id: *u64) c_int;
pub extern "c" fn pthread_setname_np(name: [*:0]const u8) E;
pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) E;

pub extern "c" fn arc4random_buf(buf: [*]u8, len: usize) void;

// Grand Central Dispatch is exposed by libSystem.
pub extern "c" fn dispatch_release(object: *anyopaque) void;

pub const dispatch_semaphore_t = *opaque {};
pub extern "c" fn dispatch_semaphore_create(value: isize) ?dispatch_semaphore_t;
pub extern "c" fn dispatch_semaphore_wait(dsema: dispatch_semaphore_t, timeout: dispatch_time_t) isize;
pub extern "c" fn dispatch_semaphore_signal(dsema: dispatch_semaphore_t) isize;

pub const dispatch_time_t = u64;
pub const DISPATCH_TIME_NOW = @as(dispatch_time_t, 0);
pub const DISPATCH_TIME_FOREVER = ~@as(dispatch_time_t, 0);
pub extern "c" fn dispatch_time(when: dispatch_time_t, delta: i64) dispatch_time_t;

const dispatch_once_t = usize;
const dispatch_function_t = fn (?*anyopaque) callconv(.C) void;
pub extern fn dispatch_once_f(
    predicate: *dispatch_once_t,
    context: ?*anyopaque,
    function: dispatch_function_t,
) void;

// Undocumented futex-like API available on darwin 16+
// (macOS 10.12+, iOS 10.0+, tvOS 10.0+, watchOS 3.0+, catalyst 13.0+).
//
// [ulock.h]: https://github.com/apple/darwin-xnu/blob/master/bsd/sys/ulock.h
// [sys_ulock.c]: https://github.com/apple/darwin-xnu/blob/master/bsd/kern/sys_ulock.c

pub const UL_COMPARE_AND_WAIT = 1;
pub const UL_UNFAIR_LOCK = 2;

// Obsolete/deprecated
pub const UL_OSSPINLOCK = UL_COMPARE_AND_WAIT;
pub const UL_HANDOFFLOCK = UL_UNFAIR_LOCK;

pub const ULF_WAKE_ALL = 0x100;
pub const ULF_WAKE_THREAD = 0x200;
pub const ULF_WAIT_WORKQ_DATA_CONTENTION = 0x10000;
pub const ULF_WAIT_CANCEL_POINT = 0x20000;
pub const ULF_NO_ERRNO = 0x1000000;

// The following are only supported on darwin 19+
// (macOS 10.15+, iOS 13.0+)
pub const UL_COMPARE_AND_WAIT_SHARED = 3;
pub const UL_UNFAIR_LOCK64_SHARED = 4;
pub const UL_COMPARE_AND_WAIT64 = 5;
pub const UL_COMPARE_AND_WAIT64_SHARED = 6;
pub const ULF_WAIT_ADAPTIVE_SPIN = 0x40000;

pub extern "c" fn __ulock_wait2(op: u32, addr: ?*const anyopaque, val: u64, timeout_ns: u64, val2: u64) c_int;
pub extern "c" fn __ulock_wait(op: u32, addr: ?*const anyopaque, val: u64, timeout_us: u32) c_int;
pub extern "c" fn __ulock_wake(op: u32, addr: ?*const anyopaque, val: u64) c_int;

pub const OS_UNFAIR_LOCK_INIT = os_unfair_lock{};
pub const os_unfair_lock_t = *os_unfair_lock;
pub const os_unfair_lock = extern struct {
    _os_unfair_lock_opaque: u32 = 0,
};

pub extern "c" fn os_unfair_lock_lock(o: os_unfair_lock_t) void;
pub extern "c" fn os_unfair_lock_unlock(o: os_unfair_lock_t) void;
pub extern "c" fn os_unfair_lock_trylock(o: os_unfair_lock_t) bool;
pub extern "c" fn os_unfair_lock_assert_owner(o: os_unfair_lock_t) void;
pub extern "c" fn os_unfair_lock_assert_not_owner(o: os_unfair_lock_t) void;

// XXX: close -> close$NOCANCEL
// XXX: getdirentries -> _getdirentries64

// See: https://opensource.apple.com/source/xnu/xnu-6153.141.1/bsd/sys/_types.h.auto.html
// TODO: audit mode_t/pid_t, should likely be u16/i32
pub const fd_t = c_int;
pub const pid_t = c_int;
pub const mode_t = c_uint;
pub const uid_t = u32;
pub const gid_t = u32;

pub const in_port_t = u16;
pub const sa_family_t = u8;
pub const socklen_t = u32;
pub const sockaddr = extern struct {
    len: u8,
    family: sa_family_t,
    data: [14]u8,

    pub const SS_MAXSIZE = 128;
    pub const storage = std.x.os.Socket.Address.Native.Storage;
    pub const in = extern struct {
        len: u8 = @sizeOf(in),
        family: sa_family_t = AF.INET,
        port: in_port_t,
        addr: u32,
        zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 },
    };
    pub const in6 = extern struct {
        len: u8 = @sizeOf(in6),
        family: sa_family_t = AF.INET6,
        port: in_port_t,
        flowinfo: u32,
        addr: [16]u8,
        scope_id: u32,
    };

    /// UNIX domain socket
    pub const un = extern struct {
        len: u8 = @sizeOf(un),
        family: sa_family_t = AF.UNIX,
        path: [104]u8,
    };
};
pub const timeval = extern struct {
    tv_sec: c_long,
    tv_usec: i32,
};

pub const timezone = extern struct {
    tz_minuteswest: i32,
    tz_dsttime: i32,
};

pub const mach_timebase_info_data = extern struct {
    numer: u32,
    denom: u32,
};

pub const off_t = i64;
pub const ino_t = u64;

pub const Flock = extern struct {
    start: off_t,
    len: off_t,
    pid: pid_t,
    type: i16,
    whence: i16,
};

pub const Stat = extern struct {
    dev: i32,
    mode: u16,
    nlink: u16,
    ino: ino_t,
    uid: uid_t,
    gid: gid_t,
    rdev: i32,
    atimespec: timespec,
    mtimespec: timespec,
    ctimespec: timespec,
    birthtimespec: timespec,
    size: off_t,
    blocks: i64,
    blksize: i32,
    flags: u32,
    gen: u32,
    lspare: i32,
    qspare: [2]i64,

    pub fn atime(self: @This()) timespec {
        return self.atimespec;
    }

    pub fn mtime(self: @This()) timespec {
        return self.mtimespec;
    }

    pub fn ctime(self: @This()) timespec {
        return self.ctimespec;
    }

    pub fn birthtime(self: @This()) timespec {
        return self.birthtimespec;
    }
};

pub const timespec = extern struct {
    tv_sec: isize,
    tv_nsec: isize,
};

pub const sigset_t = u32;
pub const empty_sigset: sigset_t = 0;

pub const SIG = struct {
    pub const ERR = @intToPtr(?Sigaction.handler_fn, maxInt(usize));
    pub const DFL = @intToPtr(?Sigaction.handler_fn, 0);
    pub const IGN = @intToPtr(?Sigaction.handler_fn, 1);
    pub const HOLD = @intToPtr(?Sigaction.handler_fn, 5);

    /// block specified signal set
    pub const _BLOCK = 1;
    /// unblock specified signal set
    pub const _UNBLOCK = 2;
    /// set specified signal set
    pub const _SETMASK = 3;
    /// hangup
    pub const HUP = 1;
    /// interrupt
    pub const INT = 2;
    /// quit
    pub const QUIT = 3;
    /// illegal instruction (not reset when caught)
    pub const ILL = 4;
    /// trace trap (not reset when caught)
    pub const TRAP = 5;
    /// abort()
    pub const ABRT = 6;
    /// pollable event ([XSR] generated, not supported)
    pub const POLL = 7;
    /// compatibility
    pub const IOT = ABRT;
    /// EMT instruction
    pub const EMT = 7;
    /// floating point exception
    pub const FPE = 8;
    /// kill (cannot be caught or ignored)
    pub const KILL = 9;
    /// bus error
    pub const BUS = 10;
    /// segmentation violation
    pub const SEGV = 11;
    /// bad argument to system call
    pub const SYS = 12;
    /// write on a pipe with no one to read it
    pub const PIPE = 13;
    /// alarm clock
    pub const ALRM = 14;
    /// software termination signal from kill
    pub const TERM = 15;
    /// urgent condition on IO channel
    pub const URG = 16;
    /// sendable stop signal not from tty
    pub const STOP = 17;
    /// stop signal from tty
    pub const TSTP = 18;
    /// continue a stopped process
    pub const CONT = 19;
    /// to parent on child stop or exit
    pub const CHLD = 20;
    /// to readers pgrp upon background tty read
    pub const TTIN = 21;
    /// like TTIN for output if (tp->t_local&LTOSTOP)
    pub const TTOU = 22;
    /// input/output possible signal
    pub const IO = 23;
    /// exceeded CPU time limit
    pub const XCPU = 24;
    /// exceeded file size limit
    pub const XFSZ = 25;
    /// virtual time alarm
    pub const VTALRM = 26;
    /// profiling time alarm
    pub const PROF = 27;
    /// window size changes
    pub const WINCH = 28;
    /// information request
    pub const INFO = 29;
    /// user defined signal 1
    pub const USR1 = 30;
    /// user defined signal 2
    pub const USR2 = 31;
};

pub const siginfo_t = extern struct {
    signo: c_int,
    errno: c_int,
    code: c_int,
    pid: pid_t,
    uid: uid_t,
    status: c_int,
    addr: *anyopaque,
    value: extern union {
        int: c_int,
        ptr: *anyopaque,
    },
    si_band: c_long,
    _pad: [7]c_ulong,
};

/// Renamed from `sigaction` to `Sigaction` to avoid conflict with function name.
pub const Sigaction = extern struct {
    pub const handler_fn = switch (builtin.zig_backend) {
        .stage1 => fn (c_int) callconv(.C) void,
        else => *const fn (c_int) callconv(.C) void,
    };
    pub const sigaction_fn = switch (builtin.zig_backend) {
        .stage1 => fn (c_int, *const siginfo_t, ?*const anyopaque) callconv(.C) void,
        else => *const fn (c_int, *const siginfo_t, ?*const anyopaque) callconv(.C) void,
    };

    handler: extern union {
        handler: ?handler_fn,
        sigaction: ?sigaction_fn,
    },
    mask: sigset_t,
    flags: c_uint,
};

pub const dirent = extern struct {
    d_ino: u64,
    d_seekoff: u64,
    d_reclen: u16,
    d_namlen: u16,
    d_type: u8,
    d_name: [1024]u8,

    pub fn reclen(self: dirent) u16 {
        return self.d_reclen;
    }
};

/// Renamed from `kevent` to `Kevent` to avoid conflict with function name.
pub const Kevent = extern struct {
    ident: usize,
    filter: i16,
    flags: u16,
    fflags: u32,
    data: isize,
    udata: usize,
};

// sys/types.h on macos uses #pragma pack(4) so these checks are
// to make sure the struct is laid out the same. These values were
// produced from C code using the offsetof macro.
comptime {
    if (builtin.target.isDarwin()) {
        assert(@offsetOf(Kevent, "ident") == 0);
        assert(@offsetOf(Kevent, "filter") == 8);
        assert(@offsetOf(Kevent, "flags") == 10);
        assert(@offsetOf(Kevent, "fflags") == 12);
        assert(@offsetOf(Kevent, "data") == 16);
        assert(@offsetOf(Kevent, "udata") == 24);
    }
}

pub const kevent64_s = extern struct {
    ident: u64,
    filter: i16,
    flags: u16,
    fflags: u32,
    data: i64,
    udata: u64,
    ext: [2]u64,
};

// sys/types.h on macos uses #pragma pack() so these checks are
// to make sure the struct is laid out the same. These values were
// produced from C code using the offsetof macro.
comptime {
    if (builtin.target.isDarwin()) {
        assert(@offsetOf(kevent64_s, "ident") == 0);
        assert(@offsetOf(kevent64_s, "filter") == 8);
        assert(@offsetOf(kevent64_s, "flags") == 10);
        assert(@offsetOf(kevent64_s, "fflags") == 12);
        assert(@offsetOf(kevent64_s, "data") == 16);
        assert(@offsetOf(kevent64_s, "udata") == 24);
        assert(@offsetOf(kevent64_s, "ext") == 32);
    }
}

pub const mach_port_t = c_uint;
pub const clock_serv_t = mach_port_t;
pub const clock_res_t = c_int;
pub const mach_port_name_t = natural_t;
pub const natural_t = c_uint;
pub const mach_timespec_t = extern struct {
    tv_sec: c_uint,
    tv_nsec: clock_res_t,
};
pub const kern_return_t = c_int;
pub const host_t = mach_port_t;
pub const integer_t = c_int;
pub const task_flavor_t = natural_t;
pub const task_info_t = *integer_t;
pub const task_name_t = mach_port_name_t;
pub const vm_address_t = vm_offset_t;
pub const vm_size_t = mach_vm_size_t;
pub const vm_machine_attribute_t = usize;
pub const vm_machine_attribute_val_t = isize;

pub const CALENDAR_CLOCK = 1;

pub const PATH_MAX = 1024;
pub const IOV_MAX = 16;

pub const STDIN_FILENO = 0;
pub const STDOUT_FILENO = 1;
pub const STDERR_FILENO = 2;

pub const PROT = struct {
    /// [MC2] no permissions
    pub const NONE: vm_prot_t = 0x00;
    /// [MC2] pages can be read
    pub const READ: vm_prot_t = 0x01;
    /// [MC2] pages can be written
    pub const WRITE: vm_prot_t = 0x02;
    /// [MC2] pages can be executed
    pub const EXEC: vm_prot_t = 0x04;
    /// When a caller finds that they cannot obtain write permission on a
    /// mapped entry, the following flag can be used. The entry will be
    /// made "needs copy" effectively copying the object (using COW),
    /// and write permission will be added to the maximum protections for
    /// the associated entry.
    pub const COPY: vm_prot_t = 0x10;
};

pub const MAP = struct {
    /// allocated from memory, swap space
    pub const ANONYMOUS = 0x1000;
    /// map from file (default)
    pub const FILE = 0x0000;
    /// interpret addr exactly
    pub const FIXED = 0x0010;
    /// region may contain semaphores
    pub const HASSEMAPHORE = 0x0200;
    /// changes are private
    pub const PRIVATE = 0x0002;
    /// share changes
    pub const SHARED = 0x0001;
    /// don't cache pages for this mapping
    pub const NOCACHE = 0x0400;
    /// don't reserve needed swap area
    pub const NORESERVE = 0x0040;
    pub const FAILED = @intToPtr(*anyopaque, maxInt(usize));
};

pub const MSF = struct {
    pub const ASYNC = 0x1;
    pub const INVALIDATE = 0x2;
    // invalidate, leave mapped
    pub const KILLPAGES = 0x4;
    // deactivate, leave mapped
    pub const DEACTIVATE = 0x8;
    pub const SYNC = 0x10;
};

pub const SA = struct {
    /// take signal on signal stack
    pub const ONSTACK = 0x0001;
    /// restart system on signal return
    pub const RESTART = 0x0002;
    /// reset to SIG.DFL when taking signal
    pub const RESETHAND = 0x0004;
    /// do not generate SIG.CHLD on child stop
    pub const NOCLDSTOP = 0x0008;
    /// don't mask the signal we're delivering
    pub const NODEFER = 0x0010;
    /// don't keep zombies around
    pub const NOCLDWAIT = 0x0020;
    /// signal handler with SIGINFO args
    pub const SIGINFO = 0x0040;
    /// do not bounce off kernel's sigtramp
    pub const USERTRAMP = 0x0100;
    /// signal handler with SIGINFO args with 64bit regs information
    pub const @"64REGSET" = 0x0200;
};

pub const F_OK = 0;
pub const X_OK = 1;
pub const W_OK = 2;
pub const R_OK = 4;

pub const O = struct {
    pub const PATH = 0x0000;
    /// open for reading only
    pub const RDONLY = 0x0000;
    /// open for writing only
    pub const WRONLY = 0x0001;
    /// open for reading and writing
    pub const RDWR = 0x0002;
    /// do not block on open or for data to become available
    pub const NONBLOCK = 0x0004;
    /// append on each write
    pub const APPEND = 0x0008;
    /// create file if it does not exist
    pub const CREAT = 0x0200;
    /// truncate size to 0
    pub const TRUNC = 0x0400;
    /// error if CREAT and the file exists
    pub const EXCL = 0x0800;
    /// atomically obtain a shared lock
    pub const SHLOCK = 0x0010;
    /// atomically obtain an exclusive lock
    pub const EXLOCK = 0x0020;
    /// do not follow symlinks
    pub const NOFOLLOW = 0x0100;
    /// allow open of symlinks
    pub const SYMLINK = 0x200000;
    /// descriptor requested for event notifications only
    pub const EVTONLY = 0x8000;
    /// mark as close-on-exec
    pub const CLOEXEC = 0x1000000;
    pub const ACCMODE = 3;
    pub const ALERT = 536870912;
    pub const ASYNC = 64;
    pub const DIRECTORY = 1048576;
    pub const DP_GETRAWENCRYPTED = 1;
    pub const DP_GETRAWUNENCRYPTED = 2;
    pub const DSYNC = 4194304;
    pub const FSYNC = SYNC;
    pub const NOCTTY = 131072;
    pub const POPUP = 2147483648;
    pub const SYNC = 128;
};

pub const SEEK = struct {
    pub const SET = 0x0;
    pub const CUR = 0x1;
    pub const END = 0x2;
};

pub const DT = struct {
    pub const UNKNOWN = 0;
    pub const FIFO = 1;
    pub const CHR = 2;
    pub const DIR = 4;
    pub const BLK = 6;
    pub const REG = 8;
    pub const LNK = 10;
    pub const SOCK = 12;
    pub const WHT = 14;
};

/// no flag value
pub const KEVENT_FLAG_NONE = 0x000;

/// immediate timeout
pub const KEVENT_FLAG_IMMEDIATE = 0x001;

/// output events only include change
pub const KEVENT_FLAG_ERROR_EVENTS = 0x002;

/// add event to kq (implies enable)
pub const EV_ADD = 0x0001;

/// delete event from kq
pub const EV_DELETE = 0x0002;

/// enable event
pub const EV_ENABLE = 0x0004;

/// disable event (not reported)
pub const EV_DISABLE = 0x0008;

/// only report one occurrence
pub const EV_ONESHOT = 0x0010;

/// clear event state after reporting
pub const EV_CLEAR = 0x0020;

/// force immediate event output
/// ... with or without EV_ERROR
/// ... use KEVENT_FLAG_ERROR_EVENTS
///     on syscalls supporting flags
pub const EV_RECEIPT = 0x0040;

/// disable event after reporting
pub const EV_DISPATCH = 0x0080;

/// unique kevent per udata value
pub const EV_UDATA_SPECIFIC = 0x0100;

/// ... in combination with EV_DELETE
/// will defer delete until udata-specific
/// event enabled. EINPROGRESS will be
/// returned to indicate the deferral
pub const EV_DISPATCH2 = EV_DISPATCH | EV_UDATA_SPECIFIC;

/// report that source has vanished
/// ... only valid with EV_DISPATCH2
pub const EV_VANISHED = 0x0200;

/// reserved by system
pub const EV_SYSFLAGS = 0xF000;

/// filter-specific flag
pub const EV_FLAG0 = 0x1000;

/// filter-specific flag
pub const EV_FLAG1 = 0x2000;

/// EOF detected
pub const EV_EOF = 0x8000;

/// error, data contains errno
pub const EV_ERROR = 0x4000;

pub const EV_POLL = EV_FLAG0;
pub const EV_OOBAND = EV_FLAG1;

pub const EVFILT_READ = -1;
pub const EVFILT_WRITE = -2;

/// attached to aio requests
pub const EVFILT_AIO = -3;

/// attached to vnodes
pub const EVFILT_VNODE = -4;

/// attached to struct proc
pub const EVFILT_PROC = -5;

/// attached to struct proc
pub const EVFILT_SIGNAL = -6;

/// timers
pub const EVFILT_TIMER = -7;

/// Mach portsets
pub const EVFILT_MACHPORT = -8;

/// Filesystem events
pub const EVFILT_FS = -9;

/// User events
pub const EVFILT_USER = -10;

/// Virtual memory events
pub const EVFILT_VM = -12;

/// Exception events
pub const EVFILT_EXCEPT = -15;

pub const EVFILT_SYSCOUNT = 17;

/// On input, NOTE_TRIGGER causes the event to be triggered for output.
pub const NOTE_TRIGGER = 0x01000000;

/// ignore input fflags
pub const NOTE_FFNOP = 0x00000000;

/// and fflags
pub const NOTE_FFAND = 0x40000000;

/// or fflags
pub const NOTE_FFOR = 0x80000000;

/// copy fflags
pub const NOTE_FFCOPY = 0xc0000000;

/// mask for operations
pub const NOTE_FFCTRLMASK = 0xc0000000;
pub const NOTE_FFLAGSMASK = 0x00ffffff;

/// low water mark
pub const NOTE_LOWAT = 0x00000001;

/// OOB data
pub const NOTE_OOB = 0x00000002;

/// vnode was removed
pub const NOTE_DELETE = 0x00000001;

/// data contents changed
pub const NOTE_WRITE = 0x00000002;

/// size increased
pub const NOTE_EXTEND = 0x00000004;

/// attributes changed
pub const NOTE_ATTRIB = 0x00000008;

/// link count changed
pub const NOTE_LINK = 0x00000010;

/// vnode was renamed
pub const NOTE_RENAME = 0x00000020;

/// vnode access was revoked
pub const NOTE_REVOKE = 0x00000040;

/// No specific vnode event: to test for EVFILT_READ      activation
pub const NOTE_NONE = 0x00000080;

/// vnode was unlocked by flock(2)
pub const NOTE_FUNLOCK = 0x00000100;

/// process exited
pub const NOTE_EXIT = 0x80000000;

/// process forked
pub const NOTE_FORK = 0x40000000;

/// process exec'd
pub const NOTE_EXEC = 0x20000000;

/// shared with EVFILT_SIGNAL
pub const NOTE_SIGNAL = 0x08000000;

/// exit status to be returned, valid for child       process only
pub const NOTE_EXITSTATUS = 0x04000000;

/// provide details on reasons for exit
pub const NOTE_EXIT_DETAIL = 0x02000000;

/// mask for signal & exit status
pub const NOTE_PDATAMASK = 0x000fffff;
pub const NOTE_PCTRLMASK = (~NOTE_PDATAMASK);

pub const NOTE_EXIT_DETAIL_MASK = 0x00070000;
pub const NOTE_EXIT_DECRYPTFAIL = 0x00010000;
pub const NOTE_EXIT_MEMORY = 0x00020000;
pub const NOTE_EXIT_CSERROR = 0x00040000;

/// will react on memory          pressure
pub const NOTE_VM_PRESSURE = 0x80000000;

/// will quit on memory       pressure, possibly after cleaning up dirty state
pub const NOTE_VM_PRESSURE_TERMINATE = 0x40000000;

/// will quit immediately on      memory pressure
pub const NOTE_VM_PRESSURE_SUDDEN_TERMINATE = 0x20000000;

/// there was an error
pub const NOTE_VM_ERROR = 0x10000000;

/// data is seconds
pub const NOTE_SECONDS = 0x00000001;

/// data is microseconds
pub const NOTE_USECONDS = 0x00000002;

/// data is nanoseconds
pub const NOTE_NSECONDS = 0x00000004;

/// absolute timeout
pub const NOTE_ABSOLUTE = 0x00000008;

/// ext[1] holds leeway for power aware timers
pub const NOTE_LEEWAY = 0x00000010;

/// system does minimal timer coalescing
pub const NOTE_CRITICAL = 0x00000020;

/// system does maximum timer coalescing
pub const NOTE_BACKGROUND = 0x00000040;
pub const NOTE_MACH_CONTINUOUS_TIME = 0x00000080;

/// data is mach absolute time units
pub const NOTE_MACHTIME = 0x00000100;

pub const AF = struct {
    pub const UNSPEC = 0;
    pub const LOCAL = 1;
    pub const UNIX = LOCAL;
    pub const INET = 2;
    pub const SYS_CONTROL = 2;
    pub const IMPLINK = 3;
    pub const PUP = 4;
    pub const CHAOS = 5;
    pub const NS = 6;
    pub const ISO = 7;
    pub const OSI = ISO;
    pub const ECMA = 8;
    pub const DATAKIT = 9;
    pub const CCITT = 10;
    pub const SNA = 11;
    pub const DECnet = 12;
    pub const DLI = 13;
    pub const LAT = 14;
    pub const HYLINK = 15;
    pub const APPLETALK = 16;
    pub const ROUTE = 17;
    pub const LINK = 18;
    pub const XTP = 19;
    pub const COIP = 20;
    pub const CNT = 21;
    pub const RTIP = 22;
    pub const IPX = 23;
    pub const SIP = 24;
    pub const PIP = 25;
    pub const ISDN = 28;
    pub const E164 = ISDN;
    pub const KEY = 29;
    pub const INET6 = 30;
    pub const NATM = 31;
    pub const SYSTEM = 32;
    pub const NETBIOS = 33;
    pub const PPP = 34;
    pub const MAX = 40;
};

pub const PF = struct {
    pub const UNSPEC = AF.UNSPEC;
    pub const LOCAL = AF.LOCAL;
    pub const UNIX = PF.LOCAL;
    pub const INET = AF.INET;
    pub const IMPLINK = AF.IMPLINK;
    pub const PUP = AF.PUP;
    pub const CHAOS = AF.CHAOS;
    pub const NS = AF.NS;
    pub const ISO = AF.ISO;
    pub const OSI = AF.ISO;
    pub const ECMA = AF.ECMA;
    pub const DATAKIT = AF.DATAKIT;
    pub const CCITT = AF.CCITT;
    pub const SNA = AF.SNA;
    pub const DECnet = AF.DECnet;
    pub const DLI = AF.DLI;
    pub const LAT = AF.LAT;
    pub const HYLINK = AF.HYLINK;
    pub const APPLETALK = AF.APPLETALK;
    pub const ROUTE = AF.ROUTE;
    pub const LINK = AF.LINK;
    pub const XTP = AF.XTP;
    pub const COIP = AF.COIP;
    pub const CNT = AF.CNT;
    pub const SIP = AF.SIP;
    pub const IPX = AF.IPX;
    pub const RTIP = AF.RTIP;
    pub const PIP = AF.PIP;
    pub const ISDN = AF.ISDN;
    pub const KEY = AF.KEY;
    pub const INET6 = AF.INET6;
    pub const NATM = AF.NATM;
    pub const SYSTEM = AF.SYSTEM;
    pub const NETBIOS = AF.NETBIOS;
    pub const PPP = AF.PPP;
    pub const MAX = AF.MAX;
};

pub const SYSPROTO_EVENT = 1;
pub const SYSPROTO_CONTROL = 2;

pub const SOCK = struct {
    pub const STREAM = 1;
    pub const DGRAM = 2;
    pub const RAW = 3;
    pub const RDM = 4;
    pub const SEQPACKET = 5;
    pub const MAXADDRLEN = 255;

    /// Not actually supported by Darwin, but Zig supplies a shim.
    /// This numerical value is not ABI-stable. It need only not conflict
    /// with any other `SOCK` bits.
    pub const CLOEXEC = 1 << 15;
    /// Not actually supported by Darwin, but Zig supplies a shim.
    /// This numerical value is not ABI-stable. It need only not conflict
    /// with any other `SOCK` bits.
    pub const NONBLOCK = 1 << 16;
};

pub const IPPROTO = struct {
    pub const ICMP = 1;
    pub const ICMPV6 = 58;
    pub const TCP = 6;
    pub const UDP = 17;
    pub const IP = 0;
    pub const IPV6 = 41;
};

pub const SOL = struct {
    pub const SOCKET = 0xffff;
};

pub const SO = struct {
    pub const DEBUG = 0x0001;
    pub const ACCEPTCONN = 0x0002;
    pub const REUSEADDR = 0x0004;
    pub const KEEPALIVE = 0x0008;
    pub const DONTROUTE = 0x0010;
    pub const BROADCAST = 0x0020;
    pub const USELOOPBACK = 0x0040;
    pub const LINGER = 0x1080;
    pub const OOBINLINE = 0x0100;
    pub const REUSEPORT = 0x0200;
    pub const ACCEPTFILTER = 0x1000;
    pub const SNDBUF = 0x1001;
    pub const RCVBUF = 0x1002;
    pub const SNDLOWAT = 0x1003;
    pub const RCVLOWAT = 0x1004;
    pub const SNDTIMEO = 0x1005;
    pub const RCVTIMEO = 0x1006;
    pub const ERROR = 0x1007;
    pub const TYPE = 0x1008;

    pub const NREAD = 0x1020;
    pub const NKE = 0x1021;
    pub const NOSIGPIPE = 0x1022;
    pub const NOADDRERR = 0x1023;
    pub const NWRITE = 0x1024;
    pub const REUSESHAREUID = 0x1025;
};

pub const W = struct {
    /// [XSI] no hang in wait/no child to reap
    pub const NOHANG = 0x00000001;
    /// [XSI] notify on stop, untraced child
    pub const UNTRACED = 0x00000002;

    pub fn EXITSTATUS(x: u32) u8 {
        return @intCast(u8, x >> 8);
    }
    pub fn TERMSIG(x: u32) u32 {
        return status(x);
    }
    pub fn STOPSIG(x: u32) u32 {
        return x >> 8;
    }
    pub fn IFEXITED(x: u32) bool {
        return status(x) == 0;
    }
    pub fn IFSTOPPED(x: u32) bool {
        return status(x) == stopped and STOPSIG(x) != 0x13;
    }
    pub fn IFSIGNALED(x: u32) bool {
        return status(x) != stopped and status(x) != 0;
    }

    fn status(x: u32) u32 {
        return x & 0o177;
    }
    const stopped = 0o177;
};

pub const E = enum(u16) {
    /// No error occurred.
    SUCCESS = 0,

    /// Operation not permitted
    PERM = 1,

    /// No such file or directory
    NOENT = 2,

    /// No such process
    SRCH = 3,

    /// Interrupted system call
    INTR = 4,

    /// Input/output error
    IO = 5,

    /// Device not configured
    NXIO = 6,

    /// Argument list too long
    @"2BIG" = 7,

    /// Exec format error
    NOEXEC = 8,

    /// Bad file descriptor
    BADF = 9,

    /// No child processes
    CHILD = 10,

    /// Resource deadlock avoided
    DEADLK = 11,

    /// Cannot allocate memory
    NOMEM = 12,

    /// Permission denied
    ACCES = 13,

    /// Bad address
    FAULT = 14,

    /// Block device required
    NOTBLK = 15,

    /// Device / Resource busy
    BUSY = 16,

    /// File exists
    EXIST = 17,

    /// Cross-device link
    XDEV = 18,

    /// Operation not supported by device
    NODEV = 19,

    /// Not a directory
    NOTDIR = 20,

    /// Is a directory
    ISDIR = 21,

    /// Invalid argument
    INVAL = 22,

    /// Too many open files in system
    NFILE = 23,

    /// Too many open files
    MFILE = 24,

    /// Inappropriate ioctl for device
    NOTTY = 25,

    /// Text file busy
    TXTBSY = 26,

    /// File too large
    FBIG = 27,

    /// No space left on device
    NOSPC = 28,

    /// Illegal seek
    SPIPE = 29,

    /// Read-only file system
    ROFS = 30,

    /// Too many links
    MLINK = 31,

    /// Broken pipe
    PIPE = 32,

    // math software

    /// Numerical argument out of domain
    DOM = 33,

    /// Result too large
    RANGE = 34,

    // non-blocking and interrupt i/o

    /// Resource temporarily unavailable
    /// This is the same code used for `WOULDBLOCK`.
    AGAIN = 35,

    /// Operation now in progress
    INPROGRESS = 36,

    /// Operation already in progress
    ALREADY = 37,

    // ipc/network software -- argument errors

    /// Socket operation on non-socket
    NOTSOCK = 38,

    /// Destination address required
    DESTADDRREQ = 39,

    /// Message too long
    MSGSIZE = 40,

    /// Protocol wrong type for socket
    PROTOTYPE = 41,

    /// Protocol not available
    NOPROTOOPT = 42,

    /// Protocol not supported
    PROTONOSUPPORT = 43,

    /// Socket type not supported
    SOCKTNOSUPPORT = 44,

    /// Operation not supported
    /// The same code is used for `NOTSUP`.
    OPNOTSUPP = 45,

    /// Protocol family not supported
    PFNOSUPPORT = 46,

    /// Address family not supported by protocol family
    AFNOSUPPORT = 47,

    /// Address already in use
    ADDRINUSE = 48,
    /// Can't assign requested address

    // ipc/network software -- operational errors
    ADDRNOTAVAIL = 49,

    /// Network is down
    NETDOWN = 50,

    /// Network is unreachable
    NETUNREACH = 51,

    /// Network dropped connection on reset
    NETRESET = 52,

    /// Software caused connection abort
    CONNABORTED = 53,

    /// Connection reset by peer
    CONNRESET = 54,

    /// No buffer space available
    NOBUFS = 55,

    /// Socket is already connected
    ISCONN = 56,

    /// Socket is not connected
    NOTCONN = 57,

    /// Can't send after socket shutdown
    SHUTDOWN = 58,

    /// Too many references: can't splice
    TOOMANYREFS = 59,

    /// Operation timed out
    TIMEDOUT = 60,

    /// Connection refused
    CONNREFUSED = 61,

    /// Too many levels of symbolic links
    LOOP = 62,

    /// File name too long
    NAMETOOLONG = 63,

    /// Host is down
    HOSTDOWN = 64,

    /// No route to host
    HOSTUNREACH = 65,
    /// Directory not empty

    // quotas & mush
    NOTEMPTY = 66,

    /// Too many processes
    PROCLIM = 67,

    /// Too many users
    USERS = 68,
    /// Disc quota exceeded

    // Network File System
    DQUOT = 69,

    /// Stale NFS file handle
    STALE = 70,

    /// Too many levels of remote in path
    REMOTE = 71,

    /// RPC struct is bad
    BADRPC = 72,

    /// RPC version wrong
    RPCMISMATCH = 73,

    /// RPC prog. not avail
    PROGUNAVAIL = 74,

    /// Program version wrong
    PROGMISMATCH = 75,

    /// Bad procedure for program
    PROCUNAVAIL = 76,

    /// No locks available
    NOLCK = 77,

    /// Function not implemented
    NOSYS = 78,

    /// Inappropriate file type or format
    FTYPE = 79,

    /// Authentication error
    AUTH = 80,

    /// Need authenticator
    NEEDAUTH = 81,

    // Intelligent device errors

    /// Device power is off
    PWROFF = 82,

    /// Device error, e.g. paper out
    DEVERR = 83,

    /// Value too large to be stored in data type
    OVERFLOW = 84,

    // Program loading errors

    /// Bad executable
    BADEXEC = 85,

    /// Bad CPU type in executable
    BADARCH = 86,

    /// Shared library version mismatch
    SHLIBVERS = 87,

    /// Malformed Macho file
    BADMACHO = 88,

    /// Operation canceled
    CANCELED = 89,

    /// Identifier removed
    IDRM = 90,

    /// No message of desired type
    NOMSG = 91,

    /// Illegal byte sequence
    ILSEQ = 92,

    /// Attribute not found
    NOATTR = 93,

    /// Bad message
    BADMSG = 94,

    /// Reserved
    MULTIHOP = 95,

    /// No message available on STREAM
    NODATA = 96,

    /// Reserved
    NOLINK = 97,

    /// No STREAM resources
    NOSR = 98,

    /// Not a STREAM
    NOSTR = 99,

    /// Protocol error
    PROTO = 100,

    /// STREAM ioctl timeout
    TIME = 101,

    /// No such policy registered
    NOPOLICY = 103,

    /// State not recoverable
    NOTRECOVERABLE = 104,

    /// Previous owner died
    OWNERDEAD = 105,

    /// Interface output queue is full
    QFULL = 106,

    _,
};

pub fn getKernError(err: kern_return_t) KernE {
    return @intToEnum(KernE, @truncate(u8, @intCast(usize, err)));
}

/// Kernel return values
pub const KernE = enum(u8) {
    SUCCESS = 0,

    /// Specified address is not currently valid
    INVALID_ADDRESS = 1,

    /// Specified memory is valid, but does not permit the
    /// required forms of access.
    PROTECTION_FAILURE = 2,

    /// The address range specified is already in use, or
    /// no address range of the size specified could be
    /// found.
    NO_SPACE = 3,

    /// The function requested was not applicable to this
    /// type of argument, or an argument is invalid
    INVALID_ARGUMENT = 4,

    /// The function could not be performed.  A catch-all.
    FAILURE = 5,

    /// A system resource could not be allocated to fulfill
    /// this request.  This failure may not be permanent.
    RESOURCE_SHORTAGE = 6,

    /// The task in question does not hold receive rights
    /// for the port argument.
    NOT_RECEIVER = 7,

    /// Bogus access restriction.
    NO_ACCESS = 8,

    /// During a page fault, the target address refers to a
    /// memory object that has been destroyed.  This
    /// failure is permanent.
    MEMORY_FAILURE = 9,

    /// During a page fault, the memory object indicated
    /// that the data could not be returned.  This failure
    /// may be temporary; future attempts to access this
    /// same data may succeed, as defined by the memory
    /// object.
    MEMORY_ERROR = 10,

    /// The receive right is already a member of the portset.
    ALREADY_IN_SET = 11,

    /// The receive right is not a member of a port set.
    NOT_IN_SET = 12,

    /// The name already denotes a right in the task.
    NAME_EXISTS = 13,

    /// The operation was aborted.  Ipc code will
    /// catch this and reflect it as a message error.
    ABORTED = 14,

    /// The name doesn't denote a right in the task.
    INVALID_NAME = 15,

    /// Target task isn't an active task.
    INVALID_TASK = 16,

    /// The name denotes a right, but not an appropriate right.
    INVALID_RIGHT = 17,

    /// A blatant range error.
    INVALID_VALUE = 18,

    /// Operation would overflow limit on user-references.
    UREFS_OVERFLOW = 19,

    /// The supplied (port) capability is improper.
    INVALID_CAPABILITY = 20,

    /// The task already has send or receive rights
    /// for the port under another name.
    RIGHT_EXISTS = 21,

    /// Target host isn't actually a host.
    INVALID_HOST = 22,

    /// An attempt was made to supply "precious" data
    /// for memory that is already present in a
    /// memory object.
    MEMORY_PRESENT = 23,

    /// A page was requested of a memory manager via
    /// memory_object_data_request for an object using
    /// a MEMORY_OBJECT_COPY_CALL strategy, with the
    /// VM_PROT_WANTS_COPY flag being used to specify
    /// that the page desired is for a copy of the
    /// object, and the memory manager has detected
    /// the page was pushed into a copy of the object
    /// while the kernel was walking the shadow chain
    /// from the copy to the object. This error code
    /// is delivered via memory_object_data_error
    /// and is handled by the kernel (it forces the
    /// kernel to restart the fault). It will not be
    /// seen by users.
    MEMORY_DATA_MOVED = 24,

    /// A strategic copy was attempted of an object
    /// upon which a quicker copy is now possible.
    /// The caller should retry the copy using
    /// vm_object_copy_quickly. This error code
    /// is seen only by the kernel.
    MEMORY_RESTART_COPY = 25,

    /// An argument applied to assert processor set privilege
    /// was not a processor set control port.
    INVALID_PROCESSOR_SET = 26,

    /// The specified scheduling attributes exceed the thread's
    /// limits.
    POLICY_LIMIT = 27,

    /// The specified scheduling policy is not currently
    /// enabled for the processor set.
    INVALID_POLICY = 28,

    /// The external memory manager failed to initialize the
    /// memory object.
    INVALID_OBJECT = 29,

    /// A thread is attempting to wait for an event for which
    /// there is already a waiting thread.
    ALREADY_WAITING = 30,

    /// An attempt was made to destroy the default processor
    /// set.
    DEFAULT_SET = 31,

    /// An attempt was made to fetch an exception port that is
    /// protected, or to abort a thread while processing a
    /// protected exception.
    EXCEPTION_PROTECTED = 32,

    /// A ledger was required but not supplied.
    INVALID_LEDGER = 33,

    /// The port was not a memory cache control port.
    INVALID_MEMORY_CONTROL = 34,

    /// An argument supplied to assert security privilege
    /// was not a host security port.
    INVALID_SECURITY = 35,

    /// thread_depress_abort was called on a thread which
    /// was not currently depressed.
    NOT_DEPRESSED = 36,

    /// Object has been terminated and is no longer available
    TERMINATED = 37,

    /// Lock set has been destroyed and is no longer available.
    LOCK_SET_DESTROYED = 38,

    /// The thread holding the lock terminated before releasing
    /// the lock
    LOCK_UNSTABLE = 39,

    /// The lock is already owned by another thread
    LOCK_OWNED = 40,

    /// The lock is already owned by the calling thread
    LOCK_OWNED_SELF = 41,

    /// Semaphore has been destroyed and is no longer available.
    SEMAPHORE_DESTROYED = 42,

    /// Return from RPC indicating the target server was
    /// terminated before it successfully replied
    RPC_SERVER_TERMINATED = 43,

    /// Terminate an orphaned activation.
    RPC_TERMINATE_ORPHAN = 44,

    /// Allow an orphaned activation to continue executing.
    RPC_CONTINUE_ORPHAN = 45,

    /// Empty thread activation (No thread linked to it)
    NOT_SUPPORTED = 46,

    /// Remote node down or inaccessible.
    NODE_DOWN = 47,

    /// A signalled thread was not actually waiting.
    NOT_WAITING = 48,

    /// Some thread-oriented operation (semaphore_wait) timed out
    OPERATION_TIMED_OUT = 49,

    /// During a page fault, indicates that the page was rejected
    /// as a result of a signature check.
    CODESIGN_ERROR = 50,

    /// The requested property cannot be changed at this time.
    POLICY_STATIC = 51,

    /// The provided buffer is of insufficient size for the requested data.
    INSUFFICIENT_BUFFER_SIZE = 52,

    /// Denied by security policy
    DENIED = 53,

    /// The KC on which the function is operating is missing
    MISSING_KC = 54,

    /// The KC on which the function is operating is invalid
    INVALID_KC = 55,

    /// A search or query operation did not return a result
    NOT_FOUND = 56,

    _,
};

pub const SIGSTKSZ = 131072;
pub const MINSIGSTKSZ = 32768;

pub const SS_ONSTACK = 1;
pub const SS_DISABLE = 4;

pub const stack_t = extern struct {
    sp: [*]u8,
    size: isize,
    flags: i32,
};

pub const S = struct {
    pub const IFMT = 0o170000;

    pub const IFIFO = 0o010000;
    pub const IFCHR = 0o020000;
    pub const IFDIR = 0o040000;
    pub const IFBLK = 0o060000;
    pub const IFREG = 0o100000;
    pub const IFLNK = 0o120000;
    pub const IFSOCK = 0o140000;
    pub const IFWHT = 0o160000;

    pub const ISUID = 0o4000;
    pub const ISGID = 0o2000;
    pub const ISVTX = 0o1000;
    pub const IRWXU = 0o700;
    pub const IRUSR = 0o400;
    pub const IWUSR = 0o200;
    pub const IXUSR = 0o100;
    pub const IRWXG = 0o070;
    pub const IRGRP = 0o040;
    pub const IWGRP = 0o020;
    pub const IXGRP = 0o010;
    pub const IRWXO = 0o007;
    pub const IROTH = 0o004;
    pub const IWOTH = 0o002;
    pub const IXOTH = 0o001;

    pub fn ISFIFO(m: u32) bool {
        return m & IFMT == IFIFO;
    }

    pub fn ISCHR(m: u32) bool {
        return m & IFMT == IFCHR;
    }

    pub fn ISDIR(m: u32) bool {
        return m & IFMT == IFDIR;
    }

    pub fn ISBLK(m: u32) bool {
        return m & IFMT == IFBLK;
    }

    pub fn ISREG(m: u32) bool {
        return m & IFMT == IFREG;
    }

    pub fn ISLNK(m: u32) bool {
        return m & IFMT == IFLNK;
    }

    pub fn ISSOCK(m: u32) bool {
        return m & IFMT == IFSOCK;
    }

    pub fn IWHT(m: u32) bool {
        return m & IFMT == IFWHT;
    }
};

pub const HOST_NAME_MAX = 72;

pub const AT = struct {
    pub const FDCWD = -2;
    /// Use effective ids in access check
    pub const EACCESS = 0x0010;
    /// Act on the symlink itself not the target
    pub const SYMLINK_NOFOLLOW = 0x0020;
    /// Act on target of symlink
    pub const SYMLINK_FOLLOW = 0x0040;
    /// Path refers to directory
    pub const REMOVEDIR = 0x0080;
};

pub const addrinfo = extern struct {
    flags: i32,
    family: i32,
    socktype: i32,
    protocol: i32,
    addrlen: socklen_t,
    canonname: ?[*:0]u8,
    addr: ?*sockaddr,
    next: ?*addrinfo,
};

pub const RTLD = struct {
    pub const LAZY = 0x1;
    pub const NOW = 0x2;
    pub const LOCAL = 0x4;
    pub const GLOBAL = 0x8;
    pub const NOLOAD = 0x10;
    pub const NODELETE = 0x80;
    pub const FIRST = 0x100;

    pub const NEXT = @intToPtr(*anyopaque, @bitCast(usize, @as(isize, -1)));
    pub const DEFAULT = @intToPtr(*anyopaque, @bitCast(usize, @as(isize, -2)));
    pub const SELF = @intToPtr(*anyopaque, @bitCast(usize, @as(isize, -3)));
    pub const MAIN_ONLY = @intToPtr(*anyopaque, @bitCast(usize, @as(isize, -5)));
};

pub const F = struct {
    /// duplicate file descriptor
    pub const DUPFD = 0;
    /// get file descriptor flags
    pub const GETFD = 1;
    /// set file descriptor flags
    pub const SETFD = 2;
    /// get file status flags
    pub const GETFL = 3;
    /// set file status flags
    pub const SETFL = 4;
    /// get SIGIO/SIGURG proc/pgrp
    pub const GETOWN = 5;
    /// set SIGIO/SIGURG proc/pgrp
    pub const SETOWN = 6;
    /// get record locking information
    pub const GETLK = 7;
    /// set record locking information
    pub const SETLK = 8;
    /// F.SETLK; wait if blocked
    pub const SETLKW = 9;
    /// F.SETLK; wait if blocked, return on timeout
    pub const SETLKWTIMEOUT = 10;
    pub const FLUSH_DATA = 40;
    /// Used for regression test
    pub const CHKCLEAN = 41;
    /// Preallocate storage
    pub const PREALLOCATE = 42;
    /// Truncate a file without zeroing space
    pub const SETSIZE = 43;
    /// Issue an advisory read async with no copy to user
    pub const RDADVISE = 44;
    /// turn read ahead off/on for this fd
    pub const RDAHEAD = 45;
    /// turn data caching off/on for this fd
    pub const NOCACHE = 48;
    /// file offset to device offset
    pub const LOG2PHYS = 49;
    /// return the full path of the fd
    pub const GETPATH = 50;
    /// fsync + ask the drive to flush to the media
    pub const FULLFSYNC = 51;
    /// find which component (if any) is a package
    pub const PATHPKG_CHECK = 52;
    /// "freeze" all fs operations
    pub const FREEZE_FS = 53;
    /// "thaw" all fs operations
    pub const THAW_FS = 54;
    /// turn data caching off/on (globally) for this file
    pub const GLOBAL_NOCACHE = 55;
    /// add detached signatures
    pub const ADDSIGS = 59;
    /// add signature from same file (used by dyld for shared libs)
    pub const ADDFILESIGS = 61;
    /// used in conjunction with F.NOCACHE to indicate that DIRECT, synchonous writes
    /// should not be used (i.e. its ok to temporaily create cached pages)
    pub const NODIRECT = 62;
    ///Get the protection class of a file from the EA, returns int
    pub const GETPROTECTIONCLASS = 63;
    ///Set the protection class of a file for the EA, requires int
    pub const SETPROTECTIONCLASS = 64;
    ///file offset to device offset, extended
    pub const LOG2PHYS_EXT = 65;
    ///get record locking information, per-process
    pub const GETLKPID = 66;
    ///Mark the file as being the backing store for another filesystem
    pub const SETBACKINGSTORE = 70;
    ///return the full path of the FD, but error in specific mtmd circumstances
    pub const GETPATH_MTMINFO = 71;
    ///Returns the code directory, with associated hashes, to the caller
    pub const GETCODEDIR = 72;
    ///No SIGPIPE generated on EPIPE
    pub const SETNOSIGPIPE = 73;
    ///Status of SIGPIPE for this fd
    pub const GETNOSIGPIPE = 74;
    ///For some cases, we need to rewrap the key for AKS/MKB
    pub const TRANSCODEKEY = 75;
    ///file being written to a by single writer... if throttling enabled, writes
    ///may be broken into smaller chunks with throttling in between
    pub const SINGLE_WRITER = 76;
    ///Get the protection version number for this filesystem
    pub const GETPROTECTIONLEVEL = 77;
    ///Add detached code signatures (used by dyld for shared libs)
    pub const FINDSIGS = 78;
    ///Add signature from same file, only if it is signed by Apple (used by dyld for simulator)
    pub const ADDFILESIGS_FOR_DYLD_SIM = 83;
    ///fsync + issue barrier to drive
    pub const BARRIERFSYNC = 85;
    ///Add signature from same file, return end offset in structure on success
    pub const ADDFILESIGS_RETURN = 97;
    ///Check if Library Validation allows this Mach-O file to be mapped into the calling process
    pub const CHECK_LV = 98;
    ///Deallocate a range of the file
    pub const PUNCHHOLE = 99;
    ///Trim an active file
    pub const TRIM_ACTIVE_FILE = 100;
    ///mark the dup with FD_CLOEXEC
    pub const DUPFD_CLOEXEC = 67;
    /// shared or read lock
    pub const RDLCK = 1;
    /// unlock
    pub const UNLCK = 2;
    /// exclusive or write lock
    pub const WRLCK = 3;
};

pub const FCNTL_FS_SPECIFIC_BASE = 0x00010000;

///close-on-exec flag
pub const FD_CLOEXEC = 1;

pub const LOCK = struct {
    pub const SH = 1;
    pub const EX = 2;
    pub const UN = 8;
    pub const NB = 4;
};

pub const nfds_t = u32;
pub const pollfd = extern struct {
    fd: fd_t,
    events: i16,
    revents: i16,
};

pub const POLL = struct {
    pub const IN = 0x001;
    pub const PRI = 0x002;
    pub const OUT = 0x004;
    pub const RDNORM = 0x040;
    pub const WRNORM = OUT;
    pub const RDBAND = 0x080;
    pub const WRBAND = 0x100;

    pub const EXTEND = 0x0200;
    pub const ATTRIB = 0x0400;
    pub const NLINK = 0x0800;
    pub const WRITE = 0x1000;

    pub const ERR = 0x008;
    pub const HUP = 0x010;
    pub const NVAL = 0x020;

    pub const STANDARD = IN | PRI | OUT | RDNORM | RDBAND | WRBAND | ERR | HUP | NVAL;
};

pub const CLOCK = struct {
    pub const REALTIME = 0;
    pub const MONOTONIC = 6;
    pub const MONOTONIC_RAW = 4;
    pub const MONOTONIC_RAW_APPROX = 5;
    pub const UPTIME_RAW = 8;
    pub const UPTIME_RAW_APPROX = 9;
    pub const PROCESS_CPUTIME_ID = 12;
    pub const THREAD_CPUTIME_ID = 16;
};

/// Max open files per process
/// https://opensource.apple.com/source/xnu/xnu-4903.221.2/bsd/sys/syslimits.h.auto.html
pub const OPEN_MAX = 10240;

pub const rusage = extern struct {
    utime: timeval,
    stime: timeval,
    maxrss: isize,
    ixrss: isize,
    idrss: isize,
    isrss: isize,
    minflt: isize,
    majflt: isize,
    nswap: isize,
    inblock: isize,
    oublock: isize,
    msgsnd: isize,
    msgrcv: isize,
    nsignals: isize,
    nvcsw: isize,
    nivcsw: isize,

    pub const SELF = 0;
    pub const CHILDREN = -1;
};

pub const rlimit_resource = enum(c_int) {
    CPU = 0,
    FSIZE = 1,
    DATA = 2,
    STACK = 3,
    CORE = 4,
    RSS = 5,
    MEMLOCK = 6,
    NPROC = 7,
    NOFILE = 8,
    _,

    pub const AS: rlimit_resource = .RSS;
};

pub const rlim_t = u64;

pub const RLIM = struct {
    /// No limit
    pub const INFINITY: rlim_t = (1 << 63) - 1;

    pub const SAVED_MAX = INFINITY;
    pub const SAVED_CUR = INFINITY;
};

pub const rlimit = extern struct {
    /// Soft limit
    cur: rlim_t,
    /// Hard limit
    max: rlim_t,
};

pub const SHUT = struct {
    pub const RD = 0;
    pub const WR = 1;
    pub const RDWR = 2;
};

// Term
pub const V = struct {
    pub const EOF = 0;
    pub const EOL = 1;
    pub const EOL2 = 2;
    pub const ERASE = 3;
    pub const WERASE = 4;
    pub const KILL = 5;
    pub const REPRINT = 6;
    pub const INTR = 8;
    pub const QUIT = 9;
    pub const SUSP = 10;
    pub const DSUSP = 11;
    pub const START = 12;
    pub const STOP = 13;
    pub const LNEXT = 14;
    pub const DISCARD = 15;
    pub const MIN = 16;
    pub const TIME = 17;
    pub const STATUS = 18;
};

pub const NCCS = 20; // 2 spares (7, 19)

pub const cc_t = u8;
pub const speed_t = u64;
pub const tcflag_t = u64;

pub const IGNBRK: tcflag_t = 0x00000001; // ignore BREAK condition
pub const BRKINT: tcflag_t = 0x00000002; // map BREAK to SIGINTR
pub const IGNPAR: tcflag_t = 0x00000004; // ignore (discard) parity errors
pub const PARMRK: tcflag_t = 0x00000008; // mark parity and framing errors
pub const INPCK: tcflag_t = 0x00000010; // enable checking of parity errors
pub const ISTRIP: tcflag_t = 0x00000020; // strip 8th bit off chars
pub const INLCR: tcflag_t = 0x00000040; // map NL into CR
pub const IGNCR: tcflag_t = 0x00000080; // ignore CR
pub const ICRNL: tcflag_t = 0x00000100; // map CR to NL (ala CRMOD)
pub const IXON: tcflag_t = 0x00000200; // enable output flow control
pub const IXOFF: tcflag_t = 0x00000400; // enable input flow control
pub const IXANY: tcflag_t = 0x00000800; // any char will restart after stop
pub const IMAXBEL: tcflag_t = 0x00002000; // ring bell on input queue full
pub const IUTF8: tcflag_t = 0x00004000; // maintain state for UTF-8 VERASE

pub const OPOST: tcflag_t = 0x00000001; //enable following output processing
pub const ONLCR: tcflag_t = 0x00000002; // map NL to CR-NL (ala CRMOD)
pub const OXTABS: tcflag_t = 0x00000004; // expand tabs to spaces
pub const ONOEOT: tcflag_t = 0x00000008; // discard EOT's (^D) on output)

pub const OCRNL: tcflag_t = 0x00000010; // map CR to NL on output
pub const ONOCR: tcflag_t = 0x00000020; // no CR output at column 0
pub const ONLRET: tcflag_t = 0x00000040; // NL performs CR function
pub const OFILL: tcflag_t = 0x00000080; // use fill characters for delay
pub const NLDLY: tcflag_t = 0x00000300; // \n delay
pub const TABDLY: tcflag_t = 0x00000c04; // horizontal tab delay
pub const CRDLY: tcflag_t = 0x00003000; // \r delay
pub const FFDLY: tcflag_t = 0x00004000; // form feed delay
pub const BSDLY: tcflag_t = 0x00008000; // \b delay
pub const VTDLY: tcflag_t = 0x00010000; // vertical tab delay
pub const OFDEL: tcflag_t = 0x00020000; // fill is DEL, else NUL

pub const NL0: tcflag_t = 0x00000000;
pub const NL1: tcflag_t = 0x00000100;
pub const NL2: tcflag_t = 0x00000200;
pub const NL3: tcflag_t = 0x00000300;
pub const TAB0: tcflag_t = 0x00000000;
pub const TAB1: tcflag_t = 0x00000400;
pub const TAB2: tcflag_t = 0x00000800;
pub const TAB3: tcflag_t = 0x00000004;
pub const CR0: tcflag_t = 0x00000000;
pub const CR1: tcflag_t = 0x00001000;
pub const CR2: tcflag_t = 0x00002000;
pub const CR3: tcflag_t = 0x00003000;
pub const FF0: tcflag_t = 0x00000000;
pub const FF1: tcflag_t = 0x00004000;
pub const BS0: tcflag_t = 0x00000000;
pub const BS1: tcflag_t = 0x00008000;
pub const VT0: tcflag_t = 0x00000000;
pub const VT1: tcflag_t = 0x00010000;

pub const CIGNORE: tcflag_t = 0x00000001; // ignore control flags
pub const CSIZE: tcflag_t = 0x00000300; // character size mask
pub const CS5: tcflag_t = 0x00000000; //    5 bits (pseudo)
pub const CS6: tcflag_t = 0x00000100; //    6 bits
pub const CS7: tcflag_t = 0x00000200; //    7 bits
pub const CS8: tcflag_t = 0x00000300; //    8 bits
pub const CSTOPB: tcflag_t = 0x0000040; // send 2 stop bits
pub const CREAD: tcflag_t = 0x00000800; // enable receiver
pub const PARENB: tcflag_t = 0x00001000; // parity enable
pub const PARODD: tcflag_t = 0x00002000; // odd parity, else even
pub const HUPCL: tcflag_t = 0x00004000; // hang up on last close
pub const CLOCAL: tcflag_t = 0x00008000; // ignore modem status lines
pub const CCTS_OFLOW: tcflag_t = 0x00010000; // CTS flow control of output
pub const CRTSCTS: tcflag_t = (CCTS_OFLOW | CRTS_IFLOW);
pub const CRTS_IFLOW: tcflag_t = 0x00020000; // RTS flow control of input
pub const CDTR_IFLOW: tcflag_t = 0x00040000; // DTR flow control of input
pub const CDSR_OFLOW: tcflag_t = 0x00080000; // DSR flow control of output
pub const CCAR_OFLOW: tcflag_t = 0x00100000; // DCD flow control of output
pub const MDMBUF: tcflag_t = 0x00100000; // old name for CCAR_OFLOW

pub const ECHOKE: tcflag_t = 0x00000001; // visual erase for line kill
pub const ECHOE: tcflag_t = 0x00000002; // visually erase chars
pub const ECHOK: tcflag_t = 0x00000004; // echo NL after line kill
pub const ECHO: tcflag_t = 0x00000008; // enable echoing
pub const ECHONL: tcflag_t = 0x00000010; // echo NL even if ECHO is off
pub const ECHOPRT: tcflag_t = 0x00000020; // visual erase mode for hardcopy
pub const ECHOCTL: tcflag_t = 0x00000040; // echo control chars as ^(Char)
pub const ISIG: tcflag_t = 0x00000080; // enable signals INTR, QUIT, [D]SUSP
pub const ICANON: tcflag_t = 0x00000100; // canonicalize input lines
pub const ALTWERASE: tcflag_t = 0x00000200; // use alternate WERASE algorithm
pub const IEXTEN: tcflag_t = 0x00000400; // enable DISCARD and LNEXT
pub const EXTPROC: tcflag_t = 0x00000800; // external processing
pub const TOSTOP: tcflag_t = 0x00400000; // stop background jobs from output
pub const FLUSHO: tcflag_t = 0x00800000; // output being flushed (state)
pub const NOKERNINFO: tcflag_t = 0x02000000; // no kernel output from VSTATUS
pub const PENDIN: tcflag_t = 0x20000000; // XXX retype pending input (state)
pub const NOFLSH: tcflag_t = 0x80000000; // don't flush after interrupt

pub const TCSANOW: tcflag_t = 0; // make change immediate
pub const TCSADRAIN: tcflag_t = 1; // drain output, then change
pub const TCSAFLUSH: tcflag_t = 2; // drain output, flush input
pub const TCSASOFT: tcflag_t = 0x10; // flag - don't alter h.w. state
pub const TCSA = enum(c_uint) {
    NOW,
    DRAIN,
    FLUSH,
    _,
};

pub const B0: tcflag_t = 0;
pub const B50: tcflag_t = 50;
pub const B75: tcflag_t = 75;
pub const B110: tcflag_t = 110;
pub const B134: tcflag_t = 134;
pub const B150: tcflag_t = 150;
pub const B200: tcflag_t = 200;
pub const B300: tcflag_t = 300;
pub const B600: tcflag_t = 600;
pub const B1200: tcflag_t = 1200;
pub const B1800: tcflag_t = 1800;
pub const B2400: tcflag_t = 2400;
pub const B4800: tcflag_t = 4800;
pub const B9600: tcflag_t = 9600;
pub const B19200: tcflag_t = 19200;
pub const B38400: tcflag_t = 38400;
pub const B7200: tcflag_t = 7200;
pub const B14400: tcflag_t = 14400;
pub const B28800: tcflag_t = 28800;
pub const B57600: tcflag_t = 57600;
pub const B76800: tcflag_t = 76800;
pub const B115200: tcflag_t = 115200;
pub const B230400: tcflag_t = 230400;
pub const EXTA: tcflag_t = 19200;
pub const EXTB: tcflag_t = 38400;

pub const TCIFLUSH: tcflag_t = 1;
pub const TCOFLUSH: tcflag_t = 2;
pub const TCIOFLUSH: tcflag_t = 3;
pub const TCOOFF: tcflag_t = 1;
pub const TCOON: tcflag_t = 2;
pub const TCIOFF: tcflag_t = 3;
pub const TCION: tcflag_t = 4;

pub const termios = extern struct {
    iflag: tcflag_t, // input flags
    oflag: tcflag_t, // output flags
    cflag: tcflag_t, // control flags
    lflag: tcflag_t, // local flags
    cc: [NCCS]cc_t, // control chars
    ispeed: speed_t align(8), // input speed
    ospeed: speed_t, // output speed
};

pub const winsize = extern struct {
    ws_row: u16,
    ws_col: u16,
    ws_xpixel: u16,
    ws_ypixel: u16,
};

pub const T = struct {
    pub const IOCGWINSZ = ior(0x40000000, 't', 104, @sizeOf(winsize));
};
pub const IOCPARM_MASK = 0x1fff;

fn ior(inout: u32, group: usize, num: usize, len: usize) usize {
    return (inout | ((len & IOCPARM_MASK) << 16) | ((group) << 8) | (num));
}

// CPU families mapping
pub const CPUFAMILY = enum(u32) {
    UNKNOWN = 0,
    POWERPC_G3 = 0xcee41549,
    POWERPC_G4 = 0x77c184ae,
    POWERPC_G5 = 0xed76d8aa,
    INTEL_6_13 = 0xaa33392b,
    INTEL_PENRYN = 0x78ea4fbc,
    INTEL_NEHALEM = 0x6b5a4cd2,
    INTEL_WESTMERE = 0x573b5eec,
    INTEL_SANDYBRIDGE = 0x5490b78c,
    INTEL_IVYBRIDGE = 0x1f65e835,
    INTEL_HASWELL = 0x10b282dc,
    INTEL_BROADWELL = 0x582ed09c,
    INTEL_SKYLAKE = 0x37fc219f,
    INTEL_KABYLAKE = 0x0f817246,
    ARM_9 = 0xe73283ae,
    ARM_11 = 0x8ff620d8,
    ARM_XSCALE = 0x53b005f5,
    ARM_12 = 0xbd1b0ae9,
    ARM_13 = 0x0cc90e64,
    ARM_14 = 0x96077ef1,
    ARM_15 = 0xa8511bca,
    ARM_SWIFT = 0x1e2d6381,
    ARM_CYCLONE = 0x37a09642,
    ARM_TYPHOON = 0x2c91a47e,
    ARM_TWISTER = 0x92fb37c8,
    ARM_HURRICANE = 0x67ceee93,
    ARM_MONSOON_MISTRAL = 0xe81e7ef6,
    ARM_VORTEX_TEMPEST = 0x07d34b9f,
    ARM_LIGHTNING_THUNDER = 0x462504d2,
    ARM_FIRESTORM_ICESTORM = 0x1b588bb3,
    _,
};

pub const POSIX_SPAWN_RESETIDS = 0x0001;
pub const POSIX_SPAWN_SETPGROUP = 0x0002;
pub const POSIX_SPAWN_SETSIGDEF = 0x0004;
pub const POSIX_SPAWN_SETSIGMASK = 0x0008;
pub const POSIX_SPAWN_SETEXEC = 0x0040;
pub const POSIX_SPAWN_START_SUSPENDED = 0x0080;
pub const _POSIX_SPAWN_DISABLE_ASLR = 0x0100;
pub const POSIX_SPAWN_SETSID = 0x0400;
pub const _POSIX_SPAWN_RESLIDE = 0x0800;
pub const POSIX_SPAWN_CLOEXEC_DEFAULT = 0x4000;

pub const PT_TRACE_ME = 0;
pub const PT_CONTINUE = 7;
pub const PT_KILL = 8;
pub const PT_STEP = 9;
pub const PT_DETACH = 11;
pub const PT_ATTACHEXC = 14;
pub const PT_DENY_ATTACH = 31;

pub const caddr_t = ?[*]u8;

pub extern "c" fn ptrace(request: c_int, pid: pid_t, addr: caddr_t, data: c_int) c_int;