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
//! Wasmtime's "store" type
//!
//! This module, and its submodules, contain the `Store` type and various types
//! used to interact with it. At first glance this is a pretty confusing module
//! where you need to know the difference between:
//!
//! * `Store<T>`
//! * `StoreContext<T>`
//! * `StoreContextMut<T>`
//! * `AsContext`
//! * `AsContextMut`
//! * `StoreInner<T>`
//! * `StoreOpaque`
//! * `StoreData`
//!
//! There's... quite a lot going on here, and it's easy to be confused. This
//! comment is ideally going to serve the purpose of clarifying what all these
//! types are for and why they're motivated.
//!
//! First it's important to know what's "internal" and what's "external". Almost
//! everything above is defined as `pub`, but only some of the items are
//! reexported to the outside world to be usable from this crate. Otherwise all
//! items are `pub` within this `store` module, and the `store` module is
//! private to the `wasmtime` crate. Notably `Store<T>`, `StoreContext<T>`,
//! `StoreContextMut<T>`, `AsContext`, and `AsContextMut` are all public
//! interfaces to the `wasmtime` crate. You can think of these as:
//!
//! * `Store<T>` - an owned reference to a store, the "root of everything"
//! * `StoreContext<T>` - basically `&StoreInner<T>`
//! * `StoreContextMut<T>` - more-or-less `&mut StoreInner<T>` with caveats.
//!   Explained later.
//! * `AsContext` - similar to `AsRef`, but produces `StoreContext<T>`
//! * `AsContextMut` - similar to `AsMut`, but produces `StoreContextMut<T>`
//!
//! Next comes the internal structure of the `Store<T>` itself. This looks like:
//!
//! * `Store<T>` - this type is just a pointer large. It's primarily just
//!   intended to be consumed by the outside world. Note that the "just a
//!   pointer large" is a load-bearing implementation detail in Wasmtime. This
//!   enables it to store a pointer to its own trait object which doesn't need
//!   to change over time.
//!
//! * `StoreInner<T>` - the first layer of the contents of a `Store<T>`, what's
//!   stored inside the `Box`. This is the general Rust pattern when one struct
//!   is a layer over another. The surprising part, though, is that this is
//!   further subdivided. This structure only contains things which actually
//!   need `T` itself. The downside of this structure is that it's always
//!   generic and means that code is monomorphized into consumer crates. We
//!   strive to have things be as monomorphic as possible in `wasmtime` so this
//!   type is not heavily used.
//!
//! * `StoreOpaque` - this is the primary contents of the `StoreInner<T>` type.
//!   Stored inline in the outer type the "opaque" here means that it's a
//!   "store" but it doesn't have access to the `T`. This is the primary
//!   "internal" reference that Wasmtime uses since `T` is rarely needed by the
//!   internals of Wasmtime.
//!
//! * `StoreData` - this is a final helper struct stored within `StoreOpaque`.
//!   All references of Wasm items into a `Store` are actually indices into a
//!   table in this structure, and the `StoreData` being separate makes it a bit
//!   easier to manage/define/work with. There's no real fundamental reason this
//!   is split out, although sometimes it's useful to have separate borrows into
//!   these tables than the `StoreOpaque`.
//!
//! A major caveat with these representations is that the internal `&mut
//! StoreInner<T>` is never handed out publicly to consumers of this crate, only
//! through a wrapper of `StoreContextMut<'_, T>`. The reason for this is that
//! we want to provide mutable, but not destructive, access to the contents of a
//! `Store`. For example if a `StoreInner<T>` were replaced with some other
//! `StoreInner<T>` then that would drop live instances, possibly those
//! currently executing beneath the current stack frame. This would not be a
//! safe operation.
//!
//! This means, though, that the `wasmtime` crate, which liberally uses `&mut
//! StoreOpaque` internally, has to be careful to never actually destroy the
//! contents of `StoreOpaque`. This is an invariant that we, as the authors of
//! `wasmtime`, must uphold for the public interface to be safe.

#[cfg(all(feature = "gc", feature = "debug"))]
use crate::OwnedRooted;
use crate::RootSet;
#[cfg(feature = "gc")]
use crate::ThrownException;
#[cfg(feature = "component-model-async")]
use crate::component::ComponentStoreData;
#[cfg(feature = "component-model")]
use crate::component::concurrent;
use crate::error::OutOfMemory;
#[cfg(feature = "async")]
use crate::fiber;
use crate::module::RegisteredModuleId;
use crate::prelude::*;
#[cfg(feature = "gc")]
use crate::runtime::vm::GcRootsList;
#[cfg(feature = "stack-switching")]
use crate::runtime::vm::VMContRef;
use crate::runtime::vm::mpk::ProtectionKey;
use crate::runtime::vm::{
    self, ExportMemory, GcStore, Imports, InstanceAllocationRequest, InstanceAllocator,
    InstanceHandle, Interpreter, InterpreterRef, ModuleRuntimeInfo, OnDemandInstanceAllocator,
    SendSyncPtr, SignalHandler, StoreBox, Unwind, VMContext, VMFuncRef, VMGcRef, VMStore,
    VMStoreContext,
};
use crate::trampoline::VMHostGlobalContext;
#[cfg(feature = "debug")]
use crate::{BreakpointState, DebugHandler};
use crate::{Engine, Module, Val, ValRaw, module::ModuleRegistry};
#[cfg(feature = "gc")]
use crate::{ExnRef, Rooted};
use crate::{Global, Instance, Table};
use core::convert::Infallible;
use core::fmt;
use core::marker;
use core::mem::{self, ManuallyDrop, MaybeUninit};
use core::num::NonZeroU64;
use core::ops::{Deref, DerefMut};
use core::pin::Pin;
use core::ptr::NonNull;
use wasmtime_environ::{DefinedGlobalIndex, DefinedTableIndex, EntityRef, PrimaryMap, TripleExt};

mod context;
pub use self::context::*;
mod data;
pub use self::data::*;
mod func_refs;
use func_refs::FuncRefs;
#[cfg(feature = "component-model-async")]
mod token;
#[cfg(feature = "component-model-async")]
pub(crate) use token::StoreToken;
#[cfg(feature = "async")]
mod async_;
#[cfg(all(feature = "async", feature = "call-hook"))]
pub use self::async_::CallHookHandler;

#[cfg(feature = "gc")]
use super::vm::VMExnRef;
#[cfg(feature = "gc")]
mod gc;

/// A [`Store`] is a collection of WebAssembly instances and host-defined state.
///
/// All WebAssembly instances and items will be attached to and refer to a
/// [`Store`]. For example instances, functions, globals, and tables are all
/// attached to a [`Store`]. Instances are created by instantiating a
/// [`Module`](crate::Module) within a [`Store`].
///
/// A [`Store`] is intended to be a short-lived object in a program. No form
/// of GC is implemented at this time so once an instance is created within a
/// [`Store`] it will not be deallocated until the [`Store`] itself is dropped.
/// This makes [`Store`] unsuitable for creating an unbounded number of
/// instances in it because [`Store`] will never release this memory. It's
/// recommended to have a [`Store`] correspond roughly to the lifetime of a
/// "main instance" that an embedding is interested in executing.
///
/// ## Type parameter `T`
///
/// Each [`Store`] has a type parameter `T` associated with it. This `T`
/// represents state defined by the host. This state will be accessible through
/// the [`Caller`](crate::Caller) type that host-defined functions get access
/// to. This `T` is suitable for storing `Store`-specific information which
/// imported functions may want access to.
///
/// The data `T` can be accessed through methods like [`Store::data`] and
/// [`Store::data_mut`].
///
/// ## Stores, contexts, oh my
///
/// Most methods in Wasmtime take something of the form
/// [`AsContext`](crate::AsContext) or [`AsContextMut`](crate::AsContextMut) as
/// the first argument. These two traits allow ergonomically passing in the
/// context you currently have to any method. The primary two sources of
/// contexts are:
///
/// * `Store<T>`
/// * `Caller<'_, T>`
///
/// corresponding to what you create and what you have access to in a host
/// function. You can also explicitly acquire a [`StoreContext`] or
/// [`StoreContextMut`] and pass that around as well.
///
/// Note that all methods on [`Store`] are mirrored onto [`StoreContext`],
/// [`StoreContextMut`], and [`Caller`](crate::Caller). This way no matter what
/// form of context you have you can call various methods, create objects, etc.
///
/// ## Stores and `Default`
///
/// You can create a store with default configuration settings using
/// `Store::default()`. This will create a brand new [`Engine`] with default
/// configuration (see [`Config`](crate::Config) for more information).
///
/// ## Cross-store usage of items
///
/// In `wasmtime` wasm items such as [`Global`] and [`Memory`] "belong" to a
/// [`Store`]. The store they belong to is the one they were created with
/// (passed in as a parameter) or instantiated with. This store is the only
/// store that can be used to interact with wasm items after they're created.
///
/// The `wasmtime` crate will panic if the [`Store`] argument passed in to these
/// operations is incorrect. In other words it's considered a programmer error
/// rather than a recoverable error for the wrong [`Store`] to be used when
/// calling APIs.
///
/// [`Memory`]: crate::Memory
pub struct Store<T: 'static> {
    // for comments about `ManuallyDrop`, see `Store::into_data`
    inner: ManuallyDrop<Box<StoreInner<T>>>,
}

#[derive(Copy, Clone, Debug)]
/// Passed to the argument of [`Store::call_hook`] to indicate a state transition in
/// the WebAssembly VM.
pub enum CallHook {
    /// Indicates the VM is calling a WebAssembly function, from the host.
    CallingWasm,
    /// Indicates the VM is returning from a WebAssembly function, to the host.
    ReturningFromWasm,
    /// Indicates the VM is calling a host function, from WebAssembly.
    CallingHost,
    /// Indicates the VM is returning from a host function, to WebAssembly.
    ReturningFromHost,
}

impl CallHook {
    /// Indicates the VM is entering host code (exiting WebAssembly code)
    pub fn entering_host(&self) -> bool {
        match self {
            CallHook::ReturningFromWasm | CallHook::CallingHost => true,
            _ => false,
        }
    }
    /// Indicates the VM is exiting host code (entering WebAssembly code)
    pub fn exiting_host(&self) -> bool {
        match self {
            CallHook::ReturningFromHost | CallHook::CallingWasm => true,
            _ => false,
        }
    }
}

/// Internal contents of a `Store<T>` that live on the heap.
///
/// The members of this struct are those that need to be generic over `T`, the
/// store's internal type storage. Otherwise all things that don't rely on `T`
/// should go into `StoreOpaque`.
pub struct StoreInner<T: 'static> {
    /// Generic metadata about the store that doesn't need access to `T`.
    inner: StoreOpaque,

    limiter: Option<ResourceLimiterInner<T>>,
    call_hook: Option<CallHookInner<T>>,
    #[cfg(target_has_atomic = "64")]
    epoch_deadline_behavior:
        Option<Box<dyn FnMut(StoreContextMut<T>) -> Result<UpdateDeadline> + Send + Sync>>,

    /// The user's `T` data.
    ///
    /// Don't actually access it via this field, however! Use the
    /// `Store{,Inner,Context,ContextMut}::data[_mut]` methods instead, to
    /// preserve stacked borrows and provenance in the face of potential
    /// direct-access of `T` from Wasm code (via unsafe intrinsics).
    ///
    /// The only exception to the above is when taking ownership of the value,
    /// e.g. in `Store::into_data`, after which nothing can access this field
    /// via raw pointers anymore so there is no more provenance to preserve.
    ///
    /// For comments about `ManuallyDrop`, see `Store::into_data`.
    data_no_provenance: ManuallyDrop<T>,

    /// The user's debug handler, if any. See [`crate::DebugHandler`]
    /// for more documentation.
    ///
    /// We need this to be an `Arc` because the handler itself takes
    /// `&self` and also the whole Store mutably (via
    /// `StoreContextMut`); so we need to hold a separate reference to
    /// it while invoking it.
    #[cfg(feature = "debug")]
    debug_handler: Option<Box<dyn StoreDebugHandler<T>>>,
}

/// Adapter around `DebugHandler` that gets monomorphized into an
/// object-safe dyn trait to place in `store.debug_handler`.
#[cfg(feature = "debug")]
trait StoreDebugHandler<T: 'static>: Send + Sync {
    fn handle<'a>(
        self: Box<Self>,
        store: StoreContextMut<'a, T>,
        event: crate::DebugEvent<'a>,
    ) -> Box<dyn Future<Output = ()> + Send + 'a>;
}

#[cfg(feature = "debug")]
impl<D> StoreDebugHandler<D::Data> for D
where
    D: DebugHandler,
    D::Data: Send,
{
    fn handle<'a>(
        self: Box<Self>,
        store: StoreContextMut<'a, D::Data>,
        event: crate::DebugEvent<'a>,
    ) -> Box<dyn Future<Output = ()> + Send + 'a> {
        // Clone the underlying `DebugHandler` (the trait requires
        // Clone as a supertrait), not the Box. The clone happens here
        // rather than at the callsite because `Clone::clone` is not
        // object-safe so needs to be in a monomorphized context.
        let handler: D = (*self).clone();
        // Since we temporarily took `self` off the store at the
        // callsite, put it back now that we've cloned it.
        store.0.debug_handler = Some(self);
        Box::new(async move { handler.handle(store, event).await })
    }
}

enum ResourceLimiterInner<T> {
    Sync(Box<dyn (FnMut(&mut T) -> &mut dyn crate::ResourceLimiter) + Send + Sync>),
    #[cfg(feature = "async")]
    Async(Box<dyn (FnMut(&mut T) -> &mut dyn crate::ResourceLimiterAsync) + Send + Sync>),
}

/// Representation of a configured resource limiter for a store.
///
/// This is acquired with `resource_limiter_and_store_opaque` for example and is
/// threaded through to growth operations on tables/memories. Note that this is
/// passed around as `Option<&mut StoreResourceLimiter<'_>>` to make it
/// efficient to pass around (nullable pointer) and it's also notably passed
/// around as an `Option` to represent how this is optionally specified within a
/// store.
pub enum StoreResourceLimiter<'a> {
    Sync(&'a mut dyn crate::ResourceLimiter),
    #[cfg(feature = "async")]
    Async(&'a mut dyn crate::ResourceLimiterAsync),
}

impl StoreResourceLimiter<'_> {
    pub(crate) async fn memory_growing(
        &mut self,
        current: usize,
        desired: usize,
        maximum: Option<usize>,
    ) -> Result<bool, Error> {
        match self {
            Self::Sync(s) => s.memory_growing(current, desired, maximum),
            #[cfg(feature = "async")]
            Self::Async(s) => s.memory_growing(current, desired, maximum).await,
        }
    }

    pub(crate) fn memory_grow_failed(&mut self, error: crate::Error) -> Result<()> {
        match self {
            Self::Sync(s) => s.memory_grow_failed(error),
            #[cfg(feature = "async")]
            Self::Async(s) => s.memory_grow_failed(error),
        }
    }

    pub(crate) async fn table_growing(
        &mut self,
        current: usize,
        desired: usize,
        maximum: Option<usize>,
    ) -> Result<bool, Error> {
        match self {
            Self::Sync(s) => s.table_growing(current, desired, maximum),
            #[cfg(feature = "async")]
            Self::Async(s) => s.table_growing(current, desired, maximum).await,
        }
    }

    pub(crate) fn table_grow_failed(&mut self, error: crate::Error) -> Result<()> {
        match self {
            Self::Sync(s) => s.table_grow_failed(error),
            #[cfg(feature = "async")]
            Self::Async(s) => s.table_grow_failed(error),
        }
    }
}

enum CallHookInner<T: 'static> {
    #[cfg(feature = "call-hook")]
    Sync(Box<dyn FnMut(StoreContextMut<'_, T>, CallHook) -> Result<()> + Send + Sync>),
    #[cfg(all(feature = "async", feature = "call-hook"))]
    Async(Box<dyn CallHookHandler<T> + Send + Sync>),
    #[expect(
        dead_code,
        reason = "forcing, regardless of cfg, the type param to be used"
    )]
    ForceTypeParameterToBeUsed {
        uninhabited: Infallible,
        _marker: marker::PhantomData<T>,
    },
}

/// What to do after returning from a callback when the engine epoch reaches
/// the deadline for a Store during execution of a function using that store.
#[non_exhaustive]
pub enum UpdateDeadline {
    /// Halt execution of WebAssembly, don't update the epoch deadline, and
    /// raise a trap.
    Interrupt,
    /// Extend the deadline by the specified number of ticks.
    Continue(u64),
    /// Extend the deadline by the specified number of ticks after yielding to
    /// the async executor loop.
    ///
    /// This can only be used when WebAssembly is invoked with `*_async`
    /// methods. If WebAssembly was invoked with a synchronous method then
    /// returning this variant will raise a trap.
    #[cfg(feature = "async")]
    Yield(u64),
    /// Extend the deadline by the specified number of ticks after yielding to
    /// the async executor loop.
    ///
    /// This can only be used when WebAssembly is invoked with `*_async`
    /// methods. If WebAssembly was invoked with a synchronous method then
    /// returning this variant will raise a trap.
    ///
    /// The yield will be performed by the future provided; when using `tokio`
    /// it is recommended to provide [`tokio::task::yield_now`](https://docs.rs/tokio/latest/tokio/task/fn.yield_now.html)
    /// here.
    #[cfg(feature = "async")]
    YieldCustom(
        u64,
        ::core::pin::Pin<Box<dyn ::core::future::Future<Output = ()> + Send>>,
    ),
}

// Forward methods on `StoreOpaque` to also being on `StoreInner<T>`
impl<T> Deref for StoreInner<T> {
    type Target = StoreOpaque;
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<T> DerefMut for StoreInner<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

/// Monomorphic storage for a `Store<T>`.
///
/// This structure contains the bulk of the metadata about a `Store`. This is
/// used internally in Wasmtime when dependence on the `T` of `Store<T>` isn't
/// necessary, allowing code to be monomorphic and compiled into the `wasmtime`
/// crate itself.
pub struct StoreOpaque {
    // This `StoreOpaque` structure has references to itself. These aren't
    // immediately evident, however, so we need to tell the compiler that it
    // contains self-references. This notably suppresses `noalias` annotations
    // when this shows up in compiled code because types of this structure do
    // indeed alias itself. An example of this is `default_callee` holds a
    // `*mut dyn Store` to the address of this `StoreOpaque` itself, indeed
    // aliasing!
    //
    // It's somewhat unclear to me at this time if this is 100% sufficient to
    // get all the right codegen in all the right places. For example does
    // `Store` need to internally contain a `Pin<Box<StoreInner<T>>>`? Do the
    // contexts need to contain `Pin<&mut StoreInner<T>>`? I'm not familiar
    // enough with `Pin` to understand if it's appropriate here (we do, for
    // example want to allow movement in and out of `data: T`, just not movement
    // of most of the other members). It's also not clear if using `Pin` in a
    // few places buys us much other than a bunch of `unsafe` that we already
    // sort of hand-wave away.
    //
    // In any case this seems like a good mid-ground for now where we're at
    // least telling the compiler something about all the aliasing happening
    // within a `Store`.
    _marker: marker::PhantomPinned,

    engine: Engine,
    vm_store_context: VMStoreContext,

    // Contains all continuations ever allocated throughout the lifetime of this
    // store.
    #[cfg(feature = "stack-switching")]
    continuations: Vec<Box<VMContRef>>,

    instances: wasmtime_environ::collections::PrimaryMap<InstanceId, StoreInstance>,

    #[cfg(feature = "component-model")]
    num_component_instances: usize,
    signal_handler: Option<SignalHandler>,
    modules: ModuleRegistry,
    func_refs: FuncRefs,
    host_globals: PrimaryMap<DefinedGlobalIndex, StoreBox<VMHostGlobalContext>>,
    // GC-related fields.
    gc_store: Option<GcStore>,
    gc_roots: RootSet,
    #[cfg(feature = "gc")]
    gc_roots_list: GcRootsList,
    // Types for which the embedder has created an allocator for.
    #[cfg(feature = "gc")]
    gc_host_alloc_types: crate::hash_set::HashSet<crate::type_registry::RegisteredType>,
    /// Pending exception, if any. This is also a GC root, because it
    /// needs to be rooted somewhere between the time that a pending
    /// exception is set and the time that the handling code takes the
    /// exception object. We use this rooting strategy rather than a
    /// root in an `Err` branch of a `Result` on the host side because
    /// it is less error-prone with respect to rooting behavior. See
    /// `throw()`, `take_pending_exception()`,
    /// `peek_pending_exception()`, `has_pending_exception()`, and
    /// `catch()`.
    #[cfg(feature = "gc")]
    pending_exception: Option<VMExnRef>,

    // Numbers of resources instantiated in this store, and their limits
    instance_count: usize,
    instance_limit: usize,
    memory_count: usize,
    memory_limit: usize,
    table_count: usize,
    table_limit: usize,
    #[cfg(feature = "async")]
    async_state: fiber::AsyncState,

    // If fuel_yield_interval is enabled, then we store the remaining fuel (that isn't in
    // runtime_limits) here. The total amount of fuel is the runtime limits and reserve added
    // together. Then when we run out of gas, we inject the yield amount from the reserve
    // until the reserve is empty.
    fuel_reserve: u64,
    pub(crate) fuel_yield_interval: Option<NonZeroU64>,
    /// Indexed data within this `Store`, used to store information about
    /// globals, functions, memories, etc.
    store_data: StoreData,
    traitobj: StorePtr,
    default_caller_vmctx: SendSyncPtr<VMContext>,

    /// Used to optimized wasm->host calls when the host function is defined with
    /// `Func::new` to avoid allocating a new vector each time a function is
    /// called.
    hostcall_val_storage: Vec<Val>,
    /// Same as `hostcall_val_storage`, but for the direction of the host
    /// calling wasm.
    wasm_val_raw_storage: Vec<ValRaw>,

    /// Keep track of what protection key is being used during allocation so
    /// that the right memory pages can be enabled when entering WebAssembly
    /// guest code.
    pkey: Option<ProtectionKey>,

    /// Runtime state for components used in the handling of resources, borrow,
    /// and calls. These also interact with the `ResourceAny` type and its
    /// internal representation.
    #[cfg(feature = "component-model")]
    component_host_table: vm::component::HandleTable,
    #[cfg(feature = "component-model")]
    component_calls: vm::component::CallContexts,
    #[cfg(feature = "component-model")]
    host_resource_data: crate::component::HostResourceData,
    #[cfg(feature = "component-model")]
    concurrent_state: Option<concurrent::ConcurrentState>,

    /// State related to the executor of wasm code.
    ///
    /// For example if Pulley is enabled and configured then this will store a
    /// Pulley interpreter.
    executor: Executor,

    /// The debug breakpoint state for this store.
    ///
    /// When guest debugging is enabled, a given store may have a set
    /// of breakpoints defined, denoted by module and Wasm PC within
    /// that module. Or alternately, it may be in "single-step" mode,
    /// where every possible breakpoint is logically enabled.
    ///
    /// When execution of any instance in this store hits any defined
    /// breakpoint, a `Breakpoint` debug event is emitted and the
    /// handler defined above, if any, has a chance to perform some
    /// logic before returning to allow execution to resume.
    #[cfg(feature = "debug")]
    breakpoints: BreakpointState,
}

/// Self-pointer to `StoreInner<T>` from within a `StoreOpaque` which is chiefly
/// used to copy into instances during instantiation.
///
/// FIXME: ideally this type would get deleted and Wasmtime's reliance on it
/// would go away.
struct StorePtr(Option<NonNull<dyn VMStore>>);

// We can't make `VMStore: Send + Sync` because that requires making all of
// Wastime's internals generic over the `Store`'s `T`. So instead, we take care
// in the whole VM layer to only use the `VMStore` in ways that are `Send`- and
// `Sync`-safe and we have to have these unsafe impls.
unsafe impl Send for StorePtr {}
unsafe impl Sync for StorePtr {}

/// Executor state within `StoreOpaque`.
///
/// Effectively stores Pulley interpreter state and handles conditional support
/// for Cranelift at compile time.
pub(crate) enum Executor {
    Interpreter(Interpreter),
    #[cfg(has_host_compiler_backend)]
    Native,
}

impl Executor {
    pub(crate) fn new(engine: &Engine) -> Self {
        #[cfg(has_host_compiler_backend)]
        if cfg!(feature = "pulley") && engine.target().is_pulley() {
            Executor::Interpreter(Interpreter::new(engine))
        } else {
            Executor::Native
        }
        #[cfg(not(has_host_compiler_backend))]
        {
            debug_assert!(engine.target().is_pulley());
            Executor::Interpreter(Interpreter::new(engine))
        }
    }
}

/// A borrowed reference to `Executor` above.
pub(crate) enum ExecutorRef<'a> {
    Interpreter(InterpreterRef<'a>),
    #[cfg(has_host_compiler_backend)]
    Native,
}

/// An RAII type to automatically mark a region of code as unsafe for GC.
#[doc(hidden)]
pub struct AutoAssertNoGc<'a> {
    store: &'a mut StoreOpaque,
    entered: bool,
}

impl<'a> AutoAssertNoGc<'a> {
    #[inline]
    pub fn new(store: &'a mut StoreOpaque) -> Self {
        let entered = if !cfg!(feature = "gc") {
            false
        } else if let Some(gc_store) = store.gc_store.as_mut() {
            gc_store.gc_heap.enter_no_gc_scope();
            true
        } else {
            false
        };

        AutoAssertNoGc { store, entered }
    }

    /// Creates an `AutoAssertNoGc` value which is forcibly "not entered" and
    /// disables checks for no GC happening for the duration of this value.
    ///
    /// This is used when it is statically otherwise known that a GC doesn't
    /// happen for the various types involved.
    ///
    /// # Unsafety
    ///
    /// This method is `unsafe` as it does not provide the same safety
    /// guarantees as `AutoAssertNoGc::new`. It must be guaranteed by the
    /// caller that a GC doesn't happen.
    #[inline]
    pub unsafe fn disabled(store: &'a mut StoreOpaque) -> Self {
        if cfg!(debug_assertions) {
            AutoAssertNoGc::new(store)
        } else {
            AutoAssertNoGc {
                store,
                entered: false,
            }
        }
    }
}

impl core::ops::Deref for AutoAssertNoGc<'_> {
    type Target = StoreOpaque;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &*self.store
    }
}

impl core::ops::DerefMut for AutoAssertNoGc<'_> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut *self.store
    }
}

impl Drop for AutoAssertNoGc<'_> {
    #[inline]
    fn drop(&mut self) {
        if self.entered {
            self.store.unwrap_gc_store_mut().gc_heap.exit_no_gc_scope();
        }
    }
}

/// Used to associate instances with the store.
///
/// This is needed to track if the instance was allocated explicitly with the on-demand
/// instance allocator.
struct StoreInstance {
    handle: InstanceHandle,
    kind: StoreInstanceKind,
}

enum StoreInstanceKind {
    /// An actual, non-dummy instance.
    Real {
        /// The id of this instance's module inside our owning store's
        /// `ModuleRegistry`.
        module_id: RegisteredModuleId,
    },

    /// This is a dummy instance that is just an implementation detail for
    /// something else. For example, host-created memories internally create a
    /// dummy instance.
    ///
    /// Regardless of the configured instance allocator for the engine, dummy
    /// instances always use the on-demand allocator to deallocate the instance.
    Dummy,
}

impl<T> Store<T> {
    /// Creates a new [`Store`] to be associated with the given [`Engine`] and
    /// `data` provided.
    ///
    /// The created [`Store`] will place no additional limits on the size of
    /// linear memories or tables at runtime. Linear memories and tables will
    /// be allowed to grow to any upper limit specified in their definitions.
    /// The store will limit the number of instances, linear memories, and
    /// tables created to 10,000. This can be overridden with the
    /// [`Store::limiter`] configuration method.
    pub fn new(engine: &Engine, data: T) -> Self {
        Self::try_new(engine, data).expect(
            "allocation failure during `Store::new` (use `Store::try_new` to handle such errors)",
        )
    }

    /// Like `Store::new` but returns an error on allocation failure.
    pub fn try_new(engine: &Engine, data: T) -> Result<Self> {
        let store_data = StoreData::new();
        log::trace!("creating new store {:?}", store_data.id());

        let pkey = engine.allocator().next_available_pkey();

        let inner = StoreOpaque {
            _marker: marker::PhantomPinned,
            engine: engine.clone(),
            vm_store_context: Default::default(),
            #[cfg(feature = "stack-switching")]
            continuations: Vec::new(),
            instances: wasmtime_environ::collections::PrimaryMap::new(),
            #[cfg(feature = "component-model")]
            num_component_instances: 0,
            signal_handler: None,
            gc_store: None,
            gc_roots: RootSet::default(),
            #[cfg(feature = "gc")]
            gc_roots_list: GcRootsList::default(),
            #[cfg(feature = "gc")]
            gc_host_alloc_types: Default::default(),
            #[cfg(feature = "gc")]
            pending_exception: None,
            modules: ModuleRegistry::default(),
            func_refs: FuncRefs::default(),
            host_globals: PrimaryMap::new(),
            instance_count: 0,
            instance_limit: crate::DEFAULT_INSTANCE_LIMIT,
            memory_count: 0,
            memory_limit: crate::DEFAULT_MEMORY_LIMIT,
            table_count: 0,
            table_limit: crate::DEFAULT_TABLE_LIMIT,
            #[cfg(feature = "async")]
            async_state: Default::default(),
            fuel_reserve: 0,
            fuel_yield_interval: None,
            store_data,
            traitobj: StorePtr(None),
            default_caller_vmctx: SendSyncPtr::new(NonNull::dangling()),
            hostcall_val_storage: Vec::new(),
            wasm_val_raw_storage: Vec::new(),
            pkey,
            #[cfg(feature = "component-model")]
            component_host_table: Default::default(),
            #[cfg(feature = "component-model")]
            component_calls: Default::default(),
            #[cfg(feature = "component-model")]
            host_resource_data: Default::default(),
            executor: Executor::new(engine),
            #[cfg(feature = "component-model")]
            concurrent_state: if engine.tunables().concurrency_support {
                #[cfg(feature = "component-model-async")]
                {
                    Some(Default::default())
                }
                #[cfg(not(feature = "component-model-async"))]
                {
                    unreachable!()
                }
            } else {
                None
            },
            #[cfg(feature = "debug")]
            breakpoints: Default::default(),
        };
        let mut inner = try_new::<Box<_>>(StoreInner {
            inner,
            limiter: None,
            call_hook: None,
            #[cfg(target_has_atomic = "64")]
            epoch_deadline_behavior: None,
            data_no_provenance: ManuallyDrop::new(data),
            #[cfg(feature = "debug")]
            debug_handler: None,
        })?;

        let store_data =
            <NonNull<ManuallyDrop<T>>>::from(&mut inner.data_no_provenance).cast::<()>();
        inner.inner.vm_store_context.store_data = store_data.into();

        inner.traitobj = StorePtr(Some(NonNull::from(&mut *inner)));

        // Wasmtime uses the callee argument to host functions to learn about
        // the original pointer to the `Store` itself, allowing it to
        // reconstruct a `StoreContextMut<T>`. When we initially call a `Func`,
        // however, there's no "callee" to provide. To fix this we allocate a
        // single "default callee" for the entire `Store`. This is then used as
        // part of `Func::call` to guarantee that the `callee: *mut VMContext`
        // is never null.
        let allocator = OnDemandInstanceAllocator::default();
        let info = engine.empty_module_runtime_info();
        allocator
            .validate_module(info.env_module(), info.offsets())
            .unwrap();

        unsafe {
            // Note that this dummy instance doesn't allocate tables or memories
            // (also no limiter is passed in) so it won't have an async await
            // point meaning that it should be ok to assert the future is
            // always ready.
            let result = vm::assert_ready(inner.allocate_instance(
                None,
                AllocateInstanceKind::Dummy {
                    allocator: &allocator,
                },
                info,
                Default::default(),
            ));
            let id = match result {
                Ok(id) => id,
                Err(e) => {
                    if e.is::<OutOfMemory>() {
                        return Err(e);
                    }
                    panic!("instance allocator failed to allocate default callee")
                }
            };
            let default_caller_vmctx = inner.instance(id).vmctx();
            inner.default_caller_vmctx = default_caller_vmctx.into();
        }

        Ok(Self {
            inner: ManuallyDrop::new(inner),
        })
    }

    /// Access the underlying `T` data owned by this `Store`.
    #[inline]
    pub fn data(&self) -> &T {
        self.inner.data()
    }

    /// Access the underlying `T` data owned by this `Store`.
    #[inline]
    pub fn data_mut(&mut self) -> &mut T {
        self.inner.data_mut()
    }

    fn run_manual_drop_routines(&mut self) {
        // We need to drop the fibers of each component instance before
        // attempting to drop the instances themselves since the fibers may need
        // to be resumed and allowed to exit cleanly before we yank the state
        // out from under them.
        //
        // This will also drop any futures which might use a `&Accessor` fields
        // in their `Drop::drop` implementations, in which case they'll need to
        // be called from with in the context of a `tls::set` closure.
        #[cfg(feature = "component-model-async")]
        if self.inner.concurrent_state.is_some() {
            ComponentStoreData::drop_fibers_and_futures(&mut **self.inner);
        }

        // Ensure all fiber stacks, even cached ones, are all flushed out to the
        // instance allocator.
        self.inner.flush_fiber_stack();
    }

    /// Consumes this [`Store`], destroying it, and returns the underlying data.
    pub fn into_data(mut self) -> T {
        self.run_manual_drop_routines();

        // This is an unsafe operation because we want to avoid having a runtime
        // check or boolean for whether the data is actually contained within a
        // `Store`. The data itself is stored as `ManuallyDrop` since we're
        // manually managing the memory here, and there's also a `ManuallyDrop`
        // around the `Box<StoreInner<T>>`. The way this works though is a bit
        // tricky, so here's how things get dropped appropriately:
        //
        // * When a `Store<T>` is normally dropped, the custom destructor for
        //   `Store<T>` will drop `T`, then the `self.inner` field. The
        //   rustc-glue destructor runs for `Box<StoreInner<T>>` which drops
        //   `StoreInner<T>`. This cleans up all internal fields and doesn't
        //   touch `T` because it's wrapped in `ManuallyDrop`.
        //
        // * When calling this method we skip the top-level destructor for
        //   `Store<T>` with `mem::forget`. This skips both the destructor for
        //   `T` and the destructor for `StoreInner<T>`. We do, however, run the
        //   destructor for `Box<StoreInner<T>>` which, like above, will skip
        //   the destructor for `T` since it's `ManuallyDrop`.
        //
        // In both cases all the other fields of `StoreInner<T>` should all get
        // dropped, and the manual management of destructors is basically
        // between this method and `Drop for Store<T>`. Note that this also
        // means that `Drop for StoreInner<T>` cannot access `self.data`, so
        // there is a comment indicating this as well.
        unsafe {
            let mut inner = ManuallyDrop::take(&mut self.inner);
            core::mem::forget(self);
            ManuallyDrop::take(&mut inner.data_no_provenance)
        }
    }

    /// Configures the [`ResourceLimiter`] used to limit resource creation
    /// within this [`Store`].
    ///
    /// Whenever resources such as linear memory, tables, or instances are
    /// allocated the `limiter` specified here is invoked with the store's data
    /// `T` and the returned [`ResourceLimiter`] is used to limit the operation
    /// being allocated. The returned [`ResourceLimiter`] is intended to live
    /// within the `T` itself, for example by storing a
    /// [`StoreLimits`](crate::StoreLimits).
    ///
    /// Note that this limiter is only used to limit the creation/growth of
    /// resources in the future, this does not retroactively attempt to apply
    /// limits to the [`Store`].
    ///
    /// # Examples
    ///
    /// ```
    /// use wasmtime::*;
    ///
    /// struct MyApplicationState {
    ///     my_state: u32,
    ///     limits: StoreLimits,
    /// }
    ///
    /// let engine = Engine::default();
    /// let my_state = MyApplicationState {
    ///     my_state: 42,
    ///     limits: StoreLimitsBuilder::new()
    ///         .memory_size(1 << 20 /* 1 MB */)
    ///         .instances(2)
    ///         .build(),
    /// };
    /// let mut store = Store::new(&engine, my_state);
    /// store.limiter(|state| &mut state.limits);
    ///
    /// // Creation of smaller memories is allowed
    /// Memory::new(&mut store, MemoryType::new(1, None)).unwrap();
    ///
    /// // Creation of a larger memory, however, will exceed the 1MB limit we've
    /// // configured
    /// assert!(Memory::new(&mut store, MemoryType::new(1000, None)).is_err());
    ///
    /// // The number of instances in this store is limited to 2, so the third
    /// // instance here should fail.
    /// let module = Module::new(&engine, "(module)").unwrap();
    /// assert!(Instance::new(&mut store, &module, &[]).is_ok());
    /// assert!(Instance::new(&mut store, &module, &[]).is_ok());
    /// assert!(Instance::new(&mut store, &module, &[]).is_err());
    /// ```
    ///
    /// [`ResourceLimiter`]: crate::ResourceLimiter
    pub fn limiter(
        &mut self,
        mut limiter: impl (FnMut(&mut T) -> &mut dyn crate::ResourceLimiter) + Send + Sync + 'static,
    ) {
        // Apply the limits on instances, tables, and memory given by the limiter:
        let inner = &mut self.inner;
        let (instance_limit, table_limit, memory_limit) = {
            let l = limiter(inner.data_mut());
            (l.instances(), l.tables(), l.memories())
        };
        let innermost = &mut inner.inner;
        innermost.instance_limit = instance_limit;
        innermost.table_limit = table_limit;
        innermost.memory_limit = memory_limit;

        // Save the limiter accessor function:
        inner.limiter = Some(ResourceLimiterInner::Sync(Box::new(limiter)));
    }

    /// Configure a function that runs on calls and returns between WebAssembly
    /// and host code.
    ///
    /// The function is passed a [`CallHook`] argument, which indicates which
    /// state transition the VM is making.
    ///
    /// This function may return a [`Trap`]. If a trap is returned when an
    /// import was called, it is immediately raised as-if the host import had
    /// returned the trap. If a trap is returned after wasm returns to the host
    /// then the wasm function's result is ignored and this trap is returned
    /// instead.
    ///
    /// After this function returns a trap, it may be called for subsequent returns
    /// to host or wasm code as the trap propagates to the root call.
    ///
    /// [`Trap`]: crate::Trap
    #[cfg(feature = "call-hook")]
    pub fn call_hook(
        &mut self,
        hook: impl FnMut(StoreContextMut<'_, T>, CallHook) -> Result<()> + Send + Sync + 'static,
    ) {
        self.inner.call_hook = Some(CallHookInner::Sync(Box::new(hook)));
    }

    /// Returns the [`Engine`] that this store is associated with.
    pub fn engine(&self) -> &Engine {
        self.inner.engine()
    }

    /// Perform garbage collection.
    ///
    /// Note that it is not required to actively call this function. GC will
    /// automatically happen according to various internal heuristics. This is
    /// provided if fine-grained control over the GC is desired.
    ///
    /// If you are calling this method after an attempted allocation failed, you
    /// may pass in the [`GcHeapOutOfMemory`][crate::GcHeapOutOfMemory] error.
    /// When you do so, this method will attempt to create enough space in the
    /// GC heap for that allocation, so that it will succeed on the next
    /// attempt.
    ///
    /// # Errors
    ///
    /// This method will fail if an [async limiter is
    /// configured](Store::limiter_async) in which case [`Store::gc_async`] must
    /// be used instead.
    #[cfg(feature = "gc")]
    pub fn gc(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>) -> Result<()> {
        StoreContextMut(&mut self.inner).gc(why)
    }

    /// Returns the amount fuel in this [`Store`]. When fuel is enabled, it must
    /// be configured via [`Store::set_fuel`].
    ///
    /// # Errors
    ///
    /// This function will return an error if fuel consumption is not enabled
    /// via [`Config::consume_fuel`](crate::Config::consume_fuel).
    pub fn get_fuel(&self) -> Result<u64> {
        self.inner.get_fuel()
    }

    /// Set the fuel to this [`Store`] for wasm to consume while executing.
    ///
    /// For this method to work fuel consumption must be enabled via
    /// [`Config::consume_fuel`](crate::Config::consume_fuel). By default a
    /// [`Store`] starts with 0 fuel for wasm to execute with (meaning it will
    /// immediately trap). This function must be called for the store to have
    /// some fuel to allow WebAssembly to execute.
    ///
    /// Most WebAssembly instructions consume 1 unit of fuel. Some
    /// instructions, such as `nop`, `drop`, `block`, and `loop`, consume 0
    /// units, as any execution cost associated with them involves other
    /// instructions which do consume fuel.
    ///
    /// Note that when fuel is entirely consumed it will cause wasm to trap.
    ///
    /// # Errors
    ///
    /// This function will return an error if fuel consumption is not enabled via
    /// [`Config::consume_fuel`](crate::Config::consume_fuel).
    pub fn set_fuel(&mut self, fuel: u64) -> Result<()> {
        self.inner.set_fuel(fuel)
    }

    /// Configures a [`Store`] to yield execution of async WebAssembly code
    /// periodically.
    ///
    /// When a [`Store`] is configured to consume fuel with
    /// [`Config::consume_fuel`](crate::Config::consume_fuel) this method will
    /// configure WebAssembly to be suspended and control will be yielded back
    /// to the caller every `interval` units of fuel consumed. When using this
    /// method it requires further invocations of WebAssembly to use `*_async`
    /// entrypoints.
    ///
    /// The purpose of this behavior is to ensure that futures which represent
    /// execution of WebAssembly do not execute too long inside their
    /// `Future::poll` method. This allows for some form of cooperative
    /// multitasking where WebAssembly will voluntarily yield control
    /// periodically (based on fuel consumption) back to the running thread.
    ///
    /// Note that futures returned by this crate will automatically flag
    /// themselves to get re-polled if a yield happens. This means that
    /// WebAssembly will continue to execute, just after giving the host an
    /// opportunity to do something else.
    ///
    /// The `interval` parameter indicates how much fuel should be
    /// consumed between yields of an async future. When fuel runs out wasm will trap.
    ///
    /// # Error
    ///
    /// This method will error if fuel is not enabled or `interval` is
    /// `Some(0)`.
    #[cfg(feature = "async")]
    pub fn fuel_async_yield_interval(&mut self, interval: Option<u64>) -> Result<()> {
        self.inner.fuel_async_yield_interval(interval)
    }

    /// Sets the epoch deadline to a certain number of ticks in the future.
    ///
    /// When the Wasm guest code is compiled with epoch-interruption
    /// instrumentation
    /// ([`Config::epoch_interruption()`](crate::Config::epoch_interruption)),
    /// and when the `Engine`'s epoch is incremented
    /// ([`Engine::increment_epoch()`](crate::Engine::increment_epoch))
    /// past a deadline, execution can be configured to either trap or
    /// yield and then continue.
    ///
    /// This deadline is always set relative to the current epoch:
    /// `ticks_beyond_current` ticks in the future. The deadline can
    /// be set explicitly via this method, or refilled automatically
    /// on a yield if configured via
    /// [`epoch_deadline_async_yield_and_update()`](Store::epoch_deadline_async_yield_and_update). After
    /// this method is invoked, the deadline is reached when
    /// [`Engine::increment_epoch()`] has been invoked at least
    /// `ticks_beyond_current` times.
    ///
    /// By default a store will trap immediately with an epoch deadline of 0
    /// (which has always "elapsed"). This method is required to be configured
    /// for stores with epochs enabled to some future epoch deadline.
    ///
    /// See documentation on
    /// [`Config::epoch_interruption()`](crate::Config::epoch_interruption)
    /// for an introduction to epoch-based interruption.
    #[cfg(target_has_atomic = "64")]
    pub fn set_epoch_deadline(&mut self, ticks_beyond_current: u64) {
        self.inner.set_epoch_deadline(ticks_beyond_current);
    }

    /// Configures epoch-deadline expiration to trap.
    ///
    /// When epoch-interruption-instrumented code is executed on this
    /// store and the epoch deadline is reached before completion,
    /// with the store configured in this way, execution will
    /// terminate with a trap as soon as an epoch check in the
    /// instrumented code is reached.
    ///
    /// This behavior is the default if the store is not otherwise
    /// configured via
    /// [`epoch_deadline_trap()`](Store::epoch_deadline_trap),
    /// [`epoch_deadline_callback()`](Store::epoch_deadline_callback) or
    /// [`epoch_deadline_async_yield_and_update()`](Store::epoch_deadline_async_yield_and_update).
    ///
    /// This setting is intended to allow for coarse-grained
    /// interruption, but not a deterministic deadline of a fixed,
    /// finite interval. For deterministic interruption, see the
    /// "fuel" mechanism instead.
    ///
    /// Note that when this is used it's required to call
    /// [`Store::set_epoch_deadline`] or otherwise wasm will always immediately
    /// trap.
    ///
    /// See documentation on
    /// [`Config::epoch_interruption()`](crate::Config::epoch_interruption)
    /// for an introduction to epoch-based interruption.
    #[cfg(target_has_atomic = "64")]
    pub fn epoch_deadline_trap(&mut self) {
        self.inner.epoch_deadline_trap();
    }

    /// Configures epoch-deadline expiration to invoke a custom callback
    /// function.
    ///
    /// When epoch-interruption-instrumented code is executed on this
    /// store and the epoch deadline is reached before completion, the
    /// provided callback function is invoked.
    ///
    /// This callback should either return an [`UpdateDeadline`], or
    /// return an error, which will terminate execution with a trap.
    ///
    /// The [`UpdateDeadline`] is a positive number of ticks to
    /// add to the epoch deadline, as well as indicating what
    /// to do after the callback returns. If the [`Store`] is
    /// configured with async support, then the callback may return
    /// [`UpdateDeadline::Yield`] or [`UpdateDeadline::YieldCustom`]
    /// to yield to the async executor before updating the epoch deadline.
    /// Alternatively, the callback may return [`UpdateDeadline::Continue`] to
    /// update the epoch deadline immediately.
    ///
    /// This setting is intended to allow for coarse-grained
    /// interruption, but not a deterministic deadline of a fixed,
    /// finite interval. For deterministic interruption, see the
    /// "fuel" mechanism instead.
    ///
    /// See documentation on
    /// [`Config::epoch_interruption()`](crate::Config::epoch_interruption)
    /// for an introduction to epoch-based interruption.
    #[cfg(target_has_atomic = "64")]
    pub fn epoch_deadline_callback(
        &mut self,
        callback: impl FnMut(StoreContextMut<T>) -> Result<UpdateDeadline> + Send + Sync + 'static,
    ) {
        self.inner.epoch_deadline_callback(Box::new(callback));
    }

    /// Set an exception as the currently pending exception, and
    /// return an error that propagates the throw.
    ///
    /// This method takes an exception object and stores it in the
    /// `Store` as the currently pending exception. This is a special
    /// rooted slot that holds the exception as long as it is
    /// propagating. This method then returns a `ThrownException`
    /// error, which is a special type that indicates a pending
    /// exception exists. When this type propagates as an error
    /// returned from a Wasm-to-host call, the pending exception is
    /// thrown within the Wasm context, and either caught or
    /// propagated further to the host-to-Wasm call boundary. If an
    /// exception is thrown out of Wasm (or across Wasm from a
    /// hostcall) back to the host-to-Wasm call boundary, *that*
    /// invocation returns a `ThrownException`, and the pending
    /// exception slot is again set. In other words, the
    /// `ThrownException` error type should propagate upward exactly
    /// and only when a pending exception is set.
    ///
    /// To take the pending exception, use [`Self::take_pending_exception`].
    ///
    /// This method is parameterized over `R` for convenience, but
    /// will always return an `Err`.
    ///
    /// # Panics
    ///
    /// - Will panic if `exception` has been unrooted.
    /// - Will panic if `exception` is a null reference.
    /// - Will panic if a pending exception has already been set.
    #[cfg(feature = "gc")]
    pub fn throw<R>(&mut self, exception: Rooted<ExnRef>) -> Result<R, ThrownException> {
        self.inner.throw_impl(exception);
        Err(ThrownException)
    }

    /// Take the currently pending exception, if any, and return it,
    /// removing it from the "pending exception" slot.
    ///
    /// If there is no pending exception, returns `None`.
    ///
    /// Note: the returned exception is a LIFO root (see
    /// [`crate::Rooted`]), rooted in the current handle scope. Take
    /// care to ensure that it is re-rooted or otherwise does not
    /// escape this scope! It is usually best to allow an exception
    /// object to be rooted in the store's "pending exception" slot
    /// until the final consumer has taken it, rather than root it and
    /// pass it up the callstack in some other way.
    ///
    /// This method is useful to implement ad-hoc exception plumbing
    /// in various ways, but for the most idiomatic handling, see
    /// [`StoreContextMut::throw`].
    #[cfg(feature = "gc")]
    pub fn take_pending_exception(&mut self) -> Option<Rooted<ExnRef>> {
        self.inner.take_pending_exception_rooted()
    }

    /// Tests whether there is a pending exception.
    ///
    /// Ordinarily, a pending exception will be set on a store if and
    /// only if a host-side callstack is propagating a
    /// [`crate::ThrownException`] error. The final consumer that
    /// catches the exception takes it; it may re-place it to re-throw
    /// (using [`Self::throw`]) if it chooses not to actually handle the
    /// exception.
    ///
    /// This method is useful to tell whether a store is in this
    /// state, but should not be used as part of the ordinary
    /// exception-handling flow. For the most idiomatic handling, see
    /// [`StoreContextMut::throw`].
    #[cfg(feature = "gc")]
    pub fn has_pending_exception(&self) -> bool {
        self.inner.pending_exception.is_some()
    }

    /// Provide an object that views Wasm stack state, including Wasm
    /// VM-level values (locals and operand stack), when debugging is
    /// enabled.
    ///
    /// Returns `None` if debug instrumentation is not enabled for
    /// the engine containing this store.
    #[cfg(feature = "debug")]
    pub fn debug_frames(&mut self) -> Option<crate::DebugFrameCursor<'_, T>> {
        self.as_context_mut().debug_frames()
    }

    /// Start an edit session to update breakpoints.
    #[cfg(feature = "debug")]
    pub fn edit_breakpoints(&mut self) -> Option<crate::BreakpointEdit<'_>> {
        self.as_context_mut().edit_breakpoints()
    }

    /// Return all breakpoints.
    #[cfg(feature = "debug")]
    pub fn breakpoints(&self) -> Option<impl Iterator<Item = crate::Breakpoint> + '_> {
        self.as_context().breakpoints()
    }

    /// Indicate whether single-step mode is enabled.
    #[cfg(feature = "debug")]
    pub fn is_single_step(&self) -> bool {
        self.as_context().is_single_step()
    }

    /// Set the debug callback on this store.
    ///
    /// See [`crate::DebugHandler`] for more documentation.
    ///
    /// # Panics
    ///
    /// - Will panic if guest-debug support was not enabled via
    ///   [`crate::Config::guest_debug`].
    #[cfg(feature = "debug")]
    pub fn set_debug_handler(&mut self, handler: impl DebugHandler<Data = T>)
    where
        // We require `Send` here because the debug handler becomes
        // referenced from a future: when `DebugHandler::handle` is
        // invoked, its `self` references the `handler` with the
        // user's state. Note that we are careful to keep this bound
        // constrained to debug-handler-related code only and not
        // propagate it outward to the store in general. The presence
        // of the trait implementation serves as a witness that `T:
        // Send`. This is required in particular because we will have
        // a `&mut dyn VMStore` on the stack when we pause a fiber
        // with `block_on` to run a debugger hook; that `VMStore` must
        // be a `Store<T> where T: Send`.
        T: Send,
    {
        // Debug hooks rely on async support, so async entrypoints are required.
        self.inner.set_async_required(Asyncness::Yes);

        assert!(
            self.engine().tunables().debug_guest,
            "debug hooks require guest debugging to be enabled"
        );
        self.inner.debug_handler = Some(Box::new(handler));
    }

    /// Clear the debug handler on this store. If any existed, it will
    /// be dropped.
    #[cfg(feature = "debug")]
    pub fn clear_debug_handler(&mut self) {
        self.inner.debug_handler = None;
    }
}

impl<'a, T> StoreContext<'a, T> {
    /// Returns the underlying [`Engine`] this store is connected to.
    pub fn engine(&self) -> &Engine {
        self.0.engine()
    }

    /// Access the underlying data owned by this `Store`.
    ///
    /// Same as [`Store::data`].
    pub fn data(&self) -> &'a T {
        self.0.data()
    }

    /// Returns the remaining fuel in this store.
    ///
    /// For more information see [`Store::get_fuel`].
    pub fn get_fuel(&self) -> Result<u64> {
        self.0.get_fuel()
    }
}

impl<'a, T> StoreContextMut<'a, T> {
    /// Access the underlying data owned by this `Store`.
    ///
    /// Same as [`Store::data`].
    pub fn data(&self) -> &T {
        self.0.data()
    }

    /// Access the underlying data owned by this `Store`.
    ///
    /// Same as [`Store::data_mut`].
    pub fn data_mut(&mut self) -> &mut T {
        self.0.data_mut()
    }

    /// Returns the underlying [`Engine`] this store is connected to.
    pub fn engine(&self) -> &Engine {
        self.0.engine()
    }

    /// Perform garbage collection of `ExternRef`s.
    ///
    /// Same as [`Store::gc`].
    #[cfg(feature = "gc")]
    pub fn gc(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>) -> Result<()> {
        let (mut limiter, store) = self.0.validate_sync_resource_limiter_and_store_opaque()?;
        vm::assert_ready(store.gc(
            limiter.as_mut(),
            None,
            why.map(|e| e.bytes_needed()),
            Asyncness::No,
        ));
        Ok(())
    }

    /// Returns remaining fuel in this store.
    ///
    /// For more information see [`Store::get_fuel`]
    pub fn get_fuel(&self) -> Result<u64> {
        self.0.get_fuel()
    }

    /// Set the amount of fuel in this store.
    ///
    /// For more information see [`Store::set_fuel`]
    pub fn set_fuel(&mut self, fuel: u64) -> Result<()> {
        self.0.set_fuel(fuel)
    }

    /// Configures this `Store` to periodically yield while executing futures.
    ///
    /// For more information see [`Store::fuel_async_yield_interval`]
    #[cfg(feature = "async")]
    pub fn fuel_async_yield_interval(&mut self, interval: Option<u64>) -> Result<()> {
        self.0.fuel_async_yield_interval(interval)
    }

    /// Sets the epoch deadline to a certain number of ticks in the future.
    ///
    /// For more information see [`Store::set_epoch_deadline`].
    #[cfg(target_has_atomic = "64")]
    pub fn set_epoch_deadline(&mut self, ticks_beyond_current: u64) {
        self.0.set_epoch_deadline(ticks_beyond_current);
    }

    /// Configures epoch-deadline expiration to trap.
    ///
    /// For more information see [`Store::epoch_deadline_trap`].
    #[cfg(target_has_atomic = "64")]
    pub fn epoch_deadline_trap(&mut self) {
        self.0.epoch_deadline_trap();
    }

    /// Set an exception as the currently pending exception, and
    /// return an error that propagates the throw.
    ///
    /// See [`Store::throw`] for more details.
    #[cfg(feature = "gc")]
    pub fn throw<R>(&mut self, exception: Rooted<ExnRef>) -> Result<R, ThrownException> {
        self.0.inner.throw_impl(exception);
        Err(ThrownException)
    }

    /// Take the currently pending exception, if any, and return it,
    /// removing it from the "pending exception" slot.
    ///
    /// See [`Store::take_pending_exception`] for more details.
    #[cfg(feature = "gc")]
    pub fn take_pending_exception(&mut self) -> Option<Rooted<ExnRef>> {
        self.0.inner.take_pending_exception_rooted()
    }

    /// Tests whether there is a pending exception.
    ///
    /// See [`Store::has_pending_exception`] for more details.
    #[cfg(feature = "gc")]
    pub fn has_pending_exception(&self) -> bool {
        self.0.inner.pending_exception.is_some()
    }
}

impl<T> StoreInner<T> {
    #[inline]
    fn data(&self) -> &T {
        // We are actually just accessing `&self.data_no_provenance` but we must
        // do so with the `VMStoreContext::store_data` pointer's provenance. If
        // we did otherwise, i.e. directly accessed the field, we would
        // invalidate that pointer, which would in turn invalidate any direct
        // `T` accesses that Wasm code makes via unsafe intrinsics.
        let data: *const ManuallyDrop<T> = &raw const self.data_no_provenance;
        let provenance = self.inner.vm_store_context.store_data.as_ptr().cast::<T>();
        let ptr = provenance.with_addr(data.addr());

        // SAFETY: The pointer is non-null, points to our `T` data, and is valid
        // to access because of our `&self` borrow.
        debug_assert_ne!(ptr, core::ptr::null_mut());
        debug_assert_eq!(ptr.addr(), (&raw const self.data_no_provenance).addr());
        unsafe { &*ptr }
    }

    #[inline]
    fn data_limiter_and_opaque(
        &mut self,
    ) -> (
        &mut T,
        Option<&mut ResourceLimiterInner<T>>,
        &mut StoreOpaque,
    ) {
        // See the comments about provenance in `StoreInner::data` above.
        let data: *mut ManuallyDrop<T> = &raw mut self.data_no_provenance;
        let provenance = self.inner.vm_store_context.store_data.as_ptr().cast::<T>();
        let ptr = provenance.with_addr(data.addr());

        // SAFETY: The pointer is non-null, points to our `T` data, and is valid
        // to access because of our `&mut self` borrow.
        debug_assert_ne!(ptr, core::ptr::null_mut());
        debug_assert_eq!(ptr.addr(), (&raw const self.data_no_provenance).addr());
        let data = unsafe { &mut *ptr };

        let limiter = self.limiter.as_mut();

        (data, limiter, &mut self.inner)
    }

    #[inline]
    fn data_mut(&mut self) -> &mut T {
        self.data_limiter_and_opaque().0
    }

    #[inline]
    pub fn call_hook(&mut self, s: CallHook) -> Result<()> {
        if self.inner.pkey.is_none() && self.call_hook.is_none() {
            Ok(())
        } else {
            self.call_hook_slow_path(s)
        }
    }

    fn call_hook_slow_path(&mut self, s: CallHook) -> Result<()> {
        if let Some(pkey) = &self.inner.pkey {
            let allocator = self.engine().allocator();
            match s {
                CallHook::CallingWasm | CallHook::ReturningFromHost => {
                    allocator.restrict_to_pkey(*pkey)
                }
                CallHook::ReturningFromWasm | CallHook::CallingHost => allocator.allow_all_pkeys(),
            }
        }

        // Temporarily take the configured behavior to avoid mutably borrowing
        // multiple times.
        if let Some(mut call_hook) = self.call_hook.take() {
            let result = self.invoke_call_hook(&mut call_hook, s);
            self.call_hook = Some(call_hook);
            return result;
        }

        Ok(())
    }

    fn invoke_call_hook(&mut self, call_hook: &mut CallHookInner<T>, s: CallHook) -> Result<()> {
        match call_hook {
            #[cfg(feature = "call-hook")]
            CallHookInner::Sync(hook) => hook((&mut *self).as_context_mut(), s),

            #[cfg(all(feature = "async", feature = "call-hook"))]
            CallHookInner::Async(handler) => {
                if !self.can_block() {
                    bail!("couldn't grab async_cx for call hook")
                }
                return (&mut *self)
                    .as_context_mut()
                    .with_blocking(|store, cx| cx.block_on(handler.handle_call_event(store, s)))?;
            }

            CallHookInner::ForceTypeParameterToBeUsed { uninhabited, .. } => {
                let _ = s;
                match *uninhabited {}
            }
        }
    }

    #[cfg(not(feature = "async"))]
    fn flush_fiber_stack(&mut self) {
        // noop shim so code can assume this always exists.
    }

    /// Splits this `StoreInner<T>` into a `limiter`/`StoerOpaque` borrow while
    /// validating that an async limiter is not configured.
    ///
    /// This is used for sync entrypoints which need to fail if an async limiter
    /// is configured as otherwise the async entrypoint must be used instead.
    pub(crate) fn validate_sync_resource_limiter_and_store_opaque(
        &mut self,
    ) -> Result<(Option<StoreResourceLimiter<'_>>, &mut StoreOpaque)> {
        let (limiter, store) = self.resource_limiter_and_store_opaque();
        if !matches!(limiter, None | Some(StoreResourceLimiter::Sync(_))) {
            bail!(
                "when using an async resource limiter `*_async` functions must \
             be used instead"
            );
        }
        Ok((limiter, store))
    }
}

fn get_fuel(injected_fuel: i64, fuel_reserve: u64) -> u64 {
    fuel_reserve.saturating_add_signed(-injected_fuel)
}

// Add remaining fuel from the reserve into the active fuel if there is any left.
fn refuel(
    injected_fuel: &mut i64,
    fuel_reserve: &mut u64,
    yield_interval: Option<NonZeroU64>,
) -> bool {
    let fuel = get_fuel(*injected_fuel, *fuel_reserve);
    if fuel > 0 {
        set_fuel(injected_fuel, fuel_reserve, yield_interval, fuel);
        true
    } else {
        false
    }
}

fn set_fuel(
    injected_fuel: &mut i64,
    fuel_reserve: &mut u64,
    yield_interval: Option<NonZeroU64>,
    new_fuel_amount: u64,
) {
    let interval = yield_interval.unwrap_or(NonZeroU64::MAX).get();
    // If we're yielding periodically we only store the "active" amount of fuel into consumed_ptr
    // for the VM to use.
    let injected = core::cmp::min(interval, new_fuel_amount);
    // Fuel in the VM is stored as an i64, so we have to cap the amount of fuel we inject into the
    // VM at once to be i64 range.
    let injected = core::cmp::min(injected, i64::MAX as u64);
    // Add whatever is left over after injection to the reserve for later use.
    *fuel_reserve = new_fuel_amount - injected;
    // Within the VM we increment to count fuel, so inject a negative amount. The VM will halt when
    // this counter is positive.
    *injected_fuel = -(injected as i64);
}

#[doc(hidden)]
impl StoreOpaque {
    pub fn id(&self) -> StoreId {
        self.store_data.id()
    }

    pub fn bump_resource_counts(&mut self, module: &Module) -> Result<()> {
        fn bump(slot: &mut usize, max: usize, amt: usize, desc: &str) -> Result<()> {
            let new = slot.saturating_add(amt);
            if new > max {
                bail!("resource limit exceeded: {desc} count too high at {new}");
            }
            *slot = new;
            Ok(())
        }

        let module = module.env_module();
        let memories = module.num_defined_memories();
        let tables = module.num_defined_tables();

        bump(&mut self.instance_count, self.instance_limit, 1, "instance")?;
        bump(
            &mut self.memory_count,
            self.memory_limit,
            memories,
            "memory",
        )?;
        bump(&mut self.table_count, self.table_limit, tables, "table")?;

        Ok(())
    }

    #[inline]
    pub fn engine(&self) -> &Engine {
        &self.engine
    }

    #[inline]
    pub fn store_data(&self) -> &StoreData {
        &self.store_data
    }

    #[inline]
    pub fn store_data_mut(&mut self) -> &mut StoreData {
        &mut self.store_data
    }

    pub fn store_data_mut_and_registry(&mut self) -> (&mut StoreData, &ModuleRegistry) {
        (&mut self.store_data, &self.modules)
    }

    #[cfg(feature = "debug")]
    pub(crate) fn breakpoints_and_registry_mut(
        &mut self,
    ) -> (&mut BreakpointState, &mut ModuleRegistry) {
        (&mut self.breakpoints, &mut self.modules)
    }

    #[cfg(feature = "debug")]
    pub(crate) fn breakpoints_and_registry(&self) -> (&BreakpointState, &ModuleRegistry) {
        (&self.breakpoints, &self.modules)
    }

    #[inline]
    pub(crate) fn modules(&self) -> &ModuleRegistry {
        &self.modules
    }

    pub(crate) fn register_module(&mut self, module: &Module) -> Result<RegisteredModuleId> {
        self.modules.register_module(module, &self.engine)
    }

    #[cfg(feature = "component-model")]
    pub(crate) fn register_component(
        &mut self,
        component: &crate::component::Component,
    ) -> Result<()> {
        self.modules.register_component(component, &self.engine)
    }

    pub(crate) fn func_refs_and_modules(&mut self) -> (&mut FuncRefs, &ModuleRegistry) {
        (&mut self.func_refs, &self.modules)
    }

    pub(crate) fn host_globals(
        &self,
    ) -> &PrimaryMap<DefinedGlobalIndex, StoreBox<VMHostGlobalContext>> {
        &self.host_globals
    }

    pub(crate) fn host_globals_mut(
        &mut self,
    ) -> &mut PrimaryMap<DefinedGlobalIndex, StoreBox<VMHostGlobalContext>> {
        &mut self.host_globals
    }

    pub fn module_for_instance(&self, instance: StoreInstanceId) -> Option<&'_ Module> {
        instance.store_id().assert_belongs_to(self.id());
        match self.instances[instance.instance()].kind {
            StoreInstanceKind::Dummy => None,
            StoreInstanceKind::Real { module_id } => {
                let module = self
                    .modules()
                    .module_by_id(module_id)
                    .expect("should always have a registered module for real instances");
                Some(module)
            }
        }
    }

    /// Accessor from `InstanceId` to `&vm::Instance`.
    ///
    /// Note that if you have a `StoreInstanceId` you should use
    /// `StoreInstanceId::get` instead. This assumes that `id` has been
    /// validated to already belong to this store.
    #[inline]
    pub fn instance(&self, id: InstanceId) -> &vm::Instance {
        self.instances[id].handle.get()
    }

    /// Accessor from `InstanceId` to `Pin<&mut vm::Instance>`.
    ///
    /// Note that if you have a `StoreInstanceId` you should use
    /// `StoreInstanceId::get_mut` instead. This assumes that `id` has been
    /// validated to already belong to this store.
    #[inline]
    pub fn instance_mut(&mut self, id: InstanceId) -> Pin<&mut vm::Instance> {
        self.instances[id].handle.get_mut()
    }

    /// Accessor from `InstanceId` to both `Pin<&mut vm::Instance>`
    /// and `&ModuleRegistry`.
    #[inline]
    pub fn instance_and_module_registry_mut(
        &mut self,
        id: InstanceId,
    ) -> (Pin<&mut vm::Instance>, &ModuleRegistry) {
        (self.instances[id].handle.get_mut(), &self.modules)
    }

    /// Access multiple instances specified via `ids`.
    ///
    /// # Panics
    ///
    /// This method will panic if any indices in `ids` overlap.
    ///
    /// # Safety
    ///
    /// This method is not safe if the returned instances are used to traverse
    /// "laterally" between other instances. For example accessing imported
    /// items in an instance may traverse laterally to a sibling instance thus
    /// aliasing a returned value here. The caller must ensure that only defined
    /// items within the instances themselves are accessed.
    #[inline]
    pub unsafe fn optional_gc_store_and_instances_mut<const N: usize>(
        &mut self,
        ids: [InstanceId; N],
    ) -> (Option<&mut GcStore>, [Pin<&mut vm::Instance>; N]) {
        let instances = self
            .instances
            .get_disjoint_mut(ids)
            .unwrap()
            .map(|h| h.handle.get_mut());
        (self.gc_store.as_mut(), instances)
    }

    /// Pair of `Self::optional_gc_store_mut` and `Self::instance_mut`
    pub fn optional_gc_store_and_instance_mut(
        &mut self,
        id: InstanceId,
    ) -> (Option<&mut GcStore>, Pin<&mut vm::Instance>) {
        (self.gc_store.as_mut(), self.instances[id].handle.get_mut())
    }

    /// Tuple of `Self::optional_gc_store_mut`, `Self::modules`, and
    /// `Self::instance_mut`.
    pub fn optional_gc_store_and_registry_and_instance_mut(
        &mut self,
        id: InstanceId,
    ) -> (
        Option<&mut GcStore>,
        &ModuleRegistry,
        Pin<&mut vm::Instance>,
    ) {
        (
            self.gc_store.as_mut(),
            &self.modules,
            self.instances[id].handle.get_mut(),
        )
    }

    /// Get all instances (ignoring dummy instances) within this store.
    pub fn all_instances<'a>(&'a mut self) -> impl ExactSizeIterator<Item = Instance> + 'a {
        let instances = self
            .instances
            .iter()
            .filter_map(|(id, inst)| {
                if let StoreInstanceKind::Dummy = inst.kind {
                    None
                } else {
                    Some(id)
                }
            })
            .collect::<Vec<_>>();
        instances
            .into_iter()
            .map(|i| Instance::from_wasmtime(i, self))
    }

    /// Get all memories (host- or Wasm-defined) within this store.
    pub fn all_memories<'a>(&'a self) -> impl Iterator<Item = ExportMemory> + 'a {
        // NB: Host-created memories have dummy instances. Therefore, we can get
        // all memories in the store by iterating over all instances (including
        // dummy instances) and getting each of their defined memories.
        let id = self.id();
        self.instances
            .iter()
            .flat_map(move |(_, instance)| instance.handle.get().defined_memories(id))
    }

    /// Iterate over all tables (host- or Wasm-defined) within this store.
    pub fn for_each_table(&mut self, mut f: impl FnMut(&mut Self, Table)) {
        // NB: Host-created tables have dummy instances. Therefore, we can get
        // all tables in the store by iterating over all instances (including
        // dummy instances) and getting each of their defined memories.
        for id in self.instances.keys() {
            let instance = StoreInstanceId::new(self.id(), id);
            for table in 0..self.instance(id).env_module().num_defined_tables() {
                let table = DefinedTableIndex::new(table);
                f(self, Table::from_raw(instance, table));
            }
        }
    }

    /// Iterate over all globals (host- or Wasm-defined) within this store.
    pub fn for_each_global(&mut self, mut f: impl FnMut(&mut Self, Global)) {
        // First enumerate all the host-created globals.
        for global in self.host_globals.keys() {
            let global = Global::new_host(self, global);
            f(self, global);
        }

        // Then enumerate all instances' defined globals.
        for id in self.instances.keys() {
            for index in 0..self.instance(id).env_module().num_defined_globals() {
                let index = DefinedGlobalIndex::new(index);
                let global = Global::new_instance(self, id, index);
                f(self, global);
            }
        }
    }

    #[cfg(all(feature = "std", any(unix, windows)))]
    pub fn set_signal_handler(&mut self, handler: Option<SignalHandler>) {
        self.signal_handler = handler;
    }

    #[inline]
    pub fn vm_store_context(&self) -> &VMStoreContext {
        &self.vm_store_context
    }

    #[inline]
    pub fn vm_store_context_mut(&mut self) -> &mut VMStoreContext {
        &mut self.vm_store_context
    }

    /// Performs a lazy allocation of the `GcStore` within this store, returning
    /// the previous allocation if it's already present.
    ///
    /// This method will, if necessary, allocate a new `GcStore` -- linear
    /// memory and all. This is a blocking operation due to
    /// `ResourceLimiterAsync` which means that this should only be executed
    /// in a fiber context at this time.
    #[inline]
    pub(crate) async fn ensure_gc_store(
        &mut self,
        limiter: Option<&mut StoreResourceLimiter<'_>>,
    ) -> Result<&mut GcStore> {
        if self.gc_store.is_some() {
            return Ok(self.gc_store.as_mut().unwrap());
        }
        self.allocate_gc_store(limiter).await
    }

    #[inline(never)]
    async fn allocate_gc_store(
        &mut self,
        limiter: Option<&mut StoreResourceLimiter<'_>>,
    ) -> Result<&mut GcStore> {
        log::trace!("allocating GC heap for store {:?}", self.id());

        assert!(self.gc_store.is_none());
        assert_eq!(
            self.vm_store_context.gc_heap.base.as_non_null(),
            NonNull::dangling(),
        );
        assert_eq!(self.vm_store_context.gc_heap.current_length(), 0);

        let gc_store = allocate_gc_store(self, limiter).await?;
        self.vm_store_context.gc_heap = gc_store.vmmemory_definition();
        return Ok(self.gc_store.insert(gc_store));

        #[cfg(feature = "gc")]
        async fn allocate_gc_store(
            store: &mut StoreOpaque,
            limiter: Option<&mut StoreResourceLimiter<'_>>,
        ) -> Result<GcStore> {
            use wasmtime_environ::packed_option::ReservedValue;

            let engine = store.engine();
            let mem_ty = engine.tunables().gc_heap_memory_type();
            ensure!(
                engine.features().gc_types(),
                "cannot allocate a GC store when GC is disabled at configuration time"
            );

            // First, allocate the memory that will be our GC heap's storage.
            let mut request = InstanceAllocationRequest {
                id: InstanceId::reserved_value(),
                runtime_info: engine.empty_module_runtime_info(),
                imports: vm::Imports::default(),
                store,
                limiter,
            };

            let (mem_alloc_index, mem) = engine
                .allocator()
                .allocate_memory(&mut request, &mem_ty, None)
                .await?;

            // Then, allocate the actual GC heap, passing in that memory
            // storage.
            let gc_runtime = engine
                .gc_runtime()
                .context("no GC runtime: GC disabled at compile time or configuration time")?;
            let (index, heap) =
                engine
                    .allocator()
                    .allocate_gc_heap(engine, &**gc_runtime, mem_alloc_index, mem)?;

            Ok(GcStore::new(index, heap))
        }

        #[cfg(not(feature = "gc"))]
        async fn allocate_gc_store(
            _: &mut StoreOpaque,
            _: Option<&mut StoreResourceLimiter<'_>>,
        ) -> Result<GcStore> {
            bail!("cannot allocate a GC store: the `gc` feature was disabled at compile time")
        }
    }

    /// Helper method to require that a `GcStore` was previously allocated for
    /// this store, failing if it has not yet been allocated.
    ///
    /// Note that this should only be used in a context where allocation of a
    /// `GcStore` is sure to have already happened prior, otherwise this may
    /// return a confusing error to embedders which is a bug in Wasmtime.
    ///
    /// Some situations where it's safe to call this method:
    ///
    /// * There's already a non-null and non-i31 `VMGcRef` in scope. By existing
    ///   this shows proof that the `GcStore` was previously allocated.
    /// * During instantiation and instance's `needs_gc_heap` flag will be
    ///   handled and instantiation will automatically create a GC store.
    #[inline]
    #[cfg(feature = "gc")]
    pub(crate) fn require_gc_store(&self) -> Result<&GcStore> {
        match &self.gc_store {
            Some(gc_store) => Ok(gc_store),
            None => bail!("GC heap not initialized yet"),
        }
    }

    /// Same as [`Self::require_gc_store`], but mutable.
    #[inline]
    #[cfg(feature = "gc")]
    pub(crate) fn require_gc_store_mut(&mut self) -> Result<&mut GcStore> {
        match &mut self.gc_store {
            Some(gc_store) => Ok(gc_store),
            None => bail!("GC heap not initialized yet"),
        }
    }

    /// Attempts to access the GC store that has been previously allocated.
    ///
    /// This method will return `Some` if the GC store was previously allocated.
    /// A `None` return value means either that the GC heap hasn't yet been
    /// allocated or that it does not need to be allocated for this store. Note
    /// that to require a GC store in a particular situation it's recommended to
    /// use [`Self::require_gc_store_mut`] instead.
    #[inline]
    pub(crate) fn optional_gc_store_mut(&mut self) -> Option<&mut GcStore> {
        if cfg!(not(feature = "gc")) || !self.engine.features().gc_types() {
            debug_assert!(self.gc_store.is_none());
            None
        } else {
            self.gc_store.as_mut()
        }
    }

    /// Helper to assert that a GC store was previously allocated and is
    /// present.
    ///
    /// # Panics
    ///
    /// This method will panic if the GC store has not yet been allocated. This
    /// should only be used in a context where there's an existing GC reference,
    /// for example, or if `ensure_gc_store` has already been called.
    #[inline]
    #[track_caller]
    pub(crate) fn unwrap_gc_store(&self) -> &GcStore {
        self.gc_store
            .as_ref()
            .expect("attempted to access the store's GC heap before it has been allocated")
    }

    /// Same as [`Self::unwrap_gc_store`], but mutable.
    #[inline]
    #[track_caller]
    pub(crate) fn unwrap_gc_store_mut(&mut self) -> &mut GcStore {
        self.gc_store
            .as_mut()
            .expect("attempted to access the store's GC heap before it has been allocated")
    }

    #[inline]
    pub(crate) fn gc_roots(&self) -> &RootSet {
        &self.gc_roots
    }

    #[inline]
    #[cfg(feature = "gc")]
    pub(crate) fn gc_roots_mut(&mut self) -> &mut RootSet {
        &mut self.gc_roots
    }

    #[inline]
    pub(crate) fn exit_gc_lifo_scope(&mut self, scope: usize) {
        self.gc_roots.exit_lifo_scope(self.gc_store.as_mut(), scope);
    }

    #[cfg(feature = "gc")]
    async fn do_gc(&mut self, asyncness: Asyncness) {
        // If the GC heap hasn't been initialized, there is nothing to collect.
        if self.gc_store.is_none() {
            return;
        }

        log::trace!("============ Begin GC ===========");

        // Take the GC roots out of `self` so we can borrow it mutably but still
        // call mutable methods on `self`.
        let mut roots = core::mem::take(&mut self.gc_roots_list);

        self.trace_roots(&mut roots, asyncness).await;
        self.unwrap_gc_store_mut()
            .gc(asyncness, unsafe { roots.iter() })
            .await;

        // Restore the GC roots for the next GC.
        roots.clear();
        self.gc_roots_list = roots;

        log::trace!("============ End GC ===========");
    }

    #[cfg(feature = "gc")]
    async fn trace_roots(&mut self, gc_roots_list: &mut GcRootsList, asyncness: Asyncness) {
        log::trace!("Begin trace GC roots");

        // We shouldn't have any leftover, stale GC roots.
        assert!(gc_roots_list.is_empty());

        self.trace_wasm_stack_roots(gc_roots_list);
        if asyncness != Asyncness::No {
            vm::Yield::new().await;
        }
        #[cfg(feature = "stack-switching")]
        {
            self.trace_wasm_continuation_roots(gc_roots_list);
            if asyncness != Asyncness::No {
                vm::Yield::new().await;
            }
        }
        self.trace_vmctx_roots(gc_roots_list);
        if asyncness != Asyncness::No {
            vm::Yield::new().await;
        }
        self.trace_user_roots(gc_roots_list);
        self.trace_pending_exception_roots(gc_roots_list);

        log::trace!("End trace GC roots")
    }

    #[cfg(feature = "gc")]
    fn trace_wasm_stack_frame(
        &self,
        gc_roots_list: &mut GcRootsList,
        frame: crate::runtime::vm::Frame,
    ) {
        let pc = frame.pc();
        debug_assert!(pc != 0, "we should always get a valid PC for Wasm frames");

        let fp = frame.fp() as *mut usize;
        debug_assert!(
            !fp.is_null(),
            "we should always get a valid frame pointer for Wasm frames"
        );

        let (module_with_code, _offset) = self
            .modules()
            .module_and_code_by_pc(pc)
            .expect("should have module info for Wasm frame");

        if let Some(stack_map) = module_with_code.lookup_stack_map(pc) {
            log::trace!(
                "We have a stack map that maps {} bytes in this Wasm frame",
                stack_map.frame_size()
            );

            let sp = unsafe { stack_map.sp(fp) };
            for stack_slot in unsafe { stack_map.live_gc_refs(sp) } {
                unsafe {
                    self.trace_wasm_stack_slot(gc_roots_list, stack_slot);
                }
            }
        }

        #[cfg(feature = "debug")]
        if let Some(frame_table) = module_with_code.module().frame_table() {
            let relpc = module_with_code
                .text_offset(pc)
                .expect("PC should be within module");
            for stack_slot in super::debug::gc_refs_in_frame(frame_table, relpc, fp) {
                unsafe {
                    self.trace_wasm_stack_slot(gc_roots_list, stack_slot);
                }
            }
        }
    }

    #[cfg(feature = "gc")]
    unsafe fn trace_wasm_stack_slot(&self, gc_roots_list: &mut GcRootsList, stack_slot: *mut u32) {
        use crate::runtime::vm::SendSyncPtr;
        use core::ptr::NonNull;

        let raw: u32 = unsafe { core::ptr::read(stack_slot) };
        log::trace!("Stack slot @ {stack_slot:p} = {raw:#x}");

        let gc_ref = vm::VMGcRef::from_raw_u32(raw);
        if gc_ref.is_some() {
            unsafe {
                gc_roots_list
                    .add_wasm_stack_root(SendSyncPtr::new(NonNull::new(stack_slot).unwrap()));
            }
        }
    }

    #[cfg(feature = "gc")]
    fn trace_wasm_stack_roots(&mut self, gc_roots_list: &mut GcRootsList) {
        use crate::runtime::vm::Backtrace;
        log::trace!("Begin trace GC roots :: Wasm stack");

        Backtrace::trace(self, |frame| {
            self.trace_wasm_stack_frame(gc_roots_list, frame);
            core::ops::ControlFlow::Continue(())
        });

        log::trace!("End trace GC roots :: Wasm stack");
    }

    #[cfg(all(feature = "gc", feature = "stack-switching"))]
    fn trace_wasm_continuation_roots(&mut self, gc_roots_list: &mut GcRootsList) {
        use crate::{runtime::vm::Backtrace, vm::VMStackState};
        log::trace!("Begin trace GC roots :: continuations");

        for continuation in &self.continuations {
            let state = continuation.common_stack_information.state;

            // FIXME(frank-emrich) In general, it is not enough to just trace
            // through the stacks of continuations; we also need to look through
            // their `cont.bind` arguments. However, we don't currently have
            // enough RTTI information to check if any of the values in the
            // buffers used by `cont.bind` are GC values. As a workaround, note
            // that we currently disallow cont.bind-ing GC values altogether.
            // This way, it is okay not to check them here.
            match state {
                VMStackState::Suspended => {
                    Backtrace::trace_suspended_continuation(self, continuation.deref(), |frame| {
                        self.trace_wasm_stack_frame(gc_roots_list, frame);
                        core::ops::ControlFlow::Continue(())
                    });
                }
                VMStackState::Running => {
                    // Handled by `trace_wasm_stack_roots`.
                }
                VMStackState::Parent => {
                    // We don't know whether our child is suspended or running, but in
                    // either case things should be handled correctly when traversing
                    // further along in the chain, nothing required at this point.
                }
                VMStackState::Fresh | VMStackState::Returned => {
                    // Fresh/Returned continuations have no gc values on their stack.
                }
            }
        }

        log::trace!("End trace GC roots :: continuations");
    }

    #[cfg(feature = "gc")]
    fn trace_vmctx_roots(&mut self, gc_roots_list: &mut GcRootsList) {
        log::trace!("Begin trace GC roots :: vmctx");
        self.for_each_global(|store, global| global.trace_root(store, gc_roots_list));
        self.for_each_table(|store, table| table.trace_roots(store, gc_roots_list));
        log::trace!("End trace GC roots :: vmctx");
    }

    #[cfg(feature = "gc")]
    fn trace_user_roots(&mut self, gc_roots_list: &mut GcRootsList) {
        log::trace!("Begin trace GC roots :: user");
        self.gc_roots.trace_roots(gc_roots_list);
        log::trace!("End trace GC roots :: user");
    }

    #[cfg(feature = "gc")]
    fn trace_pending_exception_roots(&mut self, gc_roots_list: &mut GcRootsList) {
        log::trace!("Begin trace GC roots :: pending exception");
        if let Some(pending_exception) = self.pending_exception.as_mut() {
            unsafe {
                let root = pending_exception.as_gc_ref_mut();
                gc_roots_list.add_root(root.into(), "Pending exception");
            }
        }
        log::trace!("End trace GC roots :: pending exception");
    }

    /// Insert a host-allocated GC type into this store.
    ///
    /// This makes it suitable for the embedder to allocate instances of this
    /// type in this store, and we don't have to worry about the type being
    /// reclaimed (since it is possible that none of the Wasm modules in this
    /// store are holding it alive).
    #[cfg(feature = "gc")]
    pub(crate) fn insert_gc_host_alloc_type(&mut self, ty: crate::type_registry::RegisteredType) {
        self.gc_host_alloc_types.insert(ty);
    }

    /// Helper function execute a `init_gc_ref` when placing `gc_ref` in `dest`.
    ///
    /// This avoids allocating `GcStore` where possible.
    pub(crate) fn init_gc_ref(
        &mut self,
        dest: &mut MaybeUninit<Option<VMGcRef>>,
        gc_ref: Option<&VMGcRef>,
    ) {
        if GcStore::needs_init_barrier(gc_ref) {
            self.unwrap_gc_store_mut().init_gc_ref(dest, gc_ref)
        } else {
            dest.write(gc_ref.map(|r| r.copy_i31()));
        }
    }

    /// Helper function execute a write barrier when placing `gc_ref` in `dest`.
    ///
    /// This avoids allocating `GcStore` where possible.
    pub(crate) fn write_gc_ref(&mut self, dest: &mut Option<VMGcRef>, gc_ref: Option<&VMGcRef>) {
        GcStore::write_gc_ref_optional_store(self.optional_gc_store_mut(), dest, gc_ref)
    }

    /// Helper function to clone `gc_ref` notably avoiding allocating a
    /// `GcStore` where possible.
    pub(crate) fn clone_gc_ref(&mut self, gc_ref: &VMGcRef) -> VMGcRef {
        if gc_ref.is_i31() {
            gc_ref.copy_i31()
        } else {
            self.unwrap_gc_store_mut().clone_gc_ref(gc_ref)
        }
    }

    pub fn get_fuel(&self) -> Result<u64> {
        crate::ensure!(
            self.engine().tunables().consume_fuel,
            "fuel is not configured in this store"
        );
        let injected_fuel = unsafe { *self.vm_store_context.fuel_consumed.get() };
        Ok(get_fuel(injected_fuel, self.fuel_reserve))
    }

    pub(crate) fn refuel(&mut self) -> bool {
        let injected_fuel = unsafe { &mut *self.vm_store_context.fuel_consumed.get() };
        refuel(
            injected_fuel,
            &mut self.fuel_reserve,
            self.fuel_yield_interval,
        )
    }

    pub fn set_fuel(&mut self, fuel: u64) -> Result<()> {
        crate::ensure!(
            self.engine().tunables().consume_fuel,
            "fuel is not configured in this store"
        );
        let injected_fuel = unsafe { &mut *self.vm_store_context.fuel_consumed.get() };
        set_fuel(
            injected_fuel,
            &mut self.fuel_reserve,
            self.fuel_yield_interval,
            fuel,
        );
        Ok(())
    }

    #[cfg(feature = "async")]
    pub fn fuel_async_yield_interval(&mut self, interval: Option<u64>) -> Result<()> {
        crate::ensure!(
            self.engine().tunables().consume_fuel,
            "fuel is not configured in this store"
        );
        crate::ensure!(
            interval != Some(0),
            "fuel_async_yield_interval must not be 0"
        );

        // All future entrypoints must be async to handle the case that fuel
        // runs out and an async yield is needed.
        self.set_async_required(Asyncness::Yes);

        self.fuel_yield_interval = interval.and_then(|i| NonZeroU64::new(i));
        // Reset the fuel active + reserve states by resetting the amount.
        self.set_fuel(self.get_fuel()?)
    }

    #[inline]
    pub fn signal_handler(&self) -> Option<*const SignalHandler> {
        let handler = self.signal_handler.as_ref()?;
        Some(handler)
    }

    #[inline]
    pub fn vm_store_context_ptr(&self) -> NonNull<VMStoreContext> {
        NonNull::from(&self.vm_store_context)
    }

    #[inline]
    pub fn default_caller(&self) -> NonNull<VMContext> {
        self.default_caller_vmctx.as_non_null()
    }

    #[inline]
    pub fn traitobj(&self) -> NonNull<dyn VMStore> {
        self.traitobj.0.unwrap()
    }

    /// Takes the cached `Vec<Val>` stored internally across hostcalls to get
    /// used as part of calling the host in a `Func::new` method invocation.
    #[inline]
    pub fn take_hostcall_val_storage(&mut self) -> Vec<Val> {
        mem::take(&mut self.hostcall_val_storage)
    }

    /// Restores the vector previously taken by `take_hostcall_val_storage`
    /// above back into the store, allowing it to be used in the future for the
    /// next wasm->host call.
    #[inline]
    pub fn save_hostcall_val_storage(&mut self, storage: Vec<Val>) {
        if storage.capacity() > self.hostcall_val_storage.capacity() {
            self.hostcall_val_storage = storage;
        }
    }

    /// Same as `take_hostcall_val_storage`, but for the direction of the host
    /// calling wasm.
    #[inline]
    pub fn take_wasm_val_raw_storage(&mut self) -> Vec<ValRaw> {
        mem::take(&mut self.wasm_val_raw_storage)
    }

    /// Same as `save_hostcall_val_storage`, but for the direction of the host
    /// calling wasm.
    #[inline]
    pub fn save_wasm_val_raw_storage(&mut self, storage: Vec<ValRaw>) {
        if storage.capacity() > self.wasm_val_raw_storage.capacity() {
            self.wasm_val_raw_storage = storage;
        }
    }

    /// Translates a WebAssembly fault at the native `pc` and native `addr` to a
    /// WebAssembly-relative fault.
    ///
    /// This function may abort the process if `addr` is not found to actually
    /// reside in any linear memory. In such a situation it means that the
    /// segfault was erroneously caught by Wasmtime and is possibly indicative
    /// of a code generator bug.
    ///
    /// This function returns `None` for dynamically-bounds-checked-memories
    /// with spectre mitigations enabled since the hardware fault address is
    /// always zero in these situations which means that the trapping context
    /// doesn't have enough information to report the fault address.
    pub(crate) fn wasm_fault(&self, pc: usize, addr: usize) -> Option<vm::WasmFault> {
        // There are a few instances where a "close to zero" pointer is loaded
        // and we expect that to happen:
        //
        // * Explicitly bounds-checked memories with spectre-guards enabled will
        //   cause out-of-bounds accesses to get routed to address 0, so allow
        //   wasm instructions to fault on the null address.
        // * `call_indirect` when invoking a null function pointer may load data
        //   from the a `VMFuncRef` whose address is null, meaning any field of
        //   `VMFuncRef` could be the address of the fault.
        //
        // In these situations where the address is so small it won't be in any
        // instance, so skip the checks below.
        if addr <= mem::size_of::<VMFuncRef>() {
            const _: () = {
                // static-assert that `VMFuncRef` isn't too big to ensure that
                // it lives solely within the first page as we currently only
                // have the guarantee that the first page of memory is unmapped,
                // no more.
                assert!(mem::size_of::<VMFuncRef>() <= 512);
            };
            return None;
        }

        // Search all known instances in this store for this address. Note that
        // this is probably not the speediest way to do this. Traps, however,
        // are generally not expected to be super fast and additionally stores
        // probably don't have all that many instances or memories.
        //
        // If this loop becomes hot in the future, however, it should be
        // possible to precompute maps about linear memories in a store and have
        // a quicker lookup.
        let mut fault = None;
        for (_, instance) in self.instances.iter() {
            if let Some(f) = instance.handle.get().wasm_fault(addr) {
                assert!(fault.is_none());
                fault = Some(f);
            }
        }
        if fault.is_some() {
            return fault;
        }

        cfg_if::cfg_if! {
            if #[cfg(feature = "std")] {
                // With the standard library a rich error can be printed here
                // to stderr and the native abort path is used.
                eprintln!(
                    "\
Wasmtime caught a segfault for a wasm program because the faulting instruction
is allowed to segfault due to how linear memories are implemented. The address
that was accessed, however, is not known to any linear memory in use within this
Store. This may be indicative of a critical bug in Wasmtime's code generation
because all addresses which are known to be reachable from wasm won't reach this
message.

    pc:      0x{pc:x}
    address: 0x{addr:x}

This is a possible security issue because WebAssembly has accessed something it
shouldn't have been able to. Other accesses may have succeeded and this one just
happened to be caught. The process will now be aborted to prevent this damage
from going any further and to alert what's going on. If this is a security
issue please reach out to the Wasmtime team via its security policy
at https://bytecodealliance.org/security.
"
                );
                std::process::abort();
            } else if #[cfg(panic = "abort")] {
                // Without the standard library but with `panic=abort` then
                // it's safe to panic as that's known to halt execution. For
                // now avoid the above error message as well since without
                // `std` it's probably best to be a bit more size-conscious.
                let _ = pc;
                panic!("invalid fault");
            } else {
                // Without `std` and with `panic = "unwind"` there's no
                // dedicated API to abort the process portably, so manufacture
                // this with a double-panic.
                let _ = pc;

                struct PanicAgainOnDrop;

                impl Drop for PanicAgainOnDrop {
                    fn drop(&mut self) {
                        panic!("panicking again to trigger a process abort");
                    }

                }

                let _bomb = PanicAgainOnDrop;

                panic!("invalid fault");
            }
        }
    }

    /// Retrieve the store's protection key.
    #[inline]
    #[cfg(feature = "pooling-allocator")]
    pub(crate) fn get_pkey(&self) -> Option<ProtectionKey> {
        self.pkey
    }

    #[inline]
    #[cfg(feature = "component-model")]
    pub(crate) fn component_resource_state(
        &mut self,
    ) -> (
        &mut vm::component::CallContexts,
        &mut vm::component::HandleTable,
        &mut crate::component::HostResourceData,
    ) {
        (
            &mut self.component_calls,
            &mut self.component_host_table,
            &mut self.host_resource_data,
        )
    }

    #[cfg(feature = "component-model")]
    pub(crate) fn push_component_instance(&mut self, instance: crate::component::Instance) {
        // We don't actually need the instance itself right now, but it seems
        // like something we will almost certainly eventually want to keep
        // around, so force callers to provide it.
        let _ = instance;

        self.num_component_instances += 1;
    }

    #[inline]
    #[cfg(feature = "component-model")]
    pub(crate) fn component_resource_state_with_instance(
        &mut self,
        instance: crate::component::Instance,
    ) -> (
        &mut vm::component::CallContexts,
        &mut vm::component::HandleTable,
        &mut crate::component::HostResourceData,
        Pin<&mut vm::component::ComponentInstance>,
    ) {
        (
            &mut self.component_calls,
            &mut self.component_host_table,
            &mut self.host_resource_data,
            instance.id().from_data_get_mut(&mut self.store_data),
        )
    }

    #[cfg(feature = "component-model")]
    pub(crate) fn component_resource_state_with_instance_and_concurrent_state(
        &mut self,
        instance: crate::component::Instance,
    ) -> (
        &mut vm::component::CallContexts,
        &mut vm::component::HandleTable,
        &mut crate::component::HostResourceData,
        Pin<&mut vm::component::ComponentInstance>,
        Option<&mut concurrent::ConcurrentState>,
    ) {
        (
            &mut self.component_calls,
            &mut self.component_host_table,
            &mut self.host_resource_data,
            instance.id().from_data_get_mut(&mut self.store_data),
            self.concurrent_state.as_mut(),
        )
    }

    #[cfg(feature = "async")]
    pub(crate) fn fiber_async_state_mut(&mut self) -> &mut fiber::AsyncState {
        &mut self.async_state
    }

    #[cfg(feature = "component-model-async")]
    pub(crate) fn concurrent_state_mut(&mut self) -> &mut concurrent::ConcurrentState {
        debug_assert!(self.concurrency_support());
        self.concurrent_state.as_mut().unwrap()
    }

    #[inline]
    #[cfg(feature = "component-model")]
    pub(crate) fn concurrency_support(&self) -> bool {
        let support = self.concurrent_state.is_some();
        debug_assert_eq!(support, self.engine().tunables().concurrency_support);
        support
    }

    #[cfg(feature = "async")]
    pub(crate) fn has_pkey(&self) -> bool {
        self.pkey.is_some()
    }

    pub(crate) fn executor(&mut self) -> ExecutorRef<'_> {
        match &mut self.executor {
            Executor::Interpreter(i) => ExecutorRef::Interpreter(i.as_interpreter_ref()),
            #[cfg(has_host_compiler_backend)]
            Executor::Native => ExecutorRef::Native,
        }
    }

    #[cfg(feature = "async")]
    pub(crate) fn swap_executor(&mut self, executor: &mut Executor) {
        mem::swap(&mut self.executor, executor);
    }

    pub(crate) fn unwinder(&self) -> &'static dyn Unwind {
        match &self.executor {
            Executor::Interpreter(i) => i.unwinder(),
            #[cfg(has_host_compiler_backend)]
            Executor::Native => &vm::UnwindHost,
        }
    }

    /// Allocates a new continuation. Note that we currently don't support
    /// deallocating them. Instead, all continuations remain allocated
    /// throughout the store's lifetime.
    #[cfg(feature = "stack-switching")]
    pub fn allocate_continuation(&mut self) -> Result<*mut VMContRef> {
        // FIXME(frank-emrich) Do we need to pin this?
        let mut continuation = Box::new(VMContRef::empty());
        let stack_size = self.engine.config().async_stack_size;
        let stack = crate::vm::VMContinuationStack::new(stack_size)?;
        continuation.stack = stack;
        let ptr = continuation.deref_mut() as *mut VMContRef;
        self.continuations.push(continuation);
        Ok(ptr)
    }

    /// Constructs and executes an `InstanceAllocationRequest` and pushes the
    /// returned instance into the store.
    ///
    /// This is a helper method for invoking
    /// `InstanceAllocator::allocate_module` with the appropriate parameters
    /// from this store's own configuration. The `kind` provided is used to
    /// distinguish between "real" modules and dummy ones that are synthesized
    /// for embedder-created memories, globals, tables, etc. The `kind` will
    /// also use a different instance allocator by default, the one passed in,
    /// rather than the engine's default allocator.
    ///
    /// This method will push the instance within `StoreOpaque` onto the
    /// `instances` array and return the `InstanceId` which can be use to look
    /// it up within the store.
    ///
    /// # Safety
    ///
    /// The `imports` provided must be correctly sized/typed for the module
    /// being allocated.
    pub(crate) async unsafe fn allocate_instance(
        &mut self,
        limiter: Option<&mut StoreResourceLimiter<'_>>,
        kind: AllocateInstanceKind<'_>,
        runtime_info: &ModuleRuntimeInfo,
        imports: Imports<'_>,
    ) -> Result<InstanceId> {
        let id = self.instances.next_key();

        let allocator = match kind {
            AllocateInstanceKind::Module(_) => self.engine().allocator(),
            AllocateInstanceKind::Dummy { allocator } => allocator,
        };
        // SAFETY: this function's own contract is the same as
        // `allocate_module`, namely the imports provided are valid.
        let handle = unsafe {
            allocator
                .allocate_module(InstanceAllocationRequest {
                    id,
                    runtime_info,
                    imports,
                    store: self,
                    limiter,
                })
                .await?
        };

        let actual = match kind {
            AllocateInstanceKind::Module(module_id) => {
                log::trace!(
                    "Adding instance to store: store={:?}, module={module_id:?}, instance={id:?}",
                    self.id()
                );
                self.instances.push(StoreInstance {
                    handle,
                    kind: StoreInstanceKind::Real { module_id },
                })?
            }
            AllocateInstanceKind::Dummy { .. } => {
                log::trace!(
                    "Adding dummy instance to store: store={:?}, instance={id:?}",
                    self.id()
                );
                self.instances.push(StoreInstance {
                    handle,
                    kind: StoreInstanceKind::Dummy,
                })?
            }
        };

        // double-check we didn't accidentally allocate two instances and our
        // prediction of what the id would be is indeed the id it should be.
        assert_eq!(id, actual);

        Ok(id)
    }

    /// Set a pending exception. The `exnref` is taken and held on
    /// this store to be fetched later by an unwind. This method does
    /// *not* set up an unwind request on the TLS call state; that
    /// must be done separately.
    #[cfg(feature = "gc")]
    pub(crate) fn set_pending_exception(&mut self, exnref: VMExnRef) {
        self.pending_exception = Some(exnref);
    }

    /// Take a pending exception, if any.
    #[cfg(feature = "gc")]
    pub(crate) fn take_pending_exception(&mut self) -> Option<VMExnRef> {
        self.pending_exception.take()
    }

    /// Tests whether there is a pending exception.
    #[cfg(feature = "gc")]
    pub fn has_pending_exception(&self) -> bool {
        self.pending_exception.is_some()
    }

    #[cfg(feature = "gc")]
    fn take_pending_exception_rooted(&mut self) -> Option<Rooted<ExnRef>> {
        let vmexnref = self.take_pending_exception()?;
        let mut nogc = AutoAssertNoGc::new(self);
        Some(Rooted::new(&mut nogc, vmexnref.into()))
    }

    /// Get an owned rooted reference to the pending exception,
    /// without taking it off the store.
    #[cfg(all(feature = "gc", feature = "debug"))]
    pub(crate) fn pending_exception_owned_rooted(
        &mut self,
    ) -> Result<Option<OwnedRooted<ExnRef>>, crate::error::OutOfMemory> {
        let mut nogc = AutoAssertNoGc::new(self);
        nogc.pending_exception
            .take()
            .map(|vmexnref| {
                let cloned = nogc.clone_gc_ref(vmexnref.as_gc_ref());
                nogc.pending_exception = Some(cloned.into_exnref_unchecked());
                OwnedRooted::new(&mut nogc, vmexnref.into())
            })
            .transpose()
    }

    #[cfg(feature = "gc")]
    fn throw_impl(&mut self, exception: Rooted<ExnRef>) {
        let mut nogc = AutoAssertNoGc::new(self);
        let exnref = exception._to_raw(&mut nogc).unwrap();
        let exnref = VMGcRef::from_raw_u32(exnref)
            .expect("exception cannot be null")
            .into_exnref_unchecked();
        nogc.set_pending_exception(exnref);
    }

    #[cfg(target_has_atomic = "64")]
    pub(crate) fn set_epoch_deadline(&mut self, delta: u64) {
        // Set a new deadline based on the "epoch deadline delta".
        //
        // Also, note that when this update is performed while Wasm is
        // on the stack, the Wasm will reload the new value once we
        // return into it.
        let current_epoch = self.engine().current_epoch();
        let epoch_deadline = self.vm_store_context.epoch_deadline.get_mut();
        *epoch_deadline = current_epoch + delta;
    }

    pub(crate) fn get_epoch_deadline(&mut self) -> u64 {
        *self.vm_store_context.epoch_deadline.get_mut()
    }

    #[inline]
    pub(crate) fn validate_sync_call(&self) -> Result<()> {
        #[cfg(feature = "async")]
        if self.async_state.async_required {
            bail!("store configuration requires that `*_async` functions are used instead");
        }
        Ok(())
    }

    /// Returns whether this store is presently on a fiber and is allowed to
    /// block via `block_on` with fibers.
    pub(crate) fn can_block(&mut self) -> bool {
        #[cfg(feature = "async")]
        if true {
            return self.fiber_async_state_mut().can_block();
        }

        false
    }

    #[cfg(not(feature = "async"))]
    pub(crate) fn set_async_required(&mut self, asyncness: Asyncness) {
        match asyncness {
            Asyncness::No => {}
        }
    }
}

/// Helper parameter to [`StoreOpaque::allocate_instance`].
pub(crate) enum AllocateInstanceKind<'a> {
    /// An embedder-provided module is being allocated meaning that the default
    /// engine's allocator will be used.
    Module(RegisteredModuleId),

    /// Add a dummy instance that to the store.
    ///
    /// These are instances that are just implementation details of something
    /// else (e.g. host-created memories that are not actually defined in any
    /// Wasm module) and therefore shouldn't show up in things like core dumps.
    ///
    /// A custom, typically OnDemand-flavored, allocator is provided to execute
    /// the allocation.
    Dummy {
        allocator: &'a dyn InstanceAllocator,
    },
}

unsafe impl<T> VMStore for StoreInner<T> {
    #[cfg(feature = "component-model-async")]
    fn component_async_store(
        &mut self,
    ) -> &mut dyn crate::runtime::component::VMComponentAsyncStore {
        self
    }

    fn store_opaque(&self) -> &StoreOpaque {
        &self.inner
    }

    fn store_opaque_mut(&mut self) -> &mut StoreOpaque {
        &mut self.inner
    }

    fn resource_limiter_and_store_opaque(
        &mut self,
    ) -> (Option<StoreResourceLimiter<'_>>, &mut StoreOpaque) {
        let (data, limiter, opaque) = self.data_limiter_and_opaque();

        let limiter = limiter.map(|l| match l {
            ResourceLimiterInner::Sync(s) => StoreResourceLimiter::Sync(s(data)),
            #[cfg(feature = "async")]
            ResourceLimiterInner::Async(s) => StoreResourceLimiter::Async(s(data)),
        });

        (limiter, opaque)
    }

    #[cfg(target_has_atomic = "64")]
    fn new_epoch_updated_deadline(&mut self) -> Result<UpdateDeadline> {
        // Temporarily take the configured behavior to avoid mutably borrowing
        // multiple times.
        let mut behavior = self.epoch_deadline_behavior.take();
        let update = match &mut behavior {
            Some(callback) => callback((&mut *self).as_context_mut()),
            None => Ok(UpdateDeadline::Interrupt),
        };

        // Put back the original behavior which was replaced by `take`.
        self.epoch_deadline_behavior = behavior;
        update
    }

    #[cfg(feature = "component-model")]
    fn component_calls(&mut self) -> &mut vm::component::CallContexts {
        &mut self.component_calls
    }

    #[cfg(feature = "debug")]
    fn block_on_debug_handler(&mut self, event: crate::DebugEvent<'_>) -> crate::Result<()> {
        if let Some(handler) = self.debug_handler.take() {
            if !self.can_block() {
                bail!("could not invoke debug handler without async context");
            }
            log::trace!("about to raise debug event {event:?}");
            StoreContextMut(self).with_blocking(|store, cx| {
                cx.block_on(Pin::from(handler.handle(store, event)).as_mut())
            })
        } else {
            Ok(())
        }
    }
}

impl<T> StoreInner<T> {
    #[cfg(target_has_atomic = "64")]
    fn epoch_deadline_trap(&mut self) {
        self.epoch_deadline_behavior = None;
    }

    #[cfg(target_has_atomic = "64")]
    fn epoch_deadline_callback(
        &mut self,
        callback: Box<dyn FnMut(StoreContextMut<T>) -> Result<UpdateDeadline> + Send + Sync>,
    ) {
        self.epoch_deadline_behavior = Some(callback);
    }
}

impl<T: Default> Default for Store<T> {
    fn default() -> Store<T> {
        Store::new(&Engine::default(), T::default())
    }
}

impl<T: fmt::Debug> fmt::Debug for Store<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let inner = &**self.inner as *const StoreInner<T>;
        f.debug_struct("Store")
            .field("inner", &inner)
            .field("data", self.inner.data())
            .finish()
    }
}

impl<T> Drop for Store<T> {
    fn drop(&mut self) {
        self.run_manual_drop_routines();

        // For documentation on this `unsafe`, see `into_data`.
        unsafe {
            ManuallyDrop::drop(&mut self.inner.data_no_provenance);
            ManuallyDrop::drop(&mut self.inner);
        }
    }
}

impl Drop for StoreOpaque {
    fn drop(&mut self) {
        // NB it's important that this destructor does not access `self.data`.
        // That is deallocated by `Drop for Store<T>` above.

        unsafe {
            let allocator = self.engine.allocator();
            let ondemand = OnDemandInstanceAllocator::default();
            let store_id = self.id();

            #[cfg(feature = "gc")]
            if let Some(gc_store) = self.gc_store.take() {
                let gc_alloc_index = gc_store.allocation_index;
                log::trace!("store {store_id:?} is deallocating GC heap {gc_alloc_index:?}");
                debug_assert!(self.engine.features().gc_types());
                let (mem_alloc_index, mem) =
                    allocator.deallocate_gc_heap(gc_alloc_index, gc_store.gc_heap);
                allocator.deallocate_memory(None, mem_alloc_index, mem);
            }

            for (id, instance) in self.instances.iter_mut() {
                log::trace!("store {store_id:?} is deallocating {id:?}");
                let allocator = match instance.kind {
                    StoreInstanceKind::Dummy => &ondemand,
                    _ => allocator,
                };
                allocator.deallocate_module(&mut instance.handle);
            }

            #[cfg(feature = "component-model")]
            {
                for _ in 0..self.num_component_instances {
                    allocator.decrement_component_instance_count();
                }
            }
        }
    }
}

#[cfg_attr(
    not(any(feature = "gc", feature = "async")),
    // NB: Rust 1.89, current stable, does not fire this lint. Rust 1.90,
    // however, does, so use #[allow] until our MSRV is 1.90.
    allow(dead_code, reason = "don't want to put #[cfg] on all impls below too")
)]
pub(crate) trait AsStoreOpaque {
    fn as_store_opaque(&mut self) -> &mut StoreOpaque;
}

impl AsStoreOpaque for StoreOpaque {
    fn as_store_opaque(&mut self) -> &mut StoreOpaque {
        self
    }
}

impl AsStoreOpaque for dyn VMStore {
    fn as_store_opaque(&mut self) -> &mut StoreOpaque {
        self
    }
}

impl<T: 'static> AsStoreOpaque for Store<T> {
    fn as_store_opaque(&mut self) -> &mut StoreOpaque {
        &mut self.inner.inner
    }
}

impl<T: 'static> AsStoreOpaque for StoreInner<T> {
    fn as_store_opaque(&mut self) -> &mut StoreOpaque {
        self
    }
}

impl<T: AsStoreOpaque + ?Sized> AsStoreOpaque for &mut T {
    fn as_store_opaque(&mut self) -> &mut StoreOpaque {
        T::as_store_opaque(self)
    }
}

/// Helper enum to indicate, in some function contexts, whether `async` should
/// be taken advantage of or not.
///
/// This is used throughout Wasmtime where internal functions are all `async`
/// but external functions might be either sync or `async`. If the external
/// function is sync, then internally Wasmtime shouldn't yield as it won't do
/// anything. If the external function is `async`, however, yields are fine.
///
/// An example of this is GC. Right now GC will cooperatively yield after phases
/// of GC have passed, but this cooperative yielding is only enabled with
/// `Asyncness::Yes`.
///
/// This enum is additionally conditionally defined such that `Yes` is only
/// present in `async`-enabled builds. That ensures that this compiles down to a
/// zero-sized type in `async`-disabled builds in case that interests embedders.
#[derive(PartialEq, Eq, Copy, Clone)]
pub enum Asyncness {
    /// Don't do async things, don't yield, etc. It's ok to execute an `async`
    /// function, but it should be validated ahead of time that when doing so a
    /// yield isn't possible (e.g. `validate_sync_*` methods on Store.
    No,

    /// Async things is OK. This should only be used when the API entrypoint is
    /// itself `async`.
    #[cfg(feature = "async")]
    Yes,
}

impl core::ops::BitOr for Asyncness {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self::Output {
        match (self, rhs) {
            (Asyncness::No, Asyncness::No) => Asyncness::No,
            #[cfg(feature = "async")]
            (Asyncness::Yes, _) | (_, Asyncness::Yes) => Asyncness::Yes,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct FuelTank {
        pub consumed_fuel: i64,
        pub reserve_fuel: u64,
        pub yield_interval: Option<NonZeroU64>,
    }

    impl FuelTank {
        fn new() -> Self {
            FuelTank {
                consumed_fuel: 0,
                reserve_fuel: 0,
                yield_interval: None,
            }
        }
        fn get_fuel(&self) -> u64 {
            get_fuel(self.consumed_fuel, self.reserve_fuel)
        }
        fn refuel(&mut self) -> bool {
            refuel(
                &mut self.consumed_fuel,
                &mut self.reserve_fuel,
                self.yield_interval,
            )
        }
        fn set_fuel(&mut self, fuel: u64) {
            set_fuel(
                &mut self.consumed_fuel,
                &mut self.reserve_fuel,
                self.yield_interval,
                fuel,
            );
        }
    }

    #[test]
    fn smoke() {
        let mut tank = FuelTank::new();
        tank.set_fuel(10);
        assert_eq!(tank.consumed_fuel, -10);
        assert_eq!(tank.reserve_fuel, 0);

        tank.yield_interval = NonZeroU64::new(10);
        tank.set_fuel(25);
        assert_eq!(tank.consumed_fuel, -10);
        assert_eq!(tank.reserve_fuel, 15);
    }

    #[test]
    fn does_not_lose_precision() {
        let mut tank = FuelTank::new();
        tank.set_fuel(u64::MAX);
        assert_eq!(tank.get_fuel(), u64::MAX);

        tank.set_fuel(i64::MAX as u64);
        assert_eq!(tank.get_fuel(), i64::MAX as u64);

        tank.set_fuel(i64::MAX as u64 + 1);
        assert_eq!(tank.get_fuel(), i64::MAX as u64 + 1);
    }

    #[test]
    fn yielding_does_not_lose_precision() {
        let mut tank = FuelTank::new();

        tank.yield_interval = NonZeroU64::new(10);
        tank.set_fuel(u64::MAX);
        assert_eq!(tank.get_fuel(), u64::MAX);
        assert_eq!(tank.consumed_fuel, -10);
        assert_eq!(tank.reserve_fuel, u64::MAX - 10);

        tank.yield_interval = NonZeroU64::new(u64::MAX);
        tank.set_fuel(u64::MAX);
        assert_eq!(tank.get_fuel(), u64::MAX);
        assert_eq!(tank.consumed_fuel, -i64::MAX);
        assert_eq!(tank.reserve_fuel, u64::MAX - (i64::MAX as u64));

        tank.yield_interval = NonZeroU64::new((i64::MAX as u64) + 1);
        tank.set_fuel(u64::MAX);
        assert_eq!(tank.get_fuel(), u64::MAX);
        assert_eq!(tank.consumed_fuel, -i64::MAX);
        assert_eq!(tank.reserve_fuel, u64::MAX - (i64::MAX as u64));
    }

    #[test]
    fn refueling() {
        // It's possible to fuel to have consumed over the limit as some instructions can consume
        // multiple units of fuel at once. Refueling should be strict in it's consumption and not
        // add more fuel than there is.
        let mut tank = FuelTank::new();

        tank.yield_interval = NonZeroU64::new(10);
        tank.reserve_fuel = 42;
        tank.consumed_fuel = 4;
        assert!(tank.refuel());
        assert_eq!(tank.reserve_fuel, 28);
        assert_eq!(tank.consumed_fuel, -10);

        tank.yield_interval = NonZeroU64::new(1);
        tank.reserve_fuel = 8;
        tank.consumed_fuel = 4;
        assert_eq!(tank.get_fuel(), 4);
        assert!(tank.refuel());
        assert_eq!(tank.reserve_fuel, 3);
        assert_eq!(tank.consumed_fuel, -1);
        assert_eq!(tank.get_fuel(), 4);

        tank.yield_interval = NonZeroU64::new(10);
        tank.reserve_fuel = 3;
        tank.consumed_fuel = 4;
        assert_eq!(tank.get_fuel(), 0);
        assert!(!tank.refuel());
        assert_eq!(tank.reserve_fuel, 3);
        assert_eq!(tank.consumed_fuel, 4);
        assert_eq!(tank.get_fuel(), 0);
    }

    #[test]
    fn store_data_provenance() {
        // Test that we juggle pointer provenance and all that correctly, and
        // miri is happy with everything, while allowing both Rust code and
        // "Wasm" to access and modify the store's `T` data. Note that this is
        // not actually Wasm mutating the store data here because compiling Wasm
        // under miri is way too slow.

        unsafe fn run_wasm(store: &mut Store<u32>) {
            let ptr = store
                .inner
                .inner
                .vm_store_context
                .store_data
                .as_ptr()
                .cast::<u32>();
            unsafe { *ptr += 1 }
        }

        let engine = Engine::default();
        let mut store = Store::new(&engine, 0_u32);

        assert_eq!(*store.data(), 0);
        *store.data_mut() += 1;
        assert_eq!(*store.data(), 1);
        unsafe { run_wasm(&mut store) }
        assert_eq!(*store.data(), 2);
        *store.data_mut() += 1;
        assert_eq!(*store.data(), 3);
    }
}