Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

   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
/*      $NetBSD: hijack.c,v 1.127 2019/02/17 23:35:50 bad Exp $	*/

/*-
 * Copyright (c) 2011 Antti Kantee.  All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * XXX: rumphijack sort of works on glibc Linux.  But it's not
 * the same quality working as on NetBSD.
 * autoconf HAVE_FOO vs. __NetBSD__ / __linux__ could be further
 * improved.
 */
#include <rump/rumpuser_port.h>

#if !defined(lint)
__RCSID("$NetBSD: hijack.c,v 1.127 2019/02/17 23:35:50 bad Exp $");
#endif

#include <sys/param.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/uio.h>

#ifdef __NetBSD__
#include <sys/statvfs.h>
#endif

#ifdef HAVE_KQUEUE
#include <sys/event.h>
#endif

#ifdef __NetBSD__
#include <sys/quotactl.h>
#endif

#include <assert.h>
#include <dlfcn.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include <rump/rumpclient.h>
#include <rump/rump_syscalls.h>

#include "hijack.h"

/*
 * XXX: Consider autogenerating this, syscnames[] and syscalls[] with
 * a DSL where the tool also checks the symbols exported by this library
 * to make sure all relevant calls are accounted for.
 */
enum dualcall {
	DUALCALL_WRITE, DUALCALL_WRITEV, DUALCALL_PWRITE, DUALCALL_PWRITEV,
	DUALCALL_IOCTL, DUALCALL_FCNTL,
	DUALCALL_SOCKET, DUALCALL_ACCEPT,
#ifndef __linux__
	DUALCALL_PACCEPT,
#endif
	DUALCALL_BIND, DUALCALL_CONNECT,
	DUALCALL_GETPEERNAME, DUALCALL_GETSOCKNAME, DUALCALL_LISTEN,
	DUALCALL_RECVFROM, DUALCALL_RECVMSG,
	DUALCALL_SENDTO, DUALCALL_SENDMSG,
	DUALCALL_GETSOCKOPT, DUALCALL_SETSOCKOPT,
	DUALCALL_SHUTDOWN,
	DUALCALL_READ, DUALCALL_READV, DUALCALL_PREAD, DUALCALL_PREADV,
	DUALCALL_DUP2,
	DUALCALL_CLOSE,
	DUALCALL_POLLTS,

#ifndef __linux__
	DUALCALL_STAT, DUALCALL_LSTAT, DUALCALL_FSTAT,
#endif

	DUALCALL_CHMOD, DUALCALL_LCHMOD, DUALCALL_FCHMOD,
	DUALCALL_CHOWN, DUALCALL_LCHOWN, DUALCALL_FCHOWN,
	DUALCALL_OPEN,
	DUALCALL_CHDIR, DUALCALL_FCHDIR,
	DUALCALL_LSEEK,
	DUALCALL_UNLINK, DUALCALL_SYMLINK, DUALCALL_READLINK,
	DUALCALL_LINK, DUALCALL_RENAME,
	DUALCALL_MKDIR, DUALCALL_RMDIR,
	DUALCALL_UTIMES, DUALCALL_LUTIMES, DUALCALL_FUTIMES,
	DUALCALL_UTIMENSAT, DUALCALL_FUTIMENS,
	DUALCALL_TRUNCATE, DUALCALL_FTRUNCATE,
	DUALCALL_FSYNC,
	DUALCALL_ACCESS,

#ifndef __linux__
	DUALCALL___GETCWD,
	DUALCALL_GETDENTS,
#endif

#ifndef __linux__
	DUALCALL_MKNOD,
#endif

#ifdef __NetBSD__
	DUALCALL_GETFH, DUALCALL_FHOPEN, DUALCALL_FHSTAT, DUALCALL_FHSTATVFS1,
#endif

#ifdef HAVE_KQUEUE
	DUALCALL_KEVENT,
#endif

#ifdef __NetBSD__
	DUALCALL___SYSCTL,
	DUALCALL_MODCTL,
#endif

#ifdef __NetBSD__
	DUALCALL_NFSSVC,
#endif

#ifdef __NetBSD__
	DUALCALL_STATVFS1, DUALCALL_FSTATVFS1, DUALCALL_GETVFSSTAT, 
#endif

#ifdef __NetBSD__
	DUALCALL_MOUNT, DUALCALL_UNMOUNT,
#endif

#ifdef HAVE_FSYNC_RANGE
	DUALCALL_FSYNC_RANGE,
#endif

#ifdef HAVE_CHFLAGS
	DUALCALL_CHFLAGS, DUALCALL_LCHFLAGS, DUALCALL_FCHFLAGS,
#endif

#ifdef HAVE___QUOTACTL
	DUALCALL_QUOTACTL,
#endif
#ifdef __NetBSD__
	DUALCALL_LINKAT,
#endif
	DUALCALL__NUM
};

#define RSYS_STRING(a) __STRING(a)
#define RSYS_NAME(a) RSYS_STRING(__CONCAT(RUMP_SYS_RENAME_,a))

/*
 * Would be nice to get this automatically in sync with libc.
 * Also, this does not work for compat-using binaries (we should
 * provide all previous interfaces, not just the current ones)
 */
#if defined(__NetBSD__)

#if !__NetBSD_Prereq__(5,99,7)
#define REALSELECT select
#define REALPOLLTS pollts
#define REALKEVENT kevent
#define REALSTAT __stat30
#define REALLSTAT __lstat30
#define REALFSTAT __fstat30
#define REALUTIMES utimes
#define REALLUTIMES lutimes
#define REALFUTIMES futimes
#define REALMKNOD mknod
#define REALFHSTAT __fhstat40
#else /* >= 5.99.7 */
#define REALSELECT _sys___select50
#define REALPOLLTS _sys___pollts50
#define REALKEVENT _sys___kevent50
#define REALSTAT __stat50
#define REALLSTAT __lstat50
#define REALFSTAT __fstat50
#define REALUTIMES __utimes50
#define REALLUTIMES __lutimes50
#define REALFUTIMES __futimes50
#define REALMKNOD __mknod50
#define REALFHSTAT __fhstat50
#endif /* < 5.99.7 */

#define REALREAD _sys_read
#define REALPREAD _sys_pread
#define REALPWRITE _sys_pwrite
#define REALGETDENTS __getdents30
#define REALMOUNT __mount50
#define REALGETFH __getfh30
#define REALFHOPEN __fhopen40
#define REALFHSTATVFS1 __fhstatvfs140
#define REALSOCKET __socket30

#define LSEEK_ALIAS _lseek
#define VFORK __vfork14

int REALSTAT(const char *, struct stat *);
int REALLSTAT(const char *, struct stat *);
int REALFSTAT(int, struct stat *);
int REALMKNOD(const char *, mode_t, dev_t);
int REALGETDENTS(int, char *, size_t);

int __getcwd(char *, size_t);

#elif defined(__linux__) /* glibc, really */

#define REALREAD read
#define REALPREAD pread
#define REALPWRITE pwrite
#define REALSELECT select
#define REALPOLLTS ppoll
#define REALUTIMES utimes
#define REALLUTIMES lutimes
#define REALFUTIMES futimes
#define REALFHSTAT fhstat
#define REALSOCKET socket

#else /* !NetBSD && !linux */

#error platform not supported

#endif /* platform */

int REALSELECT(int, fd_set *, fd_set *, fd_set *, struct timeval *);
int REALPOLLTS(struct pollfd *, nfds_t,
	       const struct timespec *, const sigset_t *);
int REALKEVENT(int, const struct kevent *, size_t, struct kevent *, size_t,
	       const struct timespec *);
ssize_t REALREAD(int, void *, size_t);
ssize_t REALPREAD(int, void *, size_t, off_t);
ssize_t REALPWRITE(int, const void *, size_t, off_t);
int REALUTIMES(const char *, const struct timeval [2]);
int REALLUTIMES(const char *, const struct timeval [2]);
int REALFUTIMES(int, const struct timeval [2]);
int REALMOUNT(const char *, const char *, int, void *, size_t);
int REALGETFH(const char *, void *, size_t *);
int REALFHOPEN(const void *, size_t, int);
int REALFHSTAT(const void *, size_t, struct stat *);
int REALFHSTATVFS1(const void *, size_t, struct statvfs *, int);
int REALSOCKET(int, int, int);

#define S(a) __STRING(a)
struct sysnames {
	enum dualcall scm_callnum;
	const char *scm_hostname;
	const char *scm_rumpname;
} syscnames[] = {
	{ DUALCALL_SOCKET,	S(REALSOCKET),	RSYS_NAME(SOCKET)	},
	{ DUALCALL_ACCEPT,	"accept",	RSYS_NAME(ACCEPT)	},
#ifndef __linux__
	{ DUALCALL_PACCEPT,	"paccept",	RSYS_NAME(PACCEPT)	},
#endif
	{ DUALCALL_BIND,	"bind",		RSYS_NAME(BIND)		},
	{ DUALCALL_CONNECT,	"connect",	RSYS_NAME(CONNECT)	},
	{ DUALCALL_GETPEERNAME,	"getpeername",	RSYS_NAME(GETPEERNAME)	},
	{ DUALCALL_GETSOCKNAME,	"getsockname",	RSYS_NAME(GETSOCKNAME)	},
	{ DUALCALL_LISTEN,	"listen",	RSYS_NAME(LISTEN)	},
	{ DUALCALL_RECVFROM,	"recvfrom",	RSYS_NAME(RECVFROM)	},
	{ DUALCALL_RECVMSG,	"recvmsg",	RSYS_NAME(RECVMSG)	},
	{ DUALCALL_SENDTO,	"sendto",	RSYS_NAME(SENDTO)	},
	{ DUALCALL_SENDMSG,	"sendmsg",	RSYS_NAME(SENDMSG)	},
	{ DUALCALL_GETSOCKOPT,	"getsockopt",	RSYS_NAME(GETSOCKOPT)	},
	{ DUALCALL_SETSOCKOPT,	"setsockopt",	RSYS_NAME(SETSOCKOPT)	},
	{ DUALCALL_SHUTDOWN,	"shutdown",	RSYS_NAME(SHUTDOWN)	},
	{ DUALCALL_READ,	S(REALREAD),	RSYS_NAME(READ)		},
	{ DUALCALL_READV,	"readv",	RSYS_NAME(READV)	},
	{ DUALCALL_PREAD,	S(REALPREAD),	RSYS_NAME(PREAD)	},
	{ DUALCALL_PREADV,	"preadv",	RSYS_NAME(PREADV)	},
	{ DUALCALL_WRITE,	"write",	RSYS_NAME(WRITE)	},
	{ DUALCALL_WRITEV,	"writev",	RSYS_NAME(WRITEV)	},
	{ DUALCALL_PWRITE,	S(REALPWRITE),	RSYS_NAME(PWRITE)	},
	{ DUALCALL_PWRITEV,	"pwritev",	RSYS_NAME(PWRITEV)	},
	{ DUALCALL_IOCTL,	"ioctl",	RSYS_NAME(IOCTL)	},
	{ DUALCALL_FCNTL,	"fcntl",	RSYS_NAME(FCNTL)	},
	{ DUALCALL_DUP2,	"dup2",		RSYS_NAME(DUP2)		},
	{ DUALCALL_CLOSE,	"close",	RSYS_NAME(CLOSE)	},
	{ DUALCALL_POLLTS,	S(REALPOLLTS),	RSYS_NAME(POLLTS)	},
#ifndef __linux__
	{ DUALCALL_STAT,	S(REALSTAT),	RSYS_NAME(STAT)		},
	{ DUALCALL_LSTAT,	S(REALLSTAT),	RSYS_NAME(LSTAT)	},
	{ DUALCALL_FSTAT,	S(REALFSTAT),	RSYS_NAME(FSTAT)	},
#endif
	{ DUALCALL_CHOWN,	"chown",	RSYS_NAME(CHOWN)	},
	{ DUALCALL_LCHOWN,	"lchown",	RSYS_NAME(LCHOWN)	},
	{ DUALCALL_FCHOWN,	"fchown",	RSYS_NAME(FCHOWN)	},
	{ DUALCALL_CHMOD,	"chmod",	RSYS_NAME(CHMOD)	},
	{ DUALCALL_LCHMOD,	"lchmod",	RSYS_NAME(LCHMOD)	},
	{ DUALCALL_FCHMOD,	"fchmod",	RSYS_NAME(FCHMOD)	},
	{ DUALCALL_UTIMES,	S(REALUTIMES),	RSYS_NAME(UTIMES)	},
	{ DUALCALL_LUTIMES,	S(REALLUTIMES),	RSYS_NAME(LUTIMES)	},
	{ DUALCALL_FUTIMES,	S(REALFUTIMES),	RSYS_NAME(FUTIMES)	},
	{ DUALCALL_UTIMENSAT,	"utimensat",	RSYS_NAME(UTIMENSAT)	},
	{ DUALCALL_FUTIMENS,	"futimens",	RSYS_NAME(FUTIMENS)	},
	{ DUALCALL_OPEN,	"open",		RSYS_NAME(OPEN)		},
	{ DUALCALL_CHDIR,	"chdir",	RSYS_NAME(CHDIR)	},
	{ DUALCALL_FCHDIR,	"fchdir",	RSYS_NAME(FCHDIR)	},
	{ DUALCALL_LSEEK,	"lseek",	RSYS_NAME(LSEEK)	},
	{ DUALCALL_UNLINK,	"unlink",	RSYS_NAME(UNLINK)	},
	{ DUALCALL_SYMLINK,	"symlink",	RSYS_NAME(SYMLINK)	},
	{ DUALCALL_READLINK,	"readlink",	RSYS_NAME(READLINK)	},
	{ DUALCALL_LINK,	"link",		RSYS_NAME(LINK)		},
	{ DUALCALL_RENAME,	"rename",	RSYS_NAME(RENAME)	},
	{ DUALCALL_MKDIR,	"mkdir",	RSYS_NAME(MKDIR)	},
	{ DUALCALL_RMDIR,	"rmdir",	RSYS_NAME(RMDIR)	},
	{ DUALCALL_TRUNCATE,	"truncate",	RSYS_NAME(TRUNCATE)	},
	{ DUALCALL_FTRUNCATE,	"ftruncate",	RSYS_NAME(FTRUNCATE)	},
	{ DUALCALL_FSYNC,	"fsync",	RSYS_NAME(FSYNC)	},
	{ DUALCALL_ACCESS,	"access",	RSYS_NAME(ACCESS)	},

#ifndef __linux__
	{ DUALCALL___GETCWD,	"__getcwd",	RSYS_NAME(__GETCWD)	},
	{ DUALCALL_GETDENTS,	S(REALGETDENTS),RSYS_NAME(GETDENTS)	},
#endif

#ifndef __linux__
	{ DUALCALL_MKNOD,	S(REALMKNOD),	RSYS_NAME(MKNOD)	},
#endif

#ifdef __NetBSD__
	{ DUALCALL_GETFH,	S(REALGETFH),	RSYS_NAME(GETFH)	},
	{ DUALCALL_FHOPEN,	S(REALFHOPEN),	RSYS_NAME(FHOPEN)	},
	{ DUALCALL_FHSTAT,	S(REALFHSTAT),	RSYS_NAME(FHSTAT)	},
	{ DUALCALL_FHSTATVFS1,	S(REALFHSTATVFS1),RSYS_NAME(FHSTATVFS1)	},
#endif

#ifdef HAVE_KQUEUE
	{ DUALCALL_KEVENT,	S(REALKEVENT),	RSYS_NAME(KEVENT)	},
#endif

#ifdef __NetBSD__
	{ DUALCALL___SYSCTL,	"__sysctl",	RSYS_NAME(__SYSCTL)	},
	{ DUALCALL_MODCTL,	"modctl",	RSYS_NAME(MODCTL)	},
#endif

#ifdef __NetBSD__
	{ DUALCALL_NFSSVC,	"nfssvc",	RSYS_NAME(NFSSVC)	},
#endif

#ifdef __NetBSD__
	{ DUALCALL_STATVFS1,	"statvfs1",	RSYS_NAME(STATVFS1)	},
	{ DUALCALL_FSTATVFS1,	"fstatvfs1",	RSYS_NAME(FSTATVFS1)	},
	{ DUALCALL_GETVFSSTAT,	"getvfsstat",	RSYS_NAME(GETVFSSTAT)	},
#endif

#ifdef __NetBSD__
	{ DUALCALL_MOUNT,	S(REALMOUNT),	RSYS_NAME(MOUNT)	},
	{ DUALCALL_UNMOUNT,	"unmount",	RSYS_NAME(UNMOUNT)	},
#endif

#ifdef HAVE_FSYNC_RANGE
	{ DUALCALL_FSYNC_RANGE,	"fsync_range",	RSYS_NAME(FSYNC_RANGE)	},
#endif

#ifdef HAVE_CHFLAGS
	{ DUALCALL_CHFLAGS,	"chflags",	RSYS_NAME(CHFLAGS)	},
	{ DUALCALL_LCHFLAGS,	"lchflags",	RSYS_NAME(LCHFLAGS)	},
	{ DUALCALL_FCHFLAGS,	"fchflags",	RSYS_NAME(FCHFLAGS)	},
#endif /* HAVE_CHFLAGS */

#ifdef HAVE___QUOTACTL
	{ DUALCALL_QUOTACTL,	"__quotactl",	RSYS_NAME(__QUOTACTL)	},
#endif /* HAVE___QUOTACTL */

#ifdef __NetBSD__
	{ DUALCALL_LINKAT,	"linkat",	RSYS_NAME(LINKAT)	},
#endif
};
#undef S

struct bothsys {
	void *bs_host;
	void *bs_rump;
} syscalls[DUALCALL__NUM];
#define GETSYSCALL(which, name) syscalls[DUALCALL_##name].bs_##which

static pid_t	(*host_fork)(void);
static int	(*host_daemon)(int, int);
static void *	(*host_mmap)(void *, size_t, int, int, int, off_t);

/*
 * This tracks if our process is in a subdirectory of /rump.
 * It's preserved over exec.
 */
static bool pwdinrump;

enum pathtype { PATH_HOST, PATH_RUMP, PATH_RUMPBLANKET };

static bool		fd_isrump(int);
static enum pathtype	path_isrump(const char *);

/* default FD_SETSIZE is 256 ==> default fdoff is 128 */
static int hijack_fdoff = FD_SETSIZE/2;

/*
 * Maintain a mapping table for the usual dup2 suspects.
 * Could use atomic ops to operate on dup2vec, but an application
 * racing there is not well-defined, so don't bother.
 */
/* note: you cannot change this without editing the env-passing code */
#define DUP2HIGH 2
static uint32_t dup2vec[DUP2HIGH+1];
#define DUP2BIT (1<<31)
#define DUP2ALIAS (1<<30)
#define DUP2FDMASK ((1<<30)-1)

static bool
isdup2d(int fd)
{

	return fd <= DUP2HIGH && fd >= 0 && dup2vec[fd] & DUP2BIT;
}

static int
mapdup2(int hostfd)
{

	_DIAGASSERT(isdup2d(hostfd));
	return dup2vec[hostfd] & DUP2FDMASK;
}

static int
unmapdup2(int rumpfd)
{
	int i;

	for (i = 0; i <= DUP2HIGH; i++) {
		if (dup2vec[i] & DUP2BIT &&
		    (dup2vec[i] & DUP2FDMASK) == (unsigned)rumpfd)
			return i;
	}
	return -1;
}

static void
setdup2(int hostfd, int rumpfd)
{

	if (hostfd > DUP2HIGH) {
		_DIAGASSERT(0);
		return;
	}

	dup2vec[hostfd] = DUP2BIT | DUP2ALIAS | rumpfd;
}

static void
clrdup2(int hostfd)
{

	if (hostfd > DUP2HIGH) {
		_DIAGASSERT(0);
		return;
	}

	dup2vec[hostfd] = 0;
}

static bool
killdup2alias(int rumpfd)
{
	int hostfd;

	if ((hostfd = unmapdup2(rumpfd)) == -1)
		return false;

	if (dup2vec[hostfd] & DUP2ALIAS) {
		dup2vec[hostfd] &= ~DUP2ALIAS;
		return true;
	}
	return false;
}

//#define DEBUGJACK
#ifdef DEBUGJACK
#define DPRINTF(x) mydprintf x
static void
mydprintf(const char *fmt, ...)
{
	va_list ap;

	if (isdup2d(STDERR_FILENO))
		return;

	va_start(ap, fmt);
	vfprintf(stderr, fmt, ap);
	va_end(ap);
}

static const char *
whichfd(int fd)
{

	if (fd == -1)
		return "-1";
	else if (fd_isrump(fd))
		return "rump";
	else
		return "host";
}

static const char *
whichpath(const char *path)
{

	if (path_isrump(path))
		return "rump";
	else
		return "host";
}

#else
#define DPRINTF(x)
#endif

#define ATCALL(type, name, rcname, args, proto, vars)			\
type name args								\
{									\
	type (*fun) proto;						\
	int isrump = -1;						\
									\
	if (fd == AT_FDCWD || *path == '/') {				\
		isrump = path_isrump(path);				\
	} else {							\
		isrump = fd_isrump(fd);					\
	}								\
									\
	DPRINTF(("%s -> %d:%s (%s)\n", __STRING(name),			\
	    fd, path, isrump ? "rump" : "host"));			\
									\
	assert(isrump != -1);						\
	if (isrump) {							\
		fun = syscalls[rcname].bs_rump;				\
		if (fd != AT_FDCWD)					\
			fd = fd_host2rump(fd);				\
		path = path_host2rump(path);				\
	} else {							\
		fun = syscalls[rcname].bs_host;				\
	}								\
	return fun vars;						\
}

#define FDCALL(type, name, rcname, args, proto, vars)			\
type name args								\
{									\
	type (*fun) proto;						\
									\
	DPRINTF(("%s -> %d (%s)\n", __STRING(name), fd,	whichfd(fd)));	\
	if (fd_isrump(fd)) {						\
		fun = syscalls[rcname].bs_rump;				\
		fd = fd_host2rump(fd);					\
	} else {							\
		fun = syscalls[rcname].bs_host;				\
	}								\
									\
	return fun vars;						\
}

#define PATHCALL(type, name, rcname, args, proto, vars)			\
type name args								\
{									\
	type (*fun) proto;						\
	enum pathtype pt;						\
									\
	DPRINTF(("%s -> %s (%s)\n", __STRING(name), path,		\
	    whichpath(path)));						\
	if ((pt = path_isrump(path)) != PATH_HOST) {			\
		fun = syscalls[rcname].bs_rump;				\
		if (pt == PATH_RUMP)					\
			path = path_host2rump(path);			\
	} else {							\
		fun = syscalls[rcname].bs_host;				\
	}								\
									\
	return fun vars;						\
}

#define VFSCALL(bit, type, name, rcname, args, proto, vars)		\
type name args								\
{									\
	type (*fun) proto;						\
									\
	DPRINTF(("%s (0x%x, 0x%x)\n", __STRING(name), bit, vfsbits));	\
	if (vfsbits & bit) {						\
		fun = syscalls[rcname].bs_rump;				\
	} else {							\
		fun = syscalls[rcname].bs_host;				\
	}								\
									\
	return fun vars;						\
}

/*
 * These variables are set from the RUMPHIJACK string and control
 * which operations can product rump kernel file descriptors.
 * This should be easily extendable for future needs.
 */
#define RUMPHIJACK_DEFAULT "path=/rump,socket=all:nolocal"
static bool rumpsockets[PF_MAX];
static const char *rumpprefix;
static size_t rumpprefixlen;

static struct {
	int pf;
	const char *name;
} socketmap[] = {
	{ PF_LOCAL, "local" },
	{ PF_INET, "inet" },
#ifdef PF_LINK
	{ PF_LINK, "link" },
#endif
#ifdef PF_OROUTE
	{ PF_OROUTE, "oroute" },
#endif
	{ PF_ROUTE, "route" },
	{ PF_INET6, "inet6" },
#ifdef PF_MPLS 
	{ PF_MPLS, "mpls" },
#endif
	{ -1, NULL }
};

static void
sockparser(char *buf)
{
	char *p, *l = NULL;
	bool value;
	int i;

	/* if "all" is present, it must be specified first */
	if (strncmp(buf, "all", strlen("all")) == 0) {
		for (i = 0; i < (int)__arraycount(rumpsockets); i++) {
			rumpsockets[i] = true;
		}
		buf += strlen("all");
		if (*buf == ':')
			buf++;
	}

	for (p = strtok_r(buf, ":", &l); p; p = strtok_r(NULL, ":", &l)) {
		value = true;
		if (strncmp(p, "no", strlen("no")) == 0) {
			value = false;
			p += strlen("no");
		}

		for (i = 0; socketmap[i].name; i++) {
			if (strcmp(p, socketmap[i].name) == 0) {
				rumpsockets[socketmap[i].pf] = value;
				break;
			}
		}
		if (socketmap[i].name == NULL) {
			errx(1, "invalid socket specifier %s", p);
		}
	}
}

static void
pathparser(char *buf)
{

	/* sanity-check */
	if (*buf != '/')
		errx(1, "hijack path specifier must begin with ``/''");
	rumpprefixlen = strlen(buf);
	if (rumpprefixlen < 2)
		errx(1, "invalid hijack prefix: %s", buf);
	if (buf[rumpprefixlen-1] == '/' && strspn(buf, "/") != rumpprefixlen)
		errx(1, "hijack prefix may end in slash only if pure "
		    "slash, gave %s", buf);

	if ((rumpprefix = strdup(buf)) == NULL)
		err(1, "strdup");
	rumpprefixlen = strlen(rumpprefix);
}

static struct blanket {
	const char *pfx;
	size_t len;
} *blanket;
static int nblanket;

static void
blanketparser(char *buf)
{
	char *p, *l = NULL;
	int i;

	for (nblanket = 0, p = buf; p; p = strchr(p+1, ':'), nblanket++)
		continue;

	blanket = malloc(nblanket * sizeof(*blanket));
	if (blanket == NULL)
		err(1, "alloc blanket %d", nblanket);

	for (p = strtok_r(buf, ":", &l), i = 0; p;
	    p = strtok_r(NULL, ":", &l), i++) {
		blanket[i].pfx = strdup(p);
		if (blanket[i].pfx == NULL)
			err(1, "strdup blanket");
		blanket[i].len = strlen(p);

		if (blanket[i].len == 0 || *blanket[i].pfx != '/')
			errx(1, "invalid blanket specifier %s", p);
		if (*(blanket[i].pfx + blanket[i].len-1) == '/')
			errx(1, "invalid blanket specifier %s", p);
	}
}

#define VFSBIT_NFSSVC		0x01
#define VFSBIT_GETVFSSTAT	0x02
#define VFSBIT_FHCALLS		0x04
static unsigned vfsbits;

static struct {
	int bit;
	const char *name;
} vfscalls[] = {
	{ VFSBIT_NFSSVC, "nfssvc" },
	{ VFSBIT_GETVFSSTAT, "getvfsstat" },
	{ VFSBIT_FHCALLS, "fhcalls" },
	{ -1, NULL }
};

static void
vfsparser(char *buf)
{
	char *p, *l = NULL;
	bool turnon;
	unsigned int fullmask;
	int i;

	/* build the full mask and sanity-check while we're at it */
	fullmask = 0;
	for (i = 0; vfscalls[i].name != NULL; i++) {
		if (fullmask & vfscalls[i].bit)
			errx(1, "problem exists between vi and chair");
		fullmask |= vfscalls[i].bit;
	}


	/* if "all" is present, it must be specified first */
	if (strncmp(buf, "all", strlen("all")) == 0) {
		vfsbits = fullmask;
		buf += strlen("all");
		if (*buf == ':')
			buf++;
	}

	for (p = strtok_r(buf, ":", &l); p; p = strtok_r(NULL, ":", &l)) {
		turnon = true;
		if (strncmp(p, "no", strlen("no")) == 0) {
			turnon = false;
			p += strlen("no");
		}

		for (i = 0; vfscalls[i].name; i++) {
			if (strcmp(p, vfscalls[i].name) == 0) {
				if (turnon)
					vfsbits |= vfscalls[i].bit;
				else
					vfsbits &= ~vfscalls[i].bit;
				break;
			}
		}
		if (vfscalls[i].name == NULL) {
			errx(1, "invalid vfscall specifier %s", p);
		}
	}
}

static bool rumpsysctl = false;

static void
sysctlparser(char *buf)
{

	if (buf == NULL) {
		rumpsysctl = true;
		return;
	}

	if (strcasecmp(buf, "y") == 0 || strcasecmp(buf, "yes") == 0 ||
	    strcasecmp(buf, "yep") == 0 || strcasecmp(buf, "tottakai") == 0) {
		rumpsysctl = true;
		return;
	}
	if (strcasecmp(buf, "n") == 0 || strcasecmp(buf, "no") == 0) {
		rumpsysctl = false;
		return;
	}

	errx(1, "sysctl value should be y(es)/n(o), gave: %s", buf);
}

static bool rumpmodctl = false;

static void
modctlparser(char *buf)
{

	if (buf == NULL) {
		rumpmodctl = true;
		return;
	}

	if (strcasecmp(buf, "y") == 0 || strcasecmp(buf, "yes") == 0 ||
	    strcasecmp(buf, "yep") == 0 || strcasecmp(buf, "tottakai") == 0) {
		rumpmodctl = true;
		return;
	}
	if (strcasecmp(buf, "n") == 0 || strcasecmp(buf, "no") == 0) {
		rumpmodctl = false;
		return;
	}

	errx(1, "modctl value should be y(es)/n(o), gave: %s", buf);
}

static void
fdoffparser(char *buf)
{
	unsigned long fdoff;
	char *ep;

	if (*buf == '-') {
		errx(1, "fdoff must not be negative");
	}
	fdoff = strtoul(buf, &ep, 10);
	if (*ep != '\0')
		errx(1, "invalid fdoff specifier \"%s\"", buf);
	if (fdoff >= INT_MAX/2 || fdoff < 3)
		errx(1, "fdoff out of range");
	hijack_fdoff = fdoff;
}

static struct {
	void (*parsefn)(char *);
	const char *name;
	bool needvalues;
} hijackparse[] = {
	{ sockparser, "socket", true },
	{ pathparser, "path", true },
	{ blanketparser, "blanket", true },
	{ vfsparser, "vfs", true },
	{ sysctlparser, "sysctl", false },
	{ modctlparser, "modctl", false },
	{ fdoffparser, "fdoff", true },
	{ NULL, NULL, false },
};

static void
parsehijack(char *hijack)
{
	char *p, *p2, *l;
	const char *hijackcopy;
	bool nop2;
	int i;

	if ((hijackcopy = strdup(hijack)) == NULL)
		err(1, "strdup");

	/* disable everything explicitly */
	for (i = 0; i < PF_MAX; i++)
		rumpsockets[i] = false;

	for (p = strtok_r(hijack, ",", &l); p; p = strtok_r(NULL, ",", &l)) {
		nop2 = false;
		p2 = strchr(p, '=');
		if (!p2) {
			nop2 = true;
			p2 = p + strlen(p);
		}

		for (i = 0; hijackparse[i].parsefn; i++) {
			if (strncmp(hijackparse[i].name, p,
			    (size_t)(p2-p)) == 0) {
				if (nop2 && hijackparse[i].needvalues)
					errx(1, "invalid hijack specifier: %s",
					    hijackcopy);
				hijackparse[i].parsefn(nop2 ? NULL : p2+1);
				break;
			}
		}

		if (hijackparse[i].parsefn == NULL)
			errx(1, "invalid hijack specifier name in %s", p);
	}

}

static void __attribute__((constructor))
rcinit(void)
{
	char buf[1024];
	unsigned i, j;

	host_fork = dlsym(RTLD_NEXT, "fork");
	host_daemon = dlsym(RTLD_NEXT, "daemon");
	if (host_mmap == NULL)
		host_mmap = dlsym(RTLD_NEXT, "mmap");

	/*
	 * In theory cannot print anything during lookups because
	 * we might not have the call vector set up.  so, the errx()
	 * is a bit of a strech, but it might work.
	 */

	for (i = 0; i < DUALCALL__NUM; i++) {
		/* build runtime O(1) access */
		for (j = 0; j < __arraycount(syscnames); j++) {
			if (syscnames[j].scm_callnum == i)
				break;
		}

		if (j == __arraycount(syscnames))
			errx(1, "rumphijack error: syscall pos %d missing", i);

		syscalls[i].bs_host = dlsym(RTLD_NEXT,
		    syscnames[j].scm_hostname);
		if (syscalls[i].bs_host == NULL)
			errx(1, "hostcall %s not found!",
			    syscnames[j].scm_hostname);

		syscalls[i].bs_rump = dlsym(RTLD_NEXT,
		    syscnames[j].scm_rumpname);
		if (syscalls[i].bs_rump == NULL)
			errx(1, "rumpcall %s not found!",
			    syscnames[j].scm_rumpname);
	}

	if (rumpclient_init() == -1)
		err(1, "rumpclient init");

	/* check which syscalls we're supposed to hijack */
	if (getenv_r("RUMPHIJACK", buf, sizeof(buf)) == -1) {
		strcpy(buf, RUMPHIJACK_DEFAULT);
	}
	parsehijack(buf);

	/* set client persistence level */
	if (getenv_r("RUMPHIJACK_RETRYCONNECT", buf, sizeof(buf)) != -1) {
		if (strcmp(buf, "die") == 0)
			rumpclient_setconnretry(RUMPCLIENT_RETRYCONN_DIE);
		else if (strcmp(buf, "inftime") == 0)
			rumpclient_setconnretry(RUMPCLIENT_RETRYCONN_INFTIME);
		else if (strcmp(buf, "once") == 0)
			rumpclient_setconnretry(RUMPCLIENT_RETRYCONN_ONCE);
		else {
			time_t timeout;
			char *ep;

			timeout = (time_t)strtoll(buf, &ep, 10);
			if (timeout <= 0 || ep != buf + strlen(buf))
				errx(1, "RUMPHIJACK_RETRYCONNECT must be "
				    "keyword or integer, got: %s", buf);

			rumpclient_setconnretry(timeout);
		}
	}

	if (getenv_r("RUMPHIJACK__DUP2INFO", buf, sizeof(buf)) == 0) {
		if (sscanf(buf, "%u,%u,%u",
		    &dup2vec[0], &dup2vec[1], &dup2vec[2]) != 3) {
			warnx("invalid dup2mask: %s", buf);
			memset(dup2vec, 0, sizeof(dup2vec));
		}
		unsetenv("RUMPHIJACK__DUP2INFO");
	}
	if (getenv_r("RUMPHIJACK__PWDINRUMP", buf, sizeof(buf)) == 0) {
		pwdinrump = true;
		unsetenv("RUMPHIJACK__PWDINRUMP");
	}
}

static int
fd_rump2host(int fd)
{

	if (fd == -1)
		return fd;
	return fd + hijack_fdoff;
}

static int
fd_rump2host_withdup(int fd)
{
	int hfd;

	_DIAGASSERT(fd != -1);
	hfd = unmapdup2(fd);
	if (hfd != -1) {
		_DIAGASSERT(hfd <= DUP2HIGH);
		return hfd;
	}
	return fd_rump2host(fd);
}

static int
fd_host2rump(int fd)
{
	if (!isdup2d(fd))
		return fd - hijack_fdoff;
	else
		return mapdup2(fd);
}

static bool
fd_isrump(int fd)
{

	return isdup2d(fd) || fd >= hijack_fdoff;
}

#define assertfd(_fd_) assert(ISDUP2D(_fd_) || (_fd_) >= hijack_fdoff)

static enum pathtype
path_isrump(const char *path)
{
	size_t plen;
	int i;

	if (rumpprefix == NULL && nblanket == 0)
		return PATH_HOST;

	if (*path == '/') {
		plen = strlen(path);
		if (rumpprefix && plen >= rumpprefixlen) {
			if (strncmp(path, rumpprefix, rumpprefixlen) == 0
			    && (plen == rumpprefixlen
			      || *(path + rumpprefixlen) == '/')) {
				return PATH_RUMP;
			}
		}
		for (i = 0; i < nblanket; i++) {
			if (strncmp(path, blanket[i].pfx, blanket[i].len) == 0)
				return PATH_RUMPBLANKET;
		}

		return PATH_HOST;
	} else {
		return pwdinrump ? PATH_RUMP : PATH_HOST;
	}
}

static const char *rootpath = "/";
static const char *
path_host2rump(const char *path)
{
	const char *rv;

	if (*path == '/') {
		rv = path + rumpprefixlen;
		if (*rv == '\0')
			rv = rootpath;
	} else {
		rv = path;
	}

	return rv;
}

static int
dodup(int oldd, int minfd)
{
	int (*op_fcntl)(int, int, ...);
	int newd;
	int isrump;

	DPRINTF(("dup -> %d (minfd %d)\n", oldd, minfd));
	if (fd_isrump(oldd)) {
		op_fcntl = GETSYSCALL(rump, FCNTL);
		oldd = fd_host2rump(oldd);
		if (minfd >= hijack_fdoff)
			minfd -= hijack_fdoff;
		isrump = 1;
	} else {
		if (minfd >= hijack_fdoff) {
			errno = EINVAL;
			return -1;
		}
		op_fcntl = GETSYSCALL(host, FCNTL);
		isrump = 0;
	}

	newd = op_fcntl(oldd, F_DUPFD, minfd);

	if (isrump)
		newd = fd_rump2host(newd);
	DPRINTF(("dup <- %d\n", newd));

	return newd;
}

/*
 * Check that host fd value does not exceed fdoffset and if necessary
 * dup the file descriptor so that it doesn't collide with the dup2mask.
 */
static int
fd_host2host(int fd)
{
	int (*op_fcntl)(int, int, ...) = GETSYSCALL(host, FCNTL);
	int (*op_close)(int) = GETSYSCALL(host, CLOSE);
	int ofd, i;

	if (fd >= hijack_fdoff) {
		op_close(fd);
		errno = ENFILE;
		return -1;
	}

	for (i = 1; isdup2d(fd); i++) {
		ofd = fd;
		fd = op_fcntl(ofd, F_DUPFD, i);
		op_close(ofd);
	}

	return fd;
}

int
open(const char *path, int flags, ...)
{
	int (*op_open)(const char *, int, ...);
	bool isrump;
	va_list ap;
	enum pathtype pt;
	int fd;

	DPRINTF(("open -> %s (%s)\n", path, whichpath(path)));

	if ((pt = path_isrump(path)) != PATH_HOST) {
		if (pt == PATH_RUMP)
			path = path_host2rump(path);
		op_open = GETSYSCALL(rump, OPEN);
		isrump = true;
	} else {
		op_open = GETSYSCALL(host, OPEN);
		isrump = false;
	}

	va_start(ap, flags);
	fd = op_open(path, flags, va_arg(ap, mode_t));
	va_end(ap);

	if (isrump)
		fd = fd_rump2host(fd);
	else
		fd = fd_host2host(fd);

	DPRINTF(("open <- %d (%s)\n", fd, whichfd(fd)));
	return fd;
}

int
chdir(const char *path)
{
	int (*op_chdir)(const char *);
	enum pathtype pt;
	int rv;

	if ((pt = path_isrump(path)) != PATH_HOST) {
		op_chdir = GETSYSCALL(rump, CHDIR);
		if (pt == PATH_RUMP)
			path = path_host2rump(path);
	} else {
		op_chdir = GETSYSCALL(host, CHDIR);
	}

	rv = op_chdir(path);
	if (rv == 0)
		pwdinrump = pt != PATH_HOST;

	return rv;
}

int
fchdir(int fd)
{
	int (*op_fchdir)(int);
	bool isrump;
	int rv;

	if (fd_isrump(fd)) {
		op_fchdir = GETSYSCALL(rump, FCHDIR);
		isrump = true;
		fd = fd_host2rump(fd);
	} else {
		op_fchdir = GETSYSCALL(host, FCHDIR);
		isrump = false;
	}

	rv = op_fchdir(fd);
	if (rv == 0) {
		pwdinrump = isrump;
	}

	return rv;
}

#ifndef __linux__
int
__getcwd(char *bufp, size_t len)
{
	int (*op___getcwd)(char *, size_t);
	size_t prefixgap;
	bool iamslash;
	int rv;

	if (pwdinrump && rumpprefix) {
		if (rumpprefix[rumpprefixlen-1] == '/')
			iamslash = true;
		else
			iamslash = false;

		if (iamslash)
			prefixgap = rumpprefixlen - 1; /* ``//+path'' */
		else
			prefixgap = rumpprefixlen; /* ``/pfx+/path'' */
		if (len <= prefixgap) {
			errno = ERANGE;
			return -1;
		}

		op___getcwd = GETSYSCALL(rump, __GETCWD);
		rv = op___getcwd(bufp + prefixgap, len - prefixgap);
		if (rv == -1)
			return rv;

		/* augment the "/" part only for a non-root path */
		memcpy(bufp, rumpprefix, rumpprefixlen);

		/* append / only to non-root cwd */
		if (rv != 2)
			bufp[prefixgap] = '/';

		/* don't append extra slash in the purely-slash case */
		if (rv == 2 && !iamslash)
			bufp[rumpprefixlen] = '\0';
	} else if (pwdinrump) {
		/* assume blanket.  we can't provide a prefix here */
		op___getcwd = GETSYSCALL(rump, __GETCWD);
		rv = op___getcwd(bufp, len);
	} else {
		op___getcwd = GETSYSCALL(host, __GETCWD);
		rv = op___getcwd(bufp, len);
	}

	return rv;
}
#endif

static int
moveish(const char *from, const char *to,
    int (*rump_op)(const char *, const char *),
    int (*host_op)(const char *, const char *))
{
	int (*op)(const char *, const char *);
	enum pathtype ptf, ptt;

	if ((ptf = path_isrump(from)) != PATH_HOST) {
		if ((ptt = path_isrump(to)) == PATH_HOST) {
			errno = EXDEV;
			return -1;
		}

		if (ptf == PATH_RUMP)
			from = path_host2rump(from);
		if (ptt == PATH_RUMP)
			to = path_host2rump(to);
		op = rump_op;
	} else {
		if (path_isrump(to) != PATH_HOST) {
			errno = EXDEV;
			return -1;
		}

		op = host_op;
	}

	return op(from, to);
}

#ifdef __NetBSD__
int
linkat(int fromfd, const char *from, int tofd, const char *to, int flags)
{
	if (fromfd != AT_FDCWD || tofd != AT_FDCWD
	    || flags != AT_SYMLINK_FOLLOW)
		return ENOSYS;

	return moveish(from, to,
	    GETSYSCALL(rump, LINK), GETSYSCALL(host, LINK));
}
#endif

int
link(const char *from, const char *to)
{
	return moveish(from, to,
	    GETSYSCALL(rump, LINK), GETSYSCALL(host, LINK));
}

int
rename(const char *from, const char *to)
{
	return moveish(from, to,
	    GETSYSCALL(rump, RENAME), GETSYSCALL(host, RENAME));
}

int
REALSOCKET(int domain, int type, int protocol)
{
	int (*op_socket)(int, int, int);
	int fd;
	bool isrump;

	isrump = domain < PF_MAX && rumpsockets[domain];

	if (isrump)
		op_socket = GETSYSCALL(rump, SOCKET);
	else
		op_socket = GETSYSCALL(host, SOCKET);
	fd = op_socket(domain, type, protocol);

	if (isrump)
		fd = fd_rump2host(fd);
	else
		fd = fd_host2host(fd);
	DPRINTF(("socket <- %d\n", fd));

	return fd;
}

int
accept(int s, struct sockaddr *addr, socklen_t *addrlen)
{
	int (*op_accept)(int, struct sockaddr *, socklen_t *);
	int fd;
	bool isrump;

	isrump = fd_isrump(s);

	DPRINTF(("accept -> %d", s));
	if (isrump) {
		op_accept = GETSYSCALL(rump, ACCEPT);
		s = fd_host2rump(s);
	} else {
		op_accept = GETSYSCALL(host, ACCEPT);
	}
	fd = op_accept(s, addr, addrlen);
	if (fd != -1 && isrump)
		fd = fd_rump2host(fd);
	else
		fd = fd_host2host(fd);

	DPRINTF((" <- %d\n", fd));

	return fd;
}

#ifndef __linux__
int
paccept(int s, struct sockaddr *addr, socklen_t *addrlen,
    const sigset_t * restrict sigmask, int flags)
{
	int (*op_paccept)(int, struct sockaddr *, socklen_t *,
	    const sigset_t * restrict, int);
	int fd;
	bool isrump;

	isrump = fd_isrump(s);

	DPRINTF(("paccept -> %d", s));
	if (isrump) {
		op_paccept = GETSYSCALL(rump, PACCEPT);
		s = fd_host2rump(s);
	} else {
		op_paccept = GETSYSCALL(host, PACCEPT);
	}
	fd = op_paccept(s, addr, addrlen, sigmask, flags);
	if (fd != -1 && isrump)
		fd = fd_rump2host(fd);
	else
		fd = fd_host2host(fd);

	DPRINTF((" <- %d\n", fd));

	return fd;
}
#endif

/*
 * ioctl() and fcntl() are varargs calls and need special treatment.
 */

/*
 * Various [Linux] libc's have various signatures for ioctl so we
 * need to handle the discrepancies.  On NetBSD, we use the
 * one with unsigned long cmd.
 */
int
#ifdef HAVE_IOCTL_CMD_INT
ioctl(int fd, int cmd, ...)
{
	int (*op_ioctl)(int, int cmd, ...);
#else
ioctl(int fd, unsigned long cmd, ...)
{
	int (*op_ioctl)(int, unsigned long cmd, ...);
#endif
	va_list ap;
	int rv;

	DPRINTF(("ioctl -> %d (%s)\n", fd, whichfd(fd)));
	if (fd_isrump(fd)) {
		fd = fd_host2rump(fd);
		op_ioctl = GETSYSCALL(rump, IOCTL);
	} else {
		op_ioctl = GETSYSCALL(host, IOCTL);
	}

	va_start(ap, cmd);
	rv = op_ioctl(fd, cmd, va_arg(ap, void *));
	va_end(ap);
	DPRINTF(("ioctl <- %d\n", rv));
	return rv;
}

int
fcntl(int fd, int cmd, ...)
{
	int (*op_fcntl)(int, int, ...);
	va_list ap;
	int rv, minfd;

	DPRINTF(("fcntl -> %d (cmd %d)\n", fd, cmd));

	switch (cmd) {
	case F_DUPFD_CLOEXEC:	/* Ignore CLOEXEC bit for now */
	case F_DUPFD:
		va_start(ap, cmd);
		minfd = va_arg(ap, int);
		va_end(ap);
		return dodup(fd, minfd);

#ifdef F_CLOSEM
	case F_CLOSEM: {
		int maxdup2, i;

		/*
		 * So, if fd < HIJACKOFF, we want to do a host closem.
		 */

		if (fd < hijack_fdoff) {
			int closemfd = fd;

			if (rumpclient__closenotify(&closemfd,
			    RUMPCLIENT_CLOSE_FCLOSEM) == -1)
				return -1;
			op_fcntl = GETSYSCALL(host, FCNTL);
			rv = op_fcntl(closemfd, cmd);
			if (rv)
				return rv;
		}

		/*
		 * Additionally, we want to do a rump closem, but only
		 * for the file descriptors not dup2'd.
		 */

		for (i = 0, maxdup2 = -1; i <= DUP2HIGH; i++) {
			if (dup2vec[i] & DUP2BIT) {
				int val;

				val = dup2vec[i] & DUP2FDMASK;
				maxdup2 = MAX(val, maxdup2);
			}
		}
		
		if (fd >= hijack_fdoff)
			fd -= hijack_fdoff;
		else
			fd = 0;
		fd = MAX(maxdup2+1, fd);

		/* hmm, maybe we should close rump fd's not within dup2mask? */
		return rump_sys_fcntl(fd, F_CLOSEM);
	}
#endif /* F_CLOSEM */

#ifdef F_MAXFD
	case F_MAXFD:
		/*
		 * For maxfd, if there's a rump kernel fd, return
		 * it hostified.  Otherwise, return host's MAXFD
		 * return value.
		 */
		if ((rv = rump_sys_fcntl(fd, F_MAXFD)) != -1) {
			/*
			 * This might go a little wrong in case
			 * of dup2 to [012], but I'm not sure if
			 * there's a justification for tracking
			 * that info.  Consider e.g.
			 * dup2(rumpfd, 2) followed by rump_sys_open()
			 * returning 1.  We should return 1+HIJACKOFF,
			 * not 2+HIJACKOFF.  However, if [01] is not
			 * open, the correct return value is 2.
			 */
			return fd_rump2host(fd);
		} else {
			op_fcntl = GETSYSCALL(host, FCNTL);
			return op_fcntl(fd, F_MAXFD);
		}
		/*NOTREACHED*/
#endif /* F_MAXFD */

	default:
		if (fd_isrump(fd)) {
			fd = fd_host2rump(fd);
			op_fcntl = GETSYSCALL(rump, FCNTL);
		} else {
			op_fcntl = GETSYSCALL(host, FCNTL);
		}

		va_start(ap, cmd);
		rv = op_fcntl(fd, cmd, va_arg(ap, void *));
		va_end(ap);
		return rv;
	}
	/*NOTREACHED*/
}

int
close(int fd)
{
	int (*op_close)(int);
	int rv;

	DPRINTF(("close -> %d\n", fd));
	if (fd_isrump(fd)) {
		bool undup2 = false;
		int ofd;

		if (isdup2d(ofd = fd)) {
			undup2 = true;
		}

		fd = fd_host2rump(fd);
		if (!undup2 && killdup2alias(fd)) {
			return 0;
		}

		op_close = GETSYSCALL(rump, CLOSE);
		rv = op_close(fd);
		if (rv == 0 && undup2) {
			clrdup2(ofd);
		}
	} else {
		if (rumpclient__closenotify(&fd, RUMPCLIENT_CLOSE_CLOSE) == -1)
			return -1;
		op_close = GETSYSCALL(host, CLOSE);
		rv = op_close(fd);
	}

	return rv;
}

/*
 * write cannot issue a standard debug printf due to recursion
 */
ssize_t
write(int fd, const void *buf, size_t blen)
{
	ssize_t (*op_write)(int, const void *, size_t);

	if (fd_isrump(fd)) {
		fd = fd_host2rump(fd);
		op_write = GETSYSCALL(rump, WRITE);
	} else {
		op_write = GETSYSCALL(host, WRITE);
	}

	return op_write(fd, buf, blen);
}

/*
 * file descriptor passing
 *
 * we intercept sendmsg and recvmsg to convert file descriptors in
 * control messages.  an attempt to send a descriptor from a different kernel
 * is rejected.  (ENOTSUP)
 */

static int
_msg_convert_fds(struct msghdr *msg, int (*func)(int), bool dryrun)
{
	struct cmsghdr *cmsg;

	for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL;
	    cmsg = CMSG_NXTHDR(msg, cmsg)) {
		if (cmsg->cmsg_level == SOL_SOCKET &&
		    cmsg->cmsg_type == SCM_RIGHTS) {
			int *fdp = (void *)CMSG_DATA(cmsg);
			const size_t size =
			    cmsg->cmsg_len - __CMSG_ALIGN(sizeof(*cmsg));
			const int nfds = (int)(size / sizeof(int));
			const int * const efdp = fdp + nfds;

			while (fdp < efdp) {
				const int newval = func(*fdp);

				if (newval < 0) {
					return ENOTSUP;
				}
				if (!dryrun)
					*fdp = newval;
				fdp++;
			}
		}
	}
	return 0;
}

static int
msg_convert_fds(struct msghdr *msg, int (*func)(int))
{

	return _msg_convert_fds(msg, func, false);
}

static int
msg_check_fds(struct msghdr *msg, int (*func)(int))
{

	return _msg_convert_fds(msg, func, true);
}

ssize_t
recvmsg(int fd, struct msghdr *msg, int flags)
{
	ssize_t (*op_recvmsg)(int, struct msghdr *, int);
	ssize_t ret;
	const bool isrump = fd_isrump(fd);

	if (isrump) {
		fd = fd_host2rump(fd);
		op_recvmsg = GETSYSCALL(rump, RECVMSG);
	} else {
		op_recvmsg = GETSYSCALL(host, RECVMSG);
	}
	ret = op_recvmsg(fd, msg, flags);
	if (ret == -1) {
		return ret;
	}
	/*
	 * convert descriptors in the message.
	 */
	if (isrump) {
		msg_convert_fds(msg, fd_rump2host);
	} else {
		msg_convert_fds(msg, fd_host2host);
	}
	return ret;
}

ssize_t
recv(int fd, void *buf, size_t len, int flags)
{

	return recvfrom(fd, buf, len, flags, NULL, NULL);
}

ssize_t
send(int fd, const void *buf, size_t len, int flags)
{

	return sendto(fd, buf, len, flags, NULL, 0);
}

static int
fd_check_rump(int fd)
{

	return fd_isrump(fd) ? 0 : -1;
}

static int
fd_check_host(int fd)
{

	return !fd_isrump(fd) ? 0 : -1;
}

ssize_t
sendmsg(int fd, const struct msghdr *msg, int flags)
{
	ssize_t (*op_sendmsg)(int, const struct msghdr *, int);
	const bool isrump = fd_isrump(fd);
	int error;

	/*
	 * reject descriptors from a different kernel.
	 */
	error = msg_check_fds(__UNCONST(msg),
	    isrump ? fd_check_rump: fd_check_host);
	if (error != 0) {
		errno = error;
		return -1;
	}
	/*
	 * convert descriptors in the message to raw values.
	 */
	if (isrump) {
		fd = fd_host2rump(fd);
		/*
		 * XXX we directly modify the given message assuming:
		 * - cmsg is writable (typically on caller's stack)
		 * - caller don't care cmsg's contents after calling sendmsg.
		 *   (thus no need to restore values)
		 *
		 * it's safer to copy and modify instead.
		 */
		msg_convert_fds(__UNCONST(msg), fd_host2rump);
		op_sendmsg = GETSYSCALL(rump, SENDMSG);
	} else {
		op_sendmsg = GETSYSCALL(host, SENDMSG);
	}
	return op_sendmsg(fd, msg, flags);
}

/*
 * dup2 is special.  we allow dup2 of a rump kernel fd to 0-2 since
 * many programs do that.  dup2 of a rump kernel fd to another value
 * not >= fdoff is an error.
 *
 * Note: cannot rump2host newd, because it is often hardcoded.
 */
int
dup2(int oldd, int newd)
{
	int (*host_dup2)(int, int);
	int rv;

	DPRINTF(("dup2 -> %d (o) -> %d (n)\n", oldd, newd));

	if (fd_isrump(oldd)) {
		int (*op_close)(int) = GETSYSCALL(host, CLOSE);

		/* only allow fd 0-2 for cross-kernel dup */
		if (!(newd >= 0 && newd <= 2 && !fd_isrump(newd))) {
			errno = EBADF;
			return -1;
		}

		/* regular dup2? */
		if (fd_isrump(newd)) {
			newd = fd_host2rump(newd);
			rv = rump_sys_dup2(oldd, newd);
			return fd_rump2host(rv);
		}

		/*
		 * dup2 rump => host?  just establish an
		 * entry in the mapping table.
		 */
		op_close(newd);
		setdup2(newd, fd_host2rump(oldd));
		rv = 0;
	} else {
		host_dup2 = syscalls[DUALCALL_DUP2].bs_host;
		if (rumpclient__closenotify(&newd, RUMPCLIENT_CLOSE_DUP2) == -1)
			return -1;
		rv = host_dup2(oldd, newd);
	}

	return rv;
}

int
dup(int oldd)
{

	return dodup(oldd, 0);
}

pid_t
fork(void)
{
	pid_t rv;

	DPRINTF(("fork\n"));

	rv = rumpclient__dofork(host_fork);

	DPRINTF(("fork returns %d\n", rv));
	return rv;
}
#ifdef VFORK
/* we do not have the luxury of not requiring a stackframe */
#define	__strong_alias_macro(m, f)	__strong_alias(m, f)
__strong_alias_macro(VFORK,fork);
#endif

int
daemon(int nochdir, int noclose)
{
	struct rumpclient_fork *rf;

	if ((rf = rumpclient_prefork()) == NULL)
		return -1;

	if (host_daemon(nochdir, noclose) == -1)
		return -1;

	if (rumpclient_fork_init(rf) == -1)
		return -1;

	return 0;
}

int
execve(const char *path, char *const argv[], char *const envp[])
{
	char buf[128];
	char *dup2str;
	const char *pwdinrumpstr;
	char **newenv;
	size_t nelem;
	int rv, sverrno;
	int bonus = 2, i = 0;

	snprintf(buf, sizeof(buf), "RUMPHIJACK__DUP2INFO=%u,%u,%u",
	    dup2vec[0], dup2vec[1], dup2vec[2]);
	dup2str = strdup(buf);
	if (dup2str == NULL) {
		errno = ENOMEM;
		return -1;
	}

	if (pwdinrump) {
		pwdinrumpstr = "RUMPHIJACK__PWDINRUMP=true";
		bonus++;
	} else {
		pwdinrumpstr = NULL;
	}

	for (nelem = 0; envp && envp[nelem]; nelem++)
		continue;
	newenv = malloc(sizeof(*newenv) * (nelem+bonus));
	if (newenv == NULL) {
		free(dup2str);
		errno = ENOMEM;
		return -1;
	}
	memcpy(newenv, envp, nelem*sizeof(*newenv));
	newenv[nelem+i] = dup2str;
	i++;

	if (pwdinrumpstr) {
		newenv[nelem+i] = __UNCONST(pwdinrumpstr);
		i++;
	}
	newenv[nelem+i] = NULL;
	_DIAGASSERT(i < bonus);

	rv = rumpclient_exec(path, argv, newenv);

	_DIAGASSERT(rv != 0);
	sverrno = errno;
	free(newenv);
	free(dup2str);
	errno = sverrno;
	return rv;
}

/*
 * select is done by calling poll.
 */
int
REALSELECT(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
	struct timeval *timeout)
{
	struct pollfd *pfds;
	struct timespec ts, *tsp = NULL;
	nfds_t realnfds;
	int i, j;
	int rv, incr;

	DPRINTF(("select %d %p %p %p %p\n", nfds,
	    readfds, writefds, exceptfds, timeout));

	/*
	 * Well, first we must scan the fds to figure out how many
	 * fds there really are.  This is because up to and including
	 * nb5 poll() silently refuses nfds > process_maxopen_fds.
	 * Seems to be fixed in current, thank the maker.
	 * god damn cluster...bomb.
	 */
	
	for (i = 0, realnfds = 0; i < nfds; i++) {
		if (readfds && FD_ISSET(i, readfds)) {
			realnfds++;
			continue;
		}
		if (writefds && FD_ISSET(i, writefds)) {
			realnfds++;
			continue;
		}
		if (exceptfds && FD_ISSET(i, exceptfds)) {
			realnfds++;
			continue;
		}
	}

	if (realnfds) {
		pfds = calloc(realnfds, sizeof(*pfds));
		if (!pfds)
			return -1;
	} else {
		pfds = NULL;
	}

	for (i = 0, j = 0; i < nfds; i++) {
		incr = 0;
		if (readfds && FD_ISSET(i, readfds)) {
			pfds[j].fd = i;
			pfds[j].events |= POLLIN;
			incr=1;
		}
		if (writefds && FD_ISSET(i, writefds)) {
			pfds[j].fd = i;
			pfds[j].events |= POLLOUT;
			incr=1;
		}
		if (exceptfds && FD_ISSET(i, exceptfds)) {
			pfds[j].fd = i;
			pfds[j].events |= POLLHUP|POLLERR;
			incr=1;
		}
		if (incr)
			j++;
	}
	assert(j == (int)realnfds);

	if (timeout) {
		TIMEVAL_TO_TIMESPEC(timeout, &ts);
		tsp = &ts;
	}
	rv = REALPOLLTS(pfds, realnfds, tsp, NULL);
	/*
	 * "If select() returns with an error the descriptor sets
	 * will be unmodified"
	 */
	if (rv < 0)
		goto out;

	/*
	 * zero out results (can't use FD_ZERO for the
	 * obvious select-me-not reason).  whee.
	 *
	 * We do this here since some software ignores the return
	 * value of select, and hence if the timeout expires, it may
	 * assume all input descriptors have activity.
	 */
	for (i = 0; i < nfds; i++) {
		if (readfds)
			FD_CLR(i, readfds);
		if (writefds)
			FD_CLR(i, writefds);
		if (exceptfds)
			FD_CLR(i, exceptfds);
	}
	if (rv == 0)
		goto out;

	/*
	 * We have >0 fds with activity.  Harvest the results.
	 */
	for (i = 0; i < (int)realnfds; i++) {
		if (readfds) {
			if (pfds[i].revents & POLLIN) {
				FD_SET(pfds[i].fd, readfds);
			}
		}
		if (writefds) {
			if (pfds[i].revents & POLLOUT) {
				FD_SET(pfds[i].fd, writefds);
			}
		}
		if (exceptfds) {
			if (pfds[i].revents & (POLLHUP|POLLERR)) {
				FD_SET(pfds[i].fd, exceptfds);
			}
		}
	}

 out:
	free(pfds);
	return rv;
}

static void
checkpoll(struct pollfd *fds, nfds_t nfds, int *hostcall, int *rumpcall)
{
	nfds_t i;

	for (i = 0; i < nfds; i++) {
		if (fds[i].fd == -1)
			continue;

		if (fd_isrump(fds[i].fd))
			(*rumpcall)++;
		else
			(*hostcall)++;
	}
}

static void
adjustpoll(struct pollfd *fds, nfds_t nfds, int (*fdadj)(int))
{
	nfds_t i;

	for (i = 0; i < nfds; i++) {
		fds[i].fd = fdadj(fds[i].fd);
	}
}

/*
 * poll is easy as long as the call comes in the fds only in one
 * kernel.  otherwise its quite tricky...
 */
struct pollarg {
	struct pollfd *pfds;
	nfds_t nfds;
	const struct timespec *ts;
	const sigset_t *sigmask;
	int pipefd;
	int errnum;
};

static void *
hostpoll(void *arg)
{
	int (*op_pollts)(struct pollfd *, nfds_t, const struct timespec *,
			 const sigset_t *);
	struct pollarg *parg = arg;
	intptr_t rv;

	op_pollts = GETSYSCALL(host, POLLTS);
	rv = op_pollts(parg->pfds, parg->nfds, parg->ts, parg->sigmask);
	if (rv == -1)
		parg->errnum = errno;
	rump_sys_write(parg->pipefd, &rv, sizeof(rv));

	return (void *)rv;
}

int
REALPOLLTS(struct pollfd *fds, nfds_t nfds, const struct timespec *ts,
	const sigset_t *sigmask)
{
	int (*op_pollts)(struct pollfd *, nfds_t, const struct timespec *,
			 const sigset_t *);
	int (*host_close)(int);
	int hostcall = 0, rumpcall = 0;
	pthread_t pt;
	nfds_t i;
	int rv;

	DPRINTF(("poll %p %d %p %p\n", fds, (int)nfds, ts, sigmask));
	checkpoll(fds, nfds, &hostcall, &rumpcall);

	if (hostcall && rumpcall) {
		struct pollfd *pfd_host = NULL, *pfd_rump = NULL;
		int rpipe[2] = {-1,-1}, hpipe[2] = {-1,-1};
		struct pollarg parg;
		void *trv_val;
		int sverrno = 0, rv_rump, rv_host, errno_rump, errno_host;

		/*
		 * ok, this is where it gets tricky.  We must support
		 * this since it's a very common operation in certain
		 * types of software (telnet, netcat, etc).  We allocate
		 * two vectors and run two poll commands in separate
		 * threads.  Whichever returns first "wins" and the
		 * other kernel's fds won't show activity.
		 */
		rv = -1;

		/* allocate full vector for O(n) joining after call */
		pfd_host = malloc(sizeof(*pfd_host)*(nfds+1));
		if (!pfd_host)
			goto out;
		pfd_rump = malloc(sizeof(*pfd_rump)*(nfds+1));
		if (!pfd_rump) {
			goto out;
		}

		/*
		 * then, open two pipes, one for notifications
		 * to each kernel.
		 *
		 * At least the rump pipe should probably be
		 * cached, along with the helper threads.  This
		 * should give a microbenchmark improvement (haven't
		 * experienced a macro-level problem yet, though).
		 */
		if ((rv = rump_sys_pipe(rpipe)) == -1) {
			sverrno = errno;
		}
		if (rv == 0 && (rv = pipe(hpipe)) == -1) {
			sverrno = errno;
		}

		/* split vectors (or signal errors) */
		for (i = 0; i < nfds; i++) {
			int fd;

			fds[i].revents = 0;
			if (fds[i].fd == -1) {
				pfd_host[i].fd = -1;
				pfd_rump[i].fd = -1;
			} else if (fd_isrump(fds[i].fd)) {
				pfd_host[i].fd = -1;
				fd = fd_host2rump(fds[i].fd);
				if (fd == rpipe[0] || fd == rpipe[1]) {
					fds[i].revents = POLLNVAL;
					if (rv != -1)
						rv++;
				}
				pfd_rump[i].fd = fd;
				pfd_rump[i].events = fds[i].events;
			} else {
				pfd_rump[i].fd = -1;
				fd = fds[i].fd;
				if (fd == hpipe[0] || fd == hpipe[1]) {
					fds[i].revents = POLLNVAL;
					if (rv != -1)
						rv++;
				}
				pfd_host[i].fd = fd;
				pfd_host[i].events = fds[i].events;
			}
			pfd_rump[i].revents = pfd_host[i].revents = 0;
		}
		if (rv) {
			goto out;
		}

		pfd_host[nfds].fd = hpipe[0];
		pfd_host[nfds].events = POLLIN;
		pfd_rump[nfds].fd = rpipe[0];
		pfd_rump[nfds].events = POLLIN;

		/*
		 * then, create a thread to do host part and meanwhile
		 * do rump kernel part right here
		 */

		parg.pfds = pfd_host;
		parg.nfds = nfds+1;
		parg.ts = ts;
		parg.sigmask = sigmask;
		parg.pipefd = rpipe[1];
		pthread_create(&pt, NULL, hostpoll, &parg);

		op_pollts = GETSYSCALL(rump, POLLTS);
		rv_rump = op_pollts(pfd_rump, nfds+1, ts, NULL);
		errno_rump = errno;
		write(hpipe[1], &rv, sizeof(rv));
		pthread_join(pt, &trv_val);
		rv_host = (int)(intptr_t)trv_val;
		errno_host = parg.errnum;

		/* strip cross-thread notification from real results */
		if (rv_host > 0 && pfd_host[nfds].revents & POLLIN) {
			rv_host--;
		}
		if (rv_rump > 0 && pfd_rump[nfds].revents & POLLIN) {
			rv_rump--;
		}

		/* then merge the results into what's reported to the caller */
		if (rv_rump > 0 || rv_host > 0) {
			/* SUCCESS */

			rv = 0;
			if (rv_rump > 0) {
				for (i = 0; i < nfds; i++) {
					if (pfd_rump[i].fd != -1)
						fds[i].revents
						    = pfd_rump[i].revents;
				}
				rv += rv_rump;
			}
			if (rv_host > 0) {
				for (i = 0; i < nfds; i++) {
					if (pfd_host[i].fd != -1)
						fds[i].revents
						    = pfd_host[i].revents;
				}
				rv += rv_host;
			}
			assert(rv > 0);
			sverrno = 0;
		} else if (rv_rump == -1 || rv_host == -1) {
			/* ERROR */

			/* just pick one kernel at "random" */
			rv = -1;
			if (rv_host == -1) {
				sverrno = errno_host;
			} else if (rv_rump == -1) {
				sverrno = errno_rump;
			}
		} else {
			/* TIMEOUT */

			rv = 0;
			assert(rv_rump == 0 && rv_host == 0);
		}

 out:
		host_close = GETSYSCALL(host, CLOSE);
		if (rpipe[0] != -1)
			rump_sys_close(rpipe[0]);
		if (rpipe[1] != -1)
			rump_sys_close(rpipe[1]);
		if (hpipe[0] != -1)
			host_close(hpipe[0]);
		if (hpipe[1] != -1)
			host_close(hpipe[1]);
		free(pfd_host);
		free(pfd_rump);
		errno = sverrno;
	} else {
		if (hostcall) {
			op_pollts = GETSYSCALL(host, POLLTS);
		} else {
			op_pollts = GETSYSCALL(rump, POLLTS);
			adjustpoll(fds, nfds, fd_host2rump);
		}

		rv = op_pollts(fds, nfds, ts, sigmask);
		if (rumpcall)
			adjustpoll(fds, nfds, fd_rump2host_withdup);
	}

	return rv;
}

int
poll(struct pollfd *fds, nfds_t nfds, int timeout)
{
	struct timespec ts;
	struct timespec *tsp = NULL;

	if (timeout != INFTIM) {
		ts.tv_sec = timeout / 1000;
		ts.tv_nsec = (timeout % 1000) * 1000*1000;

		tsp = &ts;
	}

	return REALPOLLTS(fds, nfds, tsp, NULL);
}

#ifdef HAVE_KQUEUE
int
REALKEVENT(int kq, const struct kevent *changelist, size_t nchanges,
	struct kevent *eventlist, size_t nevents,
	const struct timespec *timeout)
{
	int (*op_kevent)(int, const struct kevent *, size_t,
		struct kevent *, size_t, const struct timespec *);
	const struct kevent *ev;
	size_t i;

	/*
	 * Check that we don't attempt to kevent rump kernel fd's.
	 * That needs similar treatment to select/poll, but is slightly
	 * trickier since we need to manage to different kq descriptors.
	 * (TODO, in case you're wondering).
	 */
	for (i = 0; i < nchanges; i++) {
		ev = &changelist[i];
		if (ev->filter == EVFILT_READ || ev->filter == EVFILT_WRITE ||
		    ev->filter == EVFILT_VNODE) {
			if (fd_isrump((int)ev->ident)) {
				errno = ENOTSUP;
				return -1;
			}
		}
	}

	op_kevent = GETSYSCALL(host, KEVENT);
	return op_kevent(kq, changelist, nchanges, eventlist, nevents, timeout);
}
#endif /* HAVE_KQUEUE */

/*
 * mmapping from a rump kernel is not supported, so disallow it.
 */
void *
mmap(void *addr, size_t len, int prot, int flags, int fd, off_t offset)
{

	if (flags & MAP_FILE && fd_isrump(fd)) {
		errno = ENOSYS;
		return MAP_FAILED;
	}
	if (__predict_false(host_mmap == NULL)) {
		host_mmap = rumphijack_dlsym(RTLD_NEXT, "mmap");
	}
	return host_mmap(addr, len, prot, flags, fd, offset);
}

#ifdef __NetBSD__
/*
 * these go to one or the other on a per-process configuration
 */
int __sysctl(const int *, unsigned int, void *, size_t *, const void *, size_t);
int
__sysctl(const int *name, unsigned int namelen, void *old, size_t *oldlenp,
	const void *new, size_t newlen)
{
	int (*op___sysctl)(const int *, unsigned int, void *, size_t *,
	    const void *, size_t);

	if (rumpsysctl) {
		op___sysctl = GETSYSCALL(rump, __SYSCTL);
	} else {
		op___sysctl = GETSYSCALL(host, __SYSCTL);
		/* we haven't inited yet */
		if (__predict_false(op___sysctl == NULL)) {
			op___sysctl = rumphijack_dlsym(RTLD_NEXT, "__sysctl");
		}
	}

	return op___sysctl(name, namelen, old, oldlenp, new, newlen);
}
int modctl(int, void *);
int
modctl(int operation, void *argp)
{
	int (*op_modctl)(int operation, void *argp);

	if (rumpmodctl) {
		op_modctl = GETSYSCALL(rump, MODCTL);
	} else {
		op_modctl = GETSYSCALL(host, MODCTL);
	}

	return op_modctl(operation, argp);
}
#endif

/*
 * Rest are std type calls.
 */

#ifdef HAVE_UTIMENSAT
ATCALL(int, utimensat, DUALCALL_UTIMENSAT,				\
	(int fd, const char *path, const struct timespec t[2], int f),	\
	(int, const char *, const struct timespec [2], int),
	(fd, path, t, f))
#endif

FDCALL(int, bind, DUALCALL_BIND,					\
	(int fd, const struct sockaddr *name, socklen_t namelen),	\
	(int, const struct sockaddr *, socklen_t),			\
	(fd, name, namelen))

FDCALL(int, connect, DUALCALL_CONNECT,					\
	(int fd, const struct sockaddr *name, socklen_t namelen),	\
	(int, const struct sockaddr *, socklen_t),			\
	(fd, name, namelen))

FDCALL(int, getpeername, DUALCALL_GETPEERNAME,				\
	(int fd, struct sockaddr *name, socklen_t *namelen),		\
	(int, struct sockaddr *, socklen_t *),				\
	(fd, name, namelen))

FDCALL(int, getsockname, DUALCALL_GETSOCKNAME, 				\
	(int fd, struct sockaddr *name, socklen_t *namelen),		\
	(int, struct sockaddr *, socklen_t *),				\
	(fd, name, namelen))

FDCALL(int, listen, DUALCALL_LISTEN,	 				\
	(int fd, int backlog),						\
	(int, int),							\
	(fd, backlog))

FDCALL(ssize_t, recvfrom, DUALCALL_RECVFROM, 				\
	(int fd, void *buf, size_t len, int flags,			\
	    struct sockaddr *from, socklen_t *fromlen),			\
	(int, void *, size_t, int, struct sockaddr *, socklen_t *),	\
	(fd, buf, len, flags, from, fromlen))

FDCALL(ssize_t, sendto, DUALCALL_SENDTO, 				\
	(int fd, const void *buf, size_t len, int flags,		\
	    const struct sockaddr *to, socklen_t tolen),		\
	(int, const void *, size_t, int,				\
	    const struct sockaddr *, socklen_t),			\
	(fd, buf, len, flags, to, tolen))

FDCALL(int, getsockopt, DUALCALL_GETSOCKOPT, 				\
	(int fd, int level, int optn, void *optval, socklen_t *optlen),	\
	(int, int, int, void *, socklen_t *),				\
	(fd, level, optn, optval, optlen))

FDCALL(int, setsockopt, DUALCALL_SETSOCKOPT, 				\
	(int fd, int level, int optn,					\
	    const void *optval, socklen_t optlen),			\
	(int, int, int, const void *, socklen_t),			\
	(fd, level, optn, optval, optlen))

FDCALL(int, shutdown, DUALCALL_SHUTDOWN, 				\
	(int fd, int how),						\
	(int, int),							\
	(fd, how))

FDCALL(ssize_t, REALREAD, DUALCALL_READ,				\
	(int fd, void *buf, size_t buflen),				\
	(int, void *, size_t),						\
	(fd, buf, buflen))

#ifdef __linux__
ssize_t __read_chk(int, void *, size_t)
    __attribute__((alias("read")));
#endif

FDCALL(ssize_t, readv, DUALCALL_READV, 					\
	(int fd, const struct iovec *iov, int iovcnt),			\
	(int, const struct iovec *, int),				\
	(fd, iov, iovcnt))

FDCALL(ssize_t, REALPREAD, DUALCALL_PREAD,				\
	(int fd, void *buf, size_t nbytes, off_t offset),		\
	(int, void *, size_t, off_t),					\
	(fd, buf, nbytes, offset))

FDCALL(ssize_t, preadv, DUALCALL_PREADV, 				\
	(int fd, const struct iovec *iov, int iovcnt, off_t offset),	\
	(int, const struct iovec *, int, off_t),			\
	(fd, iov, iovcnt, offset))

FDCALL(ssize_t, writev, DUALCALL_WRITEV, 				\
	(int fd, const struct iovec *iov, int iovcnt),			\
	(int, const struct iovec *, int),				\
	(fd, iov, iovcnt))

FDCALL(ssize_t, REALPWRITE, DUALCALL_PWRITE,				\
	(int fd, const void *buf, size_t nbytes, off_t offset),		\
	(int, const void *, size_t, off_t),				\
	(fd, buf, nbytes, offset))

FDCALL(ssize_t, pwritev, DUALCALL_PWRITEV, 				\
	(int fd, const struct iovec *iov, int iovcnt, off_t offset),	\
	(int, const struct iovec *, int, off_t),			\
	(fd, iov, iovcnt, offset))

#ifndef __linux__
FDCALL(int, REALFSTAT, DUALCALL_FSTAT,					\
	(int fd, struct stat *sb),					\
	(int, struct stat *),						\
	(fd, sb))
#endif

#ifdef __NetBSD__
FDCALL(int, fstatvfs1, DUALCALL_FSTATVFS1,				\
	(int fd, struct statvfs *buf, int flags),			\
	(int, struct statvfs *, int),					\
	(fd, buf, flags))
#endif

FDCALL(off_t, lseek, DUALCALL_LSEEK,					\
	(int fd, off_t offset, int whence),				\
	(int, off_t, int),						\
	(fd, offset, whence))
#ifdef LSEEK_ALIAS
__strong_alias(LSEEK_ALIAS,lseek);
#endif

#ifndef __linux__
FDCALL(int, REALGETDENTS, DUALCALL_GETDENTS,				\
	(int fd, char *buf, size_t nbytes),				\
	(int, char *, size_t),						\
	(fd, buf, nbytes))
#endif

FDCALL(int, fchown, DUALCALL_FCHOWN,					\
	(int fd, uid_t owner, gid_t group),				\
	(int, uid_t, gid_t),						\
	(fd, owner, group))

FDCALL(int, fchmod, DUALCALL_FCHMOD,					\
	(int fd, mode_t mode),						\
	(int, mode_t),							\
	(fd, mode))

FDCALL(int, ftruncate, DUALCALL_FTRUNCATE,				\
	(int fd, off_t length),						\
	(int, off_t),							\
	(fd, length))

FDCALL(int, fsync, DUALCALL_FSYNC,					\
	(int fd),							\
	(int),								\
	(fd))

#ifdef HAVE_FSYNC_RANGE
FDCALL(int, fsync_range, DUALCALL_FSYNC_RANGE,				\
	(int fd, int how, off_t start, off_t length),			\
	(int, int, off_t, off_t),					\
	(fd, how, start, length))
#endif

FDCALL(int, futimes, DUALCALL_FUTIMES,					\
	(int fd, const struct timeval *tv),				\
	(int, const struct timeval *),					\
	(fd, tv))

FDCALL(int, futimens, DUALCALL_FUTIMENS,				\
	(int fd, const struct timespec *ts),				\
	(int, const struct timespec *),					\
	(fd, ts))

#ifdef HAVE_CHFLAGS
FDCALL(int, fchflags, DUALCALL_FCHFLAGS,				\
	(int fd, u_long flags),						\
	(int, u_long),							\
	(fd, flags))
#endif

/*
 * path-based selectors
 */

#ifndef __linux__
PATHCALL(int, REALSTAT, DUALCALL_STAT,					\
	(const char *path, struct stat *sb),				\
	(const char *, struct stat *),					\
	(path, sb))

PATHCALL(int, REALLSTAT, DUALCALL_LSTAT,				\
	(const char *path, struct stat *sb),				\
	(const char *, struct stat *),					\
	(path, sb))
#endif

PATHCALL(int, chown, DUALCALL_CHOWN,					\
	(const char *path, uid_t owner, gid_t group),			\
	(const char *, uid_t, gid_t),					\
	(path, owner, group))

PATHCALL(int, lchown, DUALCALL_LCHOWN,					\
	(const char *path, uid_t owner, gid_t group),			\
	(const char *, uid_t, gid_t),					\
	(path, owner, group))

PATHCALL(int, chmod, DUALCALL_CHMOD,					\
	(const char *path, mode_t mode),				\
	(const char *, mode_t),						\
	(path, mode))

PATHCALL(int, lchmod, DUALCALL_LCHMOD,					\
	(const char *path, mode_t mode),				\
	(const char *, mode_t),						\
	(path, mode))

#ifdef __NetBSD__
PATHCALL(int, statvfs1, DUALCALL_STATVFS1,				\
	(const char *path, struct statvfs *buf, int flags),		\
	(const char *, struct statvfs *, int),				\
	(path, buf, flags))
#endif

PATHCALL(int, unlink, DUALCALL_UNLINK,					\
	(const char *path),						\
	(const char *),							\
	(path))

PATHCALL(int, symlink, DUALCALL_SYMLINK,				\
	(const char *target, const char *path),				\
	(const char *, const char *),					\
	(target, path))

/*
 * readlink() can be called from malloc which can be called
 * from dlsym() during init
 */
ssize_t
readlink(const char *path, char *buf, size_t bufsiz)
{
	int (*op_readlink)(const char *, char *, size_t);
	enum pathtype pt;

	if ((pt = path_isrump(path)) != PATH_HOST) {
		op_readlink = GETSYSCALL(rump, READLINK);
		if (pt == PATH_RUMP)
			path = path_host2rump(path);
	} else {
		op_readlink = GETSYSCALL(host, READLINK);
	}

	if (__predict_false(op_readlink == NULL)) {
		errno = ENOENT;
		return -1;
	}

	return op_readlink(path, buf, bufsiz);
}

PATHCALL(int, mkdir, DUALCALL_MKDIR,					\
	(const char *path, mode_t mode),				\
	(const char *, mode_t),						\
	(path, mode))

PATHCALL(int, rmdir, DUALCALL_RMDIR,					\
	(const char *path),						\
	(const char *),							\
	(path))

PATHCALL(int, utimes, DUALCALL_UTIMES,					\
	(const char *path, const struct timeval *tv),			\
	(const char *, const struct timeval *),				\
	(path, tv))

PATHCALL(int, lutimes, DUALCALL_LUTIMES,				\
	(const char *path, const struct timeval *tv),			\
	(const char *, const struct timeval *),				\
	(path, tv))

#ifdef HAVE_CHFLAGS
PATHCALL(int, chflags, DUALCALL_CHFLAGS,				\
	(const char *path, u_long flags),				\
	(const char *, u_long),						\
	(path, flags))

PATHCALL(int, lchflags, DUALCALL_LCHFLAGS,				\
	(const char *path, u_long flags),				\
	(const char *, u_long),						\
	(path, flags))
#endif /* HAVE_CHFLAGS */

PATHCALL(int, truncate, DUALCALL_TRUNCATE,				\
	(const char *path, off_t length),				\
	(const char *, off_t),						\
	(path, length))

PATHCALL(int, access, DUALCALL_ACCESS,					\
	(const char *path, int mode),					\
	(const char *, int),						\
	(path, mode))

#ifndef __linux__
PATHCALL(int, REALMKNOD, DUALCALL_MKNOD,				\
	(const char *path, mode_t mode, dev_t dev),			\
	(const char *, mode_t, dev_t),					\
	(path, mode, dev))
#endif

/*
 * Note: with mount the decisive parameter is the mount
 * destination directory.  This is because we don't really know
 * about the "source" directory in a generic call (and besides,
 * it might not even exist, cf. nfs).
 */
#ifdef __NetBSD__
PATHCALL(int, REALMOUNT, DUALCALL_MOUNT,				\
	(const char *type, const char *path, int flags,			\
	    void *data, size_t dlen),					\
	(const char *, const char *, int, void *, size_t),		\
	(type, path, flags, data, dlen))

PATHCALL(int, unmount, DUALCALL_UNMOUNT,				\
	(const char *path, int flags),					\
	(const char *, int),						\
	(path, flags))
#endif /* __NetBSD__ */

#ifdef HAVE___QUOTACTL
PATHCALL(int, __quotactl, DUALCALL_QUOTACTL,				\
	(const char *path, struct quotactl_args *args),			\
	(const char *, struct quotactl_args *),				\
	(path, args))
#endif /* HAVE___QUOTACTL */

#ifdef __NetBSD__
PATHCALL(int, REALGETFH, DUALCALL_GETFH,				\
	(const char *path, void *fhp, size_t *fh_size),			\
	(const char *, void *, size_t *),				\
	(path, fhp, fh_size))
#endif

/*
 * These act different on a per-process vfs configuration
 */

#ifdef __NetBSD__
VFSCALL(VFSBIT_GETVFSSTAT, int, getvfsstat, DUALCALL_GETVFSSTAT,	\
	(struct statvfs *buf, size_t buflen, int flags),		\
	(struct statvfs *, size_t, int),				\
	(buf, buflen, flags))
#endif

#ifdef __NetBSD__
VFSCALL(VFSBIT_FHCALLS, int, REALFHOPEN, DUALCALL_FHOPEN,		\
	(const void *fhp, size_t fh_size, int flags),			\
	(const char *, size_t, int),					\
	(fhp, fh_size, flags))

VFSCALL(VFSBIT_FHCALLS, int, REALFHSTAT, DUALCALL_FHSTAT,		\
	(const void *fhp, size_t fh_size, struct stat *sb),		\
	(const char *, size_t, struct stat *),				\
	(fhp, fh_size, sb))

VFSCALL(VFSBIT_FHCALLS, int, REALFHSTATVFS1, DUALCALL_FHSTATVFS1,	\
	(const void *fhp, size_t fh_size, struct statvfs *sb, int flgs),\
	(const char *, size_t, struct statvfs *, int),			\
	(fhp, fh_size, sb, flgs))
#endif


#ifdef __NetBSD__

/* finally, put nfssvc here.  "keep the namespace clean" */
#include <nfs/rpcv2.h>
#include <nfs/nfs.h>

int
nfssvc(int flags, void *argstructp)
{
	int (*op_nfssvc)(int, void *);

	if (vfsbits & VFSBIT_NFSSVC){
		struct nfsd_args *nfsdargs;

		/* massage the socket descriptor if necessary */
		if (flags == NFSSVC_ADDSOCK) {
			nfsdargs = argstructp;
			nfsdargs->sock = fd_host2rump(nfsdargs->sock);
		}
		op_nfssvc = GETSYSCALL(rump, NFSSVC);
	} else
		op_nfssvc = GETSYSCALL(host, NFSSVC);

	return op_nfssvc(flags, argstructp);
}
#endif /* __NetBSD__ */