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
//! Bindings for WASIp1 aka Preview 1 aka `wasi_snapshot_preview1`.
//!
//! This module contains runtime support for configuring and executing
//! WASIp1-using core WebAssembly modules. Support for WASIp1 is built on top of
//! support for WASIp2 available at [the crate root](crate), but that's just an
//! internal implementation detail.
//!
//! Unlike the crate root, support for WASIp1 centers around two APIs:
//!
//! * [`WasiP1Ctx`]
//! * [`add_to_linker_sync`] (or [`add_to_linker_async`])
//!
//! First a [`WasiCtxBuilder`] will be used and finalized with the [`build_p1`]
//! method to create a [`WasiCtx`]. Next a [`wasmtime::Linker`] is configured
//! with WASI imports by using the `add_to_linker_*` desired (sync or async
//! depending on [`Config::async_support`]).
//!
//! Note that WASIp1 is not as extensible or configurable as WASIp2 so the
//! support in this module is enough to run wasm modules but any customization
//! beyond that [`WasiCtxBuilder`] already supports is not possible yet.
//!
//! [`WasiCtxBuilder`]: crate::WasiCtxBuilder
//! [`build_p1`]: crate::WasiCtxBuilder::build_p1
//! [`Config::async_support`]: wasmtime::Config::async_support
//!
//! # Components vs Modules
//!
//! Note that WASIp1 does not work for components at this time, only core wasm
//! modules. That means this module is only for users of [`wasmtime::Module`]
//! and [`wasmtime::Linker`], for example. If you're using
//! [`wasmtime::component::Component`] or [`wasmtime::component::Linker`] you'll
//! want the WASIp2 [support this crate has](crate) instead.
//!
//! # Examples
//!
//! ```no_run
//! use wasmtime::{Result, Engine, Linker, Module, Store};
//! use wasmtime_wasi::preview1::{self, WasiP1Ctx};
//! use wasmtime_wasi::WasiCtxBuilder;
//!
//! // An example of executing a WASIp1 "command"
//! fn main() -> Result<()> {
//!     let args = std::env::args().skip(1).collect::<Vec<_>>();
//!     let engine = Engine::default();
//!     let module = Module::from_file(&engine, &args[0])?;
//!
//!     let mut linker: Linker<WasiP1Ctx> = Linker::new(&engine);
//!     preview1::add_to_linker_async(&mut linker, |t| t)?;
//!     let pre = linker.instantiate_pre(&module)?;
//!
//!     let wasi_ctx = WasiCtxBuilder::new()
//!         .inherit_stdio()
//!         .inherit_env()
//!         .args(&args)
//!         .build_p1();
//!
//!     let mut store = Store::new(&engine, wasi_ctx);
//!     let instance = pre.instantiate(&mut store)?;
//!     let func = instance.get_typed_func::<(), ()>(&mut store, "_start")?;
//!     func.call(&mut store, ())?;
//!
//!     Ok(())
//! }
//! ```

use crate::bindings::{
    cli::{
        stderr::Host as _, stdin::Host as _, stdout::Host as _, terminal_input, terminal_output,
        terminal_stderr::Host as _, terminal_stdin::Host as _, terminal_stdout::Host as _,
    },
    clocks::{monotonic_clock, wall_clock},
    filesystem::{preopens::Host as _, types as filesystem},
    io::streams,
};
use crate::{FsError, IsATTY, ResourceTable, StreamError, StreamResult, WasiCtx, WasiView};
use anyhow::{bail, Context};
use std::borrow::Borrow;
use std::collections::{BTreeMap, HashSet};
use std::mem::{self, size_of, size_of_val};
use std::ops::{Deref, DerefMut};
use std::slice;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use system_interface::fs::FileIoExt;
use wasmtime::component::Resource;
use wiggle::tracing::instrument;
use wiggle::{GuestError, GuestPtr, GuestStrCow, GuestType};

// Bring all WASI traits in scope that this implementation builds on.
use crate::bindings::cli::environment::Host as _;
use crate::bindings::filesystem::types::HostDescriptor as _;
use crate::bindings::io::poll::Host as _;
use crate::bindings::random::random::Host as _;

/// Structure containing state for WASIp1.
///
/// This structure is created through [`WasiCtxBuilder::build_p1`] and is
/// configured through the various methods of [`WasiCtxBuilder`]. This structure
/// itself implements generated traits for WASIp1 as well as [`WasiView`] to
/// have access to WASIp2.
///
/// Instances of [`WasiP1Ctx`] are typically stored within the `T` of
/// [`Store<T>`](wasmtime::Store).
///
/// [`WasiCtxBuilder::build_p1`]: crate::WasiCtxBuilder::build_p1
/// [`WasiCtxBuilder`]: crate::WasiCtxBuilder
///
/// # Examples
///
/// ```no_run
/// use wasmtime::{Result, Linker};
/// use wasmtime_wasi::preview1::{self, WasiP1Ctx};
/// use wasmtime_wasi::WasiCtxBuilder;
///
/// struct MyState {
///     // ... custom state as necessary ...
///
///     wasi: WasiP1Ctx,
/// }
///
/// impl MyState {
///     fn new() -> MyState {
///         MyState {
///             // .. initialize custom state if needed ..
///
///             wasi: WasiCtxBuilder::new()
///                 .arg("./foo.wasm")
///                 // .. more customization if necesssary ..
///                 .build_p1(),
///         }
///     }
/// }
///
/// fn add_to_linker(linker: &mut Linker<MyState>) -> Result<()> {
///     preview1::add_to_linker_sync(linker, |my_state| &mut my_state.wasi)?;
///     Ok(())
/// }
/// ```
pub struct WasiP1Ctx {
    table: ResourceTable,
    wasi: WasiCtx,
    adapter: WasiPreview1Adapter,
}

impl WasiP1Ctx {
    pub(crate) fn new(wasi: WasiCtx) -> Self {
        Self {
            table: ResourceTable::new(),
            wasi,
            adapter: WasiPreview1Adapter::new(),
        }
    }

    fn as_wasi_view(&mut self) -> &mut dyn WasiView {
        self
    }
}

impl WasiView for WasiP1Ctx {
    fn table(&mut self) -> &mut ResourceTable {
        &mut self.table
    }
    fn ctx(&mut self) -> &mut WasiCtx {
        &mut self.wasi
    }
}

#[derive(Debug)]
struct File {
    /// The handle to the preview2 descriptor of type [`crate::filesystem::Descriptor::File`].
    fd: Resource<filesystem::Descriptor>,

    /// The current-position pointer.
    position: Arc<AtomicU64>,

    /// In append mode, all writes append to the file.
    append: bool,

    /// When blocking, read and write calls dispatch to blocking_read and
    /// blocking_check_write on the underlying streams. When false, read and write
    /// dispatch to stream's plain read and check_write.
    blocking_mode: BlockingMode,
}

#[derive(Clone, Copy, Debug)]
enum BlockingMode {
    Blocking,
    NonBlocking,
}
impl BlockingMode {
    fn from_fdflags(flags: &types::Fdflags) -> Self {
        if flags.contains(types::Fdflags::NONBLOCK) {
            BlockingMode::NonBlocking
        } else {
            BlockingMode::Blocking
        }
    }
    async fn read(
        &self,
        host: &mut dyn WasiView,
        input_stream: Resource<streams::InputStream>,
        max_size: usize,
    ) -> Result<Vec<u8>, types::Error> {
        let max_size = max_size.try_into().unwrap_or(u64::MAX);
        match self {
            BlockingMode::Blocking => {
                match streams::HostInputStream::blocking_read(host, input_stream, max_size).await {
                    Ok(r) if r.is_empty() => Err(types::Errno::Intr.into()),
                    Ok(r) => Ok(r),
                    Err(StreamError::Closed) => Ok(Vec::new()),
                    Err(e) => Err(e.into()),
                }
            }

            BlockingMode::NonBlocking => {
                match streams::HostInputStream::read(host, input_stream, max_size).await {
                    Ok(r) => Ok(r),
                    Err(StreamError::Closed) => Ok(Vec::new()),
                    Err(e) => Err(e.into()),
                }
            }
        }
    }
    async fn write(
        &self,
        host: &mut dyn WasiView,
        output_stream: Resource<streams::OutputStream>,
        bytes: GuestPtr<'_, [u8]>,
    ) -> StreamResult<usize> {
        use streams::HostOutputStream as Streams;

        let bytes = bytes.as_cow().map_err(|e| StreamError::Trap(e.into()))?;
        let mut bytes = &bytes[..];

        match self {
            BlockingMode::Blocking => {
                let total = bytes.len();
                while !bytes.is_empty() {
                    // NOTE: blocking_write_and_flush takes at most one 4k buffer.
                    let len = bytes.len().min(4096);
                    let (chunk, rest) = bytes.split_at(len);
                    bytes = rest;

                    Streams::blocking_write_and_flush(
                        host,
                        output_stream.borrowed(),
                        Vec::from(chunk),
                    )
                    .await?
                }

                Ok(total)
            }
            BlockingMode::NonBlocking => {
                let n = match Streams::check_write(host, output_stream.borrowed()) {
                    Ok(n) => n,
                    Err(StreamError::Closed) => 0,
                    Err(e) => Err(e)?,
                };

                let len = bytes.len().min(n as usize);
                if len == 0 {
                    return Ok(0);
                }

                match Streams::write(host, output_stream.borrowed(), bytes[..len].to_vec()) {
                    Ok(()) => {}
                    Err(StreamError::Closed) => return Ok(0),
                    Err(e) => Err(e)?,
                }

                match Streams::blocking_flush(host, output_stream.borrowed()).await {
                    Ok(()) => {}
                    Err(StreamError::Closed) => return Ok(0),
                    Err(e) => Err(e)?,
                };

                Ok(len)
            }
        }
    }
}

#[derive(Debug)]
enum Descriptor {
    Stdin {
        stream: Resource<streams::InputStream>,
        isatty: IsATTY,
    },
    Stdout {
        stream: Resource<streams::OutputStream>,
        isatty: IsATTY,
    },
    Stderr {
        stream: Resource<streams::OutputStream>,
        isatty: IsATTY,
    },
    /// A fd of type [`crate::filesystem::Descriptor::Dir`]
    Directory {
        fd: Resource<filesystem::Descriptor>,
        /// The path this directory was preopened as.
        /// `None` means this directory was opened using `open-at`.
        preopen_path: Option<String>,
    },
    /// A fd of type [`crate::filesystem::Descriptor::File`]
    File(File),
}

#[derive(Debug, Default)]
struct WasiPreview1Adapter {
    descriptors: Option<Descriptors>,
}

#[derive(Debug, Default)]
struct Descriptors {
    used: BTreeMap<u32, Descriptor>,
    free: Vec<u32>,
}

impl Deref for Descriptors {
    type Target = BTreeMap<u32, Descriptor>;

    fn deref(&self) -> &Self::Target {
        &self.used
    }
}

impl DerefMut for Descriptors {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.used
    }
}

impl Descriptors {
    /// Initializes [Self] using `preopens`
    fn new(host: &mut dyn WasiView) -> Result<Self, types::Error> {
        let mut descriptors = Self::default();
        descriptors.push(Descriptor::Stdin {
            stream: host
                .get_stdin()
                .context("failed to call `get-stdin`")
                .map_err(types::Error::trap)?,
            isatty: if let Some(term_in) = host
                .get_terminal_stdin()
                .context("failed to call `get-terminal-stdin`")
                .map_err(types::Error::trap)?
            {
                terminal_input::HostTerminalInput::drop(host, term_in)
                    .context("failed to call `drop-terminal-input`")
                    .map_err(types::Error::trap)?;
                IsATTY::Yes
            } else {
                IsATTY::No
            },
        })?;
        descriptors.push(Descriptor::Stdout {
            stream: host
                .get_stdout()
                .context("failed to call `get-stdout`")
                .map_err(types::Error::trap)?,
            isatty: if let Some(term_out) = host
                .get_terminal_stdout()
                .context("failed to call `get-terminal-stdout`")
                .map_err(types::Error::trap)?
            {
                terminal_output::HostTerminalOutput::drop(host, term_out)
                    .context("failed to call `drop-terminal-output`")
                    .map_err(types::Error::trap)?;
                IsATTY::Yes
            } else {
                IsATTY::No
            },
        })?;
        descriptors.push(Descriptor::Stderr {
            stream: host
                .get_stderr()
                .context("failed to call `get-stderr`")
                .map_err(types::Error::trap)?,
            isatty: if let Some(term_out) = host
                .get_terminal_stderr()
                .context("failed to call `get-terminal-stderr`")
                .map_err(types::Error::trap)?
            {
                terminal_output::HostTerminalOutput::drop(host, term_out)
                    .context("failed to call `drop-terminal-output`")
                    .map_err(types::Error::trap)?;
                IsATTY::Yes
            } else {
                IsATTY::No
            },
        })?;

        for dir in host
            .get_directories()
            .context("failed to call `get-directories`")
            .map_err(types::Error::trap)?
        {
            descriptors.push(Descriptor::Directory {
                fd: dir.0,
                preopen_path: Some(dir.1),
            })?;
        }
        Ok(descriptors)
    }

    /// Returns next descriptor number, which was never assigned
    fn unused(&self) -> Result<u32> {
        match self.last_key_value() {
            Some((fd, _)) => {
                if let Some(fd) = fd.checked_add(1) {
                    return Ok(fd);
                }
                if self.len() == u32::MAX as usize {
                    return Err(types::Errno::Loop.into());
                }
                // TODO: Optimize
                Ok((0..u32::MAX)
                    .rev()
                    .find(|fd| !self.contains_key(fd))
                    .expect("failed to find an unused file descriptor"))
            }
            None => Ok(0),
        }
    }

    /// Removes the [Descriptor] corresponding to `fd`
    fn remove(&mut self, fd: types::Fd) -> Option<Descriptor> {
        let fd = fd.into();
        let desc = self.used.remove(&fd)?;
        self.free.push(fd);
        Some(desc)
    }

    /// Pushes the [Descriptor] returning corresponding number.
    /// This operation will try to reuse numbers previously removed via [`Self::remove`]
    /// and rely on [`Self::unused`] if no free numbers are recorded
    fn push(&mut self, desc: Descriptor) -> Result<u32> {
        let fd = if let Some(fd) = self.free.pop() {
            fd
        } else {
            self.unused()?
        };
        assert!(self.insert(fd, desc).is_none());
        Ok(fd)
    }
}

impl WasiPreview1Adapter {
    fn new() -> Self {
        Self::default()
    }
}

/// A mutably-borrowed [`WasiPreview1View`] implementation, which provides access to the stored
/// state. It can be thought of as an in-flight [`WasiPreview1Adapter`] transaction, all
/// changes will be recorded in the underlying [`WasiPreview1Adapter`] returned by
/// [`WasiPreview1View::adapter_mut`] on [`Drop`] of this struct.
// NOTE: This exists for the most part just due to the fact that `bindgen` generates methods with
// `&mut self` receivers and so this struct lets us extend the lifetime of the `&mut self` borrow
// of the [`WasiPreview1View`] to provide means to return mutably and immutably borrowed [`Descriptors`]
// without having to rely on something like `Arc<Mutex<Descriptors>>`, while also being able to
// call methods like [`Descriptor::is_file`] and hiding complexity from preview1 method implementations.
struct Transaction<'a> {
    view: &'a mut WasiP1Ctx,
    descriptors: Descriptors,
}

impl Drop for Transaction<'_> {
    /// Record changes in the [`WasiPreview1Adapter`] returned by [`WasiPreview1View::adapter_mut`]
    fn drop(&mut self) {
        let descriptors = mem::take(&mut self.descriptors);
        self.view.adapter.descriptors = Some(descriptors);
    }
}

impl Transaction<'_> {
    /// Borrows [`Descriptor`] corresponding to `fd`.
    ///
    /// # Errors
    ///
    /// Returns [`types::Errno::Badf`] if no [`Descriptor`] is found
    fn get_descriptor(&self, fd: types::Fd) -> Result<&Descriptor> {
        let fd = fd.into();
        let desc = self.descriptors.get(&fd).ok_or(types::Errno::Badf)?;
        Ok(desc)
    }

    /// Borrows [`File`] corresponding to `fd`
    /// if it describes a [`Descriptor::File`]
    fn get_file(&self, fd: types::Fd) -> Result<&File> {
        let fd = fd.into();
        match self.descriptors.get(&fd) {
            Some(Descriptor::File(file)) => Ok(file),
            _ => Err(types::Errno::Badf.into()),
        }
    }

    /// Mutably borrows [`File`] corresponding to `fd`
    /// if it describes a [`Descriptor::File`]
    fn get_file_mut(&mut self, fd: types::Fd) -> Result<&mut File> {
        let fd = fd.into();
        match self.descriptors.get_mut(&fd) {
            Some(Descriptor::File(file)) => Ok(file),
            _ => Err(types::Errno::Badf.into()),
        }
    }

    /// Borrows [`File`] corresponding to `fd`
    /// if it describes a [`Descriptor::File`]
    ///
    /// # Errors
    ///
    /// Returns [`types::Errno::Spipe`] if the descriptor corresponds to stdio
    fn get_seekable(&self, fd: types::Fd) -> Result<&File> {
        let fd = fd.into();
        match self.descriptors.get(&fd) {
            Some(Descriptor::File(file)) => Ok(file),
            Some(
                Descriptor::Stdin { .. } | Descriptor::Stdout { .. } | Descriptor::Stderr { .. },
            ) => {
                // NOTE: legacy implementation returns SPIPE here
                Err(types::Errno::Spipe.into())
            }
            _ => Err(types::Errno::Badf.into()),
        }
    }

    /// Returns [`filesystem::Descriptor`] corresponding to `fd`
    fn get_fd(&self, fd: types::Fd) -> Result<Resource<filesystem::Descriptor>> {
        match self.get_descriptor(fd)? {
            Descriptor::File(File { fd, .. }) => Ok(fd.borrowed()),
            Descriptor::Directory { fd, .. } => Ok(fd.borrowed()),
            Descriptor::Stdin { .. } | Descriptor::Stdout { .. } | Descriptor::Stderr { .. } => {
                Err(types::Errno::Badf.into())
            }
        }
    }

    /// Returns [`filesystem::Descriptor`] corresponding to `fd`
    /// if it describes a [`Descriptor::File`]
    fn get_file_fd(&self, fd: types::Fd) -> Result<Resource<filesystem::Descriptor>> {
        self.get_file(fd).map(|File { fd, .. }| fd.borrowed())
    }

    /// Returns [`filesystem::Descriptor`] corresponding to `fd`
    /// if it describes a [`Descriptor::Directory`]
    fn get_dir_fd(&self, fd: types::Fd) -> Result<Resource<filesystem::Descriptor>> {
        let fd = fd.into();
        match self.descriptors.get(&fd) {
            Some(Descriptor::Directory { fd, .. }) => Ok(fd.borrowed()),
            _ => Err(types::Errno::Badf.into()),
        }
    }
}

impl WasiP1Ctx {
    /// Lazily initializes [`WasiPreview1Adapter`] returned by [`WasiPreview1View::adapter_mut`]
    /// and returns [`Transaction`] on success
    fn transact(&mut self) -> Result<Transaction<'_>, types::Error> {
        let descriptors = if let Some(descriptors) = self.adapter.descriptors.take() {
            descriptors
        } else {
            Descriptors::new(self.as_wasi_view())?
        }
        .into();
        Ok(Transaction {
            view: self,
            descriptors,
        })
    }

    /// Lazily initializes [`WasiPreview1Adapter`] returned by [`WasiPreview1View::adapter_mut`]
    /// and returns [`filesystem::Descriptor`] corresponding to `fd`
    fn get_fd(&mut self, fd: types::Fd) -> Result<Resource<filesystem::Descriptor>, types::Error> {
        let st = self.transact()?;
        let fd = st.get_fd(fd)?;
        Ok(fd)
    }

    /// Lazily initializes [`WasiPreview1Adapter`] returned by [`WasiPreview1View::adapter_mut`]
    /// and returns [`filesystem::Descriptor`] corresponding to `fd`
    /// if it describes a [`Descriptor::File`] of [`crate::filesystem::File`] type
    fn get_file_fd(
        &mut self,
        fd: types::Fd,
    ) -> Result<Resource<filesystem::Descriptor>, types::Error> {
        let st = self.transact()?;
        let fd = st.get_file_fd(fd)?;
        Ok(fd)
    }

    /// Lazily initializes [`WasiPreview1Adapter`] returned by [`WasiPreview1View::adapter_mut`]
    /// and returns [`filesystem::Descriptor`] corresponding to `fd`
    /// if it describes a [`Descriptor::File`] or [`Descriptor::PreopenDirectory`]
    /// of [`crate::filesystem::Dir`] type
    fn get_dir_fd(
        &mut self,
        fd: types::Fd,
    ) -> Result<Resource<filesystem::Descriptor>, types::Error> {
        let st = self.transact()?;
        let fd = st.get_dir_fd(fd)?;
        Ok(fd)
    }
}

/// Adds asynchronous versions of all WASIp1 functions to the
/// [`wasmtime::Linker`] provided.
///
/// This method will add WASIp1 functions to `linker`. The `f` closure provided
/// is used to project from the `T` state that `Linker` is associated with to a
/// [`WasiP1Ctx`]. If `T` is `WasiP1Ctx` itself then this is the identity
/// closure, but otherwise it must project out the field where `WasiP1Ctx` is
/// stored within `T`.
///
/// The state provided by `f` is used to implement all WASIp1 functions and
/// provides configuration to know what to return.
///
/// Note that this function is intended for use with
/// [`Config::async_support(true)`]. If you're looking for a synchronous version
/// see [`add_to_linker_sync`].
///
/// [`Config::async_support(true)`]: wasmtime::Config::async_support
///
/// # Examples
///
/// If the `T` in `Linker<T>` is just `WasiP1Ctx`:
///
/// ```no_run
/// use wasmtime::{Result, Linker, Engine, Config};
/// use wasmtime_wasi::preview1::{self, WasiP1Ctx};
///
/// fn main() -> Result<()> {
///     let mut config = Config::new();
///     config.async_support(true);
///     let engine = Engine::new(&config)?;
///
///     let mut linker: Linker<WasiP1Ctx> = Linker::new(&engine);
///     preview1::add_to_linker_async(&mut linker, |cx| cx)?;
///
///     // ... continue to add more to `linker` as necessary and use it ...
///
///     Ok(())
/// }
/// ```
///
/// If the `T` in `Linker<T>` is custom state:
///
/// ```no_run
/// use wasmtime::{Result, Linker, Engine, Config};
/// use wasmtime_wasi::preview1::{self, WasiP1Ctx};
///
/// struct MyState {
///     // .. other custom state here ..
///
///     wasi: WasiP1Ctx,
/// }
///
/// fn main() -> Result<()> {
///     let mut config = Config::new();
///     config.async_support(true);
///     let engine = Engine::new(&config)?;
///
///     let mut linker: Linker<MyState> = Linker::new(&engine);
///     preview1::add_to_linker_async(&mut linker, |cx| &mut cx.wasi)?;
///
///     // ... continue to add more to `linker` as necessary and use it ...
///
///     Ok(())
/// }
/// ```
pub fn add_to_linker_async<T: Send>(
    linker: &mut wasmtime::Linker<T>,
    f: impl Fn(&mut T) -> &mut WasiP1Ctx + Copy + Send + Sync + 'static,
) -> anyhow::Result<()> {
    crate::preview1::wasi_snapshot_preview1::add_to_linker(linker, f)
}

/// Adds synchronous versions of all WASIp1 functions to the
/// [`wasmtime::Linker`] provided.
///
/// This method will add WASIp1 functions to `linker`. The `f` closure provided
/// is used to project from the `T` state that `Linker` is associated with to a
/// [`WasiP1Ctx`]. If `T` is `WasiP1Ctx` itself then this is the identity
/// closure, but otherwise it must project out the field where `WasiP1Ctx` is
/// stored within `T`.
///
/// The state provided by `f` is used to implement all WASIp1 functions and
/// provides configuration to know what to return.
///
/// Note that this function is intended for use with
/// [`Config::async_support(false)`]. If you're looking for a synchronous version
/// see [`add_to_linker_async`].
///
/// [`Config::async_support(false)`]: wasmtime::Config::async_support
///
/// # Examples
///
/// If the `T` in `Linker<T>` is just `WasiP1Ctx`:
///
/// ```no_run
/// use wasmtime::{Result, Linker, Engine, Config};
/// use wasmtime_wasi::preview1::{self, WasiP1Ctx};
///
/// fn main() -> Result<()> {
///     let mut config = Config::new();
///     config.async_support(true);
///     let engine = Engine::new(&config)?;
///
///     let mut linker: Linker<WasiP1Ctx> = Linker::new(&engine);
///     preview1::add_to_linker_async(&mut linker, |cx| cx)?;
///
///     // ... continue to add more to `linker` as necessary and use it ...
///
///     Ok(())
/// }
/// ```
///
/// If the `T` in `Linker<T>` is custom state:
///
/// ```no_run
/// use wasmtime::{Result, Linker, Engine, Config};
/// use wasmtime_wasi::preview1::{self, WasiP1Ctx};
///
/// struct MyState {
///     // .. other custom state here ..
///
///     wasi: WasiP1Ctx,
/// }
///
/// fn main() -> Result<()> {
///     let mut config = Config::new();
///     config.async_support(true);
///     let engine = Engine::new(&config)?;
///
///     let mut linker: Linker<MyState> = Linker::new(&engine);
///     preview1::add_to_linker_async(&mut linker, |cx| &mut cx.wasi)?;
///
///     // ... continue to add more to `linker` as necessary and use it ...
///
///     Ok(())
/// }
/// ```
pub fn add_to_linker_sync<T: Send>(
    linker: &mut wasmtime::Linker<T>,
    f: impl Fn(&mut T) -> &mut WasiP1Ctx + Copy + Send + Sync + 'static,
) -> anyhow::Result<()> {
    crate::preview1::sync::add_wasi_snapshot_preview1_to_linker(linker, f)
}

// Generate the wasi_snapshot_preview1::WasiSnapshotPreview1 trait,
// and the module types.
// None of the generated modules, traits, or types should be used externally
// to this module.
wiggle::from_witx!({
    witx: ["$CARGO_MANIFEST_DIR/witx/preview1/wasi_snapshot_preview1.witx"],
    async: {
        wasi_snapshot_preview1::{
            fd_advise, fd_close, fd_datasync, fd_fdstat_get, fd_filestat_get, fd_filestat_set_size,
            fd_filestat_set_times, fd_read, fd_pread, fd_seek, fd_sync, fd_readdir, fd_write,
            fd_pwrite, poll_oneoff, path_create_directory, path_filestat_get,
            path_filestat_set_times, path_link, path_open, path_readlink, path_remove_directory,
            path_rename, path_symlink, path_unlink_file
        }
    },
    errors: { errno => trappable Error },
});

pub(crate) mod sync {
    use anyhow::Result;
    use std::future::Future;

    wiggle::wasmtime_integration!({
        witx: ["$CARGO_MANIFEST_DIR/witx/preview1/wasi_snapshot_preview1.witx"],
        target: super,
        block_on[in_tokio]: {
            wasi_snapshot_preview1::{
                fd_advise, fd_close, fd_datasync, fd_fdstat_get, fd_filestat_get, fd_filestat_set_size,
                fd_filestat_set_times, fd_read, fd_pread, fd_seek, fd_sync, fd_readdir, fd_write,
                fd_pwrite, poll_oneoff, path_create_directory, path_filestat_get,
                path_filestat_set_times, path_link, path_open, path_readlink, path_remove_directory,
                path_rename, path_symlink, path_unlink_file
            }
        },
        errors: { errno => trappable Error },
    });

    // Small wrapper around `in_tokio` to add a `Result` layer which is always
    // `Ok`
    fn in_tokio<F: Future>(future: F) -> Result<F::Output> {
        Ok(crate::runtime::in_tokio(future))
    }
}

impl wiggle::GuestErrorType for types::Errno {
    fn success() -> Self {
        Self::Success
    }
}

impl From<StreamError> for types::Error {
    fn from(err: StreamError) -> Self {
        match err {
            StreamError::Closed => types::Errno::Io.into(),
            StreamError::LastOperationFailed(e) => match e.downcast::<std::io::Error>() {
                Ok(err) => filesystem::ErrorCode::from(err).into(),
                Err(e) => {
                    tracing::debug!("dropping error {e:?}");
                    types::Errno::Io.into()
                }
            },
            StreamError::Trap(e) => types::Error::trap(e),
        }
    }
}

impl From<FsError> for types::Error {
    fn from(err: FsError) -> Self {
        match err.downcast() {
            Ok(code) => code.into(),
            Err(e) => types::Error::trap(e),
        }
    }
}

fn systimespec(set: bool, ts: types::Timestamp, now: bool) -> Result<filesystem::NewTimestamp> {
    if set && now {
        Err(types::Errno::Inval.into())
    } else if set {
        Ok(filesystem::NewTimestamp::Timestamp(filesystem::Datetime {
            seconds: ts / 1_000_000_000,
            nanoseconds: (ts % 1_000_000_000) as _,
        }))
    } else if now {
        Ok(filesystem::NewTimestamp::Now)
    } else {
        Ok(filesystem::NewTimestamp::NoChange)
    }
}

impl TryFrom<wall_clock::Datetime> for types::Timestamp {
    type Error = types::Errno;

    fn try_from(
        wall_clock::Datetime {
            seconds,
            nanoseconds,
        }: wall_clock::Datetime,
    ) -> Result<Self, Self::Error> {
        types::Timestamp::from(seconds)
            .checked_mul(1_000_000_000)
            .and_then(|ns| ns.checked_add(nanoseconds.into()))
            .ok_or(types::Errno::Overflow)
    }
}

impl From<types::Lookupflags> for filesystem::PathFlags {
    fn from(flags: types::Lookupflags) -> Self {
        if flags.contains(types::Lookupflags::SYMLINK_FOLLOW) {
            filesystem::PathFlags::SYMLINK_FOLLOW
        } else {
            filesystem::PathFlags::empty()
        }
    }
}

impl From<types::Oflags> for filesystem::OpenFlags {
    fn from(flags: types::Oflags) -> Self {
        let mut out = filesystem::OpenFlags::empty();
        if flags.contains(types::Oflags::CREAT) {
            out |= filesystem::OpenFlags::CREATE;
        }
        if flags.contains(types::Oflags::DIRECTORY) {
            out |= filesystem::OpenFlags::DIRECTORY;
        }
        if flags.contains(types::Oflags::EXCL) {
            out |= filesystem::OpenFlags::EXCLUSIVE;
        }
        if flags.contains(types::Oflags::TRUNC) {
            out |= filesystem::OpenFlags::TRUNCATE;
        }
        out
    }
}

impl From<types::Advice> for filesystem::Advice {
    fn from(advice: types::Advice) -> Self {
        match advice {
            types::Advice::Normal => filesystem::Advice::Normal,
            types::Advice::Sequential => filesystem::Advice::Sequential,
            types::Advice::Random => filesystem::Advice::Random,
            types::Advice::Willneed => filesystem::Advice::WillNeed,
            types::Advice::Dontneed => filesystem::Advice::DontNeed,
            types::Advice::Noreuse => filesystem::Advice::NoReuse,
        }
    }
}

impl TryFrom<filesystem::DescriptorType> for types::Filetype {
    type Error = anyhow::Error;

    fn try_from(ty: filesystem::DescriptorType) -> Result<Self, Self::Error> {
        match ty {
            filesystem::DescriptorType::RegularFile => Ok(types::Filetype::RegularFile),
            filesystem::DescriptorType::Directory => Ok(types::Filetype::Directory),
            filesystem::DescriptorType::BlockDevice => Ok(types::Filetype::BlockDevice),
            filesystem::DescriptorType::CharacterDevice => Ok(types::Filetype::CharacterDevice),
            // preview1 never had a FIFO code.
            filesystem::DescriptorType::Fifo => Ok(types::Filetype::Unknown),
            // TODO: Add a way to disginguish between FILETYPE_SOCKET_STREAM and
            // FILETYPE_SOCKET_DGRAM.
            filesystem::DescriptorType::Socket => {
                bail!("sockets are not currently supported")
            }
            filesystem::DescriptorType::SymbolicLink => Ok(types::Filetype::SymbolicLink),
            filesystem::DescriptorType::Unknown => Ok(types::Filetype::Unknown),
        }
    }
}

impl From<IsATTY> for types::Filetype {
    fn from(isatty: IsATTY) -> Self {
        match isatty {
            IsATTY::Yes => types::Filetype::CharacterDevice,
            IsATTY::No => types::Filetype::Unknown,
        }
    }
}

impl From<filesystem::ErrorCode> for types::Errno {
    fn from(code: filesystem::ErrorCode) -> Self {
        match code {
            filesystem::ErrorCode::Access => types::Errno::Acces,
            filesystem::ErrorCode::WouldBlock => types::Errno::Again,
            filesystem::ErrorCode::Already => types::Errno::Already,
            filesystem::ErrorCode::BadDescriptor => types::Errno::Badf,
            filesystem::ErrorCode::Busy => types::Errno::Busy,
            filesystem::ErrorCode::Deadlock => types::Errno::Deadlk,
            filesystem::ErrorCode::Quota => types::Errno::Dquot,
            filesystem::ErrorCode::Exist => types::Errno::Exist,
            filesystem::ErrorCode::FileTooLarge => types::Errno::Fbig,
            filesystem::ErrorCode::IllegalByteSequence => types::Errno::Ilseq,
            filesystem::ErrorCode::InProgress => types::Errno::Inprogress,
            filesystem::ErrorCode::Interrupted => types::Errno::Intr,
            filesystem::ErrorCode::Invalid => types::Errno::Inval,
            filesystem::ErrorCode::Io => types::Errno::Io,
            filesystem::ErrorCode::IsDirectory => types::Errno::Isdir,
            filesystem::ErrorCode::Loop => types::Errno::Loop,
            filesystem::ErrorCode::TooManyLinks => types::Errno::Mlink,
            filesystem::ErrorCode::MessageSize => types::Errno::Msgsize,
            filesystem::ErrorCode::NameTooLong => types::Errno::Nametoolong,
            filesystem::ErrorCode::NoDevice => types::Errno::Nodev,
            filesystem::ErrorCode::NoEntry => types::Errno::Noent,
            filesystem::ErrorCode::NoLock => types::Errno::Nolck,
            filesystem::ErrorCode::InsufficientMemory => types::Errno::Nomem,
            filesystem::ErrorCode::InsufficientSpace => types::Errno::Nospc,
            filesystem::ErrorCode::Unsupported => types::Errno::Notsup,
            filesystem::ErrorCode::NotDirectory => types::Errno::Notdir,
            filesystem::ErrorCode::NotEmpty => types::Errno::Notempty,
            filesystem::ErrorCode::NotRecoverable => types::Errno::Notrecoverable,
            filesystem::ErrorCode::NoTty => types::Errno::Notty,
            filesystem::ErrorCode::NoSuchDevice => types::Errno::Nxio,
            filesystem::ErrorCode::Overflow => types::Errno::Overflow,
            filesystem::ErrorCode::NotPermitted => types::Errno::Perm,
            filesystem::ErrorCode::Pipe => types::Errno::Pipe,
            filesystem::ErrorCode::ReadOnly => types::Errno::Rofs,
            filesystem::ErrorCode::InvalidSeek => types::Errno::Spipe,
            filesystem::ErrorCode::TextFileBusy => types::Errno::Txtbsy,
            filesystem::ErrorCode::CrossDevice => types::Errno::Xdev,
        }
    }
}

impl From<std::num::TryFromIntError> for types::Error {
    fn from(_: std::num::TryFromIntError) -> Self {
        types::Errno::Overflow.into()
    }
}

impl From<GuestError> for types::Error {
    fn from(err: GuestError) -> Self {
        use wiggle::GuestError::*;
        match err {
            InvalidFlagValue { .. } => types::Errno::Inval.into(),
            InvalidEnumValue { .. } => types::Errno::Inval.into(),
            // As per
            // https://github.com/WebAssembly/wasi/blob/main/legacy/tools/witx-docs.md#pointers
            //
            // > If a misaligned pointer is passed to a function, the function
            // > shall trap.
            // >
            // > If an out-of-bounds pointer is passed to a function and the
            // > function needs to dereference it, the function shall trap.
            //
            // so this turns OOB and misalignment errors into traps.
            PtrOverflow { .. } | PtrOutOfBounds { .. } | PtrNotAligned { .. } => {
                types::Error::trap(err.into())
            }
            PtrBorrowed { .. } => types::Errno::Fault.into(),
            InvalidUtf8 { .. } => types::Errno::Ilseq.into(),
            TryFromIntError { .. } => types::Errno::Overflow.into(),
            SliceLengthsDiffer { .. } => types::Errno::Fault.into(),
            BorrowCheckerOutOfHandles { .. } => types::Errno::Fault.into(),
            InFunc { err, .. } => types::Error::from(*err),
        }
    }
}

impl From<filesystem::ErrorCode> for types::Error {
    fn from(code: filesystem::ErrorCode) -> Self {
        types::Errno::from(code).into()
    }
}

impl From<wasmtime::component::ResourceTableError> for types::Error {
    fn from(err: wasmtime::component::ResourceTableError) -> Self {
        types::Error::trap(err.into())
    }
}

type Result<T, E = types::Error> = std::result::Result<T, E>;

fn write_bytes<'a>(
    ptr: impl Borrow<GuestPtr<'a, u8>>,
    buf: &[u8],
) -> Result<GuestPtr<'a, u8>, types::Error> {
    // NOTE: legacy implementation always returns Inval errno

    let len = u32::try_from(buf.len())?;

    let ptr = ptr.borrow();
    ptr.as_array(len).copy_from_slice(buf)?;
    let next = ptr.add(len)?;
    Ok(next)
}

fn write_byte<'a>(ptr: impl Borrow<GuestPtr<'a, u8>>, byte: u8) -> Result<GuestPtr<'a, u8>> {
    let ptr = ptr.borrow();
    ptr.write(byte)?;
    let next = ptr.add(1)?;
    Ok(next)
}

fn read_str<'a>(ptr: impl Borrow<GuestPtr<'a, str>>) -> Result<GuestStrCow<'a>> {
    let s = ptr.borrow().as_cow()?;
    Ok(s)
}

fn read_string<'a>(ptr: impl Borrow<GuestPtr<'a, str>>) -> Result<String> {
    read_str(ptr).map(|s| s.to_string())
}

// Find first non-empty buffer.
fn first_non_empty_ciovec<'a, 'b>(
    ciovs: &'a types::CiovecArray<'b>,
) -> Result<Option<GuestPtr<'a, [u8]>>> {
    for iov in ciovs.iter() {
        let iov = iov?.read()?;
        if iov.buf_len == 0 {
            continue;
        }
        return Ok(Some(iov.buf.as_array(iov.buf_len)));
    }
    Ok(None)
}

// Find first non-empty buffer.
fn first_non_empty_iovec<'a>(iovs: &types::IovecArray<'a>) -> Result<Option<GuestPtr<'a, [u8]>>> {
    for iov in iovs.iter() {
        let iov = iov?.read()?;
        if iov.buf_len == 0 {
            continue;
        }
        return Ok(Some(iov.buf.as_array(iov.buf_len)));
    }
    Ok(None)
}

#[async_trait::async_trait]
// Implement the WasiSnapshotPreview1 trait using only the traits that are
// required for T, i.e., in terms of the preview 2 wit interface, and state
// stored in the WasiPreview1Adapter struct.
impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiP1Ctx {
    #[instrument(skip(self))]
    fn args_get<'b>(
        &mut self,
        argv: &GuestPtr<'b, GuestPtr<'b, u8>>,
        argv_buf: &GuestPtr<'b, u8>,
    ) -> Result<(), types::Error> {
        self.as_wasi_view()
            .get_arguments()
            .context("failed to call `get-arguments`")
            .map_err(types::Error::trap)?
            .into_iter()
            .try_fold((*argv, *argv_buf), |(argv, argv_buf), arg| -> Result<_> {
                argv.write(argv_buf)?;
                let argv = argv.add(1)?;

                let argv_buf = write_bytes(argv_buf, arg.as_bytes())?;
                let argv_buf = write_byte(argv_buf, 0)?;

                Ok((argv, argv_buf))
            })?;
        Ok(())
    }

    #[instrument(skip(self))]
    fn args_sizes_get(&mut self) -> Result<(types::Size, types::Size), types::Error> {
        let args = self
            .as_wasi_view()
            .get_arguments()
            .context("failed to call `get-arguments`")
            .map_err(types::Error::trap)?;
        let num = args.len().try_into().map_err(|_| types::Errno::Overflow)?;
        let len = args
            .iter()
            .map(|buf| buf.len() + 1) // Each argument is expected to be `\0` terminated.
            .sum::<usize>()
            .try_into()
            .map_err(|_| types::Errno::Overflow)?;
        Ok((num, len))
    }

    #[instrument(skip(self))]
    fn environ_get<'b>(
        &mut self,
        environ: &GuestPtr<'b, GuestPtr<'b, u8>>,
        environ_buf: &GuestPtr<'b, u8>,
    ) -> Result<(), types::Error> {
        self.as_wasi_view()
            .get_environment()
            .context("failed to call `get-environment`")
            .map_err(types::Error::trap)?
            .into_iter()
            .try_fold(
                (*environ, *environ_buf),
                |(environ, environ_buf), (k, v)| -> Result<_, types::Error> {
                    environ.write(environ_buf)?;
                    let environ = environ.add(1)?;

                    let environ_buf = write_bytes(environ_buf, k.as_bytes())?;
                    let environ_buf = write_byte(environ_buf, b'=')?;
                    let environ_buf = write_bytes(environ_buf, v.as_bytes())?;
                    let environ_buf = write_byte(environ_buf, 0)?;

                    Ok((environ, environ_buf))
                },
            )?;
        Ok(())
    }

    #[instrument(skip(self))]
    fn environ_sizes_get(&mut self) -> Result<(types::Size, types::Size), types::Error> {
        let environ = self
            .as_wasi_view()
            .get_environment()
            .context("failed to call `get-environment`")
            .map_err(types::Error::trap)?;
        let num = environ.len().try_into()?;
        let len = environ
            .iter()
            .map(|(k, v)| k.len() + 1 + v.len() + 1) // Key/value pairs are expected to be joined with `=`s, and terminated with `\0`s.
            .sum::<usize>()
            .try_into()?;
        Ok((num, len))
    }

    #[instrument(skip(self))]
    fn clock_res_get(&mut self, id: types::Clockid) -> Result<types::Timestamp, types::Error> {
        let res = match id {
            types::Clockid::Realtime => wall_clock::Host::resolution(self.as_wasi_view())
                .context("failed to call `wall_clock::resolution`")
                .map_err(types::Error::trap)?
                .try_into()?,
            types::Clockid::Monotonic => monotonic_clock::Host::resolution(self.as_wasi_view())
                .context("failed to call `monotonic_clock::resolution`")
                .map_err(types::Error::trap)?,
            types::Clockid::ProcessCputimeId | types::Clockid::ThreadCputimeId => {
                return Err(types::Errno::Badf.into())
            }
        };
        Ok(res)
    }

    #[instrument(skip(self))]
    fn clock_time_get(
        &mut self,
        id: types::Clockid,
        _precision: types::Timestamp,
    ) -> Result<types::Timestamp, types::Error> {
        let now = match id {
            types::Clockid::Realtime => wall_clock::Host::now(self.as_wasi_view())
                .context("failed to call `wall_clock::now`")
                .map_err(types::Error::trap)?
                .try_into()?,
            types::Clockid::Monotonic => monotonic_clock::Host::now(self.as_wasi_view())
                .context("failed to call `monotonic_clock::now`")
                .map_err(types::Error::trap)?,
            types::Clockid::ProcessCputimeId | types::Clockid::ThreadCputimeId => {
                return Err(types::Errno::Badf.into())
            }
        };
        Ok(now)
    }

    #[instrument(skip(self))]
    async fn fd_advise(
        &mut self,
        fd: types::Fd,
        offset: types::Filesize,
        len: types::Filesize,
        advice: types::Advice,
    ) -> Result<(), types::Error> {
        let fd = self.get_file_fd(fd)?;
        self.as_wasi_view()
            .advise(fd, offset, len, advice.into())
            .await
            .map_err(|e| {
                e.try_into()
                    .context("failed to call `advise`")
                    .unwrap_or_else(types::Error::trap)
            })
    }

    /// Force the allocation of space in a file.
    /// NOTE: This is similar to `posix_fallocate` in POSIX.
    #[instrument(skip(self))]
    fn fd_allocate(
        &mut self,
        fd: types::Fd,
        _offset: types::Filesize,
        _len: types::Filesize,
    ) -> Result<(), types::Error> {
        self.get_file_fd(fd)?;
        Err(types::Errno::Notsup.into())
    }

    /// Close a file descriptor.
    /// NOTE: This is similar to `close` in POSIX.
    #[instrument(skip(self))]
    async fn fd_close(&mut self, fd: types::Fd) -> Result<(), types::Error> {
        let desc = self
            .transact()?
            .descriptors
            .remove(fd)
            .ok_or(types::Errno::Badf)?;
        match desc {
            Descriptor::Stdin { stream, .. } => {
                streams::HostInputStream::drop(self.as_wasi_view(), stream)
                    .context("failed to call `drop` on `input-stream`")
            }
            Descriptor::Stdout { stream, .. } | Descriptor::Stderr { stream, .. } => {
                streams::HostOutputStream::drop(self.as_wasi_view(), stream)
                    .context("failed to call `drop` on `output-stream`")
            }
            Descriptor::File(File { fd, .. }) | Descriptor::Directory { fd, .. } => {
                filesystem::HostDescriptor::drop(self.as_wasi_view(), fd)
                    .context("failed to call `drop`")
            }
        }
        .map_err(types::Error::trap)
    }

    /// Synchronize the data of a file to disk.
    /// NOTE: This is similar to `fdatasync` in POSIX.
    #[instrument(skip(self))]
    async fn fd_datasync(&mut self, fd: types::Fd) -> Result<(), types::Error> {
        let fd = self.get_file_fd(fd)?;
        self.as_wasi_view().sync_data(fd).await.map_err(|e| {
            e.try_into()
                .context("failed to call `sync-data`")
                .unwrap_or_else(types::Error::trap)
        })
    }

    /// Get the attributes of a file descriptor.
    /// NOTE: This returns similar flags to `fsync(fd, F_GETFL)` in POSIX, as well as additional fields.
    #[instrument(skip(self))]
    async fn fd_fdstat_get(&mut self, fd: types::Fd) -> Result<types::Fdstat, types::Error> {
        let (fd, blocking, append) = match self.transact()?.get_descriptor(fd)? {
            Descriptor::Stdin { isatty, .. } => {
                let fs_rights_base = types::Rights::FD_READ;
                return Ok(types::Fdstat {
                    fs_filetype: (*isatty).into(),
                    fs_flags: types::Fdflags::empty(),
                    fs_rights_base,
                    fs_rights_inheriting: fs_rights_base,
                });
            }
            Descriptor::Stdout { isatty, .. } | Descriptor::Stderr { isatty, .. } => {
                let fs_rights_base = types::Rights::FD_WRITE;
                return Ok(types::Fdstat {
                    fs_filetype: (*isatty).into(),
                    fs_flags: types::Fdflags::empty(),
                    fs_rights_base,
                    fs_rights_inheriting: fs_rights_base,
                });
            }
            Descriptor::Directory {
                preopen_path: Some(_),
                ..
            } => {
                // Hard-coded set or rights expected by many userlands:
                let fs_rights_base = types::Rights::PATH_CREATE_DIRECTORY
                    | types::Rights::PATH_CREATE_FILE
                    | types::Rights::PATH_LINK_SOURCE
                    | types::Rights::PATH_LINK_TARGET
                    | types::Rights::PATH_OPEN
                    | types::Rights::FD_READDIR
                    | types::Rights::PATH_READLINK
                    | types::Rights::PATH_RENAME_SOURCE
                    | types::Rights::PATH_RENAME_TARGET
                    | types::Rights::PATH_SYMLINK
                    | types::Rights::PATH_REMOVE_DIRECTORY
                    | types::Rights::PATH_UNLINK_FILE
                    | types::Rights::PATH_FILESTAT_GET
                    | types::Rights::PATH_FILESTAT_SET_TIMES
                    | types::Rights::FD_FILESTAT_GET
                    | types::Rights::FD_FILESTAT_SET_TIMES;

                let fs_rights_inheriting = fs_rights_base
                    | types::Rights::FD_DATASYNC
                    | types::Rights::FD_READ
                    | types::Rights::FD_SEEK
                    | types::Rights::FD_FDSTAT_SET_FLAGS
                    | types::Rights::FD_SYNC
                    | types::Rights::FD_TELL
                    | types::Rights::FD_WRITE
                    | types::Rights::FD_ADVISE
                    | types::Rights::FD_ALLOCATE
                    | types::Rights::FD_FILESTAT_GET
                    | types::Rights::FD_FILESTAT_SET_SIZE
                    | types::Rights::FD_FILESTAT_SET_TIMES
                    | types::Rights::POLL_FD_READWRITE;

                return Ok(types::Fdstat {
                    fs_filetype: types::Filetype::Directory,
                    fs_flags: types::Fdflags::empty(),
                    fs_rights_base,
                    fs_rights_inheriting,
                });
            }
            Descriptor::Directory { fd, .. } => (fd.borrowed(), BlockingMode::Blocking, false),
            Descriptor::File(File {
                fd,
                blocking_mode,
                append,
                ..
            }) => (fd.borrowed(), *blocking_mode, *append),
        };
        let flags = self
            .as_wasi_view()
            .get_flags(fd.borrowed())
            .await
            .map_err(|e| {
                e.try_into()
                    .context("failed to call `get-flags`")
                    .unwrap_or_else(types::Error::trap)
            })?;
        let fs_filetype = self
            .as_wasi_view()
            .get_type(fd.borrowed())
            .await
            .map_err(|e| {
                e.try_into()
                    .context("failed to call `get-type`")
                    .unwrap_or_else(types::Error::trap)
            })?
            .try_into()
            .map_err(types::Error::trap)?;
        let mut fs_flags = types::Fdflags::empty();
        let mut fs_rights_base = types::Rights::all();
        if let types::Filetype::Directory = fs_filetype {
            fs_rights_base &= !types::Rights::FD_SEEK;
        }
        if !flags.contains(filesystem::DescriptorFlags::READ) {
            fs_rights_base &= !types::Rights::FD_READ;
        }
        if !flags.contains(filesystem::DescriptorFlags::WRITE) {
            fs_rights_base &= !types::Rights::FD_WRITE;
        }
        if flags.contains(filesystem::DescriptorFlags::DATA_INTEGRITY_SYNC) {
            fs_flags |= types::Fdflags::DSYNC;
        }
        if flags.contains(filesystem::DescriptorFlags::REQUESTED_WRITE_SYNC) {
            fs_flags |= types::Fdflags::RSYNC;
        }
        if flags.contains(filesystem::DescriptorFlags::FILE_INTEGRITY_SYNC) {
            fs_flags |= types::Fdflags::SYNC;
        }
        if append {
            fs_flags |= types::Fdflags::APPEND;
        }
        if matches!(blocking, BlockingMode::NonBlocking) {
            fs_flags |= types::Fdflags::NONBLOCK;
        }
        Ok(types::Fdstat {
            fs_filetype,
            fs_flags,
            fs_rights_base,
            fs_rights_inheriting: fs_rights_base,
        })
    }

    /// Adjust the flags associated with a file descriptor.
    /// NOTE: This is similar to `fcntl(fd, F_SETFL, flags)` in POSIX.
    #[instrument(skip(self))]
    fn fd_fdstat_set_flags(
        &mut self,
        fd: types::Fd,
        flags: types::Fdflags,
    ) -> Result<(), types::Error> {
        let mut st = self.transact()?;
        let File {
            append,
            blocking_mode,
            ..
        } = st.get_file_mut(fd)?;

        // Only support changing the NONBLOCK or APPEND flags.
        if flags.contains(types::Fdflags::DSYNC)
            || flags.contains(types::Fdflags::SYNC)
            || flags.contains(types::Fdflags::RSYNC)
        {
            return Err(types::Errno::Inval.into());
        }
        *append = flags.contains(types::Fdflags::APPEND);
        *blocking_mode = BlockingMode::from_fdflags(&flags);
        Ok(())
    }

    /// Does not do anything if `fd` corresponds to a valid descriptor and returns `[types::Errno::Badf]` error otherwise.
    #[instrument(skip(self))]
    fn fd_fdstat_set_rights(
        &mut self,
        fd: types::Fd,
        _fs_rights_base: types::Rights,
        _fs_rights_inheriting: types::Rights,
    ) -> Result<(), types::Error> {
        self.get_fd(fd)?;
        Ok(())
    }

    /// Return the attributes of an open file.
    #[instrument(skip(self))]
    async fn fd_filestat_get(&mut self, fd: types::Fd) -> Result<types::Filestat, types::Error> {
        let t = self.transact()?;
        let desc = t.get_descriptor(fd)?;
        match desc {
            Descriptor::Stdin { isatty, .. }
            | Descriptor::Stdout { isatty, .. }
            | Descriptor::Stderr { isatty, .. } => Ok(types::Filestat {
                dev: 0,
                ino: 0,
                filetype: (*isatty).into(),
                nlink: 0,
                size: 0,
                atim: 0,
                mtim: 0,
                ctim: 0,
            }),
            Descriptor::Directory { fd, .. } | Descriptor::File(File { fd, .. }) => {
                let fd = fd.borrowed();
                drop(t);
                let filesystem::DescriptorStat {
                    type_,
                    link_count: nlink,
                    size,
                    data_access_timestamp,
                    data_modification_timestamp,
                    status_change_timestamp,
                } = self.as_wasi_view().stat(fd.borrowed()).await.map_err(|e| {
                    e.try_into()
                        .context("failed to call `stat`")
                        .unwrap_or_else(types::Error::trap)
                })?;
                let metadata_hash = self.as_wasi_view().metadata_hash(fd).await.map_err(|e| {
                    e.try_into()
                        .context("failed to call `metadata_hash`")
                        .unwrap_or_else(types::Error::trap)
                })?;
                let filetype = type_.try_into().map_err(types::Error::trap)?;
                let zero = wall_clock::Datetime {
                    seconds: 0,
                    nanoseconds: 0,
                };
                let atim = data_access_timestamp.unwrap_or(zero).try_into()?;
                let mtim = data_modification_timestamp.unwrap_or(zero).try_into()?;
                let ctim = status_change_timestamp.unwrap_or(zero).try_into()?;
                Ok(types::Filestat {
                    dev: 1,
                    ino: metadata_hash.lower,
                    filetype,
                    nlink,
                    size,
                    atim,
                    mtim,
                    ctim,
                })
            }
        }
    }

    /// Adjust the size of an open file. If this increases the file's size, the extra bytes are filled with zeros.
    /// NOTE: This is similar to `ftruncate` in POSIX.
    #[instrument(skip(self))]
    async fn fd_filestat_set_size(
        &mut self,
        fd: types::Fd,
        size: types::Filesize,
    ) -> Result<(), types::Error> {
        let fd = self.get_file_fd(fd)?;
        self.as_wasi_view().set_size(fd, size).await.map_err(|e| {
            e.try_into()
                .context("failed to call `set-size`")
                .unwrap_or_else(types::Error::trap)
        })
    }

    /// Adjust the timestamps of an open file or directory.
    /// NOTE: This is similar to `futimens` in POSIX.
    #[instrument(skip(self))]
    async fn fd_filestat_set_times(
        &mut self,
        fd: types::Fd,
        atim: types::Timestamp,
        mtim: types::Timestamp,
        fst_flags: types::Fstflags,
    ) -> Result<(), types::Error> {
        let atim = systimespec(
            fst_flags.contains(types::Fstflags::ATIM),
            atim,
            fst_flags.contains(types::Fstflags::ATIM_NOW),
        )?;
        let mtim = systimespec(
            fst_flags.contains(types::Fstflags::MTIM),
            mtim,
            fst_flags.contains(types::Fstflags::MTIM_NOW),
        )?;

        let fd = self.get_fd(fd)?;
        self.as_wasi_view()
            .set_times(fd, atim, mtim)
            .await
            .map_err(|e| {
                e.try_into()
                    .context("failed to call `set-times`")
                    .unwrap_or_else(types::Error::trap)
            })
    }

    /// Read from a file descriptor.
    /// NOTE: This is similar to `readv` in POSIX.
    #[instrument(skip(self))]
    async fn fd_read<'a>(
        &mut self,
        fd: types::Fd,
        iovs: &types::IovecArray<'a>,
    ) -> Result<types::Size, types::Error> {
        let t = self.transact()?;
        let desc = t.get_descriptor(fd)?;
        match desc {
            Descriptor::File(File {
                fd,
                position,
                // NB: the nonblocking flag is intentionally ignored here and
                // blocking reads/writes are always performed.
                blocking_mode: _,
                ..
            }) => {
                let fd = fd.borrowed();
                let position = position.clone();
                drop(t);
                let pos = position.load(Ordering::Relaxed);
                let file = self.table().get(&fd)?.file()?;
                let Some(iov) = first_non_empty_iovec(iovs)? else {
                    return Ok(0);
                };
                let bytes_read = match (file.as_blocking_file(), iov.as_slice_mut()?) {
                    // Try to read directly into wasm memory where possible
                    // when the current thread can block and additionally wasm
                    // memory isn't shared.
                    (Some(file), Some(mut buf)) => file
                        .read_at(&mut buf, pos)
                        .map_err(|e| StreamError::LastOperationFailed(e.into()))?,
                    // ... otherwise fall back to performing the read on a
                    // blocking thread and which copies the data back into wasm
                    // memory.
                    (_, buf) => {
                        drop(buf);
                        let mut buf = vec![0; iov.len() as usize];
                        let buf = file
                            .spawn_blocking(move |file| -> Result<_, types::Error> {
                                let bytes_read = file
                                    .read_at(&mut buf, pos)
                                    .map_err(|e| StreamError::LastOperationFailed(e.into()))?;
                                buf.truncate(bytes_read);
                                Ok(buf)
                            })
                            .await?;
                        iov.get_range(0..u32::try_from(buf.len())?)
                            .unwrap()
                            .copy_from_slice(&buf)?;
                        buf.len()
                    }
                };

                let pos = pos
                    .checked_add(bytes_read.try_into()?)
                    .ok_or(types::Errno::Overflow)?;
                position.store(pos, Ordering::Relaxed);

                Ok(bytes_read.try_into()?)
            }
            Descriptor::Stdin { stream, .. } => {
                let stream = stream.borrowed();
                drop(t);
                let Some(buf) = first_non_empty_iovec(iovs)? else {
                    return Ok(0);
                };
                let read = BlockingMode::Blocking
                    .read(self, stream, buf.len().try_into()?)
                    .await?;
                if read.len() > buf.len().try_into()? {
                    return Err(types::Errno::Range.into());
                }
                let buf = buf.get_range(0..u32::try_from(read.len())?).unwrap();
                buf.copy_from_slice(&read)?;
                let n = read.len().try_into()?;
                Ok(n)
            }
            _ => return Err(types::Errno::Badf.into()),
        }
    }

    /// Read from a file descriptor, without using and updating the file descriptor's offset.
    /// NOTE: This is similar to `preadv` in POSIX.
    #[instrument(skip(self))]
    async fn fd_pread<'a>(
        &mut self,
        fd: types::Fd,
        iovs: &types::IovecArray<'a>,
        offset: types::Filesize,
    ) -> Result<types::Size, types::Error> {
        let t = self.transact()?;
        let desc = t.get_descriptor(fd)?;
        let (buf, read) = match desc {
            Descriptor::File(File {
                fd, blocking_mode, ..
            }) => {
                let fd = fd.borrowed();
                let blocking_mode = *blocking_mode;
                drop(t);
                let Some(buf) = first_non_empty_iovec(iovs)? else {
                    return Ok(0);
                };

                let stream = self
                    .as_wasi_view()
                    .read_via_stream(fd, offset)
                    .map_err(|e| {
                        e.try_into()
                            .context("failed to call `read-via-stream`")
                            .unwrap_or_else(types::Error::trap)
                    })?;
                let read = blocking_mode
                    .read(self, stream.borrowed(), buf.len().try_into()?)
                    .await;
                streams::HostInputStream::drop(self.as_wasi_view(), stream)
                    .map_err(|e| types::Error::trap(e))?;
                (buf, read?)
            }
            Descriptor::Stdin { .. } => {
                // NOTE: legacy implementation returns SPIPE here
                return Err(types::Errno::Spipe.into());
            }
            _ => return Err(types::Errno::Badf.into()),
        };
        if read.len() > buf.len().try_into()? {
            return Err(types::Errno::Range.into());
        }
        let buf = buf.get_range(0..u32::try_from(read.len())?).unwrap();
        buf.copy_from_slice(&read)?;
        let n = read.len().try_into()?;
        Ok(n)
    }

    /// Write to a file descriptor.
    /// NOTE: This is similar to `writev` in POSIX.
    #[instrument(skip(self))]
    async fn fd_write<'a>(
        &mut self,
        fd: types::Fd,
        ciovs: &types::CiovecArray<'a>,
    ) -> Result<types::Size, types::Error> {
        let t = self.transact()?;
        let desc = t.get_descriptor(fd)?;
        match desc {
            Descriptor::File(File {
                fd,
                append,
                position,
                // NB: files always use blocking writes regardless of what
                // they're configured to use since OSes don't have nonblocking
                // reads/writes anyway. This behavior originated in the first
                // implementation of WASIp1 where flags were propagated to the
                // OS and the OS ignored the nonblocking flag for files
                // generally.
                blocking_mode: _,
            }) => {
                let fd = fd.borrowed();
                let position = position.clone();
                let pos = position.load(Ordering::Relaxed);
                let append = *append;
                drop(t);
                let f = self.table().get(&fd)?.file()?;
                let Some(buf) = first_non_empty_ciovec(ciovs)? else {
                    return Ok(0);
                };

                let write = move |f: &cap_std::fs::File, buf: &[u8]| {
                    if append {
                        f.append(&buf)
                    } else {
                        f.write_at(&buf, pos)
                    }
                };

                let nwritten = match f.as_blocking_file() {
                    // If we can block then skip the copy out of wasm memory and
                    // write directly to `f`.
                    Some(f) => write(f, &buf.as_cow()?),
                    // ... otherwise copy out of wasm memory and use
                    // `spawn_blocking` to do this write in a thread that can
                    // block.
                    None => {
                        let buf = buf.to_vec()?;
                        f.spawn_blocking(move |f| write(f, &buf)).await
                    }
                };

                let nwritten = nwritten.map_err(|e| StreamError::LastOperationFailed(e.into()))?;
                if append {
                    let len = self.as_wasi_view().stat(fd).await?;
                    position.store(len.size, Ordering::Relaxed);
                } else {
                    let pos = pos
                        .checked_add(nwritten as u64)
                        .ok_or(types::Errno::Overflow)?;
                    position.store(pos, Ordering::Relaxed);
                }
                Ok(nwritten.try_into()?)
            }
            Descriptor::Stdout { stream, .. } | Descriptor::Stderr { stream, .. } => {
                let stream = stream.borrowed();
                drop(t);
                let Some(buf) = first_non_empty_ciovec(ciovs)? else {
                    return Ok(0);
                };
                let n = BlockingMode::Blocking
                    .write(self, stream, buf)
                    .await?
                    .try_into()?;
                Ok(n)
            }
            _ => Err(types::Errno::Badf.into()),
        }
    }

    /// Write to a file descriptor, without using and updating the file descriptor's offset.
    /// NOTE: This is similar to `pwritev` in POSIX.
    #[instrument(skip(self))]
    async fn fd_pwrite<'a>(
        &mut self,
        fd: types::Fd,
        ciovs: &types::CiovecArray<'a>,
        offset: types::Filesize,
    ) -> Result<types::Size, types::Error> {
        let t = self.transact()?;
        let desc = t.get_descriptor(fd)?;
        let n = match desc {
            Descriptor::File(File {
                fd, blocking_mode, ..
            }) => {
                let fd = fd.borrowed();
                let blocking_mode = *blocking_mode;
                drop(t);
                let Some(buf) = first_non_empty_ciovec(ciovs)? else {
                    return Ok(0);
                };
                let stream = self
                    .as_wasi_view()
                    .write_via_stream(fd, offset)
                    .map_err(|e| {
                        e.try_into()
                            .context("failed to call `write-via-stream`")
                            .unwrap_or_else(types::Error::trap)
                    })?;
                let result = blocking_mode
                    .write(self.as_wasi_view(), stream.borrowed(), buf)
                    .await;
                streams::HostOutputStream::drop(self.as_wasi_view(), stream)
                    .map_err(|e| types::Error::trap(e))?;
                result?
            }
            Descriptor::Stdout { .. } | Descriptor::Stderr { .. } => {
                // NOTE: legacy implementation returns SPIPE here
                return Err(types::Errno::Spipe.into());
            }
            _ => return Err(types::Errno::Badf.into()),
        };
        Ok(n.try_into()?)
    }

    /// Return a description of the given preopened file descriptor.
    #[instrument(skip(self))]
    fn fd_prestat_get(&mut self, fd: types::Fd) -> Result<types::Prestat, types::Error> {
        if let Descriptor::Directory {
            preopen_path: Some(p),
            ..
        } = self.transact()?.get_descriptor(fd)?
        {
            let pr_name_len = p.len().try_into()?;
            return Ok(types::Prestat::Dir(types::PrestatDir { pr_name_len }));
        }
        Err(types::Errno::Badf.into()) // NOTE: legacy implementation returns BADF here
    }

    /// Return a description of the given preopened file descriptor.
    #[instrument(skip(self))]
    fn fd_prestat_dir_name<'a>(
        &mut self,
        fd: types::Fd,
        path: &GuestPtr<'a, u8>,
        path_max_len: types::Size,
    ) -> Result<(), types::Error> {
        let path_max_len = path_max_len.try_into()?;
        if let Descriptor::Directory {
            preopen_path: Some(p),
            ..
        } = self.transact()?.get_descriptor(fd)?
        {
            if p.len() > path_max_len {
                return Err(types::Errno::Nametoolong.into());
            }
            write_bytes(path, p.as_bytes())?;
            return Ok(());
        }
        Err(types::Errno::Notdir.into()) // NOTE: legacy implementation returns NOTDIR here
    }

    /// Atomically replace a file descriptor by renumbering another file descriptor.
    #[instrument(skip(self))]
    fn fd_renumber(&mut self, from: types::Fd, to: types::Fd) -> Result<(), types::Error> {
        let mut st = self.transact()?;
        let desc = st.descriptors.remove(from).ok_or(types::Errno::Badf)?;
        st.descriptors.insert(to.into(), desc);
        Ok(())
    }

    /// Move the offset of a file descriptor.
    /// NOTE: This is similar to `lseek` in POSIX.
    #[instrument(skip(self))]
    async fn fd_seek(
        &mut self,
        fd: types::Fd,
        offset: types::Filedelta,
        whence: types::Whence,
    ) -> Result<types::Filesize, types::Error> {
        let t = self.transact()?;
        let File { fd, position, .. } = t.get_seekable(fd)?;
        let fd = fd.borrowed();
        let position = position.clone();
        drop(t);
        let pos = match whence {
            types::Whence::Set if offset >= 0 => {
                offset.try_into().map_err(|_| types::Errno::Inval)?
            }
            types::Whence::Cur => position
                .load(Ordering::Relaxed)
                .checked_add_signed(offset)
                .ok_or(types::Errno::Inval)?,
            types::Whence::End => {
                let filesystem::DescriptorStat { size, .. } =
                    self.as_wasi_view().stat(fd).await.map_err(|e| {
                        e.try_into()
                            .context("failed to call `stat`")
                            .unwrap_or_else(types::Error::trap)
                    })?;
                size.checked_add_signed(offset).ok_or(types::Errno::Inval)?
            }
            _ => return Err(types::Errno::Inval.into()),
        };
        position.store(pos, Ordering::Relaxed);
        Ok(pos)
    }

    /// Synchronize the data and metadata of a file to disk.
    /// NOTE: This is similar to `fsync` in POSIX.
    #[instrument(skip(self))]
    async fn fd_sync(&mut self, fd: types::Fd) -> Result<(), types::Error> {
        let fd = self.get_file_fd(fd)?;
        self.as_wasi_view().sync(fd).await.map_err(|e| {
            e.try_into()
                .context("failed to call `sync`")
                .unwrap_or_else(types::Error::trap)
        })
    }

    /// Return the current offset of a file descriptor.
    /// NOTE: This is similar to `lseek(fd, 0, SEEK_CUR)` in POSIX.
    #[instrument(skip(self))]
    fn fd_tell(&mut self, fd: types::Fd) -> Result<types::Filesize, types::Error> {
        let pos = self
            .transact()?
            .get_seekable(fd)
            .map(|File { position, .. }| position.load(Ordering::Relaxed))?;
        Ok(pos)
    }

    #[instrument(skip(self))]
    async fn fd_readdir<'a>(
        &mut self,
        fd: types::Fd,
        buf: &GuestPtr<'a, u8>,
        buf_len: types::Size,
        cookie: types::Dircookie,
    ) -> Result<types::Size, types::Error> {
        let fd = self.get_dir_fd(fd)?;
        let stream = self
            .as_wasi_view()
            .read_directory(fd.borrowed())
            .await
            .map_err(|e| {
                e.try_into()
                    .context("failed to call `read-directory`")
                    .unwrap_or_else(types::Error::trap)
            })?;
        let dir_metadata_hash = self
            .as_wasi_view()
            .metadata_hash(fd.borrowed())
            .await
            .map_err(|e| {
                e.try_into()
                    .context("failed to call `metadata-hash`")
                    .unwrap_or_else(types::Error::trap)
            })?;
        let cookie = cookie.try_into().map_err(|_| types::Errno::Overflow)?;

        let head = [
            (
                types::Dirent {
                    d_next: 1u64.to_le(),
                    d_ino: dir_metadata_hash.lower.to_le(),
                    d_type: types::Filetype::Directory,
                    d_namlen: 1u32.to_le(),
                },
                ".".into(),
            ),
            (
                types::Dirent {
                    d_next: 2u64.to_le(),
                    d_ino: dir_metadata_hash.lower.to_le(), // NOTE: incorrect, but legacy implementation returns `fd` inode here
                    d_type: types::Filetype::Directory,
                    d_namlen: 2u32.to_le(),
                },
                "..".into(),
            ),
        ];

        let mut dir = Vec::new();
        for (entry, d_next) in self
            .table()
            // remove iterator from table and use it directly:
            .delete(stream)?
            .into_iter()
            .zip(3u64..)
        {
            let filesystem::DirectoryEntry { type_, name } = entry.map_err(|e| {
                e.try_into()
                    .context("failed to inspect `read-directory` entry")
                    .unwrap_or_else(types::Error::trap)
            })?;
            let metadata_hash = self
                .as_wasi_view()
                .metadata_hash_at(fd.borrowed(), filesystem::PathFlags::empty(), name.clone())
                .await
                .map_err(|e| {
                    e.try_into()
                        .context("failed to call `metadata-hash-at`")
                        .unwrap_or_else(types::Error::trap)
                })?;
            let d_type = type_.try_into().map_err(types::Error::trap)?;
            let d_namlen: u32 = name.len().try_into().map_err(|_| types::Errno::Overflow)?;
            dir.push((
                types::Dirent {
                    d_next: d_next.to_le(),
                    d_ino: metadata_hash.lower.to_le(),
                    d_type, // endian-invariant
                    d_namlen: d_namlen.to_le(),
                },
                name,
            ))
        }

        // assume that `types::Dirent` size always fits in `u32`
        const DIRENT_SIZE: u32 = size_of::<types::Dirent>() as _;
        assert_eq!(
            types::Dirent::guest_size(),
            DIRENT_SIZE,
            "Dirent guest repr and host repr should match"
        );
        let mut buf = *buf;
        let mut cap = buf_len;
        for (ref entry, path) in head.into_iter().chain(dir.into_iter()).skip(cookie) {
            let mut path = path.into_bytes();
            assert_eq!(
                1,
                size_of_val(&entry.d_type),
                "Dirent member d_type should be endian-invariant"
            );
            let entry_len = cap.min(DIRENT_SIZE);
            let entry = entry as *const _ as _;
            let entry = unsafe { slice::from_raw_parts(entry, entry_len as _) };
            cap = cap.checked_sub(entry_len).unwrap();
            buf = write_bytes(buf, entry)?;
            if cap == 0 {
                return Ok(buf_len);
            }

            if let Ok(cap) = cap.try_into() {
                // `path` cannot be longer than `usize`, only truncate if `cap` fits in `usize`
                path.truncate(cap);
            }
            cap = cap.checked_sub(path.len() as _).unwrap();
            buf = write_bytes(buf, &path)?;
            if cap == 0 {
                return Ok(buf_len);
            }
        }
        Ok(buf_len.checked_sub(cap).unwrap())
    }

    #[instrument(skip(self))]
    async fn path_create_directory<'a>(
        &mut self,
        dirfd: types::Fd,
        path: &GuestPtr<'a, str>,
    ) -> Result<(), types::Error> {
        let dirfd = self.get_dir_fd(dirfd)?;
        let path = read_string(path)?;
        self.as_wasi_view()
            .create_directory_at(dirfd.borrowed(), path)
            .await
            .map_err(|e| {
                e.try_into()
                    .context("failed to call `create-directory-at`")
                    .unwrap_or_else(types::Error::trap)
            })
    }

    /// Return the attributes of a file or directory.
    /// NOTE: This is similar to `stat` in POSIX.
    #[instrument(skip(self))]
    async fn path_filestat_get<'a>(
        &mut self,
        dirfd: types::Fd,
        flags: types::Lookupflags,
        path: &GuestPtr<'a, str>,
    ) -> Result<types::Filestat, types::Error> {
        let dirfd = self.get_dir_fd(dirfd)?;
        let path = read_string(path)?;
        let filesystem::DescriptorStat {
            type_,
            link_count: nlink,
            size,
            data_access_timestamp,
            data_modification_timestamp,
            status_change_timestamp,
        } = self
            .as_wasi_view()
            .stat_at(dirfd.borrowed(), flags.into(), path.clone())
            .await
            .map_err(|e| {
                e.try_into()
                    .context("failed to call `stat-at`")
                    .unwrap_or_else(types::Error::trap)
            })?;
        let metadata_hash = self
            .as_wasi_view()
            .metadata_hash_at(dirfd, flags.into(), path)
            .await
            .map_err(|e| {
                e.try_into()
                    .context("failed to call `metadata-hash-at`")
                    .unwrap_or_else(types::Error::trap)
            })?;
        let filetype = type_.try_into().map_err(types::Error::trap)?;
        let zero = wall_clock::Datetime {
            seconds: 0,
            nanoseconds: 0,
        };
        let atim = data_access_timestamp.unwrap_or(zero).try_into()?;
        let mtim = data_modification_timestamp.unwrap_or(zero).try_into()?;
        let ctim = status_change_timestamp.unwrap_or(zero).try_into()?;
        Ok(types::Filestat {
            dev: 1,
            ino: metadata_hash.lower,
            filetype,
            nlink,
            size,
            atim,
            mtim,
            ctim,
        })
    }

    /// Adjust the timestamps of a file or directory.
    /// NOTE: This is similar to `utimensat` in POSIX.
    #[instrument(skip(self))]
    async fn path_filestat_set_times<'a>(
        &mut self,
        dirfd: types::Fd,
        flags: types::Lookupflags,
        path: &GuestPtr<'a, str>,
        atim: types::Timestamp,
        mtim: types::Timestamp,
        fst_flags: types::Fstflags,
    ) -> Result<(), types::Error> {
        let atim = systimespec(
            fst_flags.contains(types::Fstflags::ATIM),
            atim,
            fst_flags.contains(types::Fstflags::ATIM_NOW),
        )?;
        let mtim = systimespec(
            fst_flags.contains(types::Fstflags::MTIM),
            mtim,
            fst_flags.contains(types::Fstflags::MTIM_NOW),
        )?;

        let dirfd = self.get_dir_fd(dirfd)?;
        let path = read_string(path)?;
        self.as_wasi_view()
            .set_times_at(dirfd, flags.into(), path, atim, mtim)
            .await
            .map_err(|e| {
                e.try_into()
                    .context("failed to call `set-times-at`")
                    .unwrap_or_else(types::Error::trap)
            })
    }

    /// Create a hard link.
    /// NOTE: This is similar to `linkat` in POSIX.
    #[instrument(skip(self))]
    async fn path_link<'a>(
        &mut self,
        src_fd: types::Fd,
        src_flags: types::Lookupflags,
        src_path: &GuestPtr<'a, str>,
        target_fd: types::Fd,
        target_path: &GuestPtr<'a, str>,
    ) -> Result<(), types::Error> {
        let src_fd = self.get_dir_fd(src_fd)?;
        let target_fd = self.get_dir_fd(target_fd)?;
        let src_path = read_string(src_path)?;
        let target_path = read_string(target_path)?;
        self.as_wasi_view()
            .link_at(src_fd, src_flags.into(), src_path, target_fd, target_path)
            .await
            .map_err(|e| {
                e.try_into()
                    .context("failed to call `link-at`")
                    .unwrap_or_else(types::Error::trap)
            })
    }

    /// Open a file or directory.
    /// NOTE: This is similar to `openat` in POSIX.
    #[instrument(skip(self))]
    async fn path_open<'a>(
        &mut self,
        dirfd: types::Fd,
        dirflags: types::Lookupflags,
        path: &GuestPtr<'a, str>,
        oflags: types::Oflags,
        fs_rights_base: types::Rights,
        _fs_rights_inheriting: types::Rights,
        fdflags: types::Fdflags,
    ) -> Result<types::Fd, types::Error> {
        let path = read_string(path)?;

        let mut flags = filesystem::DescriptorFlags::empty();
        if fs_rights_base.contains(types::Rights::FD_READ) {
            flags |= filesystem::DescriptorFlags::READ;
        }
        if fs_rights_base.contains(types::Rights::FD_WRITE) {
            flags |= filesystem::DescriptorFlags::WRITE;
        }
        if fdflags.contains(types::Fdflags::SYNC) {
            flags |= filesystem::DescriptorFlags::FILE_INTEGRITY_SYNC;
        }
        if fdflags.contains(types::Fdflags::DSYNC) {
            flags |= filesystem::DescriptorFlags::DATA_INTEGRITY_SYNC;
        }
        if fdflags.contains(types::Fdflags::RSYNC) {
            flags |= filesystem::DescriptorFlags::REQUESTED_WRITE_SYNC;
        }

        let t = self.transact()?;
        let dirfd = match t.get_descriptor(dirfd)? {
            Descriptor::Directory { fd, .. } => fd.borrowed(),
            Descriptor::File(_) => return Err(types::Errno::Notdir.into()),
            _ => return Err(types::Errno::Badf.into()),
        };
        drop(t);
        let fd = self
            .as_wasi_view()
            .open_at(dirfd, dirflags.into(), path, oflags.into(), flags)
            .await
            .map_err(|e| {
                e.try_into()
                    .context("failed to call `open-at`")
                    .unwrap_or_else(types::Error::trap)
            })?;
        let mut t = self.transact()?;
        let desc = match t.view.table().get(&fd)? {
            crate::filesystem::Descriptor::Dir(_) => Descriptor::Directory {
                fd,
                preopen_path: None,
            },
            crate::filesystem::Descriptor::File(_) => Descriptor::File(File {
                fd,
                position: Default::default(),
                append: fdflags.contains(types::Fdflags::APPEND),
                blocking_mode: BlockingMode::from_fdflags(&fdflags),
            }),
        };
        let fd = t.descriptors.push(desc)?;
        Ok(fd.into())
    }

    /// Read the contents of a symbolic link.
    /// NOTE: This is similar to `readlinkat` in POSIX.
    #[instrument(skip(self))]
    async fn path_readlink<'a>(
        &mut self,
        dirfd: types::Fd,
        path: &GuestPtr<'a, str>,
        buf: &GuestPtr<'a, u8>,
        buf_len: types::Size,
    ) -> Result<types::Size, types::Error> {
        let dirfd = self.get_dir_fd(dirfd)?;
        let path = read_string(path)?;
        let mut path = self
            .as_wasi_view()
            .readlink_at(dirfd, path)
            .await
            .map_err(|e| {
                e.try_into()
                    .context("failed to call `readlink-at`")
                    .unwrap_or_else(types::Error::trap)
            })?
            .into_bytes();
        if let Ok(buf_len) = buf_len.try_into() {
            // `path` cannot be longer than `usize`, only truncate if `buf_len` fits in `usize`
            path.truncate(buf_len);
        }
        let n = path.len().try_into().map_err(|_| types::Errno::Overflow)?;
        write_bytes(buf, &path)?;
        Ok(n)
    }

    #[instrument(skip(self))]
    async fn path_remove_directory<'a>(
        &mut self,
        dirfd: types::Fd,
        path: &GuestPtr<'a, str>,
    ) -> Result<(), types::Error> {
        let dirfd = self.get_dir_fd(dirfd)?;
        let path = read_string(path)?;
        self.as_wasi_view()
            .remove_directory_at(dirfd, path)
            .await
            .map_err(|e| {
                e.try_into()
                    .context("failed to call `remove-directory-at`")
                    .unwrap_or_else(types::Error::trap)
            })
    }

    /// Rename a file or directory.
    /// NOTE: This is similar to `renameat` in POSIX.
    #[instrument(skip(self))]
    async fn path_rename<'a>(
        &mut self,
        src_fd: types::Fd,
        src_path: &GuestPtr<'a, str>,
        dest_fd: types::Fd,
        dest_path: &GuestPtr<'a, str>,
    ) -> Result<(), types::Error> {
        let src_fd = self.get_dir_fd(src_fd)?;
        let dest_fd = self.get_dir_fd(dest_fd)?;
        let src_path = read_string(src_path)?;
        let dest_path = read_string(dest_path)?;
        self.as_wasi_view()
            .rename_at(src_fd, src_path, dest_fd, dest_path)
            .await
            .map_err(|e| {
                e.try_into()
                    .context("failed to call `rename-at`")
                    .unwrap_or_else(types::Error::trap)
            })
    }

    #[instrument(skip(self))]
    async fn path_symlink<'a>(
        &mut self,
        src_path: &GuestPtr<'a, str>,
        dirfd: types::Fd,
        dest_path: &GuestPtr<'a, str>,
    ) -> Result<(), types::Error> {
        let dirfd = self.get_dir_fd(dirfd)?;
        let src_path = read_string(src_path)?;
        let dest_path = read_string(dest_path)?;
        self.as_wasi_view()
            .symlink_at(dirfd.borrowed(), src_path, dest_path)
            .await
            .map_err(|e| {
                e.try_into()
                    .context("failed to call `symlink-at`")
                    .unwrap_or_else(types::Error::trap)
            })
    }

    #[instrument(skip(self))]
    async fn path_unlink_file<'a>(
        &mut self,
        dirfd: types::Fd,
        path: &GuestPtr<'a, str>,
    ) -> Result<(), types::Error> {
        let dirfd = self.get_dir_fd(dirfd)?;
        let path = path.as_cow()?.to_string();
        self.as_wasi_view()
            .unlink_file_at(dirfd.borrowed(), path)
            .await
            .map_err(|e| {
                e.try_into()
                    .context("failed to call `unlink-file-at`")
                    .unwrap_or_else(types::Error::trap)
            })
    }

    #[instrument(skip(self))]
    async fn poll_oneoff<'a>(
        &mut self,
        subs: &GuestPtr<'a, types::Subscription>,
        events: &GuestPtr<'a, types::Event>,
        nsubscriptions: types::Size,
    ) -> Result<types::Size, types::Error> {
        if nsubscriptions == 0 {
            // Indefinite sleeping is not supported in preview1.
            return Err(types::Errno::Inval.into());
        }

        // This is a special case where `poll_oneoff` is just sleeping
        // on a single relative timer event. This special case was added
        // after experimental observations showed that std::thread::sleep
        // results in more consistent sleep times. This design ensures that
        // wasmtime can handle real-time requirements more accurately.
        if nsubscriptions == 1 {
            let sub = subs.read()?;
            if let types::SubscriptionU::Clock(clocksub) = sub.u {
                if !clocksub
                    .flags
                    .contains(types::Subclockflags::SUBSCRIPTION_CLOCK_ABSTIME)
                    && self.ctx().allow_blocking_current_thread
                {
                    std::thread::sleep(std::time::Duration::from_nanos(clocksub.timeout));
                    events.write(types::Event {
                        userdata: sub.userdata,
                        error: types::Errno::Success,
                        type_: types::Eventtype::Clock,
                        fd_readwrite: types::EventFdReadwrite {
                            flags: types::Eventrwflags::empty(),
                            nbytes: 1,
                        },
                    })?;
                    return Ok(1);
                }
            }
        }

        let subs = subs.as_array(nsubscriptions);
        let events = events.as_array(nsubscriptions);

        let n = usize::try_from(nsubscriptions).unwrap_or(usize::MAX);
        let mut pollables = Vec::with_capacity(n);
        for sub in subs.iter() {
            let sub = sub?.read()?;
            let p = match sub.u {
                types::SubscriptionU::Clock(types::SubscriptionClock {
                    id,
                    timeout,
                    flags,
                    ..
                }) => {
                    let absolute = flags.contains(types::Subclockflags::SUBSCRIPTION_CLOCK_ABSTIME);
                    let (timeout, absolute) = match id {
                        types::Clockid::Monotonic => (timeout, absolute),
                        types::Clockid::Realtime if !absolute => (timeout, false),
                        types::Clockid::Realtime => {
                            let now = wall_clock::Host::now(self.as_wasi_view())
                                .context("failed to call `wall_clock::now`")
                                .map_err(types::Error::trap)?;

                            // Convert `timeout` to `Datetime` format.
                            let seconds = timeout / 1_000_000_000;
                            let nanoseconds = timeout % 1_000_000_000;

                            let timeout = if now.seconds < seconds
                                || now.seconds == seconds
                                    && u64::from(now.nanoseconds) < nanoseconds
                            {
                                // `now` is less than `timeout`, which is expressible as u64,
                                // subtract the nanosecond counts directly
                                now.seconds * 1_000_000_000 + u64::from(now.nanoseconds) - timeout
                            } else {
                                0
                            };
                            (timeout, false)
                        }
                        _ => return Err(types::Errno::Inval.into()),
                    };
                    if absolute {
                        monotonic_clock::Host::subscribe_instant(self.as_wasi_view(), timeout)
                            .context("failed to call `monotonic_clock::subscribe_instant`")
                            .map_err(types::Error::trap)?
                    } else {
                        monotonic_clock::Host::subscribe_duration(self.as_wasi_view(), timeout)
                            .context("failed to call `monotonic_clock::subscribe_duration`")
                            .map_err(types::Error::trap)?
                    }
                }
                types::SubscriptionU::FdRead(types::SubscriptionFdReadwrite {
                    file_descriptor,
                }) => {
                    let stream = {
                        let t = self.transact()?;
                        let desc = t.get_descriptor(file_descriptor)?;
                        match desc {
                            Descriptor::Stdin { stream, .. } => stream.borrowed(),
                            Descriptor::File(File { fd, position, .. }) => {
                                let pos = position.load(Ordering::Relaxed);
                                let fd = fd.borrowed();
                                drop(t);
                                self.as_wasi_view().read_via_stream(fd, pos).map_err(|e| {
                                    e.try_into()
                                        .context("failed to call `read-via-stream`")
                                        .unwrap_or_else(types::Error::trap)
                                })?
                            }
                            // TODO: Support sockets
                            _ => return Err(types::Errno::Badf.into()),
                        }
                    };
                    streams::HostInputStream::subscribe(self.as_wasi_view(), stream)
                        .context("failed to call `subscribe` on `input-stream`")
                        .map_err(types::Error::trap)?
                }
                types::SubscriptionU::FdWrite(types::SubscriptionFdReadwrite {
                    file_descriptor,
                }) => {
                    let stream = {
                        let t = self.transact()?;
                        let desc = t.get_descriptor(file_descriptor)?;
                        match desc {
                            Descriptor::Stdout { stream, .. }
                            | Descriptor::Stderr { stream, .. } => stream.borrowed(),
                            Descriptor::File(File {
                                fd,
                                position,
                                append,
                                ..
                            }) => {
                                let fd = fd.borrowed();
                                let position = position.clone();
                                let append = *append;
                                drop(t);
                                if append {
                                    self.as_wasi_view().append_via_stream(fd).map_err(|e| {
                                        e.try_into()
                                            .context("failed to call `append-via-stream`")
                                            .unwrap_or_else(types::Error::trap)
                                    })?
                                } else {
                                    let pos = position.load(Ordering::Relaxed);
                                    self.as_wasi_view().write_via_stream(fd, pos).map_err(|e| {
                                        e.try_into()
                                            .context("failed to call `write-via-stream`")
                                            .unwrap_or_else(types::Error::trap)
                                    })?
                                }
                            }
                            // TODO: Support sockets
                            _ => return Err(types::Errno::Badf.into()),
                        }
                    };
                    streams::HostOutputStream::subscribe(self.as_wasi_view(), stream)
                        .context("failed to call `subscribe` on `output-stream`")
                        .map_err(types::Error::trap)?
                }
            };
            pollables.push(p);
        }
        let ready: HashSet<_> = self
            .as_wasi_view()
            .poll(pollables)
            .await
            .context("failed to call `poll-oneoff`")
            .map_err(types::Error::trap)?
            .into_iter()
            .collect();

        let mut count: types::Size = 0;
        for (sub, event) in (0..)
            .zip(subs.iter())
            .filter_map(|(idx, sub)| ready.contains(&idx).then_some(sub))
            .zip(events.iter())
        {
            let sub = sub?.read()?;
            let event = event?;
            let e = match sub.u {
                types::SubscriptionU::Clock(..) => types::Event {
                    userdata: sub.userdata,
                    error: types::Errno::Success,
                    type_: types::Eventtype::Clock,
                    fd_readwrite: types::EventFdReadwrite {
                        flags: types::Eventrwflags::empty(),
                        nbytes: 0,
                    },
                },
                types::SubscriptionU::FdRead(types::SubscriptionFdReadwrite {
                    file_descriptor,
                }) => {
                    let t = self.transact()?;
                    let desc = t.get_descriptor(file_descriptor)?;
                    match desc {
                        Descriptor::Stdin { .. } => types::Event {
                            userdata: sub.userdata,
                            error: types::Errno::Success,
                            type_: types::Eventtype::FdRead,
                            fd_readwrite: types::EventFdReadwrite {
                                flags: types::Eventrwflags::empty(),
                                nbytes: 1,
                            },
                        },
                        Descriptor::File(File { fd, position, .. }) => {
                            let fd = fd.borrowed();
                            let position = position.clone();
                            drop(t);
                            match self.as_wasi_view().stat(fd).await? {
                                filesystem::DescriptorStat { size, .. } => {
                                    let pos = position.load(Ordering::Relaxed);
                                    let nbytes = size.saturating_sub(pos);
                                    types::Event {
                                        userdata: sub.userdata,
                                        error: types::Errno::Success,
                                        type_: types::Eventtype::FdRead,
                                        fd_readwrite: types::EventFdReadwrite {
                                            flags: if nbytes == 0 {
                                                types::Eventrwflags::FD_READWRITE_HANGUP
                                            } else {
                                                types::Eventrwflags::empty()
                                            },
                                            nbytes: 1,
                                        },
                                    }
                                }
                            }
                        }
                        // TODO: Support sockets
                        _ => return Err(types::Errno::Badf.into()),
                    }
                }
                types::SubscriptionU::FdWrite(types::SubscriptionFdReadwrite {
                    file_descriptor,
                }) => {
                    let t = self.transact()?;
                    let desc = t.get_descriptor(file_descriptor)?;
                    match desc {
                        Descriptor::Stdout { .. } | Descriptor::Stderr { .. } => types::Event {
                            userdata: sub.userdata,
                            error: types::Errno::Success,
                            type_: types::Eventtype::FdWrite,
                            fd_readwrite: types::EventFdReadwrite {
                                flags: types::Eventrwflags::empty(),
                                nbytes: 1,
                            },
                        },
                        Descriptor::File(_) => types::Event {
                            userdata: sub.userdata,
                            error: types::Errno::Success,
                            type_: types::Eventtype::FdWrite,
                            fd_readwrite: types::EventFdReadwrite {
                                flags: types::Eventrwflags::empty(),
                                nbytes: 1,
                            },
                        },
                        // TODO: Support sockets
                        _ => return Err(types::Errno::Badf.into()),
                    }
                }
            };
            event.write(e)?;
            count = count
                .checked_add(1)
                .ok_or_else(|| types::Error::from(types::Errno::Overflow))?
        }
        Ok(count)
    }

    #[instrument(skip(self))]
    fn proc_exit(&mut self, status: types::Exitcode) -> anyhow::Error {
        // Check that the status is within WASI's range.
        if status >= 126 {
            return anyhow::Error::msg("exit with invalid exit status outside of [0..126)");
        }
        crate::I32Exit(status as i32).into()
    }

    #[instrument(skip(self))]
    fn proc_raise(&mut self, _sig: types::Signal) -> Result<(), types::Error> {
        Err(types::Errno::Notsup.into())
    }

    #[instrument(skip(self))]
    fn sched_yield(&mut self) -> Result<(), types::Error> {
        // No such thing in preview 2. Intentionally left empty.
        Ok(())
    }

    #[instrument(skip(self))]
    fn random_get<'a>(
        &mut self,
        buf: &GuestPtr<'a, u8>,
        buf_len: types::Size,
    ) -> Result<(), types::Error> {
        let rand = self
            .as_wasi_view()
            .get_random_bytes(buf_len.into())
            .context("failed to call `get-random-bytes`")
            .map_err(types::Error::trap)?;
        write_bytes(buf, &rand)?;
        Ok(())
    }

    #[allow(unused_variables)]
    #[instrument(skip(self))]
    fn sock_accept(
        &mut self,
        fd: types::Fd,
        flags: types::Fdflags,
    ) -> Result<types::Fd, types::Error> {
        todo!("preview1 sock_accept is not implemented")
    }

    #[allow(unused_variables)]
    #[instrument(skip(self))]
    fn sock_recv<'a>(
        &mut self,
        fd: types::Fd,
        ri_data: &types::IovecArray<'a>,
        ri_flags: types::Riflags,
    ) -> Result<(types::Size, types::Roflags), types::Error> {
        todo!("preview1 sock_recv is not implemented")
    }

    #[allow(unused_variables)]
    #[instrument(skip(self))]
    fn sock_send<'a>(
        &mut self,
        fd: types::Fd,
        si_data: &types::CiovecArray<'a>,
        _si_flags: types::Siflags,
    ) -> Result<types::Size, types::Error> {
        todo!("preview1 sock_send is not implemented")
    }

    #[allow(unused_variables)]
    #[instrument(skip(self))]
    fn sock_shutdown(&mut self, fd: types::Fd, how: types::Sdflags) -> Result<(), types::Error> {
        todo!("preview1 sock_shutdown is not implemented")
    }
}

trait ResourceExt<T> {
    fn borrowed(&self) -> Resource<T>;
}

impl<T: 'static> ResourceExt<T> for Resource<T> {
    fn borrowed(&self) -> Resource<T> {
        Resource::new_borrow(self.rep())
    }
}