wasmtime 42.0.2

High-level API to expose the Wasmtime runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
//! Runtime support for the Component Model Async ABI.
//!
//! This module and its submodules provide host runtime support for Component
//! Model Async features such as async-lifted exports, async-lowered imports,
//! streams, futures, and related intrinsics.  See [the Async
//! Explainer](https://github.com/WebAssembly/component-model/blob/main/design/mvp/Concurrency.md)
//! for a high-level overview.
//!
//! At the core of this support is an event loop which schedules and switches
//! between guest tasks and any host tasks they create.  Each
//! `Store` will have at most one event loop running at any given
//! time, and that loop may be suspended and resumed by the host embedder using
//! e.g. `StoreContextMut::run_concurrent`.  The `StoreContextMut::poll_until`
//! function contains the loop itself, while the
//! `StoreOpaque::concurrent_state` field holds its state.
//!
//! # Public API Overview
//!
//! ## Top-level API (e.g. kicking off host->guest calls and driving the event loop)
//!
//! - `[Typed]Func::call_concurrent`: Start a host->guest call to an
//! async-lifted or sync-lifted import, creating a guest task.
//!
//! - `StoreContextMut::run_concurrent`: Run the event loop for the specified
//! instance, allowing any and all tasks belonging to that instance to make
//! progress.
//!
//! - `StoreContextMut::spawn`: Run a background task as part of the event loop
//! for the specified instance.
//!
//! - `{Future,Stream}Reader::new`: Create a new Component Model `future` or
//! `stream` which may be passed to the guest.  This takes a
//! `{Future,Stream}Producer` implementation which will be polled for items when
//! the consumer requests them.
//!
//! - `{Future,Stream}Reader::pipe`: Consume a `future` or `stream` by
//! connecting it to a `{Future,Stream}Consumer` which will consume any items
//! produced by the write end.
//!
//! ## Host Task API (e.g. implementing concurrent host functions and background tasks)
//!
//! - `LinkerInstance::func_wrap_concurrent`: Register a concurrent host
//! function with the linker.  That function will take an `Accessor` as its
//! first parameter, which provides access to the store between (but not across)
//! await points.
//!
//! - `Accessor::with`: Access the store and its associated data.
//!
//! - `Accessor::spawn`: Run a background task as part of the event loop for the
//! store.  This is equivalent to `StoreContextMut::spawn` but more convenient to use
//! in host functions.

use crate::component::func::{self, Func, call_post_return};
use crate::component::{
    HasData, HasSelf, Instance, Resource, ResourceTable, ResourceTableError, RuntimeInstance,
};
use crate::fiber::{self, StoreFiber, StoreFiberYield};
use crate::prelude::*;
use crate::store::{Store, StoreId, StoreInner, StoreOpaque, StoreToken};
use crate::vm::component::{CallContext, ComponentInstance, InstanceState, ResourceTables};
use crate::vm::{AlwaysMut, SendSyncPtr, VMFuncRef, VMMemoryDefinition, VMStore};
use crate::{
    AsContext, AsContextMut, FuncType, Result, StoreContext, StoreContextMut, ValRaw, ValType,
    bail,
    error::{Context as _, format_err},
};
use error_contexts::GlobalErrorContextRefCount;
use futures::channel::oneshot;
use futures::future::{self, FutureExt};
use futures::stream::{FuturesUnordered, StreamExt};
use futures_and_streams::{FlatAbi, ReturnCode, TransmitHandle, TransmitIndex};
use std::any::Any;
use std::borrow::ToOwned;
use std::boxed::Box;
use std::cell::UnsafeCell;
use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque};
use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
use std::mem::{self, ManuallyDrop, MaybeUninit};
use std::ops::DerefMut;
use std::pin::{Pin, pin};
use std::ptr::{self, NonNull};
use std::sync::Arc;
use std::task::{Context, Poll, Waker};
use std::vec::Vec;
use table::{TableDebug, TableId};
use wasmtime_environ::Trap;
use wasmtime_environ::component::{
    CanonicalAbiInfo, CanonicalOptions, CanonicalOptionsDataModel, ExportIndex, MAX_FLAT_PARAMS,
    MAX_FLAT_RESULTS, OptionsIndex, PREPARE_ASYNC_NO_RESULT, PREPARE_ASYNC_WITH_RESULT,
    RuntimeComponentInstanceIndex, RuntimeTableIndex, StringEncoding,
    TypeComponentGlobalErrorContextTableIndex, TypeComponentLocalErrorContextTableIndex,
    TypeFuncIndex, TypeFutureTableIndex, TypeStreamTableIndex, TypeTupleIndex,
};
use wasmtime_environ::packed_option::ReservedValue;

pub use abort::JoinHandle;
pub use future_stream_any::{FutureAny, StreamAny};
pub use futures_and_streams::{
    Destination, DirectDestination, DirectSource, ErrorContext, FutureConsumer, FutureProducer,
    FutureReader, GuardedFutureReader, GuardedStreamReader, ReadBuffer, Source, StreamConsumer,
    StreamProducer, StreamReader, StreamResult, VecBuffer, WriteBuffer,
};
pub(crate) use futures_and_streams::{ResourcePair, lower_error_context_to_index};

mod abort;
mod error_contexts;
mod future_stream_any;
mod futures_and_streams;
pub(crate) mod table;
pub(crate) mod tls;

/// Constant defined in the Component Model spec to indicate that the async
/// intrinsic (e.g. `future.write`) has not yet completed.
const BLOCKED: u32 = 0xffff_ffff;

/// Corresponds to `CallState` in the upstream spec.
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub enum Status {
    Starting = 0,
    Started = 1,
    Returned = 2,
    StartCancelled = 3,
    ReturnCancelled = 4,
}

impl Status {
    /// Packs this status and the optional `waitable` provided into a 32-bit
    /// result that the canonical ABI requires.
    ///
    /// The low 4 bits are reserved for the status while the upper 28 bits are
    /// the waitable, if present.
    pub fn pack(self, waitable: Option<u32>) -> u32 {
        assert!(matches!(self, Status::Returned) == waitable.is_none());
        let waitable = waitable.unwrap_or(0);
        assert!(waitable < (1 << 28));
        (waitable << 4) | (self as u32)
    }
}

/// Corresponds to `EventCode` in the Component Model spec, plus related payload
/// data.
#[derive(Clone, Copy, Debug)]
enum Event {
    None,
    Cancelled,
    Subtask {
        status: Status,
    },
    StreamRead {
        code: ReturnCode,
        pending: Option<(TypeStreamTableIndex, u32)>,
    },
    StreamWrite {
        code: ReturnCode,
        pending: Option<(TypeStreamTableIndex, u32)>,
    },
    FutureRead {
        code: ReturnCode,
        pending: Option<(TypeFutureTableIndex, u32)>,
    },
    FutureWrite {
        code: ReturnCode,
        pending: Option<(TypeFutureTableIndex, u32)>,
    },
}

impl Event {
    /// Lower this event to core Wasm integers for delivery to the guest.
    ///
    /// Note that the waitable handle, if any, is assumed to be lowered
    /// separately.
    fn parts(self) -> (u32, u32) {
        const EVENT_NONE: u32 = 0;
        const EVENT_SUBTASK: u32 = 1;
        const EVENT_STREAM_READ: u32 = 2;
        const EVENT_STREAM_WRITE: u32 = 3;
        const EVENT_FUTURE_READ: u32 = 4;
        const EVENT_FUTURE_WRITE: u32 = 5;
        const EVENT_CANCELLED: u32 = 6;
        match self {
            Event::None => (EVENT_NONE, 0),
            Event::Cancelled => (EVENT_CANCELLED, 0),
            Event::Subtask { status } => (EVENT_SUBTASK, status as u32),
            Event::StreamRead { code, .. } => (EVENT_STREAM_READ, code.encode()),
            Event::StreamWrite { code, .. } => (EVENT_STREAM_WRITE, code.encode()),
            Event::FutureRead { code, .. } => (EVENT_FUTURE_READ, code.encode()),
            Event::FutureWrite { code, .. } => (EVENT_FUTURE_WRITE, code.encode()),
        }
    }
}

/// Corresponds to `CallbackCode` in the spec.
mod callback_code {
    pub const EXIT: u32 = 0;
    pub const YIELD: u32 = 1;
    pub const WAIT: u32 = 2;
}

/// A flag indicating that the callee is an async-lowered export.
///
/// This may be passed to the `async-start` intrinsic from a fused adapter.
const START_FLAG_ASYNC_CALLEE: u32 = wasmtime_environ::component::START_FLAG_ASYNC_CALLEE as u32;

/// Provides access to either store data (via the `get` method) or the store
/// itself (via [`AsContext`]/[`AsContextMut`]), as well as the component
/// instance to which the current host task belongs.
///
/// See [`Accessor::with`] for details.
pub struct Access<'a, T: 'static, D: HasData + ?Sized = HasSelf<T>> {
    store: StoreContextMut<'a, T>,
    get_data: fn(&mut T) -> D::Data<'_>,
}

impl<'a, T, D> Access<'a, T, D>
where
    D: HasData + ?Sized,
    T: 'static,
{
    /// Creates a new [`Access`] from its component parts.
    pub fn new(store: StoreContextMut<'a, T>, get_data: fn(&mut T) -> D::Data<'_>) -> Self {
        Self { store, get_data }
    }

    /// Get mutable access to the store data.
    pub fn data_mut(&mut self) -> &mut T {
        self.store.data_mut()
    }

    /// Get mutable access to the store data.
    pub fn get(&mut self) -> D::Data<'_> {
        (self.get_data)(self.data_mut())
    }

    /// Spawn a background task.
    ///
    /// See [`Accessor::spawn`] for details.
    pub fn spawn(&mut self, task: impl AccessorTask<T, D>) -> JoinHandle
    where
        T: 'static,
    {
        let accessor = Accessor {
            get_data: self.get_data,
            token: StoreToken::new(self.store.as_context_mut()),
        };
        self.store
            .as_context_mut()
            .spawn_with_accessor(accessor, task)
    }

    /// Returns the getter this accessor is using to project from `T` into
    /// `D::Data`.
    pub fn getter(&self) -> fn(&mut T) -> D::Data<'_> {
        self.get_data
    }
}

impl<'a, T, D> AsContext for Access<'a, T, D>
where
    D: HasData + ?Sized,
    T: 'static,
{
    type Data = T;

    fn as_context(&self) -> StoreContext<'_, T> {
        self.store.as_context()
    }
}

impl<'a, T, D> AsContextMut for Access<'a, T, D>
where
    D: HasData + ?Sized,
    T: 'static,
{
    fn as_context_mut(&mut self) -> StoreContextMut<'_, T> {
        self.store.as_context_mut()
    }
}

/// Provides scoped mutable access to store data in the context of a concurrent
/// host task future.
///
/// This allows multiple host task futures to execute concurrently and access
/// the store between (but not across) `await` points.
///
/// # Rationale
///
/// This structure is sort of like `&mut T` plus a projection from `&mut T` to
/// `D::Data<'_>`. The problem this is solving, however, is that it does not
/// literally store these values. The basic problem is that when a concurrent
/// host future is being polled it has access to `&mut T` (and the whole
/// `Store`) but when it's not being polled it does not have access to these
/// values. This reflects how the store is only ever polling one future at a
/// time so the store is effectively being passed between futures.
///
/// Rust's `Future` trait, however, has no means of passing a `Store`
/// temporarily between futures. The [`Context`](std::task::Context) type does
/// not have the ability to attach arbitrary information to it at this time.
/// This type, [`Accessor`], is used to bridge this expressivity gap.
///
/// The [`Accessor`] type here represents the ability to acquire, temporarily in
/// a synchronous manner, the current store. The [`Accessor::with`] function
/// yields an [`Access`] which can be used to access [`StoreContextMut`], `&mut
/// T`, or `D::Data<'_>`. Note though that [`Accessor::with`] intentionally does
/// not take an `async` closure as its argument, instead it's a synchronous
/// closure which must complete during on run of `Future::poll`. This reflects
/// how the store is temporarily made available while a host future is being
/// polled.
///
/// # Implementation
///
/// This type does not actually store `&mut T` nor `StoreContextMut<T>`, and
/// this type additionally doesn't even have a lifetime parameter. This is
/// instead a representation of proof of the ability to acquire these while a
/// future is being polled. Wasmtime will, when it polls a host future,
/// configure ambient state such that the `Accessor` that a future closes over
/// will work and be able to access the store.
///
/// This has a number of implications for users such as:
///
/// * It's intentional that `Accessor` cannot be cloned, it needs to stay within
///   the lifetime of a single future.
/// * A future is expected to, however, close over an `Accessor` and keep it
///   alive probably for the duration of the entire future.
/// * Different host futures will be given different `Accessor`s, and that's
///   intentional.
/// * The `Accessor` type is `Send` and `Sync` irrespective of `T` which
///   alleviates some otherwise required bounds to be written down.
///
/// # Using `Accessor` in `Drop`
///
/// The methods on `Accessor` are only expected to work in the context of
/// `Future::poll` and are not guaranteed to work in `Drop`. This is because a
/// host future can be dropped at any time throughout the system and Wasmtime
/// store context is not necessarily available at that time. It's recommended to
/// not use `Accessor` methods in anything connected to a `Drop` implementation
/// as they will panic and have unintended results. If you run into this though
/// feel free to file an issue on the Wasmtime repository.
pub struct Accessor<T: 'static, D = HasSelf<T>>
where
    D: HasData + ?Sized,
{
    token: StoreToken<T>,
    get_data: fn(&mut T) -> D::Data<'_>,
}

/// A helper trait to take any type of accessor-with-data in functions.
///
/// This trait is similar to [`AsContextMut`] except that it's used when
/// working with an [`Accessor`] instead of a [`StoreContextMut`]. The
/// [`Accessor`] is the main type used in concurrent settings and is passed to
/// functions such as [`Func::call_concurrent`].
///
/// This trait is implemented for [`Accessor`] and `&T` where `T` implements
/// this trait. This effectively means that regardless of the `D` in
/// `Accessor<T, D>` it can still be passed to a function which just needs a
/// store accessor.
///
/// Acquiring an [`Accessor`] can be done through
/// [`StoreContextMut::run_concurrent`] for example or in a host function
/// through
/// [`Linker::func_wrap_concurrent`](crate::component::LinkerInstance::func_wrap_concurrent).
pub trait AsAccessor {
    /// The `T` in `Store<T>` that this accessor refers to.
    type Data: 'static;

    /// The `D` in `Accessor<T, D>`, or the projection out of
    /// `Self::Data`.
    type AccessorData: HasData + ?Sized;

    /// Returns the accessor that this is referring to.
    fn as_accessor(&self) -> &Accessor<Self::Data, Self::AccessorData>;
}

impl<T: AsAccessor + ?Sized> AsAccessor for &T {
    type Data = T::Data;
    type AccessorData = T::AccessorData;

    fn as_accessor(&self) -> &Accessor<Self::Data, Self::AccessorData> {
        T::as_accessor(self)
    }
}

impl<T, D: HasData + ?Sized> AsAccessor for Accessor<T, D> {
    type Data = T;
    type AccessorData = D;

    fn as_accessor(&self) -> &Accessor<T, D> {
        self
    }
}

// Note that it is intentional at this time that `Accessor` does not actually
// store `&mut T` or anything similar. This distinctly enables the `Accessor`
// structure to be both `Send` and `Sync` regardless of what `T` is (or `D` for
// that matter). This is used to ergonomically simplify bindings where the
// majority of the time `Accessor` is closed over in a future which then needs
// to be `Send` and `Sync`. To avoid needing to write `T: Send` everywhere (as
// you already have to write `T: 'static`...) it helps to avoid this.
//
// Note as well that `Accessor` doesn't actually store its data at all. Instead
// it's more of a "proof" of what can be accessed from TLS. API design around
// `Accessor` and functions like `Linker::func_wrap_concurrent` are
// intentionally made to ensure that `Accessor` is ideally only used in the
// context that TLS variables are actually set. For example host functions are
// given `&Accessor`, not `Accessor`, and this prevents them from persisting
// the value outside of a future. Within the future the TLS variables are all
// guaranteed to be set while the future is being polled.
//
// Finally though this is not an ironclad guarantee, but nor does it need to be.
// The TLS APIs are designed to panic or otherwise model usage where they're
// called recursively or similar. It's hoped that code cannot be constructed to
// actually hit this at runtime but this is not a safety requirement at this
// time.
const _: () = {
    const fn assert<T: Send + Sync>() {}
    assert::<Accessor<UnsafeCell<u32>>>();
};

impl<T> Accessor<T> {
    /// Creates a new `Accessor` backed by the specified functions.
    ///
    /// - `get`: used to retrieve the store
    ///
    /// - `get_data`: used to "project" from the store's associated data to
    /// another type (e.g. a field of that data or a wrapper around it).
    ///
    /// - `spawn`: used to queue spawned background tasks to be run later
    pub(crate) fn new(token: StoreToken<T>) -> Self {
        Self {
            token,
            get_data: |x| x,
        }
    }
}

impl<T, D> Accessor<T, D>
where
    D: HasData + ?Sized,
{
    /// Run the specified closure, passing it mutable access to the store.
    ///
    /// This function is one of the main building blocks of the [`Accessor`]
    /// type. This yields synchronous, blocking, access to the store via an
    /// [`Access`]. The [`Access`] implements [`AsContextMut`] in addition to
    /// providing the ability to access `D` via [`Access::get`]. Note that the
    /// `fun` here is given only temporary access to the store and `T`/`D`
    /// meaning that the return value `R` here is not allowed to capture borrows
    /// into the two. If access is needed to data within `T` or `D` outside of
    /// this closure then it must be `clone`d out, for example.
    ///
    /// # Panics
    ///
    /// This function will panic if it is call recursively with any other
    /// accessor already in scope. For example if `with` is called within `fun`,
    /// then this function will panic. It is up to the embedder to ensure that
    /// this does not happen.
    pub fn with<R>(&self, fun: impl FnOnce(Access<'_, T, D>) -> R) -> R {
        tls::get(|vmstore| {
            fun(Access {
                store: self.token.as_context_mut(vmstore),
                get_data: self.get_data,
            })
        })
    }

    /// Returns the getter this accessor is using to project from `T` into
    /// `D::Data`.
    pub fn getter(&self) -> fn(&mut T) -> D::Data<'_> {
        self.get_data
    }

    /// Changes this accessor to access `D2` instead of the current type
    /// parameter `D`.
    ///
    /// This changes the underlying data access from `T` to `D2::Data<'_>`.
    ///
    /// # Panics
    ///
    /// When using this API the returned value is disconnected from `&self` and
    /// the lifetime binding the `self` argument. An `Accessor` only works
    /// within the context of the closure or async closure that it was
    /// originally given to, however. This means that due to the fact that the
    /// returned value has no lifetime connection it's possible to use the
    /// accessor outside of `&self`, the original accessor, and panic.
    ///
    /// The returned value should only be used within the scope of the original
    /// `Accessor` that `self` refers to.
    pub fn with_getter<D2: HasData>(
        &self,
        get_data: fn(&mut T) -> D2::Data<'_>,
    ) -> Accessor<T, D2> {
        Accessor {
            token: self.token,
            get_data,
        }
    }

    /// Spawn a background task which will receive an `&Accessor<T, D>` and
    /// run concurrently with any other tasks in progress for the current
    /// store.
    ///
    /// This is particularly useful for host functions which return a `stream`
    /// or `future` such that the code to write to the write end of that
    /// `stream` or `future` must run after the function returns.
    ///
    /// The returned [`JoinHandle`] may be used to cancel the task.
    ///
    /// # Panics
    ///
    /// Panics if called within a closure provided to the [`Accessor::with`]
    /// function. This can only be called outside an active invocation of
    /// [`Accessor::with`].
    pub fn spawn(&self, task: impl AccessorTask<T, D>) -> JoinHandle
    where
        T: 'static,
    {
        let accessor = self.clone_for_spawn();
        self.with(|mut access| access.as_context_mut().spawn_with_accessor(accessor, task))
    }

    fn clone_for_spawn(&self) -> Self {
        Self {
            token: self.token,
            get_data: self.get_data,
        }
    }
}

/// Represents a task which may be provided to `Accessor::spawn`,
/// `Accessor::forward`, or `StorecContextMut::spawn`.
// TODO: Replace this with `std::ops::AsyncFnOnce` when that becomes a viable
// option.
//
// As of this writing, it's not possible to specify e.g. `Send` and `Sync`
// bounds on the `Future` type returned by an `AsyncFnOnce`.  Also, using `F:
// Future<Output = Result<()>> + Send + Sync, FN: FnOnce(&Accessor<T>) -> F +
// Send + Sync + 'static` fails with a type mismatch error when we try to pass
// it an async closure (e.g. `async move |_| { ... }`).  So this seems to be the
// best we can do for the time being.
pub trait AccessorTask<T, D = HasSelf<T>>: Send + 'static
where
    D: HasData + ?Sized,
{
    /// Run the task.
    fn run(self, accessor: &Accessor<T, D>) -> impl Future<Output = Result<()>> + Send;
}

/// Represents parameter and result metadata for the caller side of a
/// guest->guest call orchestrated by a fused adapter.
enum CallerInfo {
    /// Metadata for a call to an async-lowered import
    Async {
        params: Vec<ValRaw>,
        has_result: bool,
    },
    /// Metadata for a call to an sync-lowered import
    Sync {
        params: Vec<ValRaw>,
        result_count: u32,
    },
}

/// Indicates how a guest task is waiting on a waitable set.
enum WaitMode {
    /// The guest task is waiting using `task.wait`
    Fiber(StoreFiber<'static>),
    /// The guest task is waiting via a callback declared as part of an
    /// async-lifted export.
    Callback(Instance),
}

/// Represents the reason a fiber is suspending itself.
#[derive(Debug)]
enum SuspendReason {
    /// The fiber is waiting for an event to be delivered to the specified
    /// waitable set or task.
    Waiting {
        set: TableId<WaitableSet>,
        thread: QualifiedThreadId,
        skip_may_block_check: bool,
    },
    /// The fiber has finished handling its most recent work item and is waiting
    /// for another (or to be dropped if it is no longer needed).
    NeedWork,
    /// The fiber is yielding and should be resumed once other tasks have had a
    /// chance to run.
    Yielding {
        thread: QualifiedThreadId,
        skip_may_block_check: bool,
    },
    /// The fiber was explicitly suspended with a call to `thread.suspend` or `thread.switch-to`.
    ExplicitlySuspending {
        thread: QualifiedThreadId,
        skip_may_block_check: bool,
    },
}

/// Represents a pending call into guest code for a given guest task.
enum GuestCallKind {
    /// Indicates there's an event to deliver to the task, possibly related to a
    /// waitable set the task has been waiting on or polling.
    DeliverEvent {
        /// The instance to which the task belongs.
        instance: Instance,
        /// The waitable set the event belongs to, if any.
        ///
        /// If this is `None` the event will be waiting in the
        /// `GuestTask::event` field for the task.
        set: Option<TableId<WaitableSet>>,
    },
    /// Indicates that a new guest task call is pending and may be executed
    /// using the specified closure.
    ///
    /// If the closure returns `Ok(Some(call))`, the `call` should be run
    /// immediately using `handle_guest_call`.
    StartImplicit(Box<dyn FnOnce(&mut dyn VMStore) -> Result<Option<GuestCall>> + Send + Sync>),
    StartExplicit(Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send + Sync>),
}

impl fmt::Debug for GuestCallKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::DeliverEvent { instance, set } => f
                .debug_struct("DeliverEvent")
                .field("instance", instance)
                .field("set", set)
                .finish(),
            Self::StartImplicit(_) => f.debug_tuple("StartImplicit").finish(),
            Self::StartExplicit(_) => f.debug_tuple("StartExplicit").finish(),
        }
    }
}

/// Represents a pending call into guest code for a given guest thread.
#[derive(Debug)]
struct GuestCall {
    thread: QualifiedThreadId,
    kind: GuestCallKind,
}

impl GuestCall {
    /// Returns whether or not the call is ready to run.
    ///
    /// A call will not be ready to run if either:
    ///
    /// - the (sub-)component instance to be called has already been entered and
    /// cannot be reentered until an in-progress call completes
    ///
    /// - the call is for a not-yet started task and the (sub-)component
    /// instance to be called has backpressure enabled
    fn is_ready(&self, store: &mut StoreOpaque) -> Result<bool> {
        let instance = store
            .concurrent_state_mut()
            .get_mut(self.thread.task)?
            .instance;
        let state = store.instance_state(instance).concurrent_state();

        let ready = match &self.kind {
            GuestCallKind::DeliverEvent { .. } => !state.do_not_enter,
            GuestCallKind::StartImplicit(_) => !(state.do_not_enter || state.backpressure > 0),
            GuestCallKind::StartExplicit(_) => true,
        };
        log::trace!(
            "call {self:?} ready? {ready} (do_not_enter: {}; backpressure: {})",
            state.do_not_enter,
            state.backpressure
        );
        Ok(ready)
    }
}

/// Job to be run on a worker fiber.
enum WorkerItem {
    GuestCall(GuestCall),
    Function(AlwaysMut<Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send>>),
}

/// Represents a pending work item to be handled by the event loop for a given
/// component instance.
enum WorkItem {
    /// A host task to be pushed to `ConcurrentState::futures`.
    PushFuture(AlwaysMut<HostTaskFuture>),
    /// A fiber to resume.
    ResumeFiber(StoreFiber<'static>),
    /// A pending call into guest code for a given guest task.
    GuestCall(GuestCall),
    /// A job to run on a worker fiber.
    WorkerFunction(AlwaysMut<Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send>>),
}

impl fmt::Debug for WorkItem {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::PushFuture(_) => f.debug_tuple("PushFuture").finish(),
            Self::ResumeFiber(_) => f.debug_tuple("ResumeFiber").finish(),
            Self::GuestCall(call) => f.debug_tuple("GuestCall").field(call).finish(),
            Self::WorkerFunction(_) => f.debug_tuple("WorkerFunction").finish(),
        }
    }
}

/// Whether a suspension intrinsic was cancelled or completed
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub(crate) enum WaitResult {
    Cancelled,
    Completed,
}

/// Poll the specified future until it completes on behalf of a guest->host call
/// using a sync-lowered import.
///
/// This is similar to `Instance::first_poll` except it's for sync-lowered
/// imports, meaning we don't need to handle cancellation and we can block the
/// caller until the task completes, at which point the caller can handle
/// lowering the result to the guest's stack and linear memory.
pub(crate) fn poll_and_block<R: Send + Sync + 'static>(
    store: &mut dyn VMStore,
    future: impl Future<Output = Result<R>> + Send + 'static,
    caller_instance: RuntimeInstance,
) -> Result<R> {
    let state = store.concurrent_state_mut();

    let caller = state.guest_thread.unwrap();

    // Save any existing result stashed in `GuestTask::result` so we can replace
    // it with the new result.
    let old_result = state
        .get_mut(caller.task)
        .with_context(|| format!("bad handle: {caller:?}"))?
        .result
        .take();

    // Add a temporary host task into the table so we can track its progress.
    // Note that we'll never allocate a waitable handle for the guest since
    // we're being called synchronously.
    let task = state.push(HostTask::new(caller_instance, None))?;

    log::trace!("new host task child of {caller:?}: {task:?}");

    // Wrap the future in a closure which will take care of stashing the result
    // in `GuestTask::result` and resuming this fiber when the host task
    // completes.
    let mut future = Box::pin(async move {
        let result = future.await?;
        tls::get(move |store| {
            let state = store.concurrent_state_mut();
            state.get_mut(caller.task)?.result = Some(Box::new(result) as _);

            Waitable::Host(task).set_event(
                state,
                Some(Event::Subtask {
                    status: Status::Returned,
                }),
            )?;

            Ok(())
        })
    }) as HostTaskFuture;

    // Finally, poll the future.  We can use a dummy `Waker` here because we'll
    // add the future to `ConcurrentState::futures` and poll it automatically
    // from the event loop if it doesn't complete immediately here.
    let poll = tls::set(store, || {
        future
            .as_mut()
            .poll(&mut Context::from_waker(&Waker::noop()))
    });

    match poll {
        Poll::Ready(result) => {
            // It completed immediately; check the result and delete the task.
            result?;
            log::trace!("delete host task {task:?} (already ready)");
            store.concurrent_state_mut().delete(task)?;
        }
        Poll::Pending => {
            // It did not complete immediately; add it to
            // `ConcurrentState::futures` so it will be polled via the event
            // loop; then use `GuestTask::sync_call_set` to wait for the task to
            // complete, suspending the current fiber until it does so.
            let state = store.concurrent_state_mut();
            state.push_future(future);

            let set = state.get_mut(caller.task)?.sync_call_set;
            Waitable::Host(task).join(state, Some(set))?;

            store.suspend(SuspendReason::Waiting {
                set,
                thread: caller,
                skip_may_block_check: false,
            })?;
        }
    }

    // Retrieve and return the result.
    Ok(*mem::replace(
        &mut store.concurrent_state_mut().get_mut(caller.task)?.result,
        old_result,
    )
    .unwrap()
    .downcast()
    .unwrap())
}

/// Execute the specified guest call.
fn handle_guest_call(store: &mut dyn VMStore, call: GuestCall) -> Result<()> {
    let mut next = Some(call);
    while let Some(call) = next.take() {
        match call.kind {
            GuestCallKind::DeliverEvent { instance, set } => {
                let (event, waitable) = instance
                    .get_event(store, call.thread.task, set, true)?
                    .unwrap();
                let state = store.concurrent_state_mut();
                let task = state.get_mut(call.thread.task)?;
                let runtime_instance = task.instance;
                let handle = waitable.map(|(_, v)| v).unwrap_or(0);

                log::trace!(
                    "use callback to deliver event {event:?} to {:?} for {waitable:?}",
                    call.thread,
                );

                let old_thread = store.set_thread(Some(call.thread));
                log::trace!(
                    "GuestCallKind::DeliverEvent: replaced {old_thread:?} with {:?} as current thread",
                    call.thread
                );

                store.maybe_push_call_context(call.thread.task)?;

                store.enter_instance(runtime_instance);

                let callback = store
                    .concurrent_state_mut()
                    .get_mut(call.thread.task)?
                    .callback
                    .take()
                    .unwrap();

                let code = callback(store, event, handle)?;

                store
                    .concurrent_state_mut()
                    .get_mut(call.thread.task)?
                    .callback = Some(callback);

                store.exit_instance(runtime_instance)?;

                store.maybe_pop_call_context(call.thread.task)?;

                store.set_thread(old_thread);

                next = instance.handle_callback_code(
                    store,
                    call.thread,
                    runtime_instance.index,
                    code,
                )?;

                log::trace!(
                    "GuestCallKind::DeliverEvent: restored {old_thread:?} as current thread"
                );
            }
            GuestCallKind::StartImplicit(fun) => {
                next = fun(store)?;
            }
            GuestCallKind::StartExplicit(fun) => {
                fun(store)?;
            }
        }
    }

    Ok(())
}

impl<T> Store<T> {
    /// Convenience wrapper for [`StoreContextMut::run_concurrent`].
    pub async fn run_concurrent<R>(&mut self, fun: impl AsyncFnOnce(&Accessor<T>) -> R) -> Result<R>
    where
        T: Send + 'static,
    {
        ensure!(
            self.as_context().0.concurrency_support(),
            "cannot use `run_concurrent` when Config::concurrency_support disabled",
        );
        self.as_context_mut().run_concurrent(fun).await
    }

    #[doc(hidden)]
    pub fn assert_concurrent_state_empty(&mut self) {
        self.as_context_mut().assert_concurrent_state_empty();
    }

    /// Convenience wrapper for [`StoreContextMut::spawn`].
    pub fn spawn(&mut self, task: impl AccessorTask<T, HasSelf<T>>) -> JoinHandle
    where
        T: 'static,
    {
        self.as_context_mut().spawn(task)
    }
}

impl<T> StoreContextMut<'_, T> {
    /// Assert that all the relevant tables and queues in the concurrent state
    /// for this store are empty.
    ///
    /// This is for sanity checking in integration tests
    /// (e.g. `component-async-tests`) that the relevant state has been cleared
    /// after each test concludes.  This should help us catch leaks, e.g. guest
    /// tasks which haven't been deleted despite having completed and having
    /// been dropped by their supertasks.
    #[doc(hidden)]
    pub fn assert_concurrent_state_empty(self) {
        let store = self.0;
        store
            .store_data_mut()
            .components
            .assert_instance_states_empty();
        let state = store.concurrent_state_mut();
        assert!(
            state.table.get_mut().is_empty(),
            "non-empty table: {:?}",
            state.table.get_mut()
        );
        assert!(state.high_priority.is_empty());
        assert!(state.low_priority.is_empty());
        assert!(state.guest_thread.is_none());
        assert!(state.futures.get_mut().as_ref().unwrap().is_empty());
        assert!(state.global_error_context_ref_counts.is_empty());
    }

    /// Spawn a background task to run as part of this instance's event loop.
    ///
    /// The task will receive an `&Accessor<U>` and run concurrently with
    /// any other tasks in progress for the instance.
    ///
    /// Note that the task will only make progress if and when the event loop
    /// for this instance is run.
    ///
    /// The returned [`JoinHandle`] may be used to cancel the task.
    pub fn spawn(mut self, task: impl AccessorTask<T>) -> JoinHandle
    where
        T: 'static,
    {
        let accessor = Accessor::new(StoreToken::new(self.as_context_mut()));
        self.spawn_with_accessor(accessor, task)
    }

    /// Internal implementation of `spawn` functions where a `store` is
    /// available along with an `Accessor`.
    fn spawn_with_accessor<D>(
        self,
        accessor: Accessor<T, D>,
        task: impl AccessorTask<T, D>,
    ) -> JoinHandle
    where
        T: 'static,
        D: HasData + ?Sized,
    {
        // Create an "abortable future" here where internally the future will
        // hook calls to poll and possibly spawn more background tasks on each
        // iteration.
        let (handle, future) = JoinHandle::run(async move { task.run(&accessor).await });
        self.0
            .concurrent_state_mut()
            .push_future(Box::pin(async move { future.await.unwrap_or(Ok(())) }));
        handle
    }

    /// Run the specified closure `fun` to completion as part of this store's
    /// event loop.
    ///
    /// This will run `fun` as part of this store's event loop until it
    /// yields a result.  `fun` is provided an [`Accessor`], which provides
    /// controlled access to the store and its data.
    ///
    /// This function can be used to invoke [`Func::call_concurrent`] for
    /// example within the async closure provided here.
    ///
    /// This function will unconditionally return an error if
    /// [`Config::concurrency_support`] is disabled.
    ///
    /// [`Config::concurrency_support`]: crate::Config::concurrency_support
    ///
    /// # Store-blocking behavior
    ///
    /// At this time there are certain situations in which the `Future` returned
    /// by the `AsyncFnOnce` passed to this function will not be polled for an
    /// extended period of time, despite one or more `Waker::wake` events having
    /// occurred for the task to which it belongs.  This can manifest as the
    /// `Future` seeming to be "blocked" or "locked up", but is actually due to
    /// the `Store` being held by e.g. a blocking host function, preventing the
    /// `Future` from being polled. A canonical example of this is when the
    /// `fun` provided to this function attempts to set a timeout for an
    /// invocation of a wasm function. In this situation the async closure is
    /// waiting both on (a) the wasm computation to finish, and (b) the timeout
    /// to elapse. At this time this setup will not always work and the timeout
    /// may not reliably fire.
    ///
    /// This function will not block the current thread and as such is always
    /// suitable to run in an `async` context, but the current implementation of
    /// Wasmtime can lead to situations where a certain wasm computation is
    /// required to make progress the closure to make progress. This is an
    /// artifact of Wasmtime's historical implementation of `async` functions
    /// and is the topic of [#11869] and [#11870]. In the timeout example from
    /// above it means that Wasmtime can get "wedged" for a bit where (a) must
    /// progress for a readiness notification of (b) to get delivered.
    ///
    /// This effectively means that it's not possible to reliably perform a
    /// "select" operation within the `fun` closure, which timeouts for example
    /// are based on. Fixing this requires some relatively major refactoring
    /// work within Wasmtime itself. This is a known pitfall otherwise and one
    /// that is intended to be fixed one day. In the meantime it's recommended
    /// to apply timeouts or such to the entire `run_concurrent` call itself
    /// rather than internally.
    ///
    /// [#11869]: https://github.com/bytecodealliance/wasmtime/issues/11869
    /// [#11870]: https://github.com/bytecodealliance/wasmtime/issues/11870
    ///
    /// # Example
    ///
    /// ```
    /// # use {
    /// #   wasmtime::{
    /// #     error::{Result},
    /// #     component::{ Component, Linker, Resource, ResourceTable},
    /// #     Config, Engine, Store
    /// #   },
    /// # };
    /// #
    /// # struct MyResource(u32);
    /// # struct Ctx { table: ResourceTable }
    /// #
    /// # async fn foo() -> Result<()> {
    /// # let mut config = Config::new();
    /// # let engine = Engine::new(&config)?;
    /// # let mut store = Store::new(&engine, Ctx { table: ResourceTable::new() });
    /// # let mut linker = Linker::new(&engine);
    /// # let component = Component::new(&engine, "")?;
    /// # let instance = linker.instantiate_async(&mut store, &component).await?;
    /// # let foo = instance.get_typed_func::<(Resource<MyResource>,), (Resource<MyResource>,)>(&mut store, "foo")?;
    /// # let bar = instance.get_typed_func::<(u32,), ()>(&mut store, "bar")?;
    /// store.run_concurrent(async |accessor| -> wasmtime::Result<_> {
    ///    let resource = accessor.with(|mut access| access.get().table.push(MyResource(42)))?;
    ///    let (another_resource,) = foo.call_concurrent(accessor, (resource,)).await?.0;
    ///    let value = accessor.with(|mut access| access.get().table.delete(another_resource))?;
    ///    bar.call_concurrent(accessor, (value.0,)).await?;
    ///    Ok(())
    /// }).await??;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn run_concurrent<R>(self, fun: impl AsyncFnOnce(&Accessor<T>) -> R) -> Result<R>
    where
        T: Send + 'static,
    {
        ensure!(
            self.0.concurrency_support(),
            "cannot use `run_concurrent` when Config::concurrency_support disabled",
        );
        self.do_run_concurrent(fun, false).await
    }

    pub(super) async fn run_concurrent_trap_on_idle<R>(
        self,
        fun: impl AsyncFnOnce(&Accessor<T>) -> R,
    ) -> Result<R>
    where
        T: Send + 'static,
    {
        self.do_run_concurrent(fun, true).await
    }

    async fn do_run_concurrent<R>(
        mut self,
        fun: impl AsyncFnOnce(&Accessor<T>) -> R,
        trap_on_idle: bool,
    ) -> Result<R>
    where
        T: Send + 'static,
    {
        debug_assert!(self.0.concurrency_support());
        check_recursive_run();
        let token = StoreToken::new(self.as_context_mut());

        struct Dropper<'a, T: 'static, V> {
            store: StoreContextMut<'a, T>,
            value: ManuallyDrop<V>,
        }

        impl<'a, T, V> Drop for Dropper<'a, T, V> {
            fn drop(&mut self) {
                tls::set(self.store.0, || {
                    // SAFETY: Here we drop the value without moving it for the
                    // first and only time -- per the contract for `Drop::drop`,
                    // this code won't run again, and the `value` field will no
                    // longer be accessible.
                    unsafe { ManuallyDrop::drop(&mut self.value) }
                });
            }
        }

        let accessor = &Accessor::new(token);
        let dropper = &mut Dropper {
            store: self,
            value: ManuallyDrop::new(fun(accessor)),
        };
        // SAFETY: We never move `dropper` nor its `value` field.
        let future = unsafe { Pin::new_unchecked(dropper.value.deref_mut()) };

        dropper
            .store
            .as_context_mut()
            .poll_until(future, trap_on_idle)
            .await
    }

    /// Run this store's event loop.
    ///
    /// The returned future will resolve when the specified future completes or,
    /// if `trap_on_idle` is true, when the event loop can't make further
    /// progress.
    async fn poll_until<R>(
        mut self,
        mut future: Pin<&mut impl Future<Output = R>>,
        trap_on_idle: bool,
    ) -> Result<R>
    where
        T: Send + 'static,
    {
        struct Reset<'a, T: 'static> {
            store: StoreContextMut<'a, T>,
            futures: Option<FuturesUnordered<HostTaskFuture>>,
        }

        impl<'a, T> Drop for Reset<'a, T> {
            fn drop(&mut self) {
                if let Some(futures) = self.futures.take() {
                    *self.store.0.concurrent_state_mut().futures.get_mut() = Some(futures);
                }
            }
        }

        loop {
            // Take `ConcurrentState::futures` out of the store so we can poll
            // it while also safely giving any of the futures inside access to
            // `self`.
            let futures = self.0.concurrent_state_mut().futures.get_mut().take();
            let mut reset = Reset {
                store: self.as_context_mut(),
                futures,
            };
            let mut next = pin!(reset.futures.as_mut().unwrap().next());

            enum PollResult<R> {
                Complete(R),
                ProcessWork(Vec<WorkItem>),
            }
            let result = future::poll_fn(|cx| {
                // First, poll the future we were passed as an argument and
                // return immediately if it's ready.
                if let Poll::Ready(value) = tls::set(reset.store.0, || future.as_mut().poll(cx)) {
                    return Poll::Ready(Ok(PollResult::Complete(value)));
                }

                // Next, poll `ConcurrentState::futures` (which includes any
                // pending host tasks and/or background tasks), returning
                // immediately if one of them fails.
                let next = match tls::set(reset.store.0, || next.as_mut().poll(cx)) {
                    Poll::Ready(Some(output)) => {
                        match output {
                            Err(e) => return Poll::Ready(Err(e)),
                            Ok(()) => {}
                        }
                        Poll::Ready(true)
                    }
                    Poll::Ready(None) => Poll::Ready(false),
                    Poll::Pending => Poll::Pending,
                };

                // Next, collect the next batch of work items to process, if any.
                // This will be either all of the high-priority work items, or if
                // there are none, a single low-priority work item.
                let state = reset.store.0.concurrent_state_mut();
                let ready = state.collect_work_items_to_run();
                if !ready.is_empty() {
                    return Poll::Ready(Ok(PollResult::ProcessWork(ready)));
                }

                // Finally, if we have nothing else to do right now, determine what to do
                // based on whether there are any pending futures in
                // `ConcurrentState::futures`.
                return match next {
                    Poll::Ready(true) => {
                        // In this case, one of the futures in
                        // `ConcurrentState::futures` completed
                        // successfully, so we return now and continue
                        // the outer loop in case there is another one
                        // ready to complete.
                        Poll::Ready(Ok(PollResult::ProcessWork(Vec::new())))
                    }
                    Poll::Ready(false) => {
                        // Poll the future we were passed one last time
                        // in case one of `ConcurrentState::futures` had
                        // the side effect of unblocking it.
                        if let Poll::Ready(value) =
                            tls::set(reset.store.0, || future.as_mut().poll(cx))
                        {
                            Poll::Ready(Ok(PollResult::Complete(value)))
                        } else {
                            // In this case, there are no more pending
                            // futures in `ConcurrentState::futures`,
                            // there are no remaining work items, _and_
                            // the future we were passed as an argument
                            // still hasn't completed.
                            if trap_on_idle {
                                // `trap_on_idle` is true, so we exit
                                // immediately.
                                Poll::Ready(Err(format_err!(crate::Trap::AsyncDeadlock)))
                            } else {
                                // `trap_on_idle` is false, so we assume
                                // that future will wake up and give us
                                // more work to do when it's ready to.
                                Poll::Pending
                            }
                        }
                    }
                    // There is at least one pending future in
                    // `ConcurrentState::futures` and we have nothing
                    // else to do but wait for now, so we return
                    // `Pending`.
                    Poll::Pending => Poll::Pending,
                };
            })
            .await;

            // Put the `ConcurrentState::futures` back into the store before we
            // return or handle any work items since one or more of those items
            // might append more futures.
            drop(reset);

            match result? {
                // The future we were passed as an argument completed, so we
                // return the result.
                PollResult::Complete(value) => break Ok(value),
                // The future we were passed has not yet completed, so handle
                // any work items and then loop again.
                PollResult::ProcessWork(ready) => {
                    struct Dispose<'a, T: 'static, I: Iterator<Item = WorkItem>> {
                        store: StoreContextMut<'a, T>,
                        ready: I,
                    }

                    impl<'a, T, I: Iterator<Item = WorkItem>> Drop for Dispose<'a, T, I> {
                        fn drop(&mut self) {
                            while let Some(item) = self.ready.next() {
                                match item {
                                    WorkItem::ResumeFiber(mut fiber) => fiber.dispose(self.store.0),
                                    WorkItem::PushFuture(future) => {
                                        tls::set(self.store.0, move || drop(future))
                                    }
                                    _ => {}
                                }
                            }
                        }
                    }

                    let mut dispose = Dispose {
                        store: self.as_context_mut(),
                        ready: ready.into_iter(),
                    };

                    while let Some(item) = dispose.ready.next() {
                        dispose
                            .store
                            .as_context_mut()
                            .handle_work_item(item)
                            .await?;
                    }
                }
            }
        }
    }

    /// Handle the specified work item, possibly resuming a fiber if applicable.
    async fn handle_work_item(self, item: WorkItem) -> Result<()>
    where
        T: Send,
    {
        log::trace!("handle work item {item:?}");
        match item {
            WorkItem::PushFuture(future) => {
                self.0
                    .concurrent_state_mut()
                    .futures
                    .get_mut()
                    .as_mut()
                    .unwrap()
                    .push(future.into_inner());
            }
            WorkItem::ResumeFiber(fiber) => {
                self.0.resume_fiber(fiber).await?;
            }
            WorkItem::GuestCall(call) => {
                if call.is_ready(self.0)? {
                    self.run_on_worker(WorkerItem::GuestCall(call)).await?;
                } else {
                    let state = self.0.concurrent_state_mut();
                    let task = state.get_mut(call.thread.task)?;
                    if !task.starting_sent {
                        task.starting_sent = true;
                        if let GuestCallKind::StartImplicit(_) = &call.kind {
                            Waitable::Guest(call.thread.task).set_event(
                                state,
                                Some(Event::Subtask {
                                    status: Status::Starting,
                                }),
                            )?;
                        }
                    }

                    let instance = state.get_mut(call.thread.task)?.instance;
                    self.0
                        .instance_state(instance)
                        .concurrent_state()
                        .pending
                        .insert(call.thread, call.kind);
                }
            }
            WorkItem::WorkerFunction(fun) => {
                self.run_on_worker(WorkerItem::Function(fun)).await?;
            }
        }

        Ok(())
    }

    /// Execute the specified guest call on a worker fiber.
    async fn run_on_worker(self, item: WorkerItem) -> Result<()>
    where
        T: Send,
    {
        let worker = if let Some(fiber) = self.0.concurrent_state_mut().worker.take() {
            fiber
        } else {
            fiber::make_fiber(self.0, move |store| {
                loop {
                    match store.concurrent_state_mut().worker_item.take().unwrap() {
                        WorkerItem::GuestCall(call) => handle_guest_call(store, call)?,
                        WorkerItem::Function(fun) => fun.into_inner()(store)?,
                    }

                    store.suspend(SuspendReason::NeedWork)?;
                }
            })?
        };

        let worker_item = &mut self.0.concurrent_state_mut().worker_item;
        assert!(worker_item.is_none());
        *worker_item = Some(item);

        self.0.resume_fiber(worker).await
    }

    /// Wrap the specified host function in a future which will call it, passing
    /// it an `&Accessor<T>`.
    ///
    /// See the `Accessor` documentation for details.
    pub(crate) fn wrap_call<F, R>(self, closure: F) -> impl Future<Output = Result<R>> + 'static
    where
        T: 'static,
        F: FnOnce(&Accessor<T>) -> Pin<Box<dyn Future<Output = Result<R>> + Send + '_>>
            + Send
            + Sync
            + 'static,
        R: Send + Sync + 'static,
    {
        let token = StoreToken::new(self);
        async move {
            let mut accessor = Accessor::new(token);
            closure(&mut accessor).await
        }
    }
}

impl StoreOpaque {
    /// Push a `GuestTask` onto the task stack for either a sync-to-sync,
    /// guest-to-guest call or a sync host-to-guest call.
    ///
    /// This task will only be used for the purpose of handling calls to
    /// intrinsic functions; both parameter lowering and result lifting are
    /// assumed to be taken care of elsewhere.
    pub(crate) fn enter_sync_call(
        &mut self,
        guest_caller: Option<RuntimeInstance>,
        callee_async: bool,
        callee: RuntimeInstance,
    ) -> Result<()> {
        log::trace!("enter sync call {callee:?}");

        let state = self.concurrent_state_mut();
        let thread = state.guest_thread;
        let instance = if let Some(thread) = thread {
            Some(state.get_mut(thread.task)?.instance)
        } else {
            None
        };
        let task = GuestTask::new(
            state,
            Box::new(move |_, _| unreachable!()),
            LiftResult {
                lift: Box::new(move |_, _| unreachable!()),
                ty: TypeTupleIndex::reserved_value(),
                memory: None,
                string_encoding: StringEncoding::Utf8,
            },
            if let Some(caller) = guest_caller {
                assert_eq!(caller, instance.unwrap());
                Caller::Guest {
                    thread: thread.unwrap(),
                }
            } else {
                Caller::Host {
                    tx: None,
                    exit_tx: Arc::new(oneshot::channel().0),
                    host_future_present: false,
                    caller: state.guest_thread,
                }
            },
            None,
            callee,
            callee_async,
        )?;

        let guest_task = state.push(task)?;
        let new_thread = GuestThread::new_implicit(guest_task);
        let guest_thread = state.push(new_thread)?;
        Instance::from_wasmtime(self, callee.instance).add_guest_thread_to_instance_table(
            guest_thread,
            self,
            callee.index,
        )?;

        let state = self.concurrent_state_mut();
        state.get_mut(guest_task)?.threads.insert(guest_thread);
        if guest_caller.is_some() {
            let thread = state.guest_thread.unwrap();
            state.get_mut(thread.task)?.subtasks.insert(guest_task);
        }

        self.set_thread(Some(QualifiedThreadId {
            task: guest_task,
            thread: guest_thread,
        }));

        Ok(())
    }

    /// Pop a `GuestTask` previously pushed using `enter_sync_call`.
    pub(crate) fn exit_sync_call(&mut self, guest_caller: bool) -> Result<()> {
        let thread = self.set_thread(None).unwrap();
        let instance = self.concurrent_state_mut().get_mut(thread.task)?.instance;
        log::trace!("exit sync call {instance:?}");
        Instance::from_wasmtime(self, instance.instance).cleanup_thread(
            self,
            thread,
            instance.index,
        )?;

        let state = self.concurrent_state_mut();
        let task = state.get_mut(thread.task)?;
        let caller = match &task.caller {
            &Caller::Guest { thread } => {
                assert!(guest_caller);
                Some(thread)
            }
            &Caller::Host { caller, .. } => {
                assert!(!guest_caller);
                caller
            }
        };
        self.set_thread(caller);

        let state = self.concurrent_state_mut();
        let task = state.get_mut(thread.task)?;
        if task.ready_to_delete() {
            state.delete(thread.task)?.dispose(state, thread.task)?;
        }

        Ok(())
    }

    /// Determine whether the specified instance may be entered from the host.
    ///
    /// We return `true` here only if all of the following hold:
    ///
    /// - The top-level instance is not already on the current task's call stack.
    /// - The instance is not in need of a post-return function call.
    /// - `self` has not been poisoned due to a trap.
    pub(crate) fn may_enter(&mut self, instance: RuntimeInstance) -> bool {
        if !self.concurrency_support() {
            return !self.trapped();
        }
        let state = self.concurrent_state_mut();
        if let Some(caller) = state.guest_thread {
            instance != state.get_mut(caller.task).unwrap().instance
                && self.may_enter_from_caller(caller.task, instance)
        } else {
            !self.trapped()
        }
    }

    /// Variation of `may_enter` which takes a `TableId<GuestTask>` representing
    /// the callee.
    fn may_enter_task(&mut self, task: TableId<GuestTask>) -> bool {
        let instance = self.concurrent_state_mut().get_mut(task).unwrap().instance;
        self.may_enter_from_caller(task, instance)
    }

    /// Variation of `may_enter` which takes a `TableId<GuestTask>` representing
    /// the caller, plus a `RuntimeInstance` representing the callee.
    fn may_enter_from_caller(
        &mut self,
        mut guest_task: TableId<GuestTask>,
        instance: RuntimeInstance,
    ) -> bool {
        !self.trapped() && {
            let state = self.concurrent_state_mut();
            let guest_instance = instance.instance;
            loop {
                // Note that we only compare top-level instance IDs here.  The
                // idea is that the host is not allowed to recursively enter a
                // top-level instance even if the specific leaf instance is not
                // on the stack.  This the behavior defined in the spec, and it
                // allows us to elide runtime checks in guest-to-guest adapters.
                let next_thread = match &state.get_mut(guest_task).unwrap().caller {
                    Caller::Host { caller: None, .. } => break true,
                    &Caller::Host {
                        caller: Some(caller),
                        ..
                    } => {
                        let instance = state.get_mut(caller.task).unwrap().instance;
                        if instance.instance == guest_instance {
                            break false;
                        } else {
                            caller
                        }
                    }
                    &Caller::Guest { thread } => {
                        if state.get_mut(thread.task).unwrap().instance.instance == guest_instance {
                            break false;
                        } else {
                            thread
                        }
                    }
                };
                guest_task = next_thread.task;
            }
        }
    }

    /// Helper function to retrieve the `InstanceState` for the
    /// specified instance.
    fn instance_state(&mut self, instance: RuntimeInstance) -> &mut InstanceState {
        self.component_instance_mut(instance.instance)
            .instance_state(instance.index)
    }

    fn set_thread(&mut self, thread: Option<QualifiedThreadId>) -> Option<QualifiedThreadId> {
        // Each time we switch threads, we conservatively set `task_may_block`
        // to `false` for the component instance we're switching away from (if
        // any), meaning it will be `false` for any new thread created for that
        // instance unless explicitly set otherwise.
        let state = self.concurrent_state_mut();
        let old_thread = state.guest_thread.take();
        if let Some(old_thread) = old_thread {
            let instance = state.get_mut(old_thread.task).unwrap().instance.instance;
            self.component_instance_mut(instance)
                .set_task_may_block(false)
        }

        self.concurrent_state_mut().guest_thread = thread;

        // If we're switching to a new thread, set its component instance's
        // `task_may_block` according to where it left off.
        if thread.is_some() {
            self.set_task_may_block();
        }

        old_thread
    }

    /// Set the global variable representing whether the current task may block
    /// prior to entering Wasm code.
    fn set_task_may_block(&mut self) {
        let state = self.concurrent_state_mut();
        let guest_thread = state.guest_thread.unwrap();
        let instance = state.get_mut(guest_thread.task).unwrap().instance.instance;
        let may_block = self.concurrent_state_mut().may_block(guest_thread.task);
        self.component_instance_mut(instance)
            .set_task_may_block(may_block)
    }

    pub(crate) fn check_blocking(&mut self) -> Result<()> {
        if !self.concurrency_support() {
            return Ok(());
        }
        let state = self.concurrent_state_mut();
        let task = state.guest_thread.unwrap().task;
        let instance = state.get_mut(task).unwrap().instance.instance;
        let task_may_block = self.component_instance(instance).get_task_may_block();

        if task_may_block {
            Ok(())
        } else {
            Err(Trap::CannotBlockSyncTask.into())
        }
    }

    /// Record that we're about to enter a (sub-)component instance which does
    /// not support more than one concurrent, stackful activation, meaning it
    /// cannot be entered again until the next call returns.
    fn enter_instance(&mut self, instance: RuntimeInstance) {
        log::trace!("enter {instance:?}");
        self.instance_state(instance)
            .concurrent_state()
            .do_not_enter = true;
    }

    /// Record that we've exited a (sub-)component instance previously entered
    /// with `Self::enter_instance` and then calls `Self::partition_pending`.
    /// See the documentation for the latter for details.
    fn exit_instance(&mut self, instance: RuntimeInstance) -> Result<()> {
        log::trace!("exit {instance:?}");
        self.instance_state(instance)
            .concurrent_state()
            .do_not_enter = false;
        self.partition_pending(instance)
    }

    /// Iterate over `InstanceState::pending`, moving any ready items into the
    /// "high priority" work item queue.
    ///
    /// See `GuestCall::is_ready` for details.
    fn partition_pending(&mut self, instance: RuntimeInstance) -> Result<()> {
        for (thread, kind) in
            mem::take(&mut self.instance_state(instance).concurrent_state().pending).into_iter()
        {
            let call = GuestCall { thread, kind };
            if call.is_ready(self)? {
                self.concurrent_state_mut()
                    .push_high_priority(WorkItem::GuestCall(call));
            } else {
                self.instance_state(instance)
                    .concurrent_state()
                    .pending
                    .insert(call.thread, call.kind);
            }
        }

        Ok(())
    }

    /// Implements the `backpressure.{inc,dec}` intrinsics.
    pub(crate) fn backpressure_modify(
        &mut self,
        caller_instance: RuntimeInstance,
        modify: impl FnOnce(u16) -> Option<u16>,
    ) -> Result<()> {
        let state = self.instance_state(caller_instance).concurrent_state();
        let old = state.backpressure;
        let new = modify(old).ok_or_else(|| format_err!("backpressure counter overflow"))?;
        state.backpressure = new;

        if old > 0 && new == 0 {
            // Backpressure was previously enabled and is now disabled; move any
            // newly-eligible guest calls to the "high priority" queue.
            self.partition_pending(caller_instance)?;
        }

        Ok(())
    }

    /// Resume the specified fiber, giving it exclusive access to the specified
    /// store.
    async fn resume_fiber(&mut self, fiber: StoreFiber<'static>) -> Result<()> {
        let old_thread = self.concurrent_state_mut().guest_thread;
        log::trace!("resume_fiber: save current thread {old_thread:?}");

        let fiber = fiber::resolve_or_release(self, fiber).await?;

        self.set_thread(old_thread);

        let state = self.concurrent_state_mut();

        if let Some(ref ot) = old_thread {
            state.get_mut(ot.thread)?.state = GuestThreadState::Running;
        }
        log::trace!("resume_fiber: restore current thread {old_thread:?}");

        if let Some(mut fiber) = fiber {
            log::trace!("resume_fiber: suspend reason {:?}", &state.suspend_reason);
            // See the `SuspendReason` documentation for what each case means.
            match state.suspend_reason.take().unwrap() {
                SuspendReason::NeedWork => {
                    if state.worker.is_none() {
                        state.worker = Some(fiber);
                    } else {
                        fiber.dispose(self);
                    }
                }
                SuspendReason::Yielding { thread, .. } => {
                    state.get_mut(thread.thread)?.state = GuestThreadState::Pending;
                    state.push_low_priority(WorkItem::ResumeFiber(fiber));
                }
                SuspendReason::ExplicitlySuspending { thread, .. } => {
                    state.get_mut(thread.thread)?.state = GuestThreadState::Suspended(fiber);
                }
                SuspendReason::Waiting { set, thread, .. } => {
                    let old = state
                        .get_mut(set)?
                        .waiting
                        .insert(thread, WaitMode::Fiber(fiber));
                    assert!(old.is_none());
                }
            };
        } else {
            log::trace!("resume_fiber: fiber has exited");
        }

        Ok(())
    }

    /// Suspend the current fiber, storing the reason in
    /// `ConcurrentState::suspend_reason` to indicate the conditions under which
    /// it should be resumed.
    ///
    /// See the `SuspendReason` documentation for details.
    fn suspend(&mut self, reason: SuspendReason) -> Result<()> {
        log::trace!("suspend fiber: {reason:?}");

        // If we're yielding or waiting on behalf of a guest thread, we'll need to
        // pop the call context which manages resource borrows before suspending
        // and then push it again once we've resumed.
        let task = match &reason {
            SuspendReason::Yielding { thread, .. }
            | SuspendReason::Waiting { thread, .. }
            | SuspendReason::ExplicitlySuspending { thread, .. } => Some(thread.task),
            SuspendReason::NeedWork => None,
        };

        let old_guest_thread = if let Some(task) = task {
            self.maybe_pop_call_context(task)?;
            self.concurrent_state_mut().guest_thread
        } else {
            None
        };

        // We should not have reached here unless either there's no current
        // task, or the current task is permitted to block.  In addition, we
        // special-case `thread.switch-to` and waiting for a subtask to go from
        // `starting` to `started`, both of which we consider non-blocking
        // operations despite requiring a suspend.
        assert!(
            matches!(
                reason,
                SuspendReason::ExplicitlySuspending {
                    skip_may_block_check: true,
                    ..
                } | SuspendReason::Waiting {
                    skip_may_block_check: true,
                    ..
                } | SuspendReason::Yielding {
                    skip_may_block_check: true,
                    ..
                }
            ) || old_guest_thread
                .map(|thread| self.concurrent_state_mut().may_block(thread.task))
                .unwrap_or(true)
        );

        let suspend_reason = &mut self.concurrent_state_mut().suspend_reason;
        assert!(suspend_reason.is_none());
        *suspend_reason = Some(reason);

        self.with_blocking(|_, cx| cx.suspend(StoreFiberYield::ReleaseStore))?;

        if let Some(task) = task {
            self.set_thread(old_guest_thread);
            self.maybe_push_call_context(task)?;
        }

        Ok(())
    }

    /// Push the call context for managing resource borrows for the specified
    /// guest task if it has not yet either returned a result or cancelled
    /// itself.
    fn maybe_push_call_context(&mut self, guest_task: TableId<GuestTask>) -> Result<()> {
        let task = self.concurrent_state_mut().get_mut(guest_task)?;

        if !task.returned_or_cancelled() {
            log::trace!("push call context for {guest_task:?}");
            let call_context = task.call_context.take().unwrap();
            self.component_resource_state().0.push(call_context);
        }
        Ok(())
    }

    /// Pop the call context for managing resource borrows for the specified
    /// guest task if it has not yet either returned a result or cancelled
    /// itself.
    fn maybe_pop_call_context(&mut self, guest_task: TableId<GuestTask>) -> Result<()> {
        if !self
            .concurrent_state_mut()
            .get_mut(guest_task)?
            .returned_or_cancelled()
        {
            log::trace!("pop call context for {guest_task:?}");
            let call_context = Some(self.component_resource_state().0.pop().unwrap());
            self.concurrent_state_mut()
                .get_mut(guest_task)?
                .call_context = call_context;
        }
        Ok(())
    }

    fn wait_for_event(&mut self, waitable: Waitable) -> Result<()> {
        let state = self.concurrent_state_mut();
        let caller = state.guest_thread.unwrap();
        let old_set = waitable.common(state)?.set;
        let set = state.get_mut(caller.task)?.sync_call_set;
        waitable.join(state, Some(set))?;
        self.suspend(SuspendReason::Waiting {
            set,
            thread: caller,
            skip_may_block_check: false,
        })?;
        let state = self.concurrent_state_mut();
        waitable.join(state, old_set)
    }
}

impl Instance {
    /// Get the next pending event for the specified task and (optional)
    /// waitable set, along with the waitable handle if applicable.
    fn get_event(
        self,
        store: &mut StoreOpaque,
        guest_task: TableId<GuestTask>,
        set: Option<TableId<WaitableSet>>,
        cancellable: bool,
    ) -> Result<Option<(Event, Option<(Waitable, u32)>)>> {
        let state = store.concurrent_state_mut();

        if let Some(event) = state.get_mut(guest_task)?.event.take() {
            log::trace!("deliver event {event:?} to {guest_task:?}");

            if cancellable || !matches!(event, Event::Cancelled) {
                return Ok(Some((event, None)));
            } else {
                state.get_mut(guest_task)?.event = Some(event);
            }
        }

        Ok(
            if let Some((set, waitable)) = set
                .and_then(|set| {
                    state
                        .get_mut(set)
                        .map(|v| v.ready.pop_first().map(|v| (set, v)))
                        .transpose()
                })
                .transpose()?
            {
                let common = waitable.common(state)?;
                let handle = common.handle.unwrap();
                let event = common.event.take().unwrap();

                log::trace!(
                    "deliver event {event:?} to {guest_task:?} for {waitable:?} (handle {handle}); set {set:?}"
                );

                waitable.on_delivery(store, self, event);

                Some((event, Some((waitable, handle))))
            } else {
                None
            },
        )
    }

    /// Handle the `CallbackCode` returned from an async-lifted export or its
    /// callback.
    ///
    /// If this returns `Ok(Some(call))`, then `call` should be run immediately
    /// using `handle_guest_call`.
    fn handle_callback_code(
        self,
        store: &mut StoreOpaque,
        guest_thread: QualifiedThreadId,
        runtime_instance: RuntimeComponentInstanceIndex,
        code: u32,
    ) -> Result<Option<GuestCall>> {
        let (code, set) = unpack_callback_code(code);

        log::trace!("received callback code from {guest_thread:?}: {code} (set: {set})");

        let state = store.concurrent_state_mut();

        let get_set = |store: &mut StoreOpaque, handle| {
            if handle == 0 {
                bail!("invalid waitable-set handle");
            }

            let set = store
                .instance_state(RuntimeInstance {
                    instance: self.id().instance(),
                    index: runtime_instance,
                })
                .handle_table()
                .waitable_set_rep(handle)?;

            Ok(TableId::<WaitableSet>::new(set))
        };

        Ok(match code {
            callback_code::EXIT => {
                log::trace!("implicit thread {guest_thread:?} completed");
                self.cleanup_thread(store, guest_thread, runtime_instance)?;
                let task = store.concurrent_state_mut().get_mut(guest_thread.task)?;
                if task.threads.is_empty() && !task.returned_or_cancelled() {
                    bail!(Trap::NoAsyncResult);
                }
                match &task.caller {
                    Caller::Host { .. } => {
                        if task.ready_to_delete() {
                            Waitable::Guest(guest_thread.task)
                                .delete_from(store.concurrent_state_mut())?;
                        }
                    }
                    Caller::Guest { .. } => {
                        task.exited = true;
                        task.callback = None;
                    }
                }
                None
            }
            callback_code::YIELD => {
                let task = state.get_mut(guest_thread.task)?;
                // If an `Event::Cancelled` is pending, we'll deliver that;
                // otherwise, we'll deliver `Event::None`.  Note that
                // `GuestTask::event` is only ever set to one of those two
                // `Event` variants.
                if let Some(event) = task.event {
                    assert!(matches!(event, Event::None | Event::Cancelled));
                } else {
                    task.event = Some(Event::None);
                }
                let call = GuestCall {
                    thread: guest_thread,
                    kind: GuestCallKind::DeliverEvent {
                        instance: self,
                        set: None,
                    },
                };
                if state.may_block(guest_thread.task) {
                    // Push this thread onto the "low priority" queue so it runs
                    // after any other threads have had a chance to run.
                    state.push_low_priority(WorkItem::GuestCall(call));
                    None
                } else {
                    // Yielding in a non-blocking context is defined as a no-op
                    // according to the spec, so we must run this thread
                    // immediately without allowing any others to run.
                    Some(call)
                }
            }
            callback_code::WAIT => {
                // The task may only return `WAIT` if it was created for a call
                // to an async export).  Otherwise, we'll trap.
                state.check_blocking_for(guest_thread.task)?;

                let set = get_set(store, set)?;
                let state = store.concurrent_state_mut();

                if state.get_mut(guest_thread.task)?.event.is_some()
                    || !state.get_mut(set)?.ready.is_empty()
                {
                    // An event is immediately available; deliver it ASAP.
                    state.push_high_priority(WorkItem::GuestCall(GuestCall {
                        thread: guest_thread,
                        kind: GuestCallKind::DeliverEvent {
                            instance: self,
                            set: Some(set),
                        },
                    }));
                } else {
                    // No event is immediately available.
                    //
                    // We're waiting, so register to be woken up when an event
                    // is published for this waitable set.
                    //
                    // Here we also set `GuestTask::wake_on_cancel` which allows
                    // `subtask.cancel` to interrupt the wait.
                    let old = state
                        .get_mut(guest_thread.thread)?
                        .wake_on_cancel
                        .replace(set);
                    assert!(old.is_none());
                    let old = state
                        .get_mut(set)?
                        .waiting
                        .insert(guest_thread, WaitMode::Callback(self));
                    assert!(old.is_none());
                }
                None
            }
            _ => bail!("unsupported callback code: {code}"),
        })
    }

    fn cleanup_thread(
        self,
        store: &mut StoreOpaque,
        guest_thread: QualifiedThreadId,
        runtime_instance: RuntimeComponentInstanceIndex,
    ) -> Result<()> {
        let guest_id = store
            .concurrent_state_mut()
            .get_mut(guest_thread.thread)?
            .instance_rep;
        store
            .instance_state(RuntimeInstance {
                instance: self.id().instance(),
                index: runtime_instance,
            })
            .thread_handle_table()
            .guest_thread_remove(guest_id.unwrap())?;

        store.concurrent_state_mut().delete(guest_thread.thread)?;
        let task = store.concurrent_state_mut().get_mut(guest_thread.task)?;
        task.threads.remove(&guest_thread.thread);
        Ok(())
    }

    /// Add the specified guest call to the "high priority" work item queue, to
    /// be started as soon as backpressure and/or reentrance rules allow.
    ///
    /// SAFETY: The raw pointer arguments must be valid references to guest
    /// functions (with the appropriate signatures) when the closures queued by
    /// this function are called.
    unsafe fn queue_call<T: 'static>(
        self,
        mut store: StoreContextMut<T>,
        guest_thread: QualifiedThreadId,
        callee: SendSyncPtr<VMFuncRef>,
        param_count: usize,
        result_count: usize,
        async_: bool,
        callback: Option<SendSyncPtr<VMFuncRef>>,
        post_return: Option<SendSyncPtr<VMFuncRef>>,
    ) -> Result<()> {
        /// Return a closure which will call the specified function in the scope
        /// of the specified task.
        ///
        /// This will use `GuestTask::lower_params` to lower the parameters, but
        /// will not lift the result; instead, it returns a
        /// `[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]` from which the result, if
        /// any, may be lifted.  Note that an async-lifted export will have
        /// returned its result using the `task.return` intrinsic (or not
        /// returned a result at all, in the case of `task.cancel`), in which
        /// case the "result" of this call will either be a callback code or
        /// nothing.
        ///
        /// SAFETY: `callee` must be a valid `*mut VMFuncRef` at the time when
        /// the returned closure is called.
        unsafe fn make_call<T: 'static>(
            store: StoreContextMut<T>,
            guest_thread: QualifiedThreadId,
            callee: SendSyncPtr<VMFuncRef>,
            param_count: usize,
            result_count: usize,
        ) -> impl FnOnce(&mut dyn VMStore) -> Result<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>
        + Send
        + Sync
        + 'static
        + use<T> {
            let token = StoreToken::new(store);
            move |store: &mut dyn VMStore| {
                let mut storage = [MaybeUninit::uninit(); MAX_FLAT_PARAMS];

                store
                    .concurrent_state_mut()
                    .get_mut(guest_thread.thread)?
                    .state = GuestThreadState::Running;
                let task = store.concurrent_state_mut().get_mut(guest_thread.task)?;
                let lower = task.lower_params.take().unwrap();

                lower(store, &mut storage[..param_count])?;

                let mut store = token.as_context_mut(store);

                // SAFETY: Per the contract documented in `make_call's`
                // documentation, `callee` must be a valid pointer.
                unsafe {
                    crate::Func::call_unchecked_raw(
                        &mut store,
                        callee.as_non_null(),
                        NonNull::new(
                            &mut storage[..param_count.max(result_count)]
                                as *mut [MaybeUninit<ValRaw>] as _,
                        )
                        .unwrap(),
                    )?;
                }

                Ok(storage)
            }
        }

        // SAFETY: Per the contract described in this function documentation,
        // the `callee` pointer which `call` closes over must be valid when
        // called by the closure we queue below.
        let call = unsafe {
            make_call(
                store.as_context_mut(),
                guest_thread,
                callee,
                param_count,
                result_count,
            )
        };

        let callee_instance = store
            .0
            .concurrent_state_mut()
            .get_mut(guest_thread.task)?
            .instance;

        let fun = if callback.is_some() {
            assert!(async_);

            Box::new(move |store: &mut dyn VMStore| {
                self.add_guest_thread_to_instance_table(
                    guest_thread.thread,
                    store,
                    callee_instance.index,
                )?;
                let old_thread = store.set_thread(Some(guest_thread));
                log::trace!(
                    "stackless call: replaced {old_thread:?} with {guest_thread:?} as current thread"
                );

                store.maybe_push_call_context(guest_thread.task)?;

                store.enter_instance(callee_instance);

                // SAFETY: See the documentation for `make_call` to review the
                // contract we must uphold for `call` here.
                //
                // Per the contract described in the `queue_call`
                // documentation, the `callee` pointer which `call` closes
                // over must be valid.
                let storage = call(store)?;

                store.exit_instance(callee_instance)?;

                store.maybe_pop_call_context(guest_thread.task)?;

                store.set_thread(old_thread);
                let state = store.concurrent_state_mut();
                old_thread
                    .map(|t| state.get_mut(t.thread).unwrap().state = GuestThreadState::Running);
                log::trace!("stackless call: restored {old_thread:?} as current thread");

                // SAFETY: `wasmparser` will have validated that the callback
                // function returns a `i32` result.
                let code = unsafe { storage[0].assume_init() }.get_i32() as u32;

                self.handle_callback_code(store, guest_thread, callee_instance.index, code)
            })
                as Box<dyn FnOnce(&mut dyn VMStore) -> Result<Option<GuestCall>> + Send + Sync>
        } else {
            let token = StoreToken::new(store.as_context_mut());
            Box::new(move |store: &mut dyn VMStore| {
                self.add_guest_thread_to_instance_table(
                    guest_thread.thread,
                    store,
                    callee_instance.index,
                )?;
                let old_thread = store.set_thread(Some(guest_thread));
                log::trace!(
                    "sync/async-stackful call: replaced {old_thread:?} with {guest_thread:?} as current thread",
                );
                let flags = self.id().get(store).instance_flags(callee_instance.index);

                store.maybe_push_call_context(guest_thread.task)?;

                // Unless this is a callback-less (i.e. stackful)
                // async-lifted export, we need to record that the instance
                // cannot be entered until the call returns.
                if !async_ {
                    store.enter_instance(callee_instance);
                }

                // SAFETY: See the documentation for `make_call` to review the
                // contract we must uphold for `call` here.
                //
                // Per the contract described in the `queue_call`
                // documentation, the `callee` pointer which `call` closes
                // over must be valid.
                let storage = call(store)?;

                if async_ {
                    let task = store.concurrent_state_mut().get_mut(guest_thread.task)?;
                    if task.threads.len() == 1 && !task.returned_or_cancelled() {
                        bail!(Trap::NoAsyncResult);
                    }
                } else {
                    // This is a sync-lifted export, so now is when we lift the
                    // result, optionally call the post-return function, if any,
                    // and finally notify any current or future waiters that the
                    // subtask has returned.

                    let lift = {
                        store.exit_instance(callee_instance)?;

                        let state = store.concurrent_state_mut();
                        assert!(state.get_mut(guest_thread.task)?.result.is_none());

                        state
                            .get_mut(guest_thread.task)?
                            .lift_result
                            .take()
                            .unwrap()
                    };

                    // SAFETY: `result_count` represents the number of core Wasm
                    // results returned, per `wasmparser`.
                    let result = (lift.lift)(store, unsafe {
                        mem::transmute::<&[MaybeUninit<ValRaw>], &[ValRaw]>(
                            &storage[..result_count],
                        )
                    })?;

                    let post_return_arg = match result_count {
                        0 => ValRaw::i32(0),
                        // SAFETY: `result_count` represents the number of
                        // core Wasm results returned, per `wasmparser`.
                        1 => unsafe { storage[0].assume_init() },
                        _ => unreachable!(),
                    };

                    unsafe {
                        call_post_return(
                            token.as_context_mut(store),
                            post_return.map(|v| v.as_non_null()),
                            post_return_arg,
                            flags,
                        )?;
                    }

                    self.task_complete(store, guest_thread.task, result, Status::Returned)?;
                }

                // This is a callback-less call, so the implicit thread has now completed
                self.cleanup_thread(store, guest_thread, callee_instance.index)?;

                store.set_thread(old_thread);

                store.maybe_pop_call_context(guest_thread.task)?;

                let state = store.concurrent_state_mut();
                let task = state.get_mut(guest_thread.task)?;

                match &task.caller {
                    Caller::Host { .. } => {
                        if task.ready_to_delete() {
                            Waitable::Guest(guest_thread.task).delete_from(state)?;
                        }
                    }
                    Caller::Guest { .. } => {
                        task.exited = true;
                    }
                }

                Ok(None)
            })
        };

        store
            .0
            .concurrent_state_mut()
            .push_high_priority(WorkItem::GuestCall(GuestCall {
                thread: guest_thread,
                kind: GuestCallKind::StartImplicit(fun),
            }));

        Ok(())
    }

    /// Prepare (but do not start) a guest->guest call.
    ///
    /// This is called from fused adapter code generated in
    /// `wasmtime_environ::fact::trampoline::Compiler`.  `start` and `return_`
    /// are synthesized Wasm functions which move the parameters from the caller
    /// to the callee and the result from the callee to the caller,
    /// respectively.  The adapter will call `Self::start_call` immediately
    /// after calling this function.
    ///
    /// SAFETY: All the pointer arguments must be valid pointers to guest
    /// entities (and with the expected signatures for the function references
    /// -- see `wasmtime_environ::fact::trampoline::Compiler` for details).
    unsafe fn prepare_call<T: 'static>(
        self,
        mut store: StoreContextMut<T>,
        start: *mut VMFuncRef,
        return_: *mut VMFuncRef,
        caller_instance: RuntimeComponentInstanceIndex,
        callee_instance: RuntimeComponentInstanceIndex,
        task_return_type: TypeTupleIndex,
        callee_async: bool,
        memory: *mut VMMemoryDefinition,
        string_encoding: u8,
        caller_info: CallerInfo,
    ) -> Result<()> {
        if let (CallerInfo::Sync { .. }, true) = (&caller_info, callee_async) {
            // A task may only call an async-typed function via a sync lower if
            // it was created by a call to an async export.  Otherwise, we'll
            // trap.
            store.0.check_blocking()?;
        }

        enum ResultInfo {
            Heap { results: u32 },
            Stack { result_count: u32 },
        }

        let result_info = match &caller_info {
            CallerInfo::Async {
                has_result: true,
                params,
            } => ResultInfo::Heap {
                results: params.last().unwrap().get_u32(),
            },
            CallerInfo::Async {
                has_result: false, ..
            } => ResultInfo::Stack { result_count: 0 },
            CallerInfo::Sync {
                result_count,
                params,
            } if *result_count > u32::try_from(MAX_FLAT_RESULTS).unwrap() => ResultInfo::Heap {
                results: params.last().unwrap().get_u32(),
            },
            CallerInfo::Sync { result_count, .. } => ResultInfo::Stack {
                result_count: *result_count,
            },
        };

        let sync_caller = matches!(caller_info, CallerInfo::Sync { .. });

        // Create a new guest task for the call, closing over the `start` and
        // `return_` functions to lift the parameters and lower the result,
        // respectively.
        let start = SendSyncPtr::new(NonNull::new(start).unwrap());
        let return_ = SendSyncPtr::new(NonNull::new(return_).unwrap());
        let token = StoreToken::new(store.as_context_mut());
        let state = store.0.concurrent_state_mut();
        let old_thread = state.guest_thread.unwrap();

        assert_eq!(
            state.get_mut(old_thread.task)?.instance,
            RuntimeInstance {
                instance: self.id().instance(),
                index: caller_instance,
            }
        );

        let new_task = GuestTask::new(
            state,
            Box::new(move |store, dst| {
                let mut store = token.as_context_mut(store);
                assert!(dst.len() <= MAX_FLAT_PARAMS);
                // The `+ 1` here accounts for the return pointer, if any:
                let mut src = [MaybeUninit::uninit(); MAX_FLAT_PARAMS + 1];
                let count = match caller_info {
                    // Async callers, if they have a result, use the last
                    // parameter as a return pointer so chop that off if
                    // relevant here.
                    CallerInfo::Async { params, has_result } => {
                        let params = &params[..params.len() - usize::from(has_result)];
                        for (param, src) in params.iter().zip(&mut src) {
                            src.write(*param);
                        }
                        params.len()
                    }

                    // Sync callers forward everything directly.
                    CallerInfo::Sync { params, .. } => {
                        for (param, src) in params.iter().zip(&mut src) {
                            src.write(*param);
                        }
                        params.len()
                    }
                };
                // SAFETY: `start` is a valid `*mut VMFuncRef` from
                // `wasmtime-cranelift`-generated fused adapter code.  Based on
                // how it was constructed (see
                // `wasmtime_environ::fact::trampoline::Compiler::compile_async_start_adapter`
                // for details) we know it takes count parameters and returns
                // `dst.len()` results.
                unsafe {
                    crate::Func::call_unchecked_raw(
                        &mut store,
                        start.as_non_null(),
                        NonNull::new(
                            &mut src[..count.max(dst.len())] as *mut [MaybeUninit<ValRaw>] as _,
                        )
                        .unwrap(),
                    )?;
                }
                dst.copy_from_slice(&src[..dst.len()]);
                let state = store.0.concurrent_state_mut();
                Waitable::Guest(state.guest_thread.unwrap().task).set_event(
                    state,
                    Some(Event::Subtask {
                        status: Status::Started,
                    }),
                )?;
                Ok(())
            }),
            LiftResult {
                lift: Box::new(move |store, src| {
                    // SAFETY: See comment in closure passed as `lower_params`
                    // parameter above.
                    let mut store = token.as_context_mut(store);
                    let mut my_src = src.to_owned(); // TODO: use stack to avoid allocation?
                    if let ResultInfo::Heap { results } = &result_info {
                        my_src.push(ValRaw::u32(*results));
                    }
                    // SAFETY: `return_` is a valid `*mut VMFuncRef` from
                    // `wasmtime-cranelift`-generated fused adapter code.  Based
                    // on how it was constructed (see
                    // `wasmtime_environ::fact::trampoline::Compiler::compile_async_return_adapter`
                    // for details) we know it takes `src.len()` parameters and
                    // returns up to 1 result.
                    unsafe {
                        crate::Func::call_unchecked_raw(
                            &mut store,
                            return_.as_non_null(),
                            my_src.as_mut_slice().into(),
                        )?;
                    }
                    let state = store.0.concurrent_state_mut();
                    let thread = state.guest_thread.unwrap();
                    if sync_caller {
                        state.get_mut(thread.task)?.sync_result = SyncResult::Produced(
                            if let ResultInfo::Stack { result_count } = &result_info {
                                match result_count {
                                    0 => None,
                                    1 => Some(my_src[0]),
                                    _ => unreachable!(),
                                }
                            } else {
                                None
                            },
                        );
                    }
                    Ok(Box::new(DummyResult) as Box<dyn Any + Send + Sync>)
                }),
                ty: task_return_type,
                memory: NonNull::new(memory).map(SendSyncPtr::new),
                string_encoding: StringEncoding::from_u8(string_encoding).unwrap(),
            },
            Caller::Guest { thread: old_thread },
            None,
            RuntimeInstance {
                instance: self.id().instance(),
                index: callee_instance,
            },
            callee_async,
        )?;

        let guest_task = state.push(new_task)?;
        let new_thread = GuestThread::new_implicit(guest_task);
        let guest_thread = state.push(new_thread)?;
        state.get_mut(guest_task)?.threads.insert(guest_thread);

        store
            .0
            .concurrent_state_mut()
            .get_mut(old_thread.task)?
            .subtasks
            .insert(guest_task);

        // Make the new thread the current one so that `Self::start_call` knows
        // which one to start.
        store.0.set_thread(Some(QualifiedThreadId {
            task: guest_task,
            thread: guest_thread,
        }));
        log::trace!(
            "pushed {guest_task:?}:{guest_thread:?} as current thread; old thread was {old_thread:?}"
        );

        Ok(())
    }

    /// Call the specified callback function for an async-lifted export.
    ///
    /// SAFETY: `function` must be a valid reference to a guest function of the
    /// correct signature for a callback.
    unsafe fn call_callback<T>(
        self,
        mut store: StoreContextMut<T>,
        function: SendSyncPtr<VMFuncRef>,
        event: Event,
        handle: u32,
    ) -> Result<u32> {
        let (ordinal, result) = event.parts();
        let params = &mut [
            ValRaw::u32(ordinal),
            ValRaw::u32(handle),
            ValRaw::u32(result),
        ];
        // SAFETY: `func` is a valid `*mut VMFuncRef` from either
        // `wasmtime-cranelift`-generated fused adapter code or
        // `component::Options`.  Per `wasmparser` callback signature
        // validation, we know it takes three parameters and returns one.
        unsafe {
            crate::Func::call_unchecked_raw(
                &mut store,
                function.as_non_null(),
                params.as_mut_slice().into(),
            )?;
        }
        Ok(params[0].get_u32())
    }

    /// Start a guest->guest call previously prepared using
    /// `Self::prepare_call`.
    ///
    /// This is called from fused adapter code generated in
    /// `wasmtime_environ::fact::trampoline::Compiler`.  The adapter will call
    /// this function immediately after calling `Self::prepare_call`.
    ///
    /// SAFETY: The `*mut VMFuncRef` arguments must be valid pointers to guest
    /// functions with the appropriate signatures for the current guest task.
    /// If this is a call to an async-lowered import, the actual call may be
    /// deferred and run after this function returns, in which case the pointer
    /// arguments must also be valid when the call happens.
    unsafe fn start_call<T: 'static>(
        self,
        mut store: StoreContextMut<T>,
        callback: *mut VMFuncRef,
        post_return: *mut VMFuncRef,
        callee: *mut VMFuncRef,
        param_count: u32,
        result_count: u32,
        flags: u32,
        storage: Option<&mut [MaybeUninit<ValRaw>]>,
    ) -> Result<u32> {
        let token = StoreToken::new(store.as_context_mut());
        let async_caller = storage.is_none();
        let state = store.0.concurrent_state_mut();
        let guest_thread = state.guest_thread.unwrap();
        let callee_async = state.get_mut(guest_thread.task)?.async_function;
        let callee = SendSyncPtr::new(NonNull::new(callee).unwrap());
        let param_count = usize::try_from(param_count).unwrap();
        assert!(param_count <= MAX_FLAT_PARAMS);
        let result_count = usize::try_from(result_count).unwrap();
        assert!(result_count <= MAX_FLAT_RESULTS);

        let task = state.get_mut(guest_thread.task)?;
        if !callback.is_null() {
            // We're calling an async-lifted export with a callback, so store
            // the callback and related context as part of the task so we can
            // call it later when needed.
            let callback = SendSyncPtr::new(NonNull::new(callback).unwrap());
            task.callback = Some(Box::new(move |store, event, handle| {
                let store = token.as_context_mut(store);
                unsafe { self.call_callback::<T>(store, callback, event, handle) }
            }));
        }

        let Caller::Guest { thread: caller } = &task.caller else {
            // As of this writing, `start_call` is only used for guest->guest
            // calls.
            unreachable!()
        };
        let caller = *caller;
        let caller_instance = state.get_mut(caller.task)?.instance;

        // Queue the call as a "high priority" work item.
        unsafe {
            self.queue_call(
                store.as_context_mut(),
                guest_thread,
                callee,
                param_count,
                result_count,
                (flags & START_FLAG_ASYNC_CALLEE) != 0,
                NonNull::new(callback).map(SendSyncPtr::new),
                NonNull::new(post_return).map(SendSyncPtr::new),
            )?;
        }

        let state = store.0.concurrent_state_mut();

        // Use the caller's `GuestTask::sync_call_set` to register interest in
        // the subtask...
        let guest_waitable = Waitable::Guest(guest_thread.task);
        let old_set = guest_waitable.common(state)?.set;
        let set = state.get_mut(caller.task)?.sync_call_set;
        guest_waitable.join(state, Some(set))?;

        // ... and suspend this fiber temporarily while we wait for it to start.
        //
        // Note that we _could_ call the callee directly using the current fiber
        // rather than suspend this one, but that would make reasoning about the
        // event loop more complicated and is probably only worth doing if
        // there's a measurable performance benefit.  In addition, it would mean
        // blocking the caller if the callee calls a blocking sync-lowered
        // import, and as of this writing the spec says we must not do that.
        //
        // Alternatively, the fused adapter code could be modified to call the
        // callee directly without calling a host-provided intrinsic at all (in
        // which case it would need to do its own, inline backpressure checks,
        // etc.).  Again, we'd want to see a measurable performance benefit
        // before committing to such an optimization.  And again, we'd need to
        // update the spec to allow that.
        let (status, waitable) = loop {
            store.0.suspend(SuspendReason::Waiting {
                set,
                thread: caller,
                // Normally, `StoreOpaque::suspend` would assert it's being
                // called from a context where blocking is allowed.  However, if
                // `async_caller` is `true`, we'll only "block" long enough for
                // the callee to start, i.e. we won't repeat this loop, so we
                // tell `suspend` it's okay even if we're not allowed to block.
                // Alternatively, if the callee is not an async function, then
                // we know it won't block anyway.
                skip_may_block_check: async_caller || !callee_async,
            })?;

            let state = store.0.concurrent_state_mut();

            log::trace!("taking event for {:?}", guest_thread.task);
            let event = guest_waitable.take_event(state)?;
            let Some(Event::Subtask { status }) = event else {
                unreachable!();
            };

            log::trace!("status {status:?} for {:?}", guest_thread.task);

            if status == Status::Returned {
                // It returned, so we can stop waiting.
                break (status, None);
            } else if async_caller {
                // It hasn't returned yet, but the caller is calling via an
                // async-lowered import, so we generate a handle for the task
                // waitable and return the status.
                let handle = store
                    .0
                    .instance_state(caller_instance)
                    .handle_table()
                    .subtask_insert_guest(guest_thread.task.rep())?;
                store
                    .0
                    .concurrent_state_mut()
                    .get_mut(guest_thread.task)?
                    .common
                    .handle = Some(handle);
                break (status, Some(handle));
            } else {
                // The callee hasn't returned yet, and the caller is calling via
                // a sync-lowered import, so we loop and keep waiting until the
                // callee returns.
            }
        };

        guest_waitable.join(store.0.concurrent_state_mut(), old_set)?;

        // Reset the current thread to point to the caller as it resumes control.
        store.0.set_thread(Some(caller));
        store.0.concurrent_state_mut().get_mut(caller.thread)?.state = GuestThreadState::Running;
        log::trace!("popped current thread {guest_thread:?}; new thread is {caller:?}");

        if let Some(storage) = storage {
            // The caller used a sync-lowered import to call an async-lifted
            // export, in which case the result, if any, has been stashed in
            // `GuestTask::sync_result`.
            let state = store.0.concurrent_state_mut();
            let task = state.get_mut(guest_thread.task)?;
            if let Some(result) = task.sync_result.take() {
                if let Some(result) = result {
                    storage[0] = MaybeUninit::new(result);
                }

                if task.exited && task.ready_to_delete() {
                    Waitable::Guest(guest_thread.task).delete_from(state)?;
                }
            }
        }

        Ok(status.pack(waitable))
    }

    /// Poll the specified future once on behalf of a guest->host call using an
    /// async-lowered import.
    ///
    /// If it returns `Ready`, return `Ok(None)`.  Otherwise, if it returns
    /// `Pending`, add it to the set of futures to be polled as part of this
    /// instance's event loop until it completes, and then return
    /// `Ok(Some(handle))` where `handle` is the waitable handle to return.
    ///
    /// Whether the future returns `Ready` immediately or later, the `lower`
    /// function will be used to lower the result, if any, into the guest caller's
    /// stack and linear memory unless the task has been cancelled.
    pub(crate) fn first_poll<T: 'static, R: Send + 'static>(
        self,
        mut store: StoreContextMut<'_, T>,
        future: impl Future<Output = Result<R>> + Send + 'static,
        caller_instance: RuntimeComponentInstanceIndex,
        lower: impl FnOnce(StoreContextMut<T>, R) -> Result<()> + Send + 'static,
    ) -> Result<Option<u32>> {
        let token = StoreToken::new(store.as_context_mut());
        let state = store.0.concurrent_state_mut();
        let caller = state.guest_thread.unwrap();

        // Create an abortable future which hooks calls to poll and manages call
        // context state for the future.
        let (join_handle, future) = JoinHandle::run(async move {
            let mut future = pin!(future);
            let mut call_context = None;
            future::poll_fn(move |cx| {
                // Push the call context for managing any resource borrows
                // for the task.
                tls::get(|store| {
                    if let Some(call_context) = call_context.take() {
                        token
                            .as_context_mut(store)
                            .0
                            .component_resource_state()
                            .0
                            .push(call_context);
                    }
                });

                let result = future.as_mut().poll(cx);

                if result.is_pending() {
                    // Pop the call context for managing any resource
                    // borrows for the task.
                    tls::get(|store| {
                        call_context = Some(
                            token
                                .as_context_mut(store)
                                .0
                                .component_resource_state()
                                .0
                                .pop()
                                .unwrap(),
                        );
                    });
                }
                result
            })
            .await
        });

        // We create a new host task even though it might complete immediately
        // (in which case we won't need to pass a waitable back to the guest).
        // If it does complete immediately, we'll remove it before we return.
        let task = state.push(HostTask::new(
            RuntimeInstance {
                instance: self.id().instance(),
                index: caller_instance,
            },
            Some(join_handle),
        ))?;

        log::trace!("new host task child of {caller:?}: {task:?}");

        let mut future = Box::pin(future);

        // Finally, poll the future.  We can use a dummy `Waker` here because
        // we'll add the future to `ConcurrentState::futures` and poll it
        // automatically from the event loop if it doesn't complete immediately
        // here.
        let poll = tls::set(store.0, || {
            future
                .as_mut()
                .poll(&mut Context::from_waker(&Waker::noop()))
        });

        Ok(match poll {
            Poll::Ready(None) => unreachable!(),
            Poll::Ready(Some(result)) => {
                // It finished immediately; lower the result and delete the
                // task.
                lower(store.as_context_mut(), result?)?;
                log::trace!("delete host task {task:?} (already ready)");
                store.0.concurrent_state_mut().delete(task)?;
                None
            }
            Poll::Pending => {
                // It hasn't finished yet; add the future to
                // `ConcurrentState::futures` so it will be polled by the event
                // loop and allocate a waitable handle to return to the guest.

                // Wrap the future in a closure responsible for lowering the result into
                // the guest's stack and memory, as well as notifying any waiters that
                // the task returned.
                let future =
                    Box::pin(async move {
                        let result = match future.await {
                            Some(result) => result?,
                            // Task was cancelled; nothing left to do.
                            None => return Ok(()),
                        };
                        tls::get(move |store| {
                            // Here we schedule a task to run on a worker fiber to do
                            // the lowering since it may involve a call to the guest's
                            // realloc function.  This is necessary because calling the
                            // guest while there are host embedder frames on the stack
                            // is unsound.
                            store.concurrent_state_mut().push_high_priority(
                                WorkItem::WorkerFunction(AlwaysMut::new(Box::new(move |store| {
                                    lower(token.as_context_mut(store), result)?;
                                    let state = store.concurrent_state_mut();
                                    state.get_mut(task)?.join_handle.take();
                                    Waitable::Host(task).set_event(
                                        state,
                                        Some(Event::Subtask {
                                            status: Status::Returned,
                                        }),
                                    )
                                }))),
                            );
                            Ok(())
                        })
                    });

                store.0.concurrent_state_mut().push_future(future);
                let handle = store
                    .0
                    .instance_state(RuntimeInstance {
                        instance: self.id().instance(),
                        index: caller_instance,
                    })
                    .handle_table()
                    .subtask_insert_host(task.rep())?;
                store.0.concurrent_state_mut().get_mut(task)?.common.handle = Some(handle);
                log::trace!(
                    "assign {task:?} handle {handle} for {caller:?} instance {caller_instance:?}"
                );
                Some(handle)
            }
        })
    }

    /// Implements the `task.return` intrinsic, lifting the result for the
    /// current guest task.
    pub(crate) fn task_return(
        self,
        store: &mut dyn VMStore,
        ty: TypeTupleIndex,
        options: OptionsIndex,
        storage: &[ValRaw],
    ) -> Result<()> {
        let state = store.concurrent_state_mut();
        let guest_thread = state.guest_thread.unwrap();
        let lift = state
            .get_mut(guest_thread.task)?
            .lift_result
            .take()
            .ok_or_else(|| {
                format_err!("`task.return` or `task.cancel` called more than once for current task")
            })?;
        assert!(state.get_mut(guest_thread.task)?.result.is_none());

        let CanonicalOptions {
            string_encoding,
            data_model,
            ..
        } = &self.id().get(store).component().env_component().options[options];

        let invalid = ty != lift.ty
            || string_encoding != &lift.string_encoding
            || match data_model {
                CanonicalOptionsDataModel::LinearMemory(opts) => match opts.memory {
                    Some(memory) => {
                        let expected = lift.memory.map(|v| v.as_ptr()).unwrap_or(ptr::null_mut());
                        let actual = self.id().get(store).runtime_memory(memory);
                        expected != actual.as_ptr()
                    }
                    // Memory not specified, meaning it didn't need to be
                    // specified per validation, so not invalid.
                    None => false,
                },
                // Always invalid as this isn't supported.
                CanonicalOptionsDataModel::Gc { .. } => true,
            };

        if invalid {
            bail!("invalid `task.return` signature and/or options for current task");
        }

        log::trace!("task.return for {guest_thread:?}");

        let result = (lift.lift)(store, storage)?;
        self.task_complete(store, guest_thread.task, result, Status::Returned)
    }

    /// Implements the `task.cancel` intrinsic.
    pub(crate) fn task_cancel(self, store: &mut StoreOpaque) -> Result<()> {
        let state = store.concurrent_state_mut();
        let guest_thread = state.guest_thread.unwrap();
        let task = state.get_mut(guest_thread.task)?;
        if !task.cancel_sent {
            bail!("`task.cancel` called by task which has not been cancelled")
        }
        _ = task.lift_result.take().ok_or_else(|| {
            format_err!("`task.return` or `task.cancel` called more than once for current task")
        })?;

        assert!(task.result.is_none());

        log::trace!("task.cancel for {guest_thread:?}");

        self.task_complete(
            store,
            guest_thread.task,
            Box::new(DummyResult),
            Status::ReturnCancelled,
        )
    }

    /// Complete the specified guest task (i.e. indicate that it has either
    /// returned a (possibly empty) result or cancelled itself).
    ///
    /// This will return any resource borrows and notify any current or future
    /// waiters that the task has completed.
    fn task_complete(
        self,
        store: &mut StoreOpaque,
        guest_task: TableId<GuestTask>,
        result: Box<dyn Any + Send + Sync>,
        status: Status,
    ) -> Result<()> {
        let (calls, host_table, _, instance) = store.component_resource_state_with_instance(self);
        ResourceTables {
            calls,
            host_table: Some(host_table),
            guest: Some(instance.instance_states()),
        }
        .exit_call()?;

        let state = store.concurrent_state_mut();
        let task = state.get_mut(guest_task)?;

        if let Caller::Host { tx, .. } = &mut task.caller {
            if let Some(tx) = tx.take() {
                _ = tx.send(result);
            }
        } else {
            task.result = Some(result);
            Waitable::Guest(guest_task).set_event(state, Some(Event::Subtask { status }))?;
        }

        Ok(())
    }

    /// Implements the `waitable-set.new` intrinsic.
    pub(crate) fn waitable_set_new(
        self,
        store: &mut StoreOpaque,
        caller_instance: RuntimeComponentInstanceIndex,
    ) -> Result<u32> {
        let set = store.concurrent_state_mut().push(WaitableSet::default())?;
        let handle = store
            .instance_state(RuntimeInstance {
                instance: self.id().instance(),
                index: caller_instance,
            })
            .handle_table()
            .waitable_set_insert(set.rep())?;
        log::trace!("new waitable set {set:?} (handle {handle})");
        Ok(handle)
    }

    /// Implements the `waitable-set.drop` intrinsic.
    pub(crate) fn waitable_set_drop(
        self,
        store: &mut StoreOpaque,
        caller_instance: RuntimeComponentInstanceIndex,
        set: u32,
    ) -> Result<()> {
        let rep = store
            .instance_state(RuntimeInstance {
                instance: self.id().instance(),
                index: caller_instance,
            })
            .handle_table()
            .waitable_set_remove(set)?;

        log::trace!("drop waitable set {rep} (handle {set})");

        let set = store
            .concurrent_state_mut()
            .delete(TableId::<WaitableSet>::new(rep))?;

        if !set.waiting.is_empty() {
            bail!("cannot drop waitable set with waiters");
        }

        Ok(())
    }

    /// Implements the `waitable.join` intrinsic.
    pub(crate) fn waitable_join(
        self,
        store: &mut StoreOpaque,
        caller_instance: RuntimeComponentInstanceIndex,
        waitable_handle: u32,
        set_handle: u32,
    ) -> Result<()> {
        let mut instance = self.id().get_mut(store);
        let waitable =
            Waitable::from_instance(instance.as_mut(), caller_instance, waitable_handle)?;

        let set = if set_handle == 0 {
            None
        } else {
            let set = instance.instance_states().0[caller_instance]
                .handle_table()
                .waitable_set_rep(set_handle)?;

            Some(TableId::<WaitableSet>::new(set))
        };

        log::trace!(
            "waitable {waitable:?} (handle {waitable_handle}) join set {set:?} (handle {set_handle})",
        );

        waitable.join(store.concurrent_state_mut(), set)
    }

    /// Implements the `subtask.drop` intrinsic.
    pub(crate) fn subtask_drop(
        self,
        store: &mut StoreOpaque,
        caller_instance: RuntimeComponentInstanceIndex,
        task_id: u32,
    ) -> Result<()> {
        self.waitable_join(store, caller_instance, task_id, 0)?;

        let (rep, is_host) = store
            .instance_state(RuntimeInstance {
                instance: self.id().instance(),
                index: caller_instance,
            })
            .handle_table()
            .subtask_remove(task_id)?;

        let concurrent_state = store.concurrent_state_mut();
        let (waitable, expected_caller_instance, delete) = if is_host {
            let id = TableId::<HostTask>::new(rep);
            let task = concurrent_state.get_mut(id)?;
            if task.join_handle.is_some() {
                bail!("cannot drop a subtask which has not yet resolved");
            }
            (Waitable::Host(id), task.caller_instance, true)
        } else {
            let id = TableId::<GuestTask>::new(rep);
            let task = concurrent_state.get_mut(id)?;
            if task.lift_result.is_some() {
                bail!("cannot drop a subtask which has not yet resolved");
            }
            if let &Caller::Guest { thread } = &task.caller {
                (
                    Waitable::Guest(id),
                    concurrent_state.get_mut(thread.task)?.instance,
                    concurrent_state.get_mut(id)?.exited,
                )
            } else {
                unreachable!()
            }
        };

        waitable.common(concurrent_state)?.handle = None;

        if waitable.take_event(concurrent_state)?.is_some() {
            bail!("cannot drop a subtask with an undelivered event");
        }

        if delete {
            waitable.delete_from(concurrent_state)?;
        }

        // Since waitables can neither be passed between instances nor forged,
        // this should never fail unless there's a bug in Wasmtime, but we check
        // here to be sure:
        assert_eq!(
            expected_caller_instance,
            RuntimeInstance {
                instance: self.id().instance(),
                index: caller_instance
            }
        );
        log::trace!("subtask_drop {waitable:?} (handle {task_id})");
        Ok(())
    }

    /// Implements the `waitable-set.wait` intrinsic.
    pub(crate) fn waitable_set_wait(
        self,
        store: &mut StoreOpaque,
        options: OptionsIndex,
        set: u32,
        payload: u32,
    ) -> Result<u32> {
        if !self.options(store, options).async_ {
            // The caller may only call `waitable-set.wait` from an async task
            // (i.e. a task created via a call to an async export).
            // Otherwise, we'll trap.
            store.check_blocking()?;
        }

        let &CanonicalOptions {
            cancellable,
            instance: caller_instance,
            ..
        } = &self.id().get(store).component().env_component().options[options];
        let rep = store
            .instance_state(RuntimeInstance {
                instance: self.id().instance(),
                index: caller_instance,
            })
            .handle_table()
            .waitable_set_rep(set)?;

        self.waitable_check(
            store,
            cancellable,
            WaitableCheck::Wait,
            WaitableCheckParams {
                set: TableId::new(rep),
                options,
                payload,
            },
        )
    }

    /// Implements the `waitable-set.poll` intrinsic.
    pub(crate) fn waitable_set_poll(
        self,
        store: &mut StoreOpaque,
        options: OptionsIndex,
        set: u32,
        payload: u32,
    ) -> Result<u32> {
        let &CanonicalOptions {
            cancellable,
            instance: caller_instance,
            ..
        } = &self.id().get(store).component().env_component().options[options];
        let rep = store
            .instance_state(RuntimeInstance {
                instance: self.id().instance(),
                index: caller_instance,
            })
            .handle_table()
            .waitable_set_rep(set)?;

        self.waitable_check(
            store,
            cancellable,
            WaitableCheck::Poll,
            WaitableCheckParams {
                set: TableId::new(rep),
                options,
                payload,
            },
        )
    }

    /// Implements the `thread.index` intrinsic.
    pub(crate) fn thread_index(&self, store: &mut dyn VMStore) -> Result<u32> {
        let thread_id = store.concurrent_state_mut().guest_thread.unwrap().thread;
        // The unwrap is safe because `instance_rep` must be `Some` by this point
        Ok(store
            .concurrent_state_mut()
            .get_mut(thread_id)?
            .instance_rep
            .unwrap())
    }

    /// Implements the `thread.new-indirect` intrinsic.
    pub(crate) fn thread_new_indirect<T: 'static>(
        self,
        mut store: StoreContextMut<T>,
        runtime_instance: RuntimeComponentInstanceIndex,
        _func_ty_idx: TypeFuncIndex, // currently unused
        start_func_table_idx: RuntimeTableIndex,
        start_func_idx: u32,
        context: i32,
    ) -> Result<u32> {
        log::trace!("creating new thread");

        let start_func_ty = FuncType::new(store.engine(), [ValType::I32], []);
        let (instance, registry) = self.id().get_mut_and_registry(store.0);
        let callee = instance
            .index_runtime_func_table(registry, start_func_table_idx, start_func_idx as u64)?
            .ok_or_else(|| {
                format_err!("the start function index points to an uninitialized function")
            })?;
        if callee.type_index(store.0) != start_func_ty.type_index() {
            bail!(
                "start function does not match expected type (currently only `(i32) -> ()` is supported)"
            );
        }

        let token = StoreToken::new(store.as_context_mut());
        let start_func = Box::new(
            move |store: &mut dyn VMStore, guest_thread: QualifiedThreadId| -> Result<()> {
                let old_thread = store.set_thread(Some(guest_thread));
                log::trace!(
                    "thread start: replaced {old_thread:?} with {guest_thread:?} as current thread"
                );

                store.maybe_push_call_context(guest_thread.task)?;

                let mut store = token.as_context_mut(store);
                let mut params = [ValRaw::i32(context)];
                // Use call_unchecked rather than call or call_async, as we don't want to run the function
                // on a separate fiber if we're running in an async store.
                unsafe { callee.call_unchecked(store.as_context_mut(), &mut params)? };

                store.0.maybe_pop_call_context(guest_thread.task)?;

                self.cleanup_thread(store.0, guest_thread, runtime_instance)?;
                log::trace!("explicit thread {guest_thread:?} completed");
                let state = store.0.concurrent_state_mut();
                let task = state.get_mut(guest_thread.task)?;
                if task.threads.is_empty() && !task.returned_or_cancelled() {
                    bail!(Trap::NoAsyncResult);
                }
                store.0.set_thread(old_thread);
                let state = store.0.concurrent_state_mut();
                old_thread
                    .map(|t| state.get_mut(t.thread).unwrap().state = GuestThreadState::Running);
                if state.get_mut(guest_thread.task)?.ready_to_delete() {
                    Waitable::Guest(guest_thread.task).delete_from(state)?;
                }
                log::trace!("thread start: restored {old_thread:?} as current thread");

                Ok(())
            },
        );

        let state = store.0.concurrent_state_mut();
        let current_thread = state.guest_thread.unwrap();
        let parent_task = current_thread.task;

        let new_thread = GuestThread::new_explicit(parent_task, start_func);
        let thread_id = state.push(new_thread)?;
        state.get_mut(parent_task)?.threads.insert(thread_id);

        log::trace!("new thread with id {thread_id:?} created");

        self.add_guest_thread_to_instance_table(thread_id, store.0, runtime_instance)
    }

    pub(crate) fn resume_suspended_thread(
        self,
        store: &mut StoreOpaque,
        runtime_instance: RuntimeComponentInstanceIndex,
        thread_idx: u32,
        high_priority: bool,
    ) -> Result<()> {
        let thread_id =
            GuestThread::from_instance(self.id().get_mut(store), runtime_instance, thread_idx)?;
        let state = store.concurrent_state_mut();
        let guest_thread = QualifiedThreadId::qualify(state, thread_id)?;
        let thread = state.get_mut(guest_thread.thread)?;

        match mem::replace(&mut thread.state, GuestThreadState::Running) {
            GuestThreadState::NotStartedExplicit(start_func) => {
                log::trace!("starting thread {guest_thread:?}");
                let guest_call = WorkItem::GuestCall(GuestCall {
                    thread: guest_thread,
                    kind: GuestCallKind::StartExplicit(Box::new(move |store| {
                        start_func(store, guest_thread)
                    })),
                });
                store
                    .concurrent_state_mut()
                    .push_work_item(guest_call, high_priority);
            }
            GuestThreadState::Suspended(fiber) => {
                log::trace!("resuming thread {thread_id:?} that was suspended");
                store
                    .concurrent_state_mut()
                    .push_work_item(WorkItem::ResumeFiber(fiber), high_priority);
            }
            _ => {
                bail!("cannot resume thread which is not suspended");
            }
        }
        Ok(())
    }

    fn add_guest_thread_to_instance_table(
        self,
        thread_id: TableId<GuestThread>,
        store: &mut StoreOpaque,
        runtime_instance: RuntimeComponentInstanceIndex,
    ) -> Result<u32> {
        let guest_id = store
            .instance_state(RuntimeInstance {
                instance: self.id().instance(),
                index: runtime_instance,
            })
            .thread_handle_table()
            .guest_thread_insert(thread_id.rep())?;
        store
            .concurrent_state_mut()
            .get_mut(thread_id)?
            .instance_rep = Some(guest_id);
        Ok(guest_id)
    }

    /// Helper function for the `thread.yield`, `thread.yield-to`, `thread.suspend`,
    /// and `thread.switch-to` intrinsics.
    pub(crate) fn suspension_intrinsic(
        self,
        store: &mut StoreOpaque,
        caller: RuntimeComponentInstanceIndex,
        cancellable: bool,
        yielding: bool,
        to_thread: Option<u32>,
    ) -> Result<WaitResult> {
        if to_thread.is_none() {
            let state = store.concurrent_state_mut();
            if yielding {
                // This is a `thread.yield` call
                if !state.may_block(state.guest_thread.unwrap().task) {
                    // The spec defines `thread.yield` to be a no-op in a
                    // non-blocking context, so we return immediately without giving
                    // any other thread a chance to run.
                    return Ok(WaitResult::Completed);
                }
            } else {
                // The caller may only call `thread.suspend` from an async task
                // (i.e. a task created via a call to an async export).
                // Otherwise, we'll trap.
                store.check_blocking()?;
            }
        }

        // There could be a pending cancellation from a previous uncancellable wait
        if cancellable && store.concurrent_state_mut().take_pending_cancellation() {
            return Ok(WaitResult::Cancelled);
        }

        if let Some(thread) = to_thread {
            self.resume_suspended_thread(store, caller, thread, true)?;
        }

        let state = store.concurrent_state_mut();
        let guest_thread = state.guest_thread.unwrap();
        let reason = if yielding {
            SuspendReason::Yielding {
                thread: guest_thread,
                // Tell `StoreOpaque::suspend` it's okay to suspend here since
                // we're handling a `thread.yield-to` call; otherwise it would
                // panic if we called it in a non-blocking context.
                skip_may_block_check: to_thread.is_some(),
            }
        } else {
            SuspendReason::ExplicitlySuspending {
                thread: guest_thread,
                // Tell `StoreOpaque::suspend` it's okay to suspend here since
                // we're handling a `thread.switch-to` call; otherwise it would
                // panic if we called it in a non-blocking context.
                skip_may_block_check: to_thread.is_some(),
            }
        };

        store.suspend(reason)?;

        if cancellable && store.concurrent_state_mut().take_pending_cancellation() {
            Ok(WaitResult::Cancelled)
        } else {
            Ok(WaitResult::Completed)
        }
    }

    /// Helper function for the `waitable-set.wait` and `waitable-set.poll` intrinsics.
    fn waitable_check(
        self,
        store: &mut StoreOpaque,
        cancellable: bool,
        check: WaitableCheck,
        params: WaitableCheckParams,
    ) -> Result<u32> {
        let guest_thread = store.concurrent_state_mut().guest_thread.unwrap();

        log::trace!("waitable check for {guest_thread:?}; set {:?}", params.set);

        let state = store.concurrent_state_mut();
        let task = state.get_mut(guest_thread.task)?;

        // If we're waiting, and there are no events immediately available,
        // suspend the fiber until that changes.
        match &check {
            WaitableCheck::Wait => {
                let set = params.set;

                if (task.event.is_none()
                    || (matches!(task.event, Some(Event::Cancelled)) && !cancellable))
                    && state.get_mut(set)?.ready.is_empty()
                {
                    if cancellable {
                        let old = state
                            .get_mut(guest_thread.thread)?
                            .wake_on_cancel
                            .replace(set);
                        assert!(old.is_none());
                    }

                    store.suspend(SuspendReason::Waiting {
                        set,
                        thread: guest_thread,
                        skip_may_block_check: false,
                    })?;
                }
            }
            WaitableCheck::Poll => {}
        }

        log::trace!(
            "waitable check for {guest_thread:?}; set {:?}, part two",
            params.set
        );

        // Deliver any pending events to the guest and return.
        let event = self.get_event(store, guest_thread.task, Some(params.set), cancellable)?;

        let (ordinal, handle, result) = match &check {
            WaitableCheck::Wait => {
                let (event, waitable) = event.unwrap();
                let handle = waitable.map(|(_, v)| v).unwrap_or(0);
                let (ordinal, result) = event.parts();
                (ordinal, handle, result)
            }
            WaitableCheck::Poll => {
                if let Some((event, waitable)) = event {
                    let handle = waitable.map(|(_, v)| v).unwrap_or(0);
                    let (ordinal, result) = event.parts();
                    (ordinal, handle, result)
                } else {
                    log::trace!(
                        "no events ready to deliver via waitable-set.poll to {:?}; set {:?}",
                        guest_thread.task,
                        params.set
                    );
                    let (ordinal, result) = Event::None.parts();
                    (ordinal, 0, result)
                }
            }
        };
        let memory = self.options_memory_mut(store, params.options);
        let ptr = func::validate_inbounds_dynamic(
            &CanonicalAbiInfo::POINTER_PAIR,
            memory,
            &ValRaw::u32(params.payload),
        )?;
        memory[ptr + 0..][..4].copy_from_slice(&handle.to_le_bytes());
        memory[ptr + 4..][..4].copy_from_slice(&result.to_le_bytes());
        Ok(ordinal)
    }

    /// Implements the `subtask.cancel` intrinsic.
    pub(crate) fn subtask_cancel(
        self,
        store: &mut StoreOpaque,
        caller_instance: RuntimeComponentInstanceIndex,
        async_: bool,
        task_id: u32,
    ) -> Result<u32> {
        if !async_ {
            // The caller may only sync call `subtask.cancel` from an async task
            // (i.e. a task created via a call to an async export).  Otherwise,
            // we'll trap.
            store.check_blocking()?;
        }

        let (rep, is_host) = store
            .instance_state(RuntimeInstance {
                instance: self.id().instance(),
                index: caller_instance,
            })
            .handle_table()
            .subtask_rep(task_id)?;
        let (waitable, expected_caller_instance) = if is_host {
            let id = TableId::<HostTask>::new(rep);
            (
                Waitable::Host(id),
                store.concurrent_state_mut().get_mut(id)?.caller_instance,
            )
        } else {
            let id = TableId::<GuestTask>::new(rep);
            if let &Caller::Guest { thread } = &store.concurrent_state_mut().get_mut(id)?.caller {
                (
                    Waitable::Guest(id),
                    store.concurrent_state_mut().get_mut(thread.task)?.instance,
                )
            } else {
                unreachable!()
            }
        };
        // Since waitables can neither be passed between instances nor forged,
        // this should never fail unless there's a bug in Wasmtime, but we check
        // here to be sure:
        assert_eq!(
            expected_caller_instance,
            RuntimeInstance {
                instance: self.id().instance(),
                index: caller_instance
            }
        );

        log::trace!("subtask_cancel {waitable:?} (handle {task_id})");

        let concurrent_state = store.concurrent_state_mut();
        if let Waitable::Host(host_task) = waitable {
            if let Some(handle) = concurrent_state.get_mut(host_task)?.join_handle.take() {
                handle.abort();
                return Ok(Status::ReturnCancelled as u32);
            }
        } else {
            let caller = concurrent_state.guest_thread.unwrap();
            let guest_task = TableId::<GuestTask>::new(rep);
            let task = concurrent_state.get_mut(guest_task)?;
            if !task.already_lowered_parameters() {
                // The task is in a `starting` state, meaning it hasn't run at
                // all yet.  Here we update its fields to indicate that it is
                // ready to delete immediately once `subtask.drop` is called.
                task.lower_params = None;
                task.lift_result = None;
                task.exited = true;

                let instance = task.instance;

                assert_eq!(1, task.threads.len());
                let thread = mem::take(&mut task.threads).into_iter().next().unwrap();
                let concurrent_state = store.concurrent_state_mut();
                concurrent_state.delete(thread)?;
                assert!(concurrent_state.get_mut(guest_task)?.ready_to_delete());

                // Not yet started; cancel and remove from pending
                let pending = &mut store.instance_state(instance).concurrent_state().pending;
                let pending_count = pending.len();
                pending.retain(|thread, _| thread.task != guest_task);
                // If there were no pending threads for this task, we're in an error state
                if pending.len() == pending_count {
                    bail!("`subtask.cancel` called after terminal status delivered");
                }
                return Ok(Status::StartCancelled as u32);
            } else if !task.returned_or_cancelled() {
                // Started, but not yet returned or cancelled; send the
                // `CANCELLED` event
                task.cancel_sent = true;
                // Note that this might overwrite an event that was set earlier
                // (e.g. `Event::None` if the task is yielding, or
                // `Event::Cancelled` if it was already cancelled), but that's
                // okay -- this should supersede the previous state.
                task.event = Some(Event::Cancelled);
                for thread in task.threads.clone() {
                    let thread = QualifiedThreadId {
                        task: guest_task,
                        thread,
                    };
                    if let Some(set) = concurrent_state
                        .get_mut(thread.thread)
                        .unwrap()
                        .wake_on_cancel
                        .take()
                    {
                        let item = match concurrent_state
                            .get_mut(set)?
                            .waiting
                            .remove(&thread)
                            .unwrap()
                        {
                            WaitMode::Fiber(fiber) => WorkItem::ResumeFiber(fiber),
                            WaitMode::Callback(instance) => WorkItem::GuestCall(GuestCall {
                                thread,
                                kind: GuestCallKind::DeliverEvent {
                                    instance,
                                    set: None,
                                },
                            }),
                        };
                        concurrent_state.push_high_priority(item);

                        store.suspend(SuspendReason::Yielding {
                            thread: caller,
                            // `subtask.cancel` is not allowed to be called in a
                            // sync context, so we cannot skip the may-block check.
                            skip_may_block_check: false,
                        })?;
                        break;
                    }
                }

                let concurrent_state = store.concurrent_state_mut();
                let task = concurrent_state.get_mut(guest_task)?;
                if !task.returned_or_cancelled() {
                    if async_ {
                        return Ok(BLOCKED);
                    } else {
                        store.wait_for_event(Waitable::Guest(guest_task))?;
                    }
                }
            }
        }

        let event = waitable.take_event(store.concurrent_state_mut())?;
        if let Some(Event::Subtask {
            status: status @ (Status::Returned | Status::ReturnCancelled),
        }) = event
        {
            Ok(status as u32)
        } else {
            bail!("`subtask.cancel` called after terminal status delivered");
        }
    }

    pub(crate) fn context_get(self, store: &mut StoreOpaque, slot: u32) -> Result<u32> {
        store.concurrent_state_mut().context_get(slot)
    }

    pub(crate) fn context_set(self, store: &mut StoreOpaque, slot: u32, value: u32) -> Result<()> {
        store.concurrent_state_mut().context_set(slot, value)
    }
}

/// Trait representing component model ABI async intrinsics and fused adapter
/// helper functions.
///
/// SAFETY (callers): Most of the methods in this trait accept raw pointers,
/// which must be valid for at least the duration of the call (and possibly for
/// as long as the relevant guest task exists, in the case of `*mut VMFuncRef`
/// pointers used for async calls).
pub trait VMComponentAsyncStore {
    /// A helper function for fused adapter modules involving calls where the
    /// one of the caller or callee is async.
    ///
    /// This helper is not used when the caller and callee both use the sync
    /// ABI, only when at least one is async is this used.
    unsafe fn prepare_call(
        &mut self,
        instance: Instance,
        memory: *mut VMMemoryDefinition,
        start: *mut VMFuncRef,
        return_: *mut VMFuncRef,
        caller_instance: RuntimeComponentInstanceIndex,
        callee_instance: RuntimeComponentInstanceIndex,
        task_return_type: TypeTupleIndex,
        callee_async: bool,
        string_encoding: u8,
        result_count: u32,
        storage: *mut ValRaw,
        storage_len: usize,
    ) -> Result<()>;

    /// A helper function for fused adapter modules involving calls where the
    /// caller is sync-lowered but the callee is async-lifted.
    unsafe fn sync_start(
        &mut self,
        instance: Instance,
        callback: *mut VMFuncRef,
        callee: *mut VMFuncRef,
        param_count: u32,
        storage: *mut MaybeUninit<ValRaw>,
        storage_len: usize,
    ) -> Result<()>;

    /// A helper function for fused adapter modules involving calls where the
    /// caller is async-lowered.
    unsafe fn async_start(
        &mut self,
        instance: Instance,
        callback: *mut VMFuncRef,
        post_return: *mut VMFuncRef,
        callee: *mut VMFuncRef,
        param_count: u32,
        result_count: u32,
        flags: u32,
    ) -> Result<u32>;

    /// The `future.write` intrinsic.
    fn future_write(
        &mut self,
        instance: Instance,
        caller: RuntimeComponentInstanceIndex,
        ty: TypeFutureTableIndex,
        options: OptionsIndex,
        future: u32,
        address: u32,
    ) -> Result<u32>;

    /// The `future.read` intrinsic.
    fn future_read(
        &mut self,
        instance: Instance,
        caller: RuntimeComponentInstanceIndex,
        ty: TypeFutureTableIndex,
        options: OptionsIndex,
        future: u32,
        address: u32,
    ) -> Result<u32>;

    /// The `future.drop-writable` intrinsic.
    fn future_drop_writable(
        &mut self,
        instance: Instance,
        ty: TypeFutureTableIndex,
        writer: u32,
    ) -> Result<()>;

    /// The `stream.write` intrinsic.
    fn stream_write(
        &mut self,
        instance: Instance,
        caller: RuntimeComponentInstanceIndex,
        ty: TypeStreamTableIndex,
        options: OptionsIndex,
        stream: u32,
        address: u32,
        count: u32,
    ) -> Result<u32>;

    /// The `stream.read` intrinsic.
    fn stream_read(
        &mut self,
        instance: Instance,
        caller: RuntimeComponentInstanceIndex,
        ty: TypeStreamTableIndex,
        options: OptionsIndex,
        stream: u32,
        address: u32,
        count: u32,
    ) -> Result<u32>;

    /// The "fast-path" implementation of the `stream.write` intrinsic for
    /// "flat" (i.e. memcpy-able) payloads.
    fn flat_stream_write(
        &mut self,
        instance: Instance,
        caller: RuntimeComponentInstanceIndex,
        ty: TypeStreamTableIndex,
        options: OptionsIndex,
        payload_size: u32,
        payload_align: u32,
        stream: u32,
        address: u32,
        count: u32,
    ) -> Result<u32>;

    /// The "fast-path" implementation of the `stream.read` intrinsic for "flat"
    /// (i.e. memcpy-able) payloads.
    fn flat_stream_read(
        &mut self,
        instance: Instance,
        caller: RuntimeComponentInstanceIndex,
        ty: TypeStreamTableIndex,
        options: OptionsIndex,
        payload_size: u32,
        payload_align: u32,
        stream: u32,
        address: u32,
        count: u32,
    ) -> Result<u32>;

    /// The `stream.drop-writable` intrinsic.
    fn stream_drop_writable(
        &mut self,
        instance: Instance,
        ty: TypeStreamTableIndex,
        writer: u32,
    ) -> Result<()>;

    /// The `error-context.debug-message` intrinsic.
    fn error_context_debug_message(
        &mut self,
        instance: Instance,
        ty: TypeComponentLocalErrorContextTableIndex,
        options: OptionsIndex,
        err_ctx_handle: u32,
        debug_msg_address: u32,
    ) -> Result<()>;

    /// The `thread.new-indirect` intrinsic
    fn thread_new_indirect(
        &mut self,
        instance: Instance,
        caller: RuntimeComponentInstanceIndex,
        func_ty_idx: TypeFuncIndex,
        start_func_table_idx: RuntimeTableIndex,
        start_func_idx: u32,
        context: i32,
    ) -> Result<u32>;
}

/// SAFETY: See trait docs.
impl<T: 'static> VMComponentAsyncStore for StoreInner<T> {
    unsafe fn prepare_call(
        &mut self,
        instance: Instance,
        memory: *mut VMMemoryDefinition,
        start: *mut VMFuncRef,
        return_: *mut VMFuncRef,
        caller_instance: RuntimeComponentInstanceIndex,
        callee_instance: RuntimeComponentInstanceIndex,
        task_return_type: TypeTupleIndex,
        callee_async: bool,
        string_encoding: u8,
        result_count_or_max_if_async: u32,
        storage: *mut ValRaw,
        storage_len: usize,
    ) -> Result<()> {
        // SAFETY: The `wasmtime_cranelift`-generated code that calls
        // this method will have ensured that `storage` is a valid
        // pointer containing at least `storage_len` items.
        let params = unsafe { std::slice::from_raw_parts(storage, storage_len) }.to_vec();

        unsafe {
            instance.prepare_call(
                StoreContextMut(self),
                start,
                return_,
                caller_instance,
                callee_instance,
                task_return_type,
                callee_async,
                memory,
                string_encoding,
                match result_count_or_max_if_async {
                    PREPARE_ASYNC_NO_RESULT => CallerInfo::Async {
                        params,
                        has_result: false,
                    },
                    PREPARE_ASYNC_WITH_RESULT => CallerInfo::Async {
                        params,
                        has_result: true,
                    },
                    result_count => CallerInfo::Sync {
                        params,
                        result_count,
                    },
                },
            )
        }
    }

    unsafe fn sync_start(
        &mut self,
        instance: Instance,
        callback: *mut VMFuncRef,
        callee: *mut VMFuncRef,
        param_count: u32,
        storage: *mut MaybeUninit<ValRaw>,
        storage_len: usize,
    ) -> Result<()> {
        unsafe {
            instance
                .start_call(
                    StoreContextMut(self),
                    callback,
                    ptr::null_mut(),
                    callee,
                    param_count,
                    1,
                    START_FLAG_ASYNC_CALLEE,
                    // SAFETY: The `wasmtime_cranelift`-generated code that calls
                    // this method will have ensured that `storage` is a valid
                    // pointer containing at least `storage_len` items.
                    Some(std::slice::from_raw_parts_mut(storage, storage_len)),
                )
                .map(drop)
        }
    }

    unsafe fn async_start(
        &mut self,
        instance: Instance,
        callback: *mut VMFuncRef,
        post_return: *mut VMFuncRef,
        callee: *mut VMFuncRef,
        param_count: u32,
        result_count: u32,
        flags: u32,
    ) -> Result<u32> {
        unsafe {
            instance.start_call(
                StoreContextMut(self),
                callback,
                post_return,
                callee,
                param_count,
                result_count,
                flags,
                None,
            )
        }
    }

    fn future_write(
        &mut self,
        instance: Instance,
        caller: RuntimeComponentInstanceIndex,
        ty: TypeFutureTableIndex,
        options: OptionsIndex,
        future: u32,
        address: u32,
    ) -> Result<u32> {
        instance
            .guest_write(
                StoreContextMut(self),
                caller,
                TransmitIndex::Future(ty),
                options,
                None,
                future,
                address,
                1,
            )
            .map(|result| result.encode())
    }

    fn future_read(
        &mut self,
        instance: Instance,
        caller: RuntimeComponentInstanceIndex,
        ty: TypeFutureTableIndex,
        options: OptionsIndex,
        future: u32,
        address: u32,
    ) -> Result<u32> {
        instance
            .guest_read(
                StoreContextMut(self),
                caller,
                TransmitIndex::Future(ty),
                options,
                None,
                future,
                address,
                1,
            )
            .map(|result| result.encode())
    }

    fn stream_write(
        &mut self,
        instance: Instance,
        caller: RuntimeComponentInstanceIndex,
        ty: TypeStreamTableIndex,
        options: OptionsIndex,
        stream: u32,
        address: u32,
        count: u32,
    ) -> Result<u32> {
        instance
            .guest_write(
                StoreContextMut(self),
                caller,
                TransmitIndex::Stream(ty),
                options,
                None,
                stream,
                address,
                count,
            )
            .map(|result| result.encode())
    }

    fn stream_read(
        &mut self,
        instance: Instance,
        caller: RuntimeComponentInstanceIndex,
        ty: TypeStreamTableIndex,
        options: OptionsIndex,
        stream: u32,
        address: u32,
        count: u32,
    ) -> Result<u32> {
        instance
            .guest_read(
                StoreContextMut(self),
                caller,
                TransmitIndex::Stream(ty),
                options,
                None,
                stream,
                address,
                count,
            )
            .map(|result| result.encode())
    }

    fn future_drop_writable(
        &mut self,
        instance: Instance,
        ty: TypeFutureTableIndex,
        writer: u32,
    ) -> Result<()> {
        instance.guest_drop_writable(self, TransmitIndex::Future(ty), writer)
    }

    fn flat_stream_write(
        &mut self,
        instance: Instance,
        caller: RuntimeComponentInstanceIndex,
        ty: TypeStreamTableIndex,
        options: OptionsIndex,
        payload_size: u32,
        payload_align: u32,
        stream: u32,
        address: u32,
        count: u32,
    ) -> Result<u32> {
        instance
            .guest_write(
                StoreContextMut(self),
                caller,
                TransmitIndex::Stream(ty),
                options,
                Some(FlatAbi {
                    size: payload_size,
                    align: payload_align,
                }),
                stream,
                address,
                count,
            )
            .map(|result| result.encode())
    }

    fn flat_stream_read(
        &mut self,
        instance: Instance,
        caller: RuntimeComponentInstanceIndex,
        ty: TypeStreamTableIndex,
        options: OptionsIndex,
        payload_size: u32,
        payload_align: u32,
        stream: u32,
        address: u32,
        count: u32,
    ) -> Result<u32> {
        instance
            .guest_read(
                StoreContextMut(self),
                caller,
                TransmitIndex::Stream(ty),
                options,
                Some(FlatAbi {
                    size: payload_size,
                    align: payload_align,
                }),
                stream,
                address,
                count,
            )
            .map(|result| result.encode())
    }

    fn stream_drop_writable(
        &mut self,
        instance: Instance,
        ty: TypeStreamTableIndex,
        writer: u32,
    ) -> Result<()> {
        instance.guest_drop_writable(self, TransmitIndex::Stream(ty), writer)
    }

    fn error_context_debug_message(
        &mut self,
        instance: Instance,
        ty: TypeComponentLocalErrorContextTableIndex,
        options: OptionsIndex,
        err_ctx_handle: u32,
        debug_msg_address: u32,
    ) -> Result<()> {
        instance.error_context_debug_message(
            StoreContextMut(self),
            ty,
            options,
            err_ctx_handle,
            debug_msg_address,
        )
    }

    fn thread_new_indirect(
        &mut self,
        instance: Instance,
        caller: RuntimeComponentInstanceIndex,
        func_ty_idx: TypeFuncIndex,
        start_func_table_idx: RuntimeTableIndex,
        start_func_idx: u32,
        context: i32,
    ) -> Result<u32> {
        instance.thread_new_indirect(
            StoreContextMut(self),
            caller,
            func_ty_idx,
            start_func_table_idx,
            start_func_idx,
            context,
        )
    }
}

type HostTaskFuture = Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>;

/// Represents the state of a pending host task.
struct HostTask {
    common: WaitableCommon,
    caller_instance: RuntimeInstance,
    join_handle: Option<JoinHandle>,
}

impl HostTask {
    fn new(caller_instance: RuntimeInstance, join_handle: Option<JoinHandle>) -> Self {
        Self {
            common: WaitableCommon::default(),
            caller_instance,
            join_handle,
        }
    }
}

impl TableDebug for HostTask {
    fn type_name() -> &'static str {
        "HostTask"
    }
}

type CallbackFn = Box<dyn Fn(&mut dyn VMStore, Event, u32) -> Result<u32> + Send + Sync + 'static>;

/// Represents the caller of a given guest task.
enum Caller {
    /// The host called the guest task.
    Host {
        /// If present, may be used to deliver the result.
        tx: Option<oneshot::Sender<LiftedResult>>,
        /// Channel to notify once all subtasks spawned by this caller have
        /// completed.
        ///
        /// Note that we'll never actually send anything to this channel;
        /// dropping it when the refcount goes to zero is sufficient to notify
        /// the receiver.
        exit_tx: Arc<oneshot::Sender<()>>,
        /// If true, there's a host future that must be dropped before the task
        /// can be deleted.
        host_future_present: bool,
        /// If `Some`, represents the `QualifiedThreadId` caller of the host
        /// function which called back into a guest.  Note that this thread
        /// could belong to an entirely unrelated top-level component instance
        /// than the one the host called into.
        caller: Option<QualifiedThreadId>,
    },
    /// Another guest thread called the guest task
    Guest {
        /// The id of the caller
        thread: QualifiedThreadId,
    },
}

/// Represents a closure and related canonical ABI parameters required to
/// validate a `task.return` call at runtime and lift the result.
struct LiftResult {
    lift: RawLift,
    ty: TypeTupleIndex,
    memory: Option<SendSyncPtr<VMMemoryDefinition>>,
    string_encoding: StringEncoding,
}

/// The table ID for a guest thread, qualified by the task to which it belongs.
///
/// This exists to minimize table lookups and the necessity to pass stores around mutably
/// for the common case of identifying the task to which a thread belongs.
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
struct QualifiedThreadId {
    task: TableId<GuestTask>,
    thread: TableId<GuestThread>,
}

impl QualifiedThreadId {
    fn qualify(
        state: &mut ConcurrentState,
        thread: TableId<GuestThread>,
    ) -> Result<QualifiedThreadId> {
        Ok(QualifiedThreadId {
            task: state.get_mut(thread)?.parent_task,
            thread,
        })
    }
}

impl fmt::Debug for QualifiedThreadId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("QualifiedThreadId")
            .field(&self.task.rep())
            .field(&self.thread.rep())
            .finish()
    }
}

enum GuestThreadState {
    NotStartedImplicit,
    NotStartedExplicit(
        Box<dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync>,
    ),
    Running,
    Suspended(StoreFiber<'static>),
    Pending,
    Completed,
}
pub struct GuestThread {
    /// Context-local state used to implement the `context.{get,set}`
    /// intrinsics.
    context: [u32; 2],
    /// The owning guest task.
    parent_task: TableId<GuestTask>,
    /// If present, indicates that the thread is currently waiting on the
    /// specified set but may be cancelled and woken immediately.
    wake_on_cancel: Option<TableId<WaitableSet>>,
    /// The execution state of this guest thread
    state: GuestThreadState,
    /// The index of this thread in the component instance's handle table.
    /// This must always be `Some` after initialization.
    instance_rep: Option<u32>,
}

impl GuestThread {
    /// Retrieve the `GuestThread` corresponding to the specified guest-visible
    /// handle.
    fn from_instance(
        state: Pin<&mut ComponentInstance>,
        caller_instance: RuntimeComponentInstanceIndex,
        guest_thread: u32,
    ) -> Result<TableId<Self>> {
        let rep = state.instance_states().0[caller_instance]
            .thread_handle_table()
            .guest_thread_rep(guest_thread)?;
        Ok(TableId::new(rep))
    }

    fn new_implicit(parent_task: TableId<GuestTask>) -> Self {
        Self {
            context: [0; 2],
            parent_task,
            wake_on_cancel: None,
            state: GuestThreadState::NotStartedImplicit,
            instance_rep: None,
        }
    }

    fn new_explicit(
        parent_task: TableId<GuestTask>,
        start_func: Box<
            dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync,
        >,
    ) -> Self {
        Self {
            context: [0; 2],
            parent_task,
            wake_on_cancel: None,
            state: GuestThreadState::NotStartedExplicit(start_func),
            instance_rep: None,
        }
    }
}

impl TableDebug for GuestThread {
    fn type_name() -> &'static str {
        "GuestThread"
    }
}

enum SyncResult {
    NotProduced,
    Produced(Option<ValRaw>),
    Taken,
}

impl SyncResult {
    fn take(&mut self) -> Option<Option<ValRaw>> {
        match mem::replace(self, SyncResult::Taken) {
            SyncResult::NotProduced => None,
            SyncResult::Produced(val) => Some(val),
            SyncResult::Taken => {
                panic!("attempted to take a synchronous result that was already taken")
            }
        }
    }
}

#[derive(Debug)]
enum HostFutureState {
    NotApplicable,
    Live,
    Dropped,
}

/// Represents a pending guest task.
pub(crate) struct GuestTask {
    /// See `WaitableCommon`
    common: WaitableCommon,
    /// Closure to lower the parameters passed to this task.
    lower_params: Option<RawLower>,
    /// See `LiftResult`
    lift_result: Option<LiftResult>,
    /// A place to stash the type-erased lifted result if it can't be delivered
    /// immediately.
    result: Option<LiftedResult>,
    /// Closure to call the callback function for an async-lifted export, if
    /// provided.
    callback: Option<CallbackFn>,
    /// See `Caller`
    caller: Caller,
    /// A place to stash the call context for managing resource borrows while
    /// switching between guest tasks.
    call_context: Option<CallContext>,
    /// A place to stash the lowered result for a sync-to-async call until it
    /// can be returned to the caller.
    sync_result: SyncResult,
    /// Whether or not the task has been cancelled (i.e. whether the task is
    /// permitted to call `task.cancel`).
    cancel_sent: bool,
    /// Whether or not we've sent a `Status::Starting` event to any current or
    /// future waiters for this waitable.
    starting_sent: bool,
    /// Pending guest subtasks created by this task (directly or indirectly).
    ///
    /// This is used to re-parent subtasks which are still running when their
    /// parent task is disposed.
    subtasks: HashSet<TableId<GuestTask>>,
    /// Scratch waitable set used to watch subtasks during synchronous calls.
    sync_call_set: TableId<WaitableSet>,
    /// The runtime instance to which the exported function for this guest task
    /// belongs.
    ///
    /// Note that the task may do a sync->sync call via a fused adapter which
    /// results in that task executing code in a different instance, and it may
    /// call host functions and intrinsics from that other instance.
    instance: RuntimeInstance,
    /// If present, a pending `Event::None` or `Event::Cancelled` to be
    /// delivered to this task.
    event: Option<Event>,
    /// The `ExportIndex` of the guest function being called, if known.
    function_index: Option<ExportIndex>,
    /// Whether or not the task has exited.
    exited: bool,
    /// Threads belonging to this task
    threads: HashSet<TableId<GuestThread>>,
    /// The state of the host future that represents an async task, which must
    /// be dropped before we can delete the task.
    host_future_state: HostFutureState,
    /// Indicates whether this task was created for a call to an async-lifted
    /// export.
    async_function: bool,
}

impl GuestTask {
    fn already_lowered_parameters(&self) -> bool {
        // We reset `lower_params` after we lower the parameters
        self.lower_params.is_none()
    }

    fn returned_or_cancelled(&self) -> bool {
        // We reset `lift_result` after we return or exit
        self.lift_result.is_none()
    }

    fn ready_to_delete(&self) -> bool {
        let threads_completed = self.threads.is_empty();
        let has_sync_result = matches!(self.sync_result, SyncResult::Produced(_));
        let pending_completion_event = matches!(
            self.common.event,
            Some(Event::Subtask {
                status: Status::Returned | Status::ReturnCancelled
            })
        );
        let ready = threads_completed
            && !has_sync_result
            && !pending_completion_event
            && !matches!(self.host_future_state, HostFutureState::Live);
        log::trace!(
            "ready to delete? {ready} (threads_completed: {}, has_sync_result: {}, pending_completion_event: {}, host_future_state: {:?})",
            threads_completed,
            has_sync_result,
            pending_completion_event,
            self.host_future_state
        );
        ready
    }

    fn new(
        state: &mut ConcurrentState,
        lower_params: RawLower,
        lift_result: LiftResult,
        caller: Caller,
        callback: Option<CallbackFn>,
        instance: RuntimeInstance,
        async_function: bool,
    ) -> Result<Self> {
        let sync_call_set = state.push(WaitableSet::default())?;
        let host_future_state = match &caller {
            Caller::Guest { .. } => HostFutureState::NotApplicable,
            Caller::Host {
                host_future_present,
                ..
            } => {
                if *host_future_present {
                    HostFutureState::Live
                } else {
                    HostFutureState::NotApplicable
                }
            }
        };
        Ok(Self {
            common: WaitableCommon::default(),
            lower_params: Some(lower_params),
            lift_result: Some(lift_result),
            result: None,
            callback,
            caller,
            call_context: Some(CallContext::default()),
            sync_result: SyncResult::NotProduced,
            cancel_sent: false,
            starting_sent: false,
            subtasks: HashSet::new(),
            sync_call_set,
            instance,
            event: None,
            function_index: None,
            exited: false,
            threads: HashSet::new(),
            host_future_state,
            async_function,
        })
    }

    /// Dispose of this guest task, reparenting any pending subtasks to the
    /// caller.
    fn dispose(self, state: &mut ConcurrentState, me: TableId<GuestTask>) -> Result<()> {
        // If there are not-yet-delivered completion events for subtasks in
        // `self.sync_call_set`, recursively dispose of those subtasks as well.
        for waitable in mem::take(&mut state.get_mut(self.sync_call_set)?.ready) {
            if let Some(Event::Subtask {
                status: Status::Returned | Status::ReturnCancelled,
            }) = waitable.common(state)?.event
            {
                waitable.delete_from(state)?;
            }
        }

        assert!(self.threads.is_empty());

        state.delete(self.sync_call_set)?;

        // Reparent any pending subtasks to the caller.
        match &self.caller {
            Caller::Guest { thread } => {
                let task_mut = state.get_mut(thread.task)?;
                let present = task_mut.subtasks.remove(&me);
                assert!(present);

                for subtask in &self.subtasks {
                    task_mut.subtasks.insert(*subtask);
                }

                for subtask in &self.subtasks {
                    state.get_mut(*subtask)?.caller = Caller::Guest { thread: *thread };
                }
            }
            Caller::Host {
                exit_tx, caller, ..
            } => {
                for subtask in &self.subtasks {
                    state.get_mut(*subtask)?.caller = Caller::Host {
                        tx: None,
                        // Clone `exit_tx` to ensure that it is only dropped
                        // once all transitive subtasks of the host call have
                        // exited:
                        exit_tx: exit_tx.clone(),
                        host_future_present: false,
                        caller: *caller,
                    };
                }
            }
        }

        for subtask in self.subtasks {
            let task = state.get_mut(subtask)?;
            if task.exited && task.ready_to_delete() {
                Waitable::Guest(subtask).delete_from(state)?;
            }
        }

        Ok(())
    }
}

impl TableDebug for GuestTask {
    fn type_name() -> &'static str {
        "GuestTask"
    }
}

/// Represents state common to all kinds of waitables.
#[derive(Default)]
struct WaitableCommon {
    /// The currently pending event for this waitable, if any.
    event: Option<Event>,
    /// The set to which this waitable belongs, if any.
    set: Option<TableId<WaitableSet>>,
    /// The handle with which the guest refers to this waitable, if any.
    handle: Option<u32>,
}

/// Represents a Component Model Async `waitable`.
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
enum Waitable {
    /// A host task
    Host(TableId<HostTask>),
    /// A guest task
    Guest(TableId<GuestTask>),
    /// The read or write end of a stream or future
    Transmit(TableId<TransmitHandle>),
}

impl Waitable {
    /// Retrieve the `Waitable` corresponding to the specified guest-visible
    /// handle.
    fn from_instance(
        state: Pin<&mut ComponentInstance>,
        caller_instance: RuntimeComponentInstanceIndex,
        waitable: u32,
    ) -> Result<Self> {
        use crate::runtime::vm::component::Waitable;

        let (waitable, kind) = state.instance_states().0[caller_instance]
            .handle_table()
            .waitable_rep(waitable)?;

        Ok(match kind {
            Waitable::Subtask { is_host: true } => Self::Host(TableId::new(waitable)),
            Waitable::Subtask { is_host: false } => Self::Guest(TableId::new(waitable)),
            Waitable::Stream | Waitable::Future => Self::Transmit(TableId::new(waitable)),
        })
    }

    /// Retrieve the host-visible identifier for this `Waitable`.
    fn rep(&self) -> u32 {
        match self {
            Self::Host(id) => id.rep(),
            Self::Guest(id) => id.rep(),
            Self::Transmit(id) => id.rep(),
        }
    }

    /// Move this `Waitable` to the specified set (when `set` is `Some(_)`) or
    /// remove it from any set it may currently belong to (when `set` is
    /// `None`).
    fn join(&self, state: &mut ConcurrentState, set: Option<TableId<WaitableSet>>) -> Result<()> {
        log::trace!("waitable {self:?} join set {set:?}",);

        let old = mem::replace(&mut self.common(state)?.set, set);

        if let Some(old) = old {
            match *self {
                Waitable::Host(id) => state.remove_child(id, old),
                Waitable::Guest(id) => state.remove_child(id, old),
                Waitable::Transmit(id) => state.remove_child(id, old),
            }?;

            state.get_mut(old)?.ready.remove(self);
        }

        if let Some(set) = set {
            match *self {
                Waitable::Host(id) => state.add_child(id, set),
                Waitable::Guest(id) => state.add_child(id, set),
                Waitable::Transmit(id) => state.add_child(id, set),
            }?;

            if self.common(state)?.event.is_some() {
                self.mark_ready(state)?;
            }
        }

        Ok(())
    }

    /// Retrieve mutable access to the `WaitableCommon` for this `Waitable`.
    fn common<'a>(&self, state: &'a mut ConcurrentState) -> Result<&'a mut WaitableCommon> {
        Ok(match self {
            Self::Host(id) => &mut state.get_mut(*id)?.common,
            Self::Guest(id) => &mut state.get_mut(*id)?.common,
            Self::Transmit(id) => &mut state.get_mut(*id)?.common,
        })
    }

    /// Set or clear the pending event for this waitable and either deliver it
    /// to the first waiter, if any, or mark it as ready to be delivered to the
    /// next waiter that arrives.
    fn set_event(&self, state: &mut ConcurrentState, event: Option<Event>) -> Result<()> {
        log::trace!("set event for {self:?}: {event:?}");
        self.common(state)?.event = event;
        self.mark_ready(state)
    }

    /// Take the pending event from this waitable, leaving `None` in its place.
    fn take_event(&self, state: &mut ConcurrentState) -> Result<Option<Event>> {
        let common = self.common(state)?;
        let event = common.event.take();
        if let Some(set) = self.common(state)?.set {
            state.get_mut(set)?.ready.remove(self);
        }

        Ok(event)
    }

    /// Deliver the current event for this waitable to the first waiter, if any,
    /// or else mark it as ready to be delivered to the next waiter that
    /// arrives.
    fn mark_ready(&self, state: &mut ConcurrentState) -> Result<()> {
        if let Some(set) = self.common(state)?.set {
            state.get_mut(set)?.ready.insert(*self);
            if let Some((thread, mode)) = state.get_mut(set)?.waiting.pop_first() {
                let wake_on_cancel = state.get_mut(thread.thread)?.wake_on_cancel.take();
                assert!(wake_on_cancel.is_none() || wake_on_cancel == Some(set));

                let item = match mode {
                    WaitMode::Fiber(fiber) => WorkItem::ResumeFiber(fiber),
                    WaitMode::Callback(instance) => WorkItem::GuestCall(GuestCall {
                        thread,
                        kind: GuestCallKind::DeliverEvent {
                            instance,
                            set: Some(set),
                        },
                    }),
                };
                state.push_high_priority(item);
            }
        }
        Ok(())
    }

    /// Remove this waitable from the instance's rep table.
    fn delete_from(&self, state: &mut ConcurrentState) -> Result<()> {
        match self {
            Self::Host(task) => {
                log::trace!("delete host task {task:?}");
                state.delete(*task)?;
            }
            Self::Guest(task) => {
                log::trace!("delete guest task {task:?}");
                state.delete(*task)?.dispose(state, *task)?;
            }
            Self::Transmit(task) => {
                state.delete(*task)?;
            }
        }

        Ok(())
    }
}

impl fmt::Debug for Waitable {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Host(id) => write!(f, "{id:?}"),
            Self::Guest(id) => write!(f, "{id:?}"),
            Self::Transmit(id) => write!(f, "{id:?}"),
        }
    }
}

/// Represents a Component Model Async `waitable-set`.
#[derive(Default)]
struct WaitableSet {
    /// Which waitables in this set have pending events, if any.
    ready: BTreeSet<Waitable>,
    /// Which guest threads are currently waiting on this set, if any.
    waiting: BTreeMap<QualifiedThreadId, WaitMode>,
}

impl TableDebug for WaitableSet {
    fn type_name() -> &'static str {
        "WaitableSet"
    }
}

/// Type-erased closure to lower the parameters for a guest task.
type RawLower =
    Box<dyn FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync>;

/// Type-erased closure to lift the result for a guest task.
type RawLift = Box<
    dyn FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
>;

/// Type erased result of a guest task which may be downcast to the expected
/// type by a host caller (or simply ignored in the case of a guest caller; see
/// `DummyResult`).
type LiftedResult = Box<dyn Any + Send + Sync>;

/// Used to return a result from a `LiftFn` when the actual result has already
/// been lowered to a guest task's stack and linear memory.
struct DummyResult;

/// Represents the Component Model Async state of a (sub-)component instance.
#[derive(Default)]
pub struct ConcurrentInstanceState {
    /// Whether backpressure is set for this instance (enabled if >0)
    backpressure: u16,
    /// Whether this instance can be entered
    do_not_enter: bool,
    /// Pending calls for this instance which require `Self::backpressure` to be
    /// `true` and/or `Self::do_not_enter` to be false before they can proceed.
    pending: BTreeMap<QualifiedThreadId, GuestCallKind>,
}

impl ConcurrentInstanceState {
    pub fn pending_is_empty(&self) -> bool {
        self.pending.is_empty()
    }
}

/// Represents the Component Model Async state of a store.
pub struct ConcurrentState {
    /// The currently running guest thread, if any.
    guest_thread: Option<QualifiedThreadId>,

    /// The set of pending host and background tasks, if any.
    ///
    /// See `ComponentInstance::poll_until` for where we temporarily take this
    /// out, poll it, then put it back to avoid any mutable aliasing hazards.
    futures: AlwaysMut<Option<FuturesUnordered<HostTaskFuture>>>,
    /// The table of waitables, waitable sets, etc.
    table: AlwaysMut<ResourceTable>,
    /// The "high priority" work queue for this store's event loop.
    high_priority: Vec<WorkItem>,
    /// The "low priority" work queue for this store's event loop.
    low_priority: VecDeque<WorkItem>,
    /// A place to stash the reason a fiber is suspending so that the code which
    /// resumed it will know under what conditions the fiber should be resumed
    /// again.
    suspend_reason: Option<SuspendReason>,
    /// A cached fiber which is waiting for work to do.
    ///
    /// This helps us avoid creating a new fiber for each `GuestCall` work item.
    worker: Option<StoreFiber<'static>>,
    /// A place to stash the work item for which we're resuming a worker fiber.
    worker_item: Option<WorkerItem>,

    /// Reference counts for all component error contexts
    ///
    /// NOTE: it is possible the global ref count to be *greater* than the sum of
    /// (sub)component ref counts as tracked by `error_context_tables`, for
    /// example when the host holds one or more references to error contexts.
    ///
    /// The key of this primary map is often referred to as the "rep" (i.e. host-side
    /// component-wide representation) of the index into concurrent state for a given
    /// stored `ErrorContext`.
    ///
    /// Stated another way, `TypeComponentGlobalErrorContextTableIndex` is essentially the same
    /// as a `TableId<ErrorContextState>`.
    global_error_context_ref_counts:
        BTreeMap<TypeComponentGlobalErrorContextTableIndex, GlobalErrorContextRefCount>,
}

impl Default for ConcurrentState {
    fn default() -> Self {
        Self {
            guest_thread: None,
            table: AlwaysMut::new(ResourceTable::new()),
            futures: AlwaysMut::new(Some(FuturesUnordered::new())),
            high_priority: Vec::new(),
            low_priority: VecDeque::new(),
            suspend_reason: None,
            worker: None,
            worker_item: None,
            global_error_context_ref_counts: BTreeMap::new(),
        }
    }
}

impl ConcurrentState {
    /// Take ownership of any fibers and futures owned by this object.
    ///
    /// This should be used when disposing of the `Store` containing this object
    /// in order to gracefully resolve any and all fibers using
    /// `StoreFiber::dispose`.  This is necessary to avoid possible
    /// use-after-free bugs due to fibers which may still have access to the
    /// `Store`.
    ///
    /// Additionally, the futures collected with this function should be dropped
    /// within a `tls::set` call, which will ensure than any futures closing
    /// over an `&Accessor` will have access to the store when dropped, allowing
    /// e.g. `WithAccessor[AndValue]` instances to be disposed of without
    /// panicking.
    ///
    /// Note that this will leave the object in an inconsistent and unusable
    /// state, so it should only be used just prior to dropping it.
    pub(crate) fn take_fibers_and_futures(
        &mut self,
        fibers: &mut Vec<StoreFiber<'static>>,
        futures: &mut Vec<FuturesUnordered<HostTaskFuture>>,
    ) {
        for entry in self.table.get_mut().iter_mut() {
            if let Some(set) = entry.downcast_mut::<WaitableSet>() {
                for mode in mem::take(&mut set.waiting).into_values() {
                    if let WaitMode::Fiber(fiber) = mode {
                        fibers.push(fiber);
                    }
                }
            } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
                if let GuestThreadState::Suspended(fiber) =
                    mem::replace(&mut thread.state, GuestThreadState::Completed)
                {
                    fibers.push(fiber);
                }
            }
        }

        if let Some(fiber) = self.worker.take() {
            fibers.push(fiber);
        }

        let mut handle_item = |item| match item {
            WorkItem::ResumeFiber(fiber) => {
                fibers.push(fiber);
            }
            WorkItem::PushFuture(future) => {
                self.futures
                    .get_mut()
                    .as_mut()
                    .unwrap()
                    .push(future.into_inner());
            }
            _ => {}
        };

        for item in mem::take(&mut self.high_priority) {
            handle_item(item);
        }
        for item in mem::take(&mut self.low_priority) {
            handle_item(item);
        }

        if let Some(them) = self.futures.get_mut().take() {
            futures.push(them);
        }
    }

    /// Collect the next set of work items to run. This will be either all
    /// high-priority items, or a single low-priority item if there are no
    /// high-priority items.
    fn collect_work_items_to_run(&mut self) -> Vec<WorkItem> {
        let mut ready = mem::take(&mut self.high_priority);
        if ready.is_empty() {
            if let Some(item) = self.low_priority.pop_back() {
                ready.push(item);
            }
        }
        ready
    }

    fn push<V: Send + Sync + 'static>(
        &mut self,
        value: V,
    ) -> Result<TableId<V>, ResourceTableError> {
        self.table.get_mut().push(value).map(TableId::from)
    }

    fn get_mut<V: 'static>(&mut self, id: TableId<V>) -> Result<&mut V, ResourceTableError> {
        self.table.get_mut().get_mut(&Resource::from(id))
    }

    pub fn add_child<T: 'static, U: 'static>(
        &mut self,
        child: TableId<T>,
        parent: TableId<U>,
    ) -> Result<(), ResourceTableError> {
        self.table
            .get_mut()
            .add_child(Resource::from(child), Resource::from(parent))
    }

    pub fn remove_child<T: 'static, U: 'static>(
        &mut self,
        child: TableId<T>,
        parent: TableId<U>,
    ) -> Result<(), ResourceTableError> {
        self.table
            .get_mut()
            .remove_child(Resource::from(child), Resource::from(parent))
    }

    fn delete<V: 'static>(&mut self, id: TableId<V>) -> Result<V, ResourceTableError> {
        self.table.get_mut().delete(Resource::from(id))
    }

    fn push_future(&mut self, future: HostTaskFuture) {
        // Note that we can't directly push to `ConcurrentState::futures` here
        // since this may be called from a future that's being polled inside
        // `Self::poll_until`, which temporarily removes the `FuturesUnordered`
        // so it has exclusive access while polling it.  Therefore, we push a
        // work item to the "high priority" queue, which will actually push to
        // `ConcurrentState::futures` later.
        self.push_high_priority(WorkItem::PushFuture(AlwaysMut::new(future)));
    }

    fn push_high_priority(&mut self, item: WorkItem) {
        log::trace!("push high priority: {item:?}");
        self.high_priority.push(item);
    }

    fn push_low_priority(&mut self, item: WorkItem) {
        log::trace!("push low priority: {item:?}");
        self.low_priority.push_front(item);
    }

    fn push_work_item(&mut self, item: WorkItem, high_priority: bool) {
        if high_priority {
            self.push_high_priority(item);
        } else {
            self.push_low_priority(item);
        }
    }

    /// Implements the `context.get` intrinsic.
    pub(crate) fn context_get(&mut self, slot: u32) -> Result<u32> {
        let thread = self.guest_thread.unwrap();
        let val = self.get_mut(thread.thread)?.context[usize::try_from(slot).unwrap()];
        log::trace!("context_get {thread:?} slot {slot} val {val:#x}");
        Ok(val)
    }

    /// Implements the `context.set` intrinsic.
    pub(crate) fn context_set(&mut self, slot: u32, val: u32) -> Result<()> {
        let thread = self.guest_thread.unwrap();
        log::trace!("context_set {thread:?} slot {slot} val {val:#x}");
        self.get_mut(thread.thread)?.context[usize::try_from(slot).unwrap()] = val;
        Ok(())
    }

    /// Returns whether there's a pending cancellation on the current guest thread,
    /// consuming the event if so.
    fn take_pending_cancellation(&mut self) -> bool {
        let thread = self.guest_thread.unwrap();
        if let Some(event) = self.get_mut(thread.task).unwrap().event.take() {
            assert!(matches!(event, Event::Cancelled));
            true
        } else {
            false
        }
    }

    fn check_blocking_for(&mut self, task: TableId<GuestTask>) -> Result<()> {
        if self.may_block(task) {
            Ok(())
        } else {
            Err(Trap::CannotBlockSyncTask.into())
        }
    }

    fn may_block(&mut self, task: TableId<GuestTask>) -> bool {
        let task = self.get_mut(task).unwrap();
        task.async_function || task.returned_or_cancelled()
    }
}

/// Provide a type hint to compiler about the shape of a parameter lower
/// closure.
fn for_any_lower<
    F: FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync,
>(
    fun: F,
) -> F {
    fun
}

/// Provide a type hint to compiler about the shape of a result lift closure.
fn for_any_lift<
    F: FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
>(
    fun: F,
) -> F {
    fun
}

/// Wrap the specified future in a `poll_fn` which asserts that the future is
/// only polled from the event loop of the specified `Store`.
///
/// See `StoreContextMut::run_concurrent` for details.
fn checked<F: Future + Send + 'static>(
    id: StoreId,
    fut: F,
) -> impl Future<Output = F::Output> + Send + 'static {
    async move {
        let mut fut = pin!(fut);
        future::poll_fn(move |cx| {
            let message = "\
                `Future`s which depend on asynchronous component tasks, streams, or \
                futures to complete may only be polled from the event loop of the \
                store to which they belong.  Please use \
                `StoreContextMut::{run_concurrent,spawn}` to poll or await them.\
            ";
            tls::try_get(|store| {
                let matched = match store {
                    tls::TryGet::Some(store) => store.id() == id,
                    tls::TryGet::Taken | tls::TryGet::None => false,
                };

                if !matched {
                    panic!("{message}")
                }
            });
            fut.as_mut().poll(cx)
        })
        .await
    }
}

/// Assert that `StoreContextMut::run_concurrent` has not been called from
/// within an store's event loop.
fn check_recursive_run() {
    tls::try_get(|store| {
        if !matches!(store, tls::TryGet::None) {
            panic!("Recursive `StoreContextMut::run_concurrent` calls not supported")
        }
    });
}

fn unpack_callback_code(code: u32) -> (u32, u32) {
    (code & 0xF, code >> 4)
}

/// Helper struct for packaging parameters to be passed to
/// `ComponentInstance::waitable_check` for calls to `waitable-set.wait` or
/// `waitable-set.poll`.
struct WaitableCheckParams {
    set: TableId<WaitableSet>,
    options: OptionsIndex,
    payload: u32,
}

/// Indicates whether `ComponentInstance::waitable_check` is being called for
/// `waitable-set.wait` or `waitable-set.poll`.
enum WaitableCheck {
    Wait,
    Poll,
}

/// Represents a guest task called from the host, prepared using `prepare_call`.
pub(crate) struct PreparedCall<R> {
    /// The guest export to be called
    handle: Func,
    /// The guest thread created by `prepare_call`
    thread: QualifiedThreadId,
    /// The number of lowered core Wasm parameters to pass to the call.
    param_count: usize,
    /// The `oneshot::Receiver` to which the result of the call will be
    /// delivered when it is available.
    rx: oneshot::Receiver<LiftedResult>,
    /// The `oneshot::Receiver` which will resolve when the task -- and any
    /// transitive subtasks -- have all exited.
    exit_rx: oneshot::Receiver<()>,
    _phantom: PhantomData<R>,
}

impl<R> PreparedCall<R> {
    /// Get a copy of the `TaskId` for this `PreparedCall`.
    pub(crate) fn task_id(&self) -> TaskId {
        TaskId {
            task: self.thread.task,
        }
    }
}

/// Represents a task created by `prepare_call`.
pub(crate) struct TaskId {
    task: TableId<GuestTask>,
}

impl TaskId {
    /// The host future for an async task was dropped. If the parameters have not been lowered yet,
    /// it is no longer valid to do so, as the lowering closure would see a dangling pointer. In this case,
    /// we delete the task eagerly. Otherwise, there may be running threads, or ones that are suspended
    /// and can be resumed by other tasks for this component, so we mark the future as dropped
    /// and delete the task when all threads are done.
    pub(crate) fn host_future_dropped<T>(&self, store: StoreContextMut<T>) -> Result<()> {
        let task = store.0.concurrent_state_mut().get_mut(self.task)?;
        if !task.already_lowered_parameters() {
            Waitable::Guest(self.task).delete_from(store.0.concurrent_state_mut())?
        } else {
            task.host_future_state = HostFutureState::Dropped;
            if task.ready_to_delete() {
                Waitable::Guest(self.task).delete_from(store.0.concurrent_state_mut())?
            }
        }
        Ok(())
    }
}

/// Prepare a call to the specified exported Wasm function, providing functions
/// for lowering the parameters and lifting the result.
///
/// To enqueue the returned `PreparedCall` in the `ComponentInstance`'s event
/// loop, use `queue_call`.
pub(crate) fn prepare_call<T, R>(
    mut store: StoreContextMut<T>,
    handle: Func,
    param_count: usize,
    host_future_present: bool,
    lower_params: impl FnOnce(Func, StoreContextMut<T>, &mut [MaybeUninit<ValRaw>]) -> Result<()>
    + Send
    + Sync
    + 'static,
    lift_result: impl FnOnce(Func, &mut StoreOpaque, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>>
    + Send
    + Sync
    + 'static,
) -> Result<PreparedCall<R>> {
    let (options, _flags, ty, raw_options) = handle.abi_info(store.0);

    let instance = handle.instance().id().get(store.0);
    let options = &instance.component().env_component().options[options];
    let ty = &instance.component().types()[ty];
    let async_function = ty.async_;
    let task_return_type = ty.results;
    let component_instance = raw_options.instance;
    let callback = options.callback.map(|i| instance.runtime_callback(i));
    let memory = options
        .memory()
        .map(|i| instance.runtime_memory(i))
        .map(SendSyncPtr::new);
    let string_encoding = options.string_encoding;
    let token = StoreToken::new(store.as_context_mut());
    let state = store.0.concurrent_state_mut();

    let (tx, rx) = oneshot::channel();
    let (exit_tx, exit_rx) = oneshot::channel();

    let caller = state.guest_thread;
    let mut task = GuestTask::new(
        state,
        Box::new(for_any_lower(move |store, params| {
            lower_params(handle, token.as_context_mut(store), params)
        })),
        LiftResult {
            lift: Box::new(for_any_lift(move |store, result| {
                lift_result(handle, store, result)
            })),
            ty: task_return_type,
            memory,
            string_encoding,
        },
        Caller::Host {
            tx: Some(tx),
            exit_tx: Arc::new(exit_tx),
            host_future_present,
            caller,
        },
        callback.map(|callback| {
            let callback = SendSyncPtr::new(callback);
            let instance = handle.instance();
            Box::new(move |store: &mut dyn VMStore, event, handle| {
                let store = token.as_context_mut(store);
                // SAFETY: Per the contract of `prepare_call`, the callback
                // will remain valid at least as long is this task exists.
                unsafe { instance.call_callback(store, callback, event, handle) }
            }) as CallbackFn
        }),
        RuntimeInstance {
            instance: handle.instance().id().instance(),
            index: component_instance,
        },
        async_function,
    )?;
    task.function_index = Some(handle.index());

    let task = state.push(task)?;
    let thread = state.push(GuestThread::new_implicit(task))?;
    state.get_mut(task)?.threads.insert(thread);

    if !store.0.may_enter_task(task) {
        bail!(crate::Trap::CannotEnterComponent);
    }

    Ok(PreparedCall {
        handle,
        thread: QualifiedThreadId { task, thread },
        param_count,
        rx,
        exit_rx,
        _phantom: PhantomData,
    })
}

/// Queue a call previously prepared using `prepare_call` to be run as part of
/// the associated `ComponentInstance`'s event loop.
///
/// The returned future will resolve to the result once it is available, but
/// must only be polled via the instance's event loop. See
/// `StoreContextMut::run_concurrent` for details.
pub(crate) fn queue_call<T: 'static, R: Send + 'static>(
    mut store: StoreContextMut<T>,
    prepared: PreparedCall<R>,
) -> Result<impl Future<Output = Result<(R, oneshot::Receiver<()>)>> + Send + 'static + use<T, R>> {
    let PreparedCall {
        handle,
        thread,
        param_count,
        rx,
        exit_rx,
        ..
    } = prepared;

    queue_call0(store.as_context_mut(), handle, thread, param_count)?;

    Ok(checked(
        store.0.id(),
        rx.map(move |result| {
            result
                .map(|v| (*v.downcast().unwrap(), exit_rx))
                .map_err(crate::Error::from)
        }),
    ))
}

/// Queue a call previously prepared using `prepare_call` to be run as part of
/// the associated `ComponentInstance`'s event loop.
fn queue_call0<T: 'static>(
    store: StoreContextMut<T>,
    handle: Func,
    guest_thread: QualifiedThreadId,
    param_count: usize,
) -> Result<()> {
    let (_options, _, _ty, raw_options) = handle.abi_info(store.0);
    let is_concurrent = raw_options.async_;
    let callback = raw_options.callback;
    let instance = handle.instance();
    let callee = handle.lifted_core_func(store.0);
    let post_return = handle.post_return_core_func(store.0);
    let callback = callback.map(|i| {
        let instance = instance.id().get(store.0);
        SendSyncPtr::new(instance.runtime_callback(i))
    });

    log::trace!("queueing call {guest_thread:?}");

    // SAFETY: `callee`, `callback`, and `post_return` are valid pointers
    // (with signatures appropriate for this call) and will remain valid as
    // long as this instance is valid.
    unsafe {
        instance.queue_call(
            store,
            guest_thread,
            SendSyncPtr::new(callee),
            param_count,
            1,
            is_concurrent,
            callback,
            post_return.map(SendSyncPtr::new),
        )
    }
}