1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
use super::table::{TableDebug, TableId};
use super::{Event, GlobalErrorContextRefCount, Waitable, WaitableCommon};
use crate::component::concurrent::{ConcurrentState, WorkItem, tls};
use crate::component::func::{self, LiftContext, LowerContext};
use crate::component::matching::InstanceType;
use crate::component::types;
use crate::component::values::ErrorContextAny;
use crate::component::{
AsAccessor, ComponentInstanceId, ComponentType, FutureAny, Instance, Lift, Lower, StreamAny,
Val, WasmList,
};
use crate::store::{StoreOpaque, StoreToken};
use crate::vm::component::{ComponentInstance, HandleTable, TransmitLocalState};
use crate::vm::{AlwaysMut, VMStore};
use crate::{AsContext, AsContextMut, StoreContextMut, ValRaw};
use crate::{
Error, Result, bail,
error::{Context as _, format_err},
};
use buffers::{Extender, SliceBuffer, UntypedWriteBuffer};
use core::fmt;
use core::future;
use core::iter;
use core::marker::PhantomData;
use core::mem::{self, MaybeUninit};
use core::pin::Pin;
use core::task::{Context, Poll, Waker, ready};
use futures::channel::oneshot;
use futures::{FutureExt as _, stream};
use std::any::{Any, TypeId};
use std::boxed::Box;
use std::io::Cursor;
use std::string::String;
use std::sync::{Arc, Mutex};
use std::vec::Vec;
use wasmtime_environ::component::{
CanonicalAbiInfo, ComponentTypes, InterfaceType, OptionsIndex, RuntimeComponentInstanceIndex,
TypeComponentGlobalErrorContextTableIndex, TypeComponentLocalErrorContextTableIndex,
TypeFutureTableIndex, TypeStreamTableIndex,
};
pub use buffers::{ReadBuffer, VecBuffer, WriteBuffer};
mod buffers;
/// Enum for distinguishing between a stream or future in functions that handle
/// both.
#[derive(Copy, Clone, Debug)]
pub enum TransmitKind {
Stream,
Future,
}
/// Represents `{stream,future}.{read,write}` results.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum ReturnCode {
Blocked,
Completed(u32),
Dropped(u32),
Cancelled(u32),
}
impl ReturnCode {
/// Pack `self` into a single 32-bit integer that may be returned to the
/// guest.
///
/// This corresponds to `pack_copy_result` in the Component Model spec.
pub fn encode(&self) -> u32 {
const BLOCKED: u32 = 0xffff_ffff;
const COMPLETED: u32 = 0x0;
const DROPPED: u32 = 0x1;
const CANCELLED: u32 = 0x2;
match self {
ReturnCode::Blocked => BLOCKED,
ReturnCode::Completed(n) => {
debug_assert!(*n < (1 << 28));
(n << 4) | COMPLETED
}
ReturnCode::Dropped(n) => {
debug_assert!(*n < (1 << 28));
(n << 4) | DROPPED
}
ReturnCode::Cancelled(n) => {
debug_assert!(*n < (1 << 28));
(n << 4) | CANCELLED
}
}
}
/// Returns `Self::Completed` with the specified count (or zero if
/// `matches!(kind, TransmitKind::Future)`)
fn completed(kind: TransmitKind, count: u32) -> Self {
Self::Completed(if let TransmitKind::Future = kind {
0
} else {
count
})
}
}
/// Represents a stream or future type index.
///
/// This is useful as a parameter type for functions which operate on either a
/// future or a stream.
#[derive(Copy, Clone, Debug)]
pub enum TransmitIndex {
Stream(TypeStreamTableIndex),
Future(TypeFutureTableIndex),
}
impl TransmitIndex {
pub fn kind(&self) -> TransmitKind {
match self {
TransmitIndex::Stream(_) => TransmitKind::Stream,
TransmitIndex::Future(_) => TransmitKind::Future,
}
}
}
/// Retrieve the payload type of the specified stream or future, or `None` if it
/// has no payload type.
fn payload(ty: TransmitIndex, types: &ComponentTypes) -> Option<InterfaceType> {
match ty {
TransmitIndex::Future(ty) => types[types[ty].ty].payload,
TransmitIndex::Stream(ty) => types[types[ty].ty].payload,
}
}
/// Retrieve the host rep and state for the specified guest-visible waitable
/// handle.
fn get_mut_by_index_from(
handle_table: &mut HandleTable,
ty: TransmitIndex,
index: u32,
) -> Result<(u32, &mut TransmitLocalState)> {
match ty {
TransmitIndex::Stream(ty) => handle_table.stream_rep(ty, index),
TransmitIndex::Future(ty) => handle_table.future_rep(ty, index),
}
}
fn lower<T: func::Lower + Send + 'static, B: WriteBuffer<T>, U: 'static>(
mut store: StoreContextMut<U>,
instance: Instance,
options: OptionsIndex,
ty: TransmitIndex,
address: usize,
count: usize,
buffer: &mut B,
) -> Result<()> {
let count = buffer.remaining().len().min(count);
let lower = &mut if T::MAY_REQUIRE_REALLOC {
LowerContext::new
} else {
LowerContext::new_without_realloc
}(store.as_context_mut(), options, instance);
if address % usize::try_from(T::ALIGN32)? != 0 {
bail!("read pointer not aligned");
}
lower
.as_slice_mut()
.get_mut(address..)
.and_then(|b| b.get_mut(..T::SIZE32 * count))
.ok_or_else(|| crate::format_err!("read pointer out of bounds of memory"))?;
if let Some(ty) = payload(ty, lower.types) {
T::linear_store_list_to_memory(lower, ty, address, &buffer.remaining()[..count])?;
}
buffer.skip(count);
Ok(())
}
fn lift<T: func::Lift + Send + 'static, B: ReadBuffer<T>>(
lift: &mut LiftContext<'_>,
ty: Option<InterfaceType>,
buffer: &mut B,
address: usize,
count: usize,
) -> Result<()> {
let count = count.min(buffer.remaining_capacity());
if T::IS_RUST_UNIT_TYPE {
// SAFETY: `T::IS_RUST_UNIT_TYPE` is only true for `()`, a
// zero-sized type, so `MaybeUninit::uninit().assume_init()`
// is a valid way to populate the zero-sized buffer.
buffer.extend(
iter::repeat_with(|| unsafe { MaybeUninit::uninit().assume_init() }).take(count),
)
} else {
let ty = ty.unwrap();
if address % usize::try_from(T::ALIGN32)? != 0 {
bail!("write pointer not aligned");
}
lift.memory()
.get(address..)
.and_then(|b| b.get(..T::SIZE32 * count))
.ok_or_else(|| crate::format_err!("write pointer out of bounds of memory"))?;
let list = &WasmList::new(address, count, lift, ty)?;
T::linear_lift_into_from_memory(lift, list, &mut Extender(buffer))?
}
Ok(())
}
/// Represents the state associated with an error context
#[derive(Debug, PartialEq, Eq, PartialOrd)]
pub(super) struct ErrorContextState {
/// Debug message associated with the error context
pub(crate) debug_msg: String,
}
/// Represents the size and alignment for a "flat" Component Model type,
/// i.e. one containing no pointers or handles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct FlatAbi {
pub(super) size: u32,
pub(super) align: u32,
}
/// Represents the buffer for a host- or guest-initiated stream read.
pub struct Destination<'a, T, B> {
id: TableId<TransmitState>,
buffer: &'a mut B,
host_buffer: Option<&'a mut Cursor<Vec<u8>>>,
_phantom: PhantomData<fn() -> T>,
}
impl<'a, T, B> Destination<'a, T, B> {
/// Reborrow `self` so it can be used again later.
pub fn reborrow(&mut self) -> Destination<'_, T, B> {
Destination {
id: self.id,
buffer: &mut *self.buffer,
host_buffer: self.host_buffer.as_deref_mut(),
_phantom: PhantomData,
}
}
/// Take the buffer out of `self`, leaving a default-initialized one in its
/// place.
///
/// This can be useful for reusing the previously-stored buffer's capacity
/// instead of allocating a fresh one.
pub fn take_buffer(&mut self) -> B
where
B: Default,
{
mem::take(self.buffer)
}
/// Store the specified buffer in `self`.
///
/// Any items contained in the buffer will be delivered to the reader after
/// the `StreamProducer::poll_produce` call to which this `Destination` was
/// passed returns (unless overwritten by another call to `set_buffer`).
///
/// If items are stored via this buffer _and_ written via a
/// `DirectDestination` view of `self`, then the items in the buffer will be
/// delivered after the ones written using `DirectDestination`.
pub fn set_buffer(&mut self, buffer: B) {
*self.buffer = buffer;
}
/// Return the remaining number of items the current read has capacity to
/// accept, if known.
///
/// This will return `Some(_)` if the reader is a guest; it will return
/// `None` if the reader is the host.
///
/// Note that this can return `Some(0)`. This means that the guest is
/// attempting to perform a zero-length read which typically means that it's
/// trying to wait for this stream to be ready-to-read but is not actually
/// ready to receive the items yet. The host in this case is allowed to
/// either block waiting for readiness or immediately complete the
/// operation. The guest is expected to handle both cases. Some more
/// discussion about this case can be found in the discussion of ["Stream
/// Readiness" in the component-model repo][docs].
///
/// [docs]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/Concurrency.md#stream-readiness
pub fn remaining(&self, mut store: impl AsContextMut) -> Option<usize> {
let transmit = store
.as_context_mut()
.0
.concurrent_state_mut()
.get_mut(self.id)
.unwrap();
if let &ReadState::GuestReady { count, .. } = &transmit.read {
let &WriteState::HostReady { guest_offset, .. } = &transmit.write else {
unreachable!()
};
Some(count - guest_offset)
} else {
None
}
}
}
impl<'a, B> Destination<'a, u8, B> {
/// Return a `DirectDestination` view of `self`.
///
/// If the reader is a guest, this will provide direct access to the guest's
/// read buffer. If the reader is a host, this will provide access to a
/// buffer which will be delivered to the host before any items stored using
/// `Destination::set_buffer`.
///
/// `capacity` will only be used if the reader is a host, in which case it
/// will update the length of the buffer, possibly zero-initializing the new
/// elements if the new length is larger than the old length.
pub fn as_direct<D>(
mut self,
store: StoreContextMut<'a, D>,
capacity: usize,
) -> DirectDestination<'a, D> {
if let Some(buffer) = self.host_buffer.as_deref_mut() {
buffer.set_position(0);
if buffer.get_mut().is_empty() {
buffer.get_mut().resize(capacity, 0);
}
}
DirectDestination {
id: self.id,
host_buffer: self.host_buffer,
store,
}
}
}
/// Represents a read from a `stream<u8>`, providing direct access to the
/// writer's buffer.
pub struct DirectDestination<'a, D: 'static> {
id: TableId<TransmitState>,
host_buffer: Option<&'a mut Cursor<Vec<u8>>>,
store: StoreContextMut<'a, D>,
}
impl<D: 'static> std::io::Write for DirectDestination<'_, D> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let rem = self.remaining();
let n = rem.len().min(buf.len());
rem[..n].copy_from_slice(&buf[..n]);
self.mark_written(n);
Ok(n)
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl<D: 'static> DirectDestination<'_, D> {
/// Provide direct access to the writer's buffer.
pub fn remaining(&mut self) -> &mut [u8] {
if let Some(buffer) = self.host_buffer.as_deref_mut() {
buffer.get_mut()
} else {
let transmit = self
.store
.as_context_mut()
.0
.concurrent_state_mut()
.get_mut(self.id)
.unwrap();
let &ReadState::GuestReady {
address,
count,
options,
instance,
..
} = &transmit.read
else {
unreachable!();
};
let &WriteState::HostReady { guest_offset, .. } = &transmit.write else {
unreachable!()
};
instance
.options_memory_mut(self.store.0, options)
.get_mut((address + guest_offset)..)
.and_then(|b| b.get_mut(..(count - guest_offset)))
.unwrap()
}
}
/// Mark the specified number of bytes as written to the writer's buffer.
///
/// This will panic if the count is larger than the size of the
/// buffer returned by `Self::remaining`.
pub fn mark_written(&mut self, count: usize) {
if let Some(buffer) = self.host_buffer.as_deref_mut() {
buffer.set_position(
buffer
.position()
.checked_add(u64::try_from(count).unwrap())
.unwrap(),
);
} else {
let transmit = self
.store
.as_context_mut()
.0
.concurrent_state_mut()
.get_mut(self.id)
.unwrap();
let ReadState::GuestReady {
count: read_count, ..
} = &transmit.read
else {
unreachable!();
};
let WriteState::HostReady { guest_offset, .. } = &mut transmit.write else {
unreachable!()
};
if *guest_offset + count > *read_count {
panic!(
"write count ({count}) must be less than or equal to read count ({read_count})"
)
} else {
*guest_offset += count;
}
}
}
}
/// Represents the state of a `Stream{Producer,Consumer}`.
#[derive(Copy, Clone, Debug)]
pub enum StreamResult {
/// The operation completed normally, and the producer or consumer may be
/// able to produce or consume more items, respectively.
Completed,
/// The operation was interrupted (i.e. it wrapped up early after receiving
/// a `finish` parameter value of true in a call to `poll_produce` or
/// `poll_consume`), and the producer or consumer may be able to produce or
/// consume more items, respectively.
Cancelled,
/// The operation completed normally, but the producer or consumer will
/// _not_ able to produce or consume more items, respectively.
Dropped,
}
/// Represents the host-owned write end of a stream.
pub trait StreamProducer<D>: Send + 'static {
/// The payload type of this stream.
type Item;
/// The `WriteBuffer` type to use when delivering items.
type Buffer: WriteBuffer<Self::Item> + Default;
/// Handle a host- or guest-initiated read by delivering zero or more items
/// to the specified destination.
///
/// This will be called whenever the reader starts a read.
///
/// # Arguments
///
/// * `self` - a `Pin`'d version of self to perform Rust-level
/// future-related operations on.
/// * `cx` - a Rust-related [`Context`] which is passed to other
/// future-related operations or used to acquire a waker.
/// * `store` - the Wasmtime store that this operation is happening within.
/// Used, for example, to consult the state `D` associated with the store.
/// * `destination` - the location that items are to be written to.
/// * `finish` - a flag indicating whether the host should strive to
/// immediately complete/cancel any pending operation. See below for more
/// details.
///
/// # Behavior
///
/// If the implementation is able to produce one or more items immediately,
/// it should write them to `destination` and return either
/// `Poll::Ready(Ok(StreamResult::Completed))` if it expects to produce more
/// items, or `Poll::Ready(Ok(StreamResult::Dropped))` if it cannot produce
/// any more items.
///
/// If the implementation is unable to produce any items immediately, but
/// expects to do so later, and `finish` is _false_, it should store the
/// waker from `cx` for later and return `Poll::Pending` without writing
/// anything to `destination`. Later, it should alert the waker when either
/// the items arrive, the stream has ended, or an error occurs.
///
/// If more items are written to `destination` than the reader has immediate
/// capacity to accept, they will be retained in memory by the caller and
/// used to satisfy future reads, in which case `poll_produce` will only be
/// called again once all those items have been delivered.
///
/// # Zero-length reads
///
/// This function may be called with a zero-length capacity buffer
/// (i.e. `Destination::remaining` returns `Some(0)`). This indicates that
/// the guest wants to wait to see if an item is ready without actually
/// reading the item. For example think of a UNIX `poll` function run on a
/// TCP stream, seeing if it's readable without actually reading it.
///
/// In this situation the host is allowed to either return immediately or
/// wait for readiness. Note that waiting for readiness is not always
/// possible. For example it's impossible to test if a Rust-native `Future`
/// is ready without actually reading the item. Stream-specific
/// optimizations, such as testing if a TCP stream is readable, may be
/// possible however.
///
/// For a zero-length read, the host is allowed to:
///
/// - Return `Poll::Ready(Ok(StreamResult::Completed))` without writing
/// anything if it expects to be able to produce items immediately (i.e.
/// without first returning `Poll::Pending`) the next time `poll_produce`
/// is called with non-zero capacity. This is the best-case scenario of
/// fulfilling the guest's desire -- items aren't read/buffered but the
/// host is saying it's ready when the guest is.
///
/// - Return `Poll::Ready(Ok(StreamResult::Completed))` without actually
/// testing for readiness. The guest doesn't know this yet, but the guest
/// will realize that zero-length reads won't work on this stream when a
/// subsequent nonzero read attempt is made which returns `Poll::Pending`
/// here.
///
/// - Return `Poll::Pending` if the host has performed necessary async work
/// to wait for this stream to be readable without actually reading
/// anything. This is also a best-case scenario where the host is letting
/// the guest know that nothing is ready yet. Later the zero-length read
/// will complete and then the guest will attempt a nonzero-length read to
/// actually read some bytes.
///
/// - Return `Poll::Ready(Ok(StreamResult::Completed))` after calling
/// `Destination::set_buffer` with one more more items. Note, however,
/// that this creates the hazard that the items will never be received by
/// the guest if it decides not to do another non-zero-length read before
/// closing the stream. Moreover, if `Self::Item` is e.g. a
/// `Resource<_>`, they may end up leaking in that scenario. It is not
/// recommended to do this and it's better to return
/// `StreamResult::Completed` without buffering anything instead.
///
/// For more discussion on zero-length reads see the [documentation in the
/// component-model repo itself][docs].
///
/// [docs]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/Concurrency.md#stream-readiness
///
/// # Return
///
/// This function can return a number of possible cases from this function:
///
/// * `Poll::Pending` - this operation cannot complete at this time. The
/// Rust-level `Future::poll` contract applies here where a waker should
/// be stored from the `cx` argument and be arranged to receive a
/// notification when this implementation can make progress. For example
/// if you call `Future::poll` on a sub-future, that's enough. If items
/// were written to `destination` then a trap in the guest will be raised.
///
/// Note that implementations should strive to avoid this return value
/// when `finish` is `true`. In such a situation the guest is attempting
/// to, for example, cancel a previous operation. By returning
/// `Poll::Pending` the guest will be blocked during the cancellation
/// request. If `finish` is `true` then `StreamResult::Cancelled` is
/// favored to indicate that no items were read. If a short read happened,
/// however, it's ok to return `StreamResult::Completed` indicating some
/// items were read.
///
/// * `Poll::Ok(StreamResult::Completed)` - items, if applicable, were
/// written to the `destination`.
///
/// * `Poll::Ok(StreamResult::Cancelled)` - used when `finish` is `true` and
/// the implementation was able to successfully cancel any async work that
/// a previous read kicked off, if any. The host should not buffer values
/// received after returning `Cancelled` because the guest will not be
/// aware of these values and the guest could close the stream after
/// cancelling a read. Hosts should only return `Cancelled` when there are
/// no more async operations in flight for a previous read.
///
/// If items were written to `destination` then a trap in the guest will
/// be raised. If `finish` is `false` then this return value will raise a
/// trap in the guest.
///
/// * `Poll::Ok(StreamResult::Dropped)` - end-of-stream marker, indicating
/// that this producer should not be polled again. Note that items may
/// still be written to `destination`.
///
/// # Errors
///
/// The implementation may alternatively choose to return `Err(_)` to
/// indicate an unrecoverable error. This will cause the guest (if any) to
/// trap and render the component instance (if any) unusable. The
/// implementation should report errors that _are_ recoverable by other
/// means (e.g. by writing to a `future`) and return
/// `Poll::Ready(Ok(StreamResult::Dropped))`.
fn poll_produce<'a>(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
store: StoreContextMut<'a, D>,
destination: Destination<'a, Self::Item, Self::Buffer>,
finish: bool,
) -> Poll<Result<StreamResult>>;
/// Attempt to convert the specified object into a `Box<dyn Any>` which may
/// be downcast to the specified type.
///
/// The implementation must ensure that, if it returns `Ok(_)`, a downcast
/// to the specified type is guaranteed to succeed.
fn try_into(me: Pin<Box<Self>>, _ty: TypeId) -> Result<Box<dyn Any>, Pin<Box<Self>>> {
Err(me)
}
}
impl<T, D> StreamProducer<D> for iter::Empty<T>
where
T: Send + Sync + 'static,
{
type Item = T;
type Buffer = Option<Self::Item>;
fn poll_produce<'a>(
self: Pin<&mut Self>,
_: &mut Context<'_>,
_: StoreContextMut<'a, D>,
_: Destination<'a, Self::Item, Self::Buffer>,
_: bool,
) -> Poll<Result<StreamResult>> {
Poll::Ready(Ok(StreamResult::Dropped))
}
}
impl<T, D> StreamProducer<D> for stream::Empty<T>
where
T: Send + Sync + 'static,
{
type Item = T;
type Buffer = Option<Self::Item>;
fn poll_produce<'a>(
self: Pin<&mut Self>,
_: &mut Context<'_>,
_: StoreContextMut<'a, D>,
_: Destination<'a, Self::Item, Self::Buffer>,
_: bool,
) -> Poll<Result<StreamResult>> {
Poll::Ready(Ok(StreamResult::Dropped))
}
}
impl<T, D> StreamProducer<D> for Vec<T>
where
T: Unpin + Send + Sync + 'static,
{
type Item = T;
type Buffer = VecBuffer<T>;
fn poll_produce<'a>(
self: Pin<&mut Self>,
_: &mut Context<'_>,
_: StoreContextMut<'a, D>,
mut dst: Destination<'a, Self::Item, Self::Buffer>,
_: bool,
) -> Poll<Result<StreamResult>> {
dst.set_buffer(mem::take(self.get_mut()).into());
Poll::Ready(Ok(StreamResult::Dropped))
}
}
impl<T, D> StreamProducer<D> for Box<[T]>
where
T: Unpin + Send + Sync + 'static,
{
type Item = T;
type Buffer = VecBuffer<T>;
fn poll_produce<'a>(
self: Pin<&mut Self>,
_: &mut Context<'_>,
_: StoreContextMut<'a, D>,
mut dst: Destination<'a, Self::Item, Self::Buffer>,
_: bool,
) -> Poll<Result<StreamResult>> {
dst.set_buffer(mem::take(self.get_mut()).into_vec().into());
Poll::Ready(Ok(StreamResult::Dropped))
}
}
#[cfg(feature = "component-model-async-bytes")]
impl<D> StreamProducer<D> for bytes::Bytes {
type Item = u8;
type Buffer = Cursor<Self>;
fn poll_produce<'a>(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
mut store: StoreContextMut<'a, D>,
mut dst: Destination<'a, Self::Item, Self::Buffer>,
_: bool,
) -> Poll<Result<StreamResult>> {
let cap = dst.remaining(&mut store);
let Some(cap) = cap.and_then(core::num::NonZeroUsize::new) else {
// on 0-length or host reads, buffer the bytes
dst.set_buffer(Cursor::new(mem::take(self.get_mut())));
return Poll::Ready(Ok(StreamResult::Dropped));
};
let cap = cap.into();
// data does not fit in destination, fill it and buffer the rest
dst.set_buffer(Cursor::new(self.split_off(cap)));
let mut dst = dst.as_direct(store, cap);
dst.remaining().copy_from_slice(&self);
dst.mark_written(cap);
Poll::Ready(Ok(StreamResult::Dropped))
}
}
#[cfg(feature = "component-model-async-bytes")]
impl<D> StreamProducer<D> for bytes::BytesMut {
type Item = u8;
type Buffer = Cursor<Self>;
fn poll_produce<'a>(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
mut store: StoreContextMut<'a, D>,
mut dst: Destination<'a, Self::Item, Self::Buffer>,
_: bool,
) -> Poll<Result<StreamResult>> {
let cap = dst.remaining(&mut store);
let Some(cap) = cap.and_then(core::num::NonZeroUsize::new) else {
// on 0-length or host reads, buffer the bytes
dst.set_buffer(Cursor::new(mem::take(self.get_mut())));
return Poll::Ready(Ok(StreamResult::Dropped));
};
let cap = cap.into();
// data does not fit in destination, fill it and buffer the rest
dst.set_buffer(Cursor::new(self.split_off(cap)));
let mut dst = dst.as_direct(store, cap);
dst.remaining().copy_from_slice(&self);
dst.mark_written(cap);
Poll::Ready(Ok(StreamResult::Dropped))
}
}
/// Represents the buffer for a host- or guest-initiated stream write.
pub struct Source<'a, T> {
id: TableId<TransmitState>,
host_buffer: Option<&'a mut dyn WriteBuffer<T>>,
}
impl<'a, T> Source<'a, T> {
/// Reborrow `self` so it can be used again later.
pub fn reborrow(&mut self) -> Source<'_, T> {
Source {
id: self.id,
host_buffer: self.host_buffer.as_deref_mut(),
}
}
/// Accept zero or more items from the writer.
pub fn read<B, S: AsContextMut>(&mut self, mut store: S, buffer: &mut B) -> Result<()>
where
T: func::Lift + 'static,
B: ReadBuffer<T>,
{
if let Some(input) = &mut self.host_buffer {
let count = input.remaining().len().min(buffer.remaining_capacity());
buffer.move_from(*input, count);
} else {
let store = store.as_context_mut();
let transmit = store.0.concurrent_state_mut().get_mut(self.id)?;
let &ReadState::HostReady { guest_offset, .. } = &transmit.read else {
unreachable!();
};
let &WriteState::GuestReady {
ty,
address,
count,
options,
instance,
..
} = &transmit.write
else {
unreachable!()
};
let cx = &mut LiftContext::new(store.0.store_opaque_mut(), options, instance);
let ty = payload(ty, cx.types);
let old_remaining = buffer.remaining_capacity();
lift::<T, B>(
cx,
ty,
buffer,
address + (T::SIZE32 * guest_offset),
count - guest_offset,
)?;
let transmit = store.0.concurrent_state_mut().get_mut(self.id)?;
let ReadState::HostReady { guest_offset, .. } = &mut transmit.read else {
unreachable!();
};
*guest_offset += old_remaining - buffer.remaining_capacity();
}
Ok(())
}
/// Return the number of items remaining to be read from the current write
/// operation.
pub fn remaining(&self, mut store: impl AsContextMut) -> usize
where
T: 'static,
{
let transmit = store
.as_context_mut()
.0
.concurrent_state_mut()
.get_mut(self.id)
.unwrap();
if let &WriteState::GuestReady { count, .. } = &transmit.write {
let &ReadState::HostReady { guest_offset, .. } = &transmit.read else {
unreachable!()
};
count - guest_offset
} else if let Some(host_buffer) = &self.host_buffer {
host_buffer.remaining().len()
} else {
unreachable!()
}
}
}
impl<'a> Source<'a, u8> {
/// Return a `DirectSource` view of `self`.
pub fn as_direct<D>(self, store: StoreContextMut<'a, D>) -> DirectSource<'a, D> {
DirectSource {
id: self.id,
host_buffer: self.host_buffer,
store,
}
}
}
/// Represents a write to a `stream<u8>`, providing direct access to the
/// writer's buffer.
pub struct DirectSource<'a, D: 'static> {
id: TableId<TransmitState>,
host_buffer: Option<&'a mut dyn WriteBuffer<u8>>,
store: StoreContextMut<'a, D>,
}
impl<D: 'static> std::io::Read for DirectSource<'_, D> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let rem = self.remaining();
let n = rem.len().min(buf.len());
buf[..n].copy_from_slice(&rem[..n]);
self.mark_read(n);
Ok(n)
}
}
impl<D: 'static> DirectSource<'_, D> {
/// Provide direct access to the writer's buffer.
pub fn remaining(&mut self) -> &[u8] {
if let Some(buffer) = self.host_buffer.as_deref_mut() {
buffer.remaining()
} else {
let transmit = self
.store
.as_context_mut()
.0
.concurrent_state_mut()
.get_mut(self.id)
.unwrap();
let &WriteState::GuestReady {
address,
count,
options,
instance,
..
} = &transmit.write
else {
unreachable!()
};
let &ReadState::HostReady { guest_offset, .. } = &transmit.read else {
unreachable!()
};
instance
.options_memory(self.store.0, options)
.get((address + guest_offset)..)
.and_then(|b| b.get(..(count - guest_offset)))
.unwrap()
}
}
/// Mark the specified number of bytes as read from the writer's buffer.
///
/// This will panic if the count is larger than the size of the buffer
/// returned by `Self::remaining`.
pub fn mark_read(&mut self, count: usize) {
if let Some(buffer) = self.host_buffer.as_deref_mut() {
buffer.skip(count);
} else {
let transmit = self
.store
.as_context_mut()
.0
.concurrent_state_mut()
.get_mut(self.id)
.unwrap();
let WriteState::GuestReady {
count: write_count, ..
} = &transmit.write
else {
unreachable!()
};
let ReadState::HostReady { guest_offset, .. } = &mut transmit.read else {
unreachable!()
};
if *guest_offset + count > *write_count {
panic!(
"read count ({count}) must be less than or equal to write count ({write_count})"
)
} else {
*guest_offset += count;
}
}
}
}
/// Represents the host-owned read end of a stream.
pub trait StreamConsumer<D>: Send + 'static {
/// The payload type of this stream.
type Item;
/// Handle a host- or guest-initiated write by accepting zero or more items
/// from the specified source.
///
/// This will be called whenever the writer starts a write.
///
/// If the implementation is able to consume one or more items immediately,
/// it should take them from `source` and return either
/// `Poll::Ready(Ok(StreamResult::Completed))` if it expects to be able to consume
/// more items, or `Poll::Ready(Ok(StreamResult::Dropped))` if it cannot
/// accept any more items. Alternatively, it may return `Poll::Pending` to
/// indicate that the caller should delay sending a `COMPLETED` event to the
/// writer until a later call to this function returns `Poll::Ready(_)`.
/// For more about that, see the `Backpressure` section below.
///
/// If the implementation cannot consume any items immediately and `finish`
/// is _false_, it should store the waker from `cx` for later and return
/// `Poll::Pending` without writing anything to `destination`. Later, it
/// should alert the waker when either (1) the items arrive, (2) the stream
/// has ended, or (3) an error occurs.
///
/// If the implementation cannot consume any items immediately and `finish`
/// is _true_, it should, if possible, return
/// `Poll::Ready(Ok(StreamResult::Cancelled))` immediately without taking
/// anything from `source`. However, that might not be possible if an
/// earlier call to `poll_consume` kicked off an asynchronous operation
/// which needs to be completed (and possibly interrupted) gracefully, in
/// which case the implementation may return `Poll::Pending` and later alert
/// the waker as described above. In other words, when `finish` is true,
/// the implementation should prioritize returning a result to the reader
/// (even if no items can be consumed) rather than wait indefinitely for at
/// capacity to free up.
///
/// In all of the above cases, the implementation may alternatively choose
/// to return `Err(_)` to indicate an unrecoverable error. This will cause
/// the guest (if any) to trap and render the component instance (if any)
/// unusable. The implementation should report errors that _are_
/// recoverable by other means (e.g. by writing to a `future`) and return
/// `Poll::Ready(Ok(StreamResult::Dropped))`.
///
/// Note that the implementation should only return
/// `Poll::Ready(Ok(StreamResult::Cancelled))` without having taken any
/// items from `source` if called with `finish` set to true. If it does so
/// when `finish` is false, the caller will trap. Additionally, it should
/// only return `Poll::Ready(Ok(StreamResult::Completed))` after taking at
/// least one item from `source` if there is an item available; otherwise,
/// the caller will trap. If `poll_consume` is called with no items in
/// `source`, it should only return `Poll::Ready(_)` once it is able to
/// accept at least one item during the next call to `poll_consume`.
///
/// Note that any items which the implementation of this trait takes from
/// `source` become the responsibility of that implementation. For that
/// reason, an implementation which forwards items to an upstream sink
/// should reserve capacity in that sink before taking items out of
/// `source`, if possible. Alternatively, it might buffer items which can't
/// be forwarded immediately and send them once capacity is freed up.
///
/// ## Backpressure
///
/// As mentioned above, an implementation might choose to return
/// `Poll::Pending` after taking items from `source`, which tells the caller
/// to delay sending a `COMPLETED` event to the writer. This can be used as
/// a form of backpressure when the items are forwarded to an upstream sink
/// asynchronously. Note, however, that it's not possible to "put back"
/// items into `source` once they've been taken out, so if the upstream sink
/// is unable to accept all the items, that cannot be communicated to the
/// writer at this level of abstraction. Just as with application-specific,
/// recoverable errors, information about which items could be forwarded and
/// which could not must be communicated out-of-band, e.g. by writing to an
/// application-specific `future`.
///
/// Similarly, if the writer cancels the write after items have been taken
/// from `source` but before the items have all been forwarded to an
/// upstream sink, `poll_consume` will be called with `finish` set to true,
/// and the implementation may either:
///
/// - Interrupt the forwarding process gracefully. This may be preferable
/// if there is an out-of-band channel for communicating to the writer how
/// many items were forwarded before being interrupted.
///
/// - Allow the forwarding to complete without interrupting it. This is
/// usually preferable if there's no out-of-band channel for reporting back
/// to the writer how many items were forwarded.
fn poll_consume(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
store: StoreContextMut<D>,
source: Source<'_, Self::Item>,
finish: bool,
) -> Poll<Result<StreamResult>>;
}
/// Represents a host-owned write end of a future.
pub trait FutureProducer<D>: Send + 'static {
/// The payload type of this future.
type Item;
/// Handle a host- or guest-initiated read by producing a value.
///
/// This is equivalent to `StreamProducer::poll_produce`, but with a
/// simplified interface for futures.
///
/// If `finish` is true, the implementation may return
/// `Poll::Ready(Ok(None))` to indicate the operation was canceled before it
/// could produce a value. Otherwise, it must either return
/// `Poll::Ready(Ok(Some(_)))`, `Poll::Ready(Err(_))`, or `Poll::Pending`.
fn poll_produce(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
store: StoreContextMut<D>,
finish: bool,
) -> Poll<Result<Option<Self::Item>>>;
}
impl<T, E, D, Fut> FutureProducer<D> for Fut
where
E: Into<Error>,
Fut: Future<Output = Result<T, E>> + ?Sized + Send + 'static,
{
type Item = T;
fn poll_produce<'a>(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
_: StoreContextMut<'a, D>,
finish: bool,
) -> Poll<Result<Option<T>>> {
match self.poll(cx) {
Poll::Ready(Ok(v)) => Poll::Ready(Ok(Some(v))),
Poll::Ready(Err(err)) => Poll::Ready(Err(err.into())),
Poll::Pending if finish => Poll::Ready(Ok(None)),
Poll::Pending => Poll::Pending,
}
}
}
/// Represents a host-owned read end of a future.
pub trait FutureConsumer<D>: Send + 'static {
/// The payload type of this future.
type Item;
/// Handle a host- or guest-initiated write by consuming a value.
///
/// This is equivalent to `StreamProducer::poll_produce`, but with a
/// simplified interface for futures.
///
/// If `finish` is true, the implementation may return `Poll::Ready(Ok(()))`
/// without taking the item from `source`, which indicates the operation was
/// canceled before it could consume the value. Otherwise, it must either
/// take the item from `source` and return `Poll::Ready(Ok(()))`, or else
/// return `Poll::Ready(Err(_))` or `Poll::Pending` (with or without taking
/// the item).
fn poll_consume(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
store: StoreContextMut<D>,
source: Source<'_, Self::Item>,
finish: bool,
) -> Poll<Result<()>>;
}
/// Represents the readable end of a Component Model `future`.
///
/// Note that `FutureReader` instances must be disposed of using either `pipe`
/// or `close`; otherwise the in-store representation will leak and the writer
/// end will hang indefinitely. Consider using [`GuardedFutureReader`] to
/// ensure that disposal happens automatically.
pub struct FutureReader<T> {
id: TableId<TransmitHandle>,
_phantom: PhantomData<T>,
}
impl<T> FutureReader<T> {
/// Create a new future with the specified producer.
///
/// # Panics
///
/// Panics if [`Config::concurrency_support`] is not enabled.
///
/// [`Config::concurrency_support`]: crate::Config::concurrency_support
pub fn new<S: AsContextMut>(
mut store: S,
producer: impl FutureProducer<S::Data, Item = T>,
) -> Self
where
T: func::Lower + func::Lift + Send + Sync + 'static,
{
assert!(store.as_context().0.concurrency_support());
struct Producer<P>(P);
impl<D, T: func::Lower + 'static, P: FutureProducer<D, Item = T>> StreamProducer<D>
for Producer<P>
{
type Item = P::Item;
type Buffer = Option<P::Item>;
fn poll_produce<'a>(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
store: StoreContextMut<D>,
mut destination: Destination<'a, Self::Item, Self::Buffer>,
finish: bool,
) -> Poll<Result<StreamResult>> {
// SAFETY: This is a standard pin-projection, and we never move
// out of `self`.
let producer = unsafe { self.map_unchecked_mut(|v| &mut v.0) };
Poll::Ready(Ok(
if let Some(value) = ready!(producer.poll_produce(cx, store, finish))? {
destination.set_buffer(Some(value));
// Here we return `StreamResult::Completed` even though
// we've produced the last item we'll ever produce.
// That's because the ABI expects
// `ReturnCode::Completed(1)` rather than
// `ReturnCode::Dropped(1)`. In any case, we won't be
// called again since the future will have resolved.
StreamResult::Completed
} else {
StreamResult::Cancelled
},
))
}
}
Self::new_(
store
.as_context_mut()
.new_transmit(TransmitKind::Future, Producer(producer)),
)
}
pub(super) fn new_(id: TableId<TransmitHandle>) -> Self {
Self {
id,
_phantom: PhantomData,
}
}
pub(super) fn id(&self) -> TableId<TransmitHandle> {
self.id
}
/// Set the consumer that accepts the result of this future.
pub fn pipe<S: AsContextMut>(
self,
mut store: S,
consumer: impl FutureConsumer<S::Data, Item = T> + Unpin,
) where
T: func::Lift + 'static,
{
struct Consumer<C>(C);
impl<D: 'static, T: func::Lift + 'static, C: FutureConsumer<D, Item = T>> StreamConsumer<D>
for Consumer<C>
{
type Item = T;
fn poll_consume(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
mut store: StoreContextMut<D>,
mut source: Source<Self::Item>,
finish: bool,
) -> Poll<Result<StreamResult>> {
// SAFETY: This is a standard pin-projection, and we never move
// out of `self`.
let consumer = unsafe { self.map_unchecked_mut(|v| &mut v.0) };
ready!(consumer.poll_consume(
cx,
store.as_context_mut(),
source.reborrow(),
finish
))?;
Poll::Ready(Ok(if source.remaining(store) == 0 {
// Here we return `StreamResult::Completed` even though
// we've consumed the last item we'll ever consume. That's
// because the ABI expects `ReturnCode::Completed(1)` rather
// than `ReturnCode::Dropped(1)`. In any case, we won't be
// called again since the future will have resolved.
StreamResult::Completed
} else {
StreamResult::Cancelled
}))
}
}
store
.as_context_mut()
.set_consumer(self.id, TransmitKind::Future, Consumer(consumer));
}
/// Transfer ownership of the read end of a future from a guest to the host.
fn lift_from_index(cx: &mut LiftContext<'_>, ty: InterfaceType, index: u32) -> Result<Self> {
let id = lift_index_to_future(cx, ty, index)?;
Ok(Self::new_(id))
}
/// Close this `FutureReader`.
///
/// This will close this half of the future which will signal to a pending
/// write, if any, that the reader side is dropped. If the writer half has
/// not yet written a value then when it attempts to write a value it will
/// see that this end is closed.
///
/// # Panics
///
/// Panics if the store that the [`Accessor`] is derived from does not own
/// this future. Usage of this future after calling `close` will also cause
/// a panic.
///
/// [`Accessor`]: crate::component::Accessor
pub fn close(&mut self, mut store: impl AsContextMut) {
future_close(store.as_context_mut().0, &mut self.id)
}
/// Convenience method around [`Self::close`].
pub fn close_with(&mut self, accessor: impl AsAccessor) {
accessor.as_accessor().with(|access| self.close(access))
}
/// Returns a [`GuardedFutureReader`] which will auto-close this future on
/// drop and clean it up from the store.
///
/// Note that the `accessor` provided must own this future and is
/// additionally transferred to the `GuardedFutureReader` return value.
pub fn guard<A>(self, accessor: A) -> GuardedFutureReader<T, A>
where
A: AsAccessor,
{
GuardedFutureReader::new(accessor, self)
}
/// Attempts to convert this [`FutureReader<T>`] to a [`FutureAny`].
///
/// # Errors
///
/// This function will return an error if `self` does not belong to
/// `store`.
pub fn try_into_future_any(self, store: impl AsContextMut) -> Result<FutureAny>
where
T: ComponentType + 'static,
{
FutureAny::try_from_future_reader(store, self)
}
/// Attempts to convert a [`FutureAny`] into a [`FutureReader<T>`].
///
/// # Errors
///
/// This function will fail if `T` doesn't match the type of the value that
/// `future` is sending.
pub fn try_from_future_any(future: FutureAny) -> Result<Self>
where
T: ComponentType + 'static,
{
future.try_into_future_reader()
}
}
impl<T> fmt::Debug for FutureReader<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FutureReader")
.field("id", &self.id)
.finish()
}
}
pub(super) fn future_close(store: &mut StoreOpaque, id: &mut TableId<TransmitHandle>) {
let id = mem::replace(id, TableId::new(u32::MAX));
store.host_drop_reader(id, TransmitKind::Future).unwrap();
}
/// Transfer ownership of the read end of a future from the host to a guest.
pub(super) fn lift_index_to_future(
cx: &mut LiftContext<'_>,
ty: InterfaceType,
index: u32,
) -> Result<TableId<TransmitHandle>> {
match ty {
InterfaceType::Future(src) => {
let handle_table = cx
.instance_mut()
.table_for_transmit(TransmitIndex::Future(src));
let (rep, is_done) = handle_table.future_remove_readable(src, index)?;
if is_done {
bail!("cannot lift future after being notified that the writable end dropped");
}
let id = TableId::<TransmitHandle>::new(rep);
let concurrent_state = cx.concurrent_state_mut();
let future = concurrent_state.get_mut(id)?;
future.common.handle = None;
let state = future.state;
if concurrent_state.get_mut(state)?.done {
bail!("cannot lift future after previous read succeeded");
}
Ok(id)
}
_ => func::bad_type_info(),
}
}
/// Transfer ownership of the read end of a future from the host to a guest.
pub(super) fn lower_future_to_index<U>(
id: TableId<TransmitHandle>,
cx: &mut LowerContext<'_, U>,
ty: InterfaceType,
) -> Result<u32> {
match ty {
InterfaceType::Future(dst) => {
let concurrent_state = cx.store.0.concurrent_state_mut();
let state = concurrent_state.get_mut(id)?.state;
let rep = concurrent_state.get_mut(state)?.read_handle.rep();
let handle = cx
.instance_mut()
.table_for_transmit(TransmitIndex::Future(dst))
.future_insert_read(dst, rep)?;
cx.store.0.concurrent_state_mut().get_mut(id)?.common.handle = Some(handle);
Ok(handle)
}
_ => func::bad_type_info(),
}
}
// SAFETY: This relies on the `ComponentType` implementation for `u32` being
// safe and correct since we lift and lower future handles as `u32`s.
unsafe impl<T: ComponentType> ComponentType for FutureReader<T> {
const ABI: CanonicalAbiInfo = CanonicalAbiInfo::SCALAR4;
type Lower = <u32 as func::ComponentType>::Lower;
fn typecheck(ty: &InterfaceType, types: &InstanceType<'_>) -> Result<()> {
match ty {
InterfaceType::Future(ty) => {
let ty = types.types[*ty].ty;
types::typecheck_payload::<T>(types.types[ty].payload.as_ref(), types)
}
other => bail!("expected `future`, found `{}`", func::desc(other)),
}
}
}
// SAFETY: See the comment on the `ComponentType` `impl` for this type.
unsafe impl<T: ComponentType> func::Lower for FutureReader<T> {
fn linear_lower_to_flat<U>(
&self,
cx: &mut LowerContext<'_, U>,
ty: InterfaceType,
dst: &mut MaybeUninit<Self::Lower>,
) -> Result<()> {
lower_future_to_index(self.id, cx, ty)?.linear_lower_to_flat(cx, InterfaceType::U32, dst)
}
fn linear_lower_to_memory<U>(
&self,
cx: &mut LowerContext<'_, U>,
ty: InterfaceType,
offset: usize,
) -> Result<()> {
lower_future_to_index(self.id, cx, ty)?.linear_lower_to_memory(
cx,
InterfaceType::U32,
offset,
)
}
}
// SAFETY: See the comment on the `ComponentType` `impl` for this type.
unsafe impl<T: ComponentType> func::Lift for FutureReader<T> {
fn linear_lift_from_flat(
cx: &mut LiftContext<'_>,
ty: InterfaceType,
src: &Self::Lower,
) -> Result<Self> {
let index = u32::linear_lift_from_flat(cx, InterfaceType::U32, src)?;
Self::lift_from_index(cx, ty, index)
}
fn linear_lift_from_memory(
cx: &mut LiftContext<'_>,
ty: InterfaceType,
bytes: &[u8],
) -> Result<Self> {
let index = u32::linear_lift_from_memory(cx, InterfaceType::U32, bytes)?;
Self::lift_from_index(cx, ty, index)
}
}
/// A [`FutureReader`] paired with an [`Accessor`].
///
/// This is an RAII wrapper around [`FutureReader`] that ensures it is closed
/// when dropped. This can be created through [`GuardedFutureReader::new`] or
/// [`FutureReader::guard`].
///
/// [`Accessor`]: crate::component::Accessor
pub struct GuardedFutureReader<T, A>
where
A: AsAccessor,
{
// This field is `None` to implement the conversion from this guard back to
// `FutureReader`. When `None` is seen in the destructor it will cause the
// destructor to do nothing.
reader: Option<FutureReader<T>>,
accessor: A,
}
impl<T, A> GuardedFutureReader<T, A>
where
A: AsAccessor,
{
/// Create a new `GuardedFutureReader` with the specified `accessor` and `reader`.
///
/// # Panics
///
/// Panics if [`Config::concurrency_support`] is not enabled.
///
/// [`Config::concurrency_support`]: crate::Config::concurrency_support
pub fn new(accessor: A, reader: FutureReader<T>) -> Self {
assert!(
accessor
.as_accessor()
.with(|a| a.as_context().0.concurrency_support())
);
Self {
reader: Some(reader),
accessor,
}
}
/// Extracts the underlying [`FutureReader`] from this guard, returning it
/// back.
pub fn into_future(self) -> FutureReader<T> {
self.into()
}
}
impl<T, A> From<GuardedFutureReader<T, A>> for FutureReader<T>
where
A: AsAccessor,
{
fn from(mut guard: GuardedFutureReader<T, A>) -> Self {
guard.reader.take().unwrap()
}
}
impl<T, A> Drop for GuardedFutureReader<T, A>
where
A: AsAccessor,
{
fn drop(&mut self) {
if let Some(reader) = &mut self.reader {
reader.close_with(&self.accessor)
}
}
}
/// Represents the readable end of a Component Model `stream`.
///
/// Note that `StreamReader` instances must be disposed of using `close`;
/// otherwise the in-store representation will leak and the writer end will hang
/// indefinitely. Consider using [`GuardedStreamReader`] to ensure that
/// disposal happens automatically.
pub struct StreamReader<T> {
id: TableId<TransmitHandle>,
_phantom: PhantomData<T>,
}
impl<T> StreamReader<T> {
/// Create a new stream with the specified producer.
///
/// # Panics
///
/// Panics if [`Config::concurrency_support`] is not enabled.
///
/// [`Config::concurrency_support`]: crate::Config::concurrency_support
pub fn new<S: AsContextMut>(
mut store: S,
producer: impl StreamProducer<S::Data, Item = T>,
) -> Self
where
T: func::Lower + func::Lift + Send + Sync + 'static,
{
assert!(store.as_context().0.concurrency_support());
Self::new_(
store
.as_context_mut()
.new_transmit(TransmitKind::Stream, producer),
)
}
pub(super) fn new_(id: TableId<TransmitHandle>) -> Self {
Self {
id,
_phantom: PhantomData,
}
}
pub(super) fn id(&self) -> TableId<TransmitHandle> {
self.id
}
/// Attempt to consume this object by converting it into the specified type.
///
/// This can be useful for "short-circuiting" host-to-host streams,
/// bypassing the guest entirely. For example, if a guest task returns a
/// host-created stream and then exits, this function may be used to
/// retrieve the write end, after which the guest instance and store may be
/// disposed of if no longer needed.
///
/// This will return `Ok(_)` if and only if the following conditions are
/// met:
///
/// - The stream was created by the host (i.e. not by the guest).
///
/// - The `StreamProducer::try_into` function returns `Ok(_)` when given the
/// producer provided to `StreamReader::new` when the stream was created,
/// along with `TypeId::of::<V>()`.
pub fn try_into<V: 'static>(mut self, mut store: impl AsContextMut) -> Result<V, Self> {
let store = store.as_context_mut();
let state = store.0.concurrent_state_mut();
let id = state.get_mut(self.id).unwrap().state;
if let WriteState::HostReady { try_into, .. } = &state.get_mut(id).unwrap().write {
match try_into(TypeId::of::<V>()) {
Some(result) => {
self.close(store);
Ok(*result.downcast::<V>().unwrap())
}
None => Err(self),
}
} else {
Err(self)
}
}
/// Set the consumer that accepts the items delivered to this stream.
pub fn pipe<S: AsContextMut>(
self,
mut store: S,
consumer: impl StreamConsumer<S::Data, Item = T>,
) where
T: 'static,
{
store
.as_context_mut()
.set_consumer(self.id, TransmitKind::Stream, consumer);
}
/// Transfer ownership of the read end of a stream from a guest to the host.
fn lift_from_index(cx: &mut LiftContext<'_>, ty: InterfaceType, index: u32) -> Result<Self> {
let id = lift_index_to_stream(cx, ty, index)?;
Ok(Self::new_(id))
}
/// Close this `StreamReader`.
///
/// This will signal that this portion of the stream is closed causing all
/// future writes to return immediately with "DROPPED".
///
/// # Panics
///
/// Panics if the `store` does not own this future. Usage of this future
/// after calling `close` will also cause a panic.
pub fn close(&mut self, mut store: impl AsContextMut) {
stream_close(store.as_context_mut().0, &mut self.id);
}
/// Convenience method around [`Self::close`].
pub fn close_with(&mut self, accessor: impl AsAccessor) {
accessor.as_accessor().with(|access| self.close(access))
}
/// Returns a [`GuardedStreamReader`] which will auto-close this stream on
/// drop and clean it up from the store.
///
/// Note that the `accessor` provided must own this future and is
/// additionally transferred to the `GuardedStreamReader` return value.
pub fn guard<A>(self, accessor: A) -> GuardedStreamReader<T, A>
where
A: AsAccessor,
{
GuardedStreamReader::new(accessor, self)
}
/// Attempts to convert this [`StreamReader<T>`] to a [`StreamAny`].
///
/// # Errors
///
/// This function will return an error if `self` does not belong to
/// `store`.
pub fn try_into_stream_any(self, store: impl AsContextMut) -> Result<StreamAny>
where
T: ComponentType + 'static,
{
StreamAny::try_from_stream_reader(store, self)
}
/// Attempts to convert a [`StreamAny`] into a [`StreamReader<T>`].
///
/// # Errors
///
/// This function will fail if `T` doesn't match the type of the value that
/// `stream` is sending.
pub fn try_from_stream_any(stream: StreamAny) -> Result<Self>
where
T: ComponentType + 'static,
{
stream.try_into_stream_reader()
}
}
impl<T> fmt::Debug for StreamReader<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StreamReader")
.field("id", &self.id)
.finish()
}
}
pub(super) fn stream_close(store: &mut StoreOpaque, id: &mut TableId<TransmitHandle>) {
let id = mem::replace(id, TableId::new(u32::MAX));
store.host_drop_reader(id, TransmitKind::Stream).unwrap();
}
/// Transfer ownership of the read end of a stream from a guest to the host.
pub(super) fn lift_index_to_stream(
cx: &mut LiftContext<'_>,
ty: InterfaceType,
index: u32,
) -> Result<TableId<TransmitHandle>> {
match ty {
InterfaceType::Stream(src) => {
let handle_table = cx
.instance_mut()
.table_for_transmit(TransmitIndex::Stream(src));
let (rep, is_done) = handle_table.stream_remove_readable(src, index)?;
if is_done {
bail!("cannot lift stream after being notified that the writable end dropped");
}
let id = TableId::<TransmitHandle>::new(rep);
cx.concurrent_state_mut().get_mut(id)?.common.handle = None;
Ok(id)
}
_ => func::bad_type_info(),
}
}
/// Transfer ownership of the read end of a stream from the host to a guest.
pub(super) fn lower_stream_to_index<U>(
id: TableId<TransmitHandle>,
cx: &mut LowerContext<'_, U>,
ty: InterfaceType,
) -> Result<u32> {
match ty {
InterfaceType::Stream(dst) => {
let concurrent_state = cx.store.0.concurrent_state_mut();
let state = concurrent_state.get_mut(id)?.state;
let rep = concurrent_state.get_mut(state)?.read_handle.rep();
let handle = cx
.instance_mut()
.table_for_transmit(TransmitIndex::Stream(dst))
.stream_insert_read(dst, rep)?;
cx.store.0.concurrent_state_mut().get_mut(id)?.common.handle = Some(handle);
Ok(handle)
}
_ => func::bad_type_info(),
}
}
// SAFETY: This relies on the `ComponentType` implementation for `u32` being
// safe and correct since we lift and lower stream handles as `u32`s.
unsafe impl<T: ComponentType> ComponentType for StreamReader<T> {
const ABI: CanonicalAbiInfo = CanonicalAbiInfo::SCALAR4;
type Lower = <u32 as func::ComponentType>::Lower;
fn typecheck(ty: &InterfaceType, types: &InstanceType<'_>) -> Result<()> {
match ty {
InterfaceType::Stream(ty) => {
let ty = types.types[*ty].ty;
types::typecheck_payload::<T>(types.types[ty].payload.as_ref(), types)
}
other => bail!("expected `stream`, found `{}`", func::desc(other)),
}
}
}
// SAFETY: See the comment on the `ComponentType` `impl` for this type.
unsafe impl<T: ComponentType> func::Lower for StreamReader<T> {
fn linear_lower_to_flat<U>(
&self,
cx: &mut LowerContext<'_, U>,
ty: InterfaceType,
dst: &mut MaybeUninit<Self::Lower>,
) -> Result<()> {
lower_stream_to_index(self.id, cx, ty)?.linear_lower_to_flat(cx, InterfaceType::U32, dst)
}
fn linear_lower_to_memory<U>(
&self,
cx: &mut LowerContext<'_, U>,
ty: InterfaceType,
offset: usize,
) -> Result<()> {
lower_stream_to_index(self.id, cx, ty)?.linear_lower_to_memory(
cx,
InterfaceType::U32,
offset,
)
}
}
// SAFETY: See the comment on the `ComponentType` `impl` for this type.
unsafe impl<T: ComponentType> func::Lift for StreamReader<T> {
fn linear_lift_from_flat(
cx: &mut LiftContext<'_>,
ty: InterfaceType,
src: &Self::Lower,
) -> Result<Self> {
let index = u32::linear_lift_from_flat(cx, InterfaceType::U32, src)?;
Self::lift_from_index(cx, ty, index)
}
fn linear_lift_from_memory(
cx: &mut LiftContext<'_>,
ty: InterfaceType,
bytes: &[u8],
) -> Result<Self> {
let index = u32::linear_lift_from_memory(cx, InterfaceType::U32, bytes)?;
Self::lift_from_index(cx, ty, index)
}
}
/// A [`StreamReader`] paired with an [`Accessor`].
///
/// This is an RAII wrapper around [`StreamReader`] that ensures it is closed
/// when dropped. This can be created through [`GuardedStreamReader::new`] or
/// [`StreamReader::guard`].
///
/// [`Accessor`]: crate::component::Accessor
pub struct GuardedStreamReader<T, A>
where
A: AsAccessor,
{
// This field is `None` to implement the conversion from this guard back to
// `StreamReader`. When `None` is seen in the destructor it will cause the
// destructor to do nothing.
reader: Option<StreamReader<T>>,
accessor: A,
}
impl<T, A> GuardedStreamReader<T, A>
where
A: AsAccessor,
{
/// Create a new `GuardedStreamReader` with the specified `accessor` and
/// `reader`.
///
/// # Panics
///
/// Panics if [`Config::concurrency_support`] is not enabled.
///
/// [`Config::concurrency_support`]: crate::Config::concurrency_support
pub fn new(accessor: A, reader: StreamReader<T>) -> Self {
assert!(
accessor
.as_accessor()
.with(|a| a.as_context().0.concurrency_support())
);
Self {
reader: Some(reader),
accessor,
}
}
/// Extracts the underlying [`StreamReader`] from this guard, returning it
/// back.
pub fn into_stream(self) -> StreamReader<T> {
self.into()
}
}
impl<T, A> From<GuardedStreamReader<T, A>> for StreamReader<T>
where
A: AsAccessor,
{
fn from(mut guard: GuardedStreamReader<T, A>) -> Self {
guard.reader.take().unwrap()
}
}
impl<T, A> Drop for GuardedStreamReader<T, A>
where
A: AsAccessor,
{
fn drop(&mut self) {
if let Some(reader) = &mut self.reader {
reader.close_with(&self.accessor)
}
}
}
/// Represents a Component Model `error-context`.
pub struct ErrorContext {
rep: u32,
}
impl ErrorContext {
pub(crate) fn new(rep: u32) -> Self {
Self { rep }
}
/// Convert this `ErrorContext` into a [`Val`].
pub fn into_val(self) -> Val {
Val::ErrorContext(ErrorContextAny(self.rep))
}
/// Attempt to convert the specified [`Val`] to a `ErrorContext`.
pub fn from_val(_: impl AsContextMut, value: &Val) -> Result<Self> {
let Val::ErrorContext(ErrorContextAny(rep)) = value else {
bail!("expected `error-context`; got `{}`", value.desc());
};
Ok(Self::new(*rep))
}
fn lift_from_index(cx: &mut LiftContext<'_>, ty: InterfaceType, index: u32) -> Result<Self> {
match ty {
InterfaceType::ErrorContext(src) => {
let rep = cx
.instance_mut()
.table_for_error_context(src)
.error_context_rep(index)?;
Ok(Self { rep })
}
_ => func::bad_type_info(),
}
}
}
pub(crate) fn lower_error_context_to_index<U>(
rep: u32,
cx: &mut LowerContext<'_, U>,
ty: InterfaceType,
) -> Result<u32> {
match ty {
InterfaceType::ErrorContext(dst) => {
let tbl = cx.instance_mut().table_for_error_context(dst);
tbl.error_context_insert(rep)
}
_ => func::bad_type_info(),
}
}
// SAFETY: This relies on the `ComponentType` implementation for `u32` being
// safe and correct since we lift and lower future handles as `u32`s.
unsafe impl func::ComponentType for ErrorContext {
const ABI: CanonicalAbiInfo = CanonicalAbiInfo::SCALAR4;
type Lower = <u32 as func::ComponentType>::Lower;
fn typecheck(ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {
match ty {
InterfaceType::ErrorContext(_) => Ok(()),
other => bail!("expected `error`, found `{}`", func::desc(other)),
}
}
}
// SAFETY: See the comment on the `ComponentType` `impl` for this type.
unsafe impl func::Lower for ErrorContext {
fn linear_lower_to_flat<T>(
&self,
cx: &mut LowerContext<'_, T>,
ty: InterfaceType,
dst: &mut MaybeUninit<Self::Lower>,
) -> Result<()> {
lower_error_context_to_index(self.rep, cx, ty)?.linear_lower_to_flat(
cx,
InterfaceType::U32,
dst,
)
}
fn linear_lower_to_memory<T>(
&self,
cx: &mut LowerContext<'_, T>,
ty: InterfaceType,
offset: usize,
) -> Result<()> {
lower_error_context_to_index(self.rep, cx, ty)?.linear_lower_to_memory(
cx,
InterfaceType::U32,
offset,
)
}
}
// SAFETY: See the comment on the `ComponentType` `impl` for this type.
unsafe impl func::Lift for ErrorContext {
fn linear_lift_from_flat(
cx: &mut LiftContext<'_>,
ty: InterfaceType,
src: &Self::Lower,
) -> Result<Self> {
let index = u32::linear_lift_from_flat(cx, InterfaceType::U32, src)?;
Self::lift_from_index(cx, ty, index)
}
fn linear_lift_from_memory(
cx: &mut LiftContext<'_>,
ty: InterfaceType,
bytes: &[u8],
) -> Result<Self> {
let index = u32::linear_lift_from_memory(cx, InterfaceType::U32, bytes)?;
Self::lift_from_index(cx, ty, index)
}
}
/// Represents the read or write end of a stream or future.
pub(super) struct TransmitHandle {
pub(super) common: WaitableCommon,
/// See `TransmitState`
state: TableId<TransmitState>,
}
impl TransmitHandle {
fn new(state: TableId<TransmitState>) -> Self {
Self {
common: WaitableCommon::default(),
state,
}
}
}
impl TableDebug for TransmitHandle {
fn type_name() -> &'static str {
"TransmitHandle"
}
}
/// Represents the state of a stream or future.
struct TransmitState {
/// The write end of the stream or future.
write_handle: TableId<TransmitHandle>,
/// The read end of the stream or future.
read_handle: TableId<TransmitHandle>,
/// See `WriteState`
write: WriteState,
/// See `ReadState`
read: ReadState,
/// Whether futher values may be transmitted via this stream or future.
done: bool,
/// The original creator of this stream, used for type-checking with
/// `{Future,Stream}Any`.
pub(super) origin: TransmitOrigin,
}
#[derive(Copy, Clone)]
pub(super) enum TransmitOrigin {
Host,
GuestFuture(ComponentInstanceId, TypeFutureTableIndex),
GuestStream(ComponentInstanceId, TypeStreamTableIndex),
}
impl TransmitState {
fn new(origin: TransmitOrigin) -> Self {
Self {
write_handle: TableId::new(u32::MAX),
read_handle: TableId::new(u32::MAX),
read: ReadState::Open,
write: WriteState::Open,
done: false,
origin,
}
}
}
impl TableDebug for TransmitState {
fn type_name() -> &'static str {
"TransmitState"
}
}
impl TransmitOrigin {
fn guest(id: ComponentInstanceId, index: TransmitIndex) -> Self {
match index {
TransmitIndex::Future(ty) => TransmitOrigin::GuestFuture(id, ty),
TransmitIndex::Stream(ty) => TransmitOrigin::GuestStream(id, ty),
}
}
}
type PollStream = Box<
dyn Fn() -> Pin<Box<dyn Future<Output = Result<StreamResult>> + Send + 'static>> + Send + Sync,
>;
type TryInto = Box<dyn Fn(TypeId) -> Option<Box<dyn Any>> + Send + Sync>;
/// Represents the state of the write end of a stream or future.
enum WriteState {
/// The write end is open, but no write is pending.
Open,
/// The write end is owned by a guest task and a write is pending.
GuestReady {
instance: Instance,
caller: RuntimeComponentInstanceIndex,
ty: TransmitIndex,
flat_abi: Option<FlatAbi>,
options: OptionsIndex,
address: usize,
count: usize,
handle: u32,
},
/// The write end is owned by the host, which is ready to produce items.
HostReady {
produce: PollStream,
try_into: TryInto,
guest_offset: usize,
cancel: bool,
cancel_waker: Option<Waker>,
},
/// The write end has been dropped.
Dropped,
}
impl fmt::Debug for WriteState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Open => f.debug_tuple("Open").finish(),
Self::GuestReady { .. } => f.debug_tuple("GuestReady").finish(),
Self::HostReady { .. } => f.debug_tuple("HostReady").finish(),
Self::Dropped => f.debug_tuple("Dropped").finish(),
}
}
}
/// Represents the state of the read end of a stream or future.
enum ReadState {
/// The read end is open, but no read is pending.
Open,
/// The read end is owned by a guest task and a read is pending.
GuestReady {
ty: TransmitIndex,
caller: RuntimeComponentInstanceIndex,
flat_abi: Option<FlatAbi>,
instance: Instance,
options: OptionsIndex,
address: usize,
count: usize,
handle: u32,
},
/// The read end is owned by a host task, and it is ready to consume items.
HostReady {
consume: PollStream,
guest_offset: usize,
cancel: bool,
cancel_waker: Option<Waker>,
},
/// Both the read and write ends are owned by the host.
HostToHost {
accept: Box<
dyn for<'a> Fn(
&'a mut UntypedWriteBuffer<'a>,
)
-> Pin<Box<dyn Future<Output = Result<StreamResult>> + Send + 'a>>
+ Send
+ Sync,
>,
buffer: Vec<u8>,
limit: usize,
},
/// The read end has been dropped.
Dropped,
}
impl fmt::Debug for ReadState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Open => f.debug_tuple("Open").finish(),
Self::GuestReady { .. } => f.debug_tuple("GuestReady").finish(),
Self::HostReady { .. } => f.debug_tuple("HostReady").finish(),
Self::HostToHost { .. } => f.debug_tuple("HostToHost").finish(),
Self::Dropped => f.debug_tuple("Dropped").finish(),
}
}
}
fn return_code(kind: TransmitKind, state: StreamResult, guest_offset: usize) -> ReturnCode {
let count = guest_offset.try_into().unwrap();
match state {
StreamResult::Dropped => ReturnCode::Dropped(count),
StreamResult::Completed => ReturnCode::completed(kind, count),
StreamResult::Cancelled => ReturnCode::Cancelled(count),
}
}
impl StoreOpaque {
fn pipe_from_guest(
&mut self,
kind: TransmitKind,
id: TableId<TransmitState>,
future: Pin<Box<dyn Future<Output = Result<StreamResult>> + Send + 'static>>,
) {
let future = async move {
let stream_state = future.await?;
tls::get(|store| {
let state = store.concurrent_state_mut();
let transmit = state.get_mut(id)?;
let ReadState::HostReady {
consume,
guest_offset,
..
} = mem::replace(&mut transmit.read, ReadState::Open)
else {
unreachable!();
};
let code = return_code(kind, stream_state, guest_offset);
transmit.read = match stream_state {
StreamResult::Dropped => ReadState::Dropped,
StreamResult::Completed | StreamResult::Cancelled => ReadState::HostReady {
consume,
guest_offset: 0,
cancel: false,
cancel_waker: None,
},
};
let WriteState::GuestReady { ty, handle, .. } =
mem::replace(&mut transmit.write, WriteState::Open)
else {
unreachable!();
};
state.send_write_result(ty, id, handle, code)?;
Ok(())
})
};
self.concurrent_state_mut().push_future(future.boxed());
}
fn pipe_to_guest(
&mut self,
kind: TransmitKind,
id: TableId<TransmitState>,
future: Pin<Box<dyn Future<Output = Result<StreamResult>> + Send + 'static>>,
) {
let future = async move {
let stream_state = future.await?;
tls::get(|store| {
let state = store.concurrent_state_mut();
let transmit = state.get_mut(id)?;
let WriteState::HostReady {
produce,
try_into,
guest_offset,
..
} = mem::replace(&mut transmit.write, WriteState::Open)
else {
unreachable!();
};
let code = return_code(kind, stream_state, guest_offset);
transmit.write = match stream_state {
StreamResult::Dropped => WriteState::Dropped,
StreamResult::Completed | StreamResult::Cancelled => WriteState::HostReady {
produce,
try_into,
guest_offset: 0,
cancel: false,
cancel_waker: None,
},
};
let ReadState::GuestReady { ty, handle, .. } =
mem::replace(&mut transmit.read, ReadState::Open)
else {
unreachable!();
};
state.send_read_result(ty, id, handle, code)?;
Ok(())
})
};
self.concurrent_state_mut().push_future(future.boxed());
}
/// Drop the read end of a stream or future read from the host.
fn host_drop_reader(&mut self, id: TableId<TransmitHandle>, kind: TransmitKind) -> Result<()> {
let state = self.concurrent_state_mut();
let transmit_id = state.get_mut(id)?.state;
let transmit = state
.get_mut(transmit_id)
.with_context(|| format!("error closing reader {transmit_id:?}"))?;
log::trace!(
"host_drop_reader state {transmit_id:?}; read state {:?} write state {:?}",
transmit.read,
transmit.write
);
transmit.read = ReadState::Dropped;
// If the write end is already dropped, it should stay dropped,
// otherwise, it should be opened.
let new_state = if let WriteState::Dropped = &transmit.write {
WriteState::Dropped
} else {
WriteState::Open
};
let write_handle = transmit.write_handle;
match mem::replace(&mut transmit.write, new_state) {
// If a guest is waiting to write, notify it that the read end has
// been dropped.
WriteState::GuestReady { ty, handle, .. } => {
state.update_event(
write_handle.rep(),
match ty {
TransmitIndex::Future(ty) => Event::FutureWrite {
code: ReturnCode::Dropped(0),
pending: Some((ty, handle)),
},
TransmitIndex::Stream(ty) => Event::StreamWrite {
code: ReturnCode::Dropped(0),
pending: Some((ty, handle)),
},
},
)?;
}
WriteState::HostReady { .. } => {}
WriteState::Open => {
state.update_event(
write_handle.rep(),
match kind {
TransmitKind::Future => Event::FutureWrite {
code: ReturnCode::Dropped(0),
pending: None,
},
TransmitKind::Stream => Event::StreamWrite {
code: ReturnCode::Dropped(0),
pending: None,
},
},
)?;
}
WriteState::Dropped => {
log::trace!("host_drop_reader delete {transmit_id:?}");
state.delete_transmit(transmit_id)?;
}
}
Ok(())
}
/// Drop the write end of a stream or future read from the host.
fn host_drop_writer(
&mut self,
id: TableId<TransmitHandle>,
on_drop_open: Option<fn() -> Result<()>>,
) -> Result<()> {
let state = self.concurrent_state_mut();
let transmit_id = state.get_mut(id)?.state;
let transmit = state
.get_mut(transmit_id)
.with_context(|| format!("error closing writer {transmit_id:?}"))?;
log::trace!(
"host_drop_writer state {transmit_id:?}; write state {:?} read state {:?}",
transmit.read,
transmit.write
);
// Existing queued transmits must be updated with information for the impending writer closure
match &mut transmit.write {
WriteState::GuestReady { .. } => {
unreachable!("can't call `host_drop_writer` on a guest-owned writer");
}
WriteState::HostReady { .. } => {}
v @ WriteState::Open => {
if let (Some(on_drop_open), false) = (
on_drop_open,
transmit.done || matches!(transmit.read, ReadState::Dropped),
) {
on_drop_open()?;
} else {
*v = WriteState::Dropped;
}
}
WriteState::Dropped => unreachable!("write state is already dropped"),
}
let transmit = self.concurrent_state_mut().get_mut(transmit_id)?;
// If the existing read state is dropped, then there's nothing to read
// and we can keep it that way.
//
// If the read state was any other state, then we must set the new state to open
// to indicate that there *is* data to be read
let new_state = if let ReadState::Dropped = &transmit.read {
ReadState::Dropped
} else {
ReadState::Open
};
let read_handle = transmit.read_handle;
// Swap in the new read state
match mem::replace(&mut transmit.read, new_state) {
// If the guest was ready to read, then we cannot drop the reader (or writer);
// we must deliver the event, and update the state associated with the handle to
// represent that a read must be performed
ReadState::GuestReady { ty, handle, .. } => {
// Ensure the final read of the guest is queued, with appropriate closure indicator
self.concurrent_state_mut().update_event(
read_handle.rep(),
match ty {
TransmitIndex::Future(ty) => Event::FutureRead {
code: ReturnCode::Dropped(0),
pending: Some((ty, handle)),
},
TransmitIndex::Stream(ty) => Event::StreamRead {
code: ReturnCode::Dropped(0),
pending: Some((ty, handle)),
},
},
)?;
}
ReadState::HostReady { .. } | ReadState::HostToHost { .. } => {}
// If the read state is open, then there are no registered readers of the stream/future
ReadState::Open => {
self.concurrent_state_mut().update_event(
read_handle.rep(),
match on_drop_open {
Some(_) => Event::FutureRead {
code: ReturnCode::Dropped(0),
pending: None,
},
None => Event::StreamRead {
code: ReturnCode::Dropped(0),
pending: None,
},
},
)?;
}
// If the read state was already dropped, then we can remove the transmit state completely
// (both writer and reader have been dropped)
ReadState::Dropped => {
log::trace!("host_drop_writer delete {transmit_id:?}");
self.concurrent_state_mut().delete_transmit(transmit_id)?;
}
}
Ok(())
}
pub(super) fn transmit_origin(
&mut self,
id: TableId<TransmitHandle>,
) -> Result<TransmitOrigin> {
let state = self.concurrent_state_mut();
let state_id = state.get_mut(id)?.state;
Ok(state.get_mut(state_id)?.origin)
}
}
impl<T> StoreContextMut<'_, T> {
fn new_transmit<P: StreamProducer<T>>(
mut self,
kind: TransmitKind,
producer: P,
) -> TableId<TransmitHandle>
where
P::Item: func::Lower,
{
let token = StoreToken::new(self.as_context_mut());
let state = self.0.concurrent_state_mut();
let (_, read) = state.new_transmit(TransmitOrigin::Host).unwrap();
let producer = Arc::new(Mutex::new(Some((Box::pin(producer), P::Buffer::default()))));
let id = state.get_mut(read).unwrap().state;
let mut dropped = false;
let produce = Box::new({
let producer = producer.clone();
move || {
let producer = producer.clone();
async move {
let (mut mine, mut buffer) = producer.lock().unwrap().take().unwrap();
let (result, cancelled) = if buffer.remaining().is_empty() {
future::poll_fn(|cx| {
tls::get(|store| {
let transmit = store.concurrent_state_mut().get_mut(id).unwrap();
let &WriteState::HostReady { cancel, .. } = &transmit.write else {
unreachable!();
};
let mut host_buffer =
if let ReadState::HostToHost { buffer, .. } = &mut transmit.read {
Some(Cursor::new(mem::take(buffer)))
} else {
None
};
let poll = mine.as_mut().poll_produce(
cx,
token.as_context_mut(store),
Destination {
id,
buffer: &mut buffer,
host_buffer: host_buffer.as_mut(),
_phantom: PhantomData,
},
cancel,
);
let transmit = store.concurrent_state_mut().get_mut(id).unwrap();
let host_offset = if let (
Some(host_buffer),
ReadState::HostToHost { buffer, limit, .. },
) = (host_buffer, &mut transmit.read)
{
*limit = usize::try_from(host_buffer.position()).unwrap();
*buffer = host_buffer.into_inner();
*limit
} else {
0
};
{
let WriteState::HostReady {
guest_offset,
cancel,
cancel_waker,
..
} = &mut transmit.write
else {
unreachable!();
};
if poll.is_pending() {
if !buffer.remaining().is_empty()
|| *guest_offset > 0
|| host_offset > 0
{
return Poll::Ready(Err(format_err!(
"StreamProducer::poll_produce returned Poll::Pending \
after producing at least one item"
)));
}
*cancel_waker = Some(cx.waker().clone());
} else {
*cancel_waker = None;
*cancel = false;
}
}
poll.map(|v| v.map(|result| (result, cancel)))
})
})
.await?
} else {
(StreamResult::Completed, false)
};
let (guest_offset, host_offset, count) = tls::get(|store| {
let transmit = store.concurrent_state_mut().get_mut(id).unwrap();
let (count, host_offset) = match &transmit.read {
&ReadState::GuestReady { count, .. } => (count, 0),
&ReadState::HostToHost { limit, .. } => (1, limit),
_ => unreachable!(),
};
let guest_offset = match &transmit.write {
&WriteState::HostReady { guest_offset, .. } => guest_offset,
_ => unreachable!(),
};
(guest_offset, host_offset, count)
});
match result {
StreamResult::Completed => {
if count > 1
&& buffer.remaining().is_empty()
&& guest_offset == 0
&& host_offset == 0
{
bail!(
"StreamProducer::poll_produce returned StreamResult::Completed \
without producing any items"
);
}
}
StreamResult::Cancelled => {
if !cancelled {
bail!(
"StreamProducer::poll_produce returned StreamResult::Cancelled \
without being given a `finish` parameter value of true"
);
}
}
StreamResult::Dropped => {
dropped = true;
}
}
let write_buffer = !buffer.remaining().is_empty() || host_offset > 0;
*producer.lock().unwrap() = Some((mine, buffer));
if write_buffer {
write(token, id, producer.clone(), kind).await?;
}
Ok(if dropped {
if producer.lock().unwrap().as_ref().unwrap().1.remaining().is_empty()
{
StreamResult::Dropped
} else {
StreamResult::Completed
}
} else {
result
})
}
.boxed()
}
});
let try_into = Box::new(move |ty| {
let (mine, buffer) = producer.lock().unwrap().take().unwrap();
match P::try_into(mine, ty) {
Ok(value) => Some(value),
Err(mine) => {
*producer.lock().unwrap() = Some((mine, buffer));
None
}
}
});
state.get_mut(id).unwrap().write = WriteState::HostReady {
produce,
try_into,
guest_offset: 0,
cancel: false,
cancel_waker: None,
};
read
}
fn set_consumer<C: StreamConsumer<T>>(
mut self,
id: TableId<TransmitHandle>,
kind: TransmitKind,
consumer: C,
) {
let token = StoreToken::new(self.as_context_mut());
let state = self.0.concurrent_state_mut();
let id = state.get_mut(id).unwrap().state;
let transmit = state.get_mut(id).unwrap();
let consumer = Arc::new(Mutex::new(Some(Box::pin(consumer))));
let consume_with_buffer = {
let consumer = consumer.clone();
async move |mut host_buffer: Option<&mut dyn WriteBuffer<C::Item>>| {
let mut mine = consumer.lock().unwrap().take().unwrap();
let host_buffer_remaining_before =
host_buffer.as_deref_mut().map(|v| v.remaining().len());
let (result, cancelled) = future::poll_fn(|cx| {
tls::get(|store| {
let cancel = match &store.concurrent_state_mut().get_mut(id).unwrap().read {
&ReadState::HostReady { cancel, .. } => cancel,
ReadState::Open => false,
_ => unreachable!(),
};
let poll = mine.as_mut().poll_consume(
cx,
token.as_context_mut(store),
Source {
id,
host_buffer: host_buffer.as_deref_mut(),
},
cancel,
);
if let ReadState::HostReady {
cancel_waker,
cancel,
..
} = &mut store.concurrent_state_mut().get_mut(id).unwrap().read
{
if poll.is_pending() {
*cancel_waker = Some(cx.waker().clone());
} else {
*cancel_waker = None;
*cancel = false;
}
}
poll.map(|v| v.map(|result| (result, cancel)))
})
})
.await?;
let (guest_offset, count) = tls::get(|store| {
let transmit = store.concurrent_state_mut().get_mut(id).unwrap();
(
match &transmit.read {
&ReadState::HostReady { guest_offset, .. } => guest_offset,
ReadState::Open => 0,
_ => unreachable!(),
},
match &transmit.write {
&WriteState::GuestReady { count, .. } => count,
WriteState::HostReady { .. } => host_buffer_remaining_before.unwrap(),
_ => unreachable!(),
},
)
});
match result {
StreamResult::Completed => {
if count > 0
&& guest_offset == 0
&& host_buffer_remaining_before
.zip(host_buffer.map(|v| v.remaining().len()))
.map(|(before, after)| before == after)
.unwrap_or(false)
{
bail!(
"StreamConsumer::poll_consume returned StreamResult::Completed \
without consuming any items"
);
}
if let TransmitKind::Future = kind {
tls::get(|store| {
store.concurrent_state_mut().get_mut(id).unwrap().done = true;
});
}
}
StreamResult::Cancelled => {
if !cancelled {
bail!(
"StreamConsumer::poll_consume returned StreamResult::Cancelled \
without being given a `finish` parameter value of true"
);
}
}
StreamResult::Dropped => {}
}
*consumer.lock().unwrap() = Some(mine);
Ok(result)
}
};
let consume = {
let consume = consume_with_buffer.clone();
Box::new(move || {
let consume = consume.clone();
async move { consume(None).await }.boxed()
})
};
match &transmit.write {
WriteState::Open => {
transmit.read = ReadState::HostReady {
consume,
guest_offset: 0,
cancel: false,
cancel_waker: None,
};
}
&WriteState::GuestReady { .. } => {
let future = consume();
transmit.read = ReadState::HostReady {
consume,
guest_offset: 0,
cancel: false,
cancel_waker: None,
};
self.0.pipe_from_guest(kind, id, future);
}
WriteState::HostReady { .. } => {
let WriteState::HostReady { produce, .. } = mem::replace(
&mut transmit.write,
WriteState::HostReady {
produce: Box::new(|| unreachable!()),
try_into: Box::new(|_| unreachable!()),
guest_offset: 0,
cancel: false,
cancel_waker: None,
},
) else {
unreachable!();
};
transmit.read = ReadState::HostToHost {
accept: Box::new(move |input| {
let consume = consume_with_buffer.clone();
async move { consume(Some(input.get_mut::<C::Item>())).await }.boxed()
}),
buffer: Vec::new(),
limit: 0,
};
let future = async move {
loop {
if tls::get(|store| {
crate::error::Ok(matches!(
store.concurrent_state_mut().get_mut(id)?.read,
ReadState::Dropped
))
})? {
break Ok(());
}
match produce().await? {
StreamResult::Completed | StreamResult::Cancelled => {}
StreamResult::Dropped => break Ok(()),
}
if let TransmitKind::Future = kind {
break Ok(());
}
}
}
.map(move |result| {
tls::get(|store| store.concurrent_state_mut().delete_transmit(id))?;
result
});
state.push_future(Box::pin(future));
}
WriteState::Dropped => {
let reader = transmit.read_handle;
self.0.host_drop_reader(reader, kind).unwrap();
}
}
}
}
async fn write<D: 'static, P: Send + 'static, T: func::Lower + 'static, B: WriteBuffer<T>>(
token: StoreToken<D>,
id: TableId<TransmitState>,
pair: Arc<Mutex<Option<(P, B)>>>,
kind: TransmitKind,
) -> Result<()> {
let (read, guest_offset) = tls::get(|store| {
let transmit = store.concurrent_state_mut().get_mut(id)?;
let guest_offset = if let &WriteState::HostReady { guest_offset, .. } = &transmit.write {
Some(guest_offset)
} else {
None
};
crate::error::Ok((
mem::replace(&mut transmit.read, ReadState::Open),
guest_offset,
))
})?;
match read {
ReadState::GuestReady {
ty,
flat_abi,
options,
address,
count,
handle,
instance,
caller,
} => {
let guest_offset = guest_offset.unwrap();
if let TransmitKind::Future = kind {
tls::get(|store| {
store.concurrent_state_mut().get_mut(id)?.done = true;
crate::error::Ok(())
})?;
}
let old_remaining = pair.lock().unwrap().as_mut().unwrap().1.remaining().len();
let accept = {
let pair = pair.clone();
move |mut store: StoreContextMut<D>| {
lower::<T, B, D>(
store.as_context_mut(),
instance,
options,
ty,
address + (T::SIZE32 * guest_offset),
count - guest_offset,
&mut pair.lock().unwrap().as_mut().unwrap().1,
)?;
crate::error::Ok(())
}
};
if guest_offset < count {
if T::MAY_REQUIRE_REALLOC {
// For payloads which may require a realloc call, use a
// oneshot::channel and background task. This is
// necessary because calling the guest while there are
// host embedder frames on the stack is unsound.
let (tx, rx) = oneshot::channel();
tls::get(move |store| {
store
.concurrent_state_mut()
.push_high_priority(WorkItem::WorkerFunction(AlwaysMut::new(Box::new(
move |store| {
_ = tx.send(accept(token.as_context_mut(store))?);
Ok(())
},
))))
});
rx.await?
} else {
// Optimize flat payloads (i.e. those which do not
// require calling the guest's realloc function) by
// lowering directly instead of using a oneshot::channel
// and background task.
tls::get(|store| accept(token.as_context_mut(store)))?
};
}
tls::get(|store| {
let count =
old_remaining - pair.lock().unwrap().as_mut().unwrap().1.remaining().len();
let transmit = store.concurrent_state_mut().get_mut(id)?;
let WriteState::HostReady { guest_offset, .. } = &mut transmit.write else {
unreachable!();
};
*guest_offset += count;
transmit.read = ReadState::GuestReady {
ty,
flat_abi,
options,
address,
count,
handle,
instance,
caller,
};
crate::error::Ok(())
})?;
Ok(())
}
ReadState::HostToHost {
accept,
mut buffer,
limit,
} => {
let mut state = StreamResult::Completed;
let mut position = 0;
while !matches!(state, StreamResult::Dropped) && position < limit {
let mut slice_buffer = SliceBuffer::new(buffer, position, limit);
state = accept(&mut UntypedWriteBuffer::new(&mut slice_buffer)).await?;
(buffer, position, _) = slice_buffer.into_parts();
}
{
let (mine, mut buffer) = pair.lock().unwrap().take().unwrap();
while !(matches!(state, StreamResult::Dropped) || buffer.remaining().is_empty()) {
state = accept(&mut UntypedWriteBuffer::new(&mut buffer)).await?;
}
*pair.lock().unwrap() = Some((mine, buffer));
}
tls::get(|store| {
store.concurrent_state_mut().get_mut(id)?.read = match state {
StreamResult::Dropped => ReadState::Dropped,
StreamResult::Completed | StreamResult::Cancelled => ReadState::HostToHost {
accept,
buffer,
limit: 0,
},
};
crate::error::Ok(())
})?;
Ok(())
}
_ => unreachable!(),
}
}
impl Instance {
/// Handle a host- or guest-initiated write by delivering the item(s) to the
/// `StreamConsumer` for the specified stream or future.
fn consume(
self,
store: &mut dyn VMStore,
kind: TransmitKind,
transmit_id: TableId<TransmitState>,
consume: PollStream,
guest_offset: usize,
cancel: bool,
) -> Result<ReturnCode> {
let mut future = consume();
store.concurrent_state_mut().get_mut(transmit_id)?.read = ReadState::HostReady {
consume,
guest_offset,
cancel,
cancel_waker: None,
};
let poll = tls::set(store, || {
future
.as_mut()
.poll(&mut Context::from_waker(&Waker::noop()))
});
Ok(match poll {
Poll::Ready(state) => {
let transmit = store.concurrent_state_mut().get_mut(transmit_id)?;
let ReadState::HostReady { guest_offset, .. } = &mut transmit.read else {
unreachable!();
};
let code = return_code(kind, state?, mem::replace(guest_offset, 0));
transmit.write = WriteState::Open;
code
}
Poll::Pending => {
store.pipe_from_guest(kind, transmit_id, future);
ReturnCode::Blocked
}
})
}
/// Handle a host- or guest-initiated read by polling the `StreamProducer`
/// for the specified stream or future for items.
fn produce(
self,
store: &mut dyn VMStore,
kind: TransmitKind,
transmit_id: TableId<TransmitState>,
produce: PollStream,
try_into: TryInto,
guest_offset: usize,
cancel: bool,
) -> Result<ReturnCode> {
let mut future = produce();
store.concurrent_state_mut().get_mut(transmit_id)?.write = WriteState::HostReady {
produce,
try_into,
guest_offset,
cancel,
cancel_waker: None,
};
let poll = tls::set(store, || {
future
.as_mut()
.poll(&mut Context::from_waker(&Waker::noop()))
});
Ok(match poll {
Poll::Ready(state) => {
let transmit = store.concurrent_state_mut().get_mut(transmit_id)?;
let WriteState::HostReady { guest_offset, .. } = &mut transmit.write else {
unreachable!();
};
let code = return_code(kind, state?, mem::replace(guest_offset, 0));
transmit.read = ReadState::Open;
code
}
Poll::Pending => {
store.pipe_to_guest(kind, transmit_id, future);
ReturnCode::Blocked
}
})
}
/// Drop the writable end of the specified stream or future from the guest.
pub(super) fn guest_drop_writable(
self,
store: &mut StoreOpaque,
ty: TransmitIndex,
writer: u32,
) -> Result<()> {
let table = self.id().get_mut(store).table_for_transmit(ty);
let transmit_rep = match ty {
TransmitIndex::Future(ty) => table.future_remove_writable(ty, writer)?,
TransmitIndex::Stream(ty) => table.stream_remove_writable(ty, writer)?,
};
let id = TableId::<TransmitHandle>::new(transmit_rep);
log::trace!("guest_drop_writable: drop writer {id:?}");
match ty {
TransmitIndex::Stream(_) => store.host_drop_writer(id, None),
TransmitIndex::Future(_) => store.host_drop_writer(
id,
Some(|| {
Err(format_err!(
"cannot drop future write end without first writing a value"
))
}),
),
}
}
/// Copy `count` items from `read_address` to `write_address` for the
/// specified stream or future.
fn copy<T: 'static>(
self,
mut store: StoreContextMut<T>,
flat_abi: Option<FlatAbi>,
write_caller: RuntimeComponentInstanceIndex,
write_ty: TransmitIndex,
write_options: OptionsIndex,
write_address: usize,
read_caller: RuntimeComponentInstanceIndex,
read_ty: TransmitIndex,
read_options: OptionsIndex,
read_address: usize,
count: usize,
rep: u32,
) -> Result<()> {
let types = self.id().get(store.0).component().types();
match (write_ty, read_ty) {
(TransmitIndex::Future(write_ty), TransmitIndex::Future(read_ty)) => {
assert_eq!(count, 1);
let payload = types[types[write_ty].ty].payload;
if write_caller == read_caller && !allow_intra_component_read_write(payload) {
bail!(
"cannot read from and write to intra-component future with non-numeric payload"
)
}
let val = payload
.map(|ty| {
let lift =
&mut LiftContext::new(store.0.store_opaque_mut(), write_options, self);
let abi = lift.types.canonical_abi(&ty);
// FIXME: needs to read an i64 for memory64
if write_address % usize::try_from(abi.align32)? != 0 {
bail!("write pointer not aligned");
}
let bytes = lift
.memory()
.get(write_address..)
.and_then(|b| b.get(..usize::try_from(abi.size32).unwrap()))
.ok_or_else(|| {
crate::format_err!("write pointer out of bounds of memory")
})?;
Val::load(lift, ty, bytes)
})
.transpose()?;
if let Some(val) = val {
let lower = &mut LowerContext::new(store.as_context_mut(), read_options, self);
let types = lower.types;
let ty = types[types[read_ty].ty].payload.unwrap();
let ptr = func::validate_inbounds_dynamic(
types.canonical_abi(&ty),
lower.as_slice_mut(),
&ValRaw::u32(read_address.try_into().unwrap()),
)?;
val.store(lower, ty, ptr)?;
}
}
(TransmitIndex::Stream(write_ty), TransmitIndex::Stream(read_ty)) => {
if write_caller == read_caller
&& !allow_intra_component_read_write(types[types[write_ty].ty].payload)
{
bail!(
"cannot read from and write to intra-component stream with non-numeric payload"
)
}
if let Some(flat_abi) = flat_abi {
// Fast path memcpy for "flat" (i.e. no pointers or handles) payloads:
let length_in_bytes = usize::try_from(flat_abi.size).unwrap() * count;
if length_in_bytes > 0 {
if write_address % usize::try_from(flat_abi.align)? != 0 {
bail!("write pointer not aligned");
}
if read_address % usize::try_from(flat_abi.align)? != 0 {
bail!("read pointer not aligned");
}
let store_opaque = store.0.store_opaque_mut();
{
let src = self
.options_memory(store_opaque, write_options)
.get(write_address..)
.and_then(|b| b.get(..length_in_bytes))
.ok_or_else(|| {
crate::format_err!("write pointer out of bounds of memory")
})?
.as_ptr();
let dst = self
.options_memory_mut(store_opaque, read_options)
.get_mut(read_address..)
.and_then(|b| b.get_mut(..length_in_bytes))
.ok_or_else(|| {
crate::format_err!("read pointer out of bounds of memory")
})?
.as_mut_ptr();
// SAFETY: Both `src` and `dst` have been validated
// above.
unsafe {
if write_caller == read_caller {
// If the same instance owns both ends of
// the stream, the source and destination
// buffers might overlap.
src.copy_to(dst, length_in_bytes)
} else {
// Since the read and write ends of the
// stream are owned by distinct instances,
// the buffers cannot possibly belong to the
// same memory and thus cannot overlap.
src.copy_to_nonoverlapping(dst, length_in_bytes)
}
}
}
}
} else {
let store_opaque = store.0.store_opaque_mut();
let lift = &mut LiftContext::new(store_opaque, write_options, self);
let ty = lift.types[lift.types[write_ty].ty].payload.unwrap();
let abi = lift.types.canonical_abi(&ty);
let size = usize::try_from(abi.size32).unwrap();
if write_address % usize::try_from(abi.align32)? != 0 {
bail!("write pointer not aligned");
}
let bytes = lift
.memory()
.get(write_address..)
.and_then(|b| b.get(..size * count))
.ok_or_else(|| {
crate::format_err!("write pointer out of bounds of memory")
})?;
let values = (0..count)
.map(|index| Val::load(lift, ty, &bytes[(index * size)..][..size]))
.collect::<Result<Vec<_>>>()?;
let id = TableId::<TransmitHandle>::new(rep);
log::trace!("copy values {values:?} for {id:?}");
let lower = &mut LowerContext::new(store.as_context_mut(), read_options, self);
let ty = lower.types[lower.types[read_ty].ty].payload.unwrap();
let abi = lower.types.canonical_abi(&ty);
if read_address % usize::try_from(abi.align32)? != 0 {
bail!("read pointer not aligned");
}
let size = usize::try_from(abi.size32).unwrap();
lower
.as_slice_mut()
.get_mut(read_address..)
.and_then(|b| b.get_mut(..size * count))
.ok_or_else(|| {
crate::format_err!("read pointer out of bounds of memory")
})?;
let mut ptr = read_address;
for value in values {
value.store(lower, ty, ptr)?;
ptr += size
}
}
}
_ => unreachable!(),
}
Ok(())
}
fn check_bounds(
self,
store: &StoreOpaque,
options: OptionsIndex,
ty: TransmitIndex,
address: usize,
count: usize,
) -> Result<()> {
let types = self.id().get(store).component().types();
let size = usize::try_from(
match ty {
TransmitIndex::Future(ty) => types[types[ty].ty]
.payload
.map(|ty| types.canonical_abi(&ty).size32),
TransmitIndex::Stream(ty) => types[types[ty].ty]
.payload
.map(|ty| types.canonical_abi(&ty).size32),
}
.unwrap_or(0),
)
.unwrap();
if count > 0 && size > 0 {
self.options_memory(store, options)
.get(address..)
.and_then(|b| b.get(..(size * count)))
.map(drop)
.ok_or_else(|| crate::format_err!("read pointer out of bounds of memory"))
} else {
Ok(())
}
}
/// Write to the specified stream or future from the guest.
pub(super) fn guest_write<T: 'static>(
self,
mut store: StoreContextMut<T>,
caller: RuntimeComponentInstanceIndex,
ty: TransmitIndex,
options: OptionsIndex,
flat_abi: Option<FlatAbi>,
handle: u32,
address: u32,
count: u32,
) -> Result<ReturnCode> {
if !self.options(store.0, options).async_ {
// The caller may only sync call `{stream,future}.write` from an
// async task (i.e. a task created via a call to an async export).
// Otherwise, we'll trap.
store.0.check_blocking()?;
}
let address = usize::try_from(address).unwrap();
let count = usize::try_from(count).unwrap();
self.check_bounds(store.0, options, ty, address, count)?;
let (rep, state) = self.id().get_mut(store.0).get_mut_by_index(ty, handle)?;
let TransmitLocalState::Write { done } = *state else {
bail!(
"invalid handle {handle}; expected `Write`; got {:?}",
*state
);
};
if done {
bail!("cannot write to stream after being notified that the readable end dropped");
}
*state = TransmitLocalState::Busy;
let transmit_handle = TableId::<TransmitHandle>::new(rep);
let concurrent_state = store.0.concurrent_state_mut();
let transmit_id = concurrent_state.get_mut(transmit_handle)?.state;
let transmit = concurrent_state.get_mut(transmit_id)?;
log::trace!(
"guest_write {count} to {transmit_handle:?} (handle {handle}; state {transmit_id:?}); {:?}",
transmit.read
);
if transmit.done {
bail!("cannot write to future after previous write succeeded or readable end dropped");
}
let new_state = if let ReadState::Dropped = &transmit.read {
ReadState::Dropped
} else {
ReadState::Open
};
let set_guest_ready = |me: &mut ConcurrentState| {
let transmit = me.get_mut(transmit_id)?;
assert!(
matches!(&transmit.write, WriteState::Open),
"expected `WriteState::Open`; got `{:?}`",
transmit.write
);
transmit.write = WriteState::GuestReady {
instance: self,
caller,
ty,
flat_abi,
options,
address,
count,
handle,
};
Ok::<_, crate::Error>(())
};
let mut result = match mem::replace(&mut transmit.read, new_state) {
ReadState::GuestReady {
ty: read_ty,
flat_abi: read_flat_abi,
options: read_options,
address: read_address,
count: read_count,
handle: read_handle,
instance: read_instance,
caller: read_caller,
} => {
assert_eq!(flat_abi, read_flat_abi);
if let TransmitIndex::Future(_) = ty {
transmit.done = true;
}
// Note that zero-length reads and writes are handling specially
// by the spec to allow each end to signal readiness to the
// other. Quoting the spec:
//
// ```
// The meaning of a read or write when the length is 0 is that
// the caller is querying the "readiness" of the other
// side. When a 0-length read/write rendezvous with a
// non-0-length read/write, only the 0-length read/write
// completes; the non-0-length read/write is kept pending (and
// ready for a subsequent rendezvous).
//
// In the corner case where a 0-length read and write
// rendezvous, only the writer is notified of readiness. To
// avoid livelock, the Canonical ABI requires that a writer must
// (eventually) follow a completed 0-length write with a
// non-0-length write that is allowed to block (allowing the
// reader end to run and rendezvous with its own non-0-length
// read).
// ```
let write_complete = count == 0 || read_count > 0;
let read_complete = count > 0;
let read_buffer_remaining = count < read_count;
let read_handle_rep = transmit.read_handle.rep();
let count = count.min(read_count);
self.copy(
store.as_context_mut(),
flat_abi,
caller,
ty,
options,
address,
read_caller,
read_ty,
read_options,
read_address,
count,
rep,
)?;
let instance = self.id().get_mut(store.0);
let types = instance.component().types();
let item_size = payload(ty, types)
.map(|ty| usize::try_from(types.canonical_abi(&ty).size32).unwrap())
.unwrap_or(0);
let concurrent_state = store.0.concurrent_state_mut();
if read_complete {
let count = u32::try_from(count).unwrap();
let total = if let Some(Event::StreamRead {
code: ReturnCode::Completed(old_total),
..
}) = concurrent_state.take_event(read_handle_rep)?
{
count + old_total
} else {
count
};
let code = ReturnCode::completed(ty.kind(), total);
concurrent_state.send_read_result(read_ty, transmit_id, read_handle, code)?;
}
if read_buffer_remaining {
let transmit = concurrent_state.get_mut(transmit_id)?;
transmit.read = ReadState::GuestReady {
ty: read_ty,
flat_abi: read_flat_abi,
options: read_options,
address: read_address + (count * item_size),
count: read_count - count,
handle: read_handle,
instance: read_instance,
caller: read_caller,
};
}
if write_complete {
ReturnCode::completed(ty.kind(), count.try_into().unwrap())
} else {
set_guest_ready(concurrent_state)?;
ReturnCode::Blocked
}
}
ReadState::HostReady {
consume,
guest_offset,
cancel,
cancel_waker,
} => {
assert!(cancel_waker.is_none());
assert!(!cancel);
assert_eq!(0, guest_offset);
if let TransmitIndex::Future(_) = ty {
transmit.done = true;
}
set_guest_ready(concurrent_state)?;
self.consume(store.0, ty.kind(), transmit_id, consume, 0, false)?
}
ReadState::HostToHost { .. } => unreachable!(),
ReadState::Open => {
set_guest_ready(concurrent_state)?;
ReturnCode::Blocked
}
ReadState::Dropped => {
if let TransmitIndex::Future(_) = ty {
transmit.done = true;
}
ReturnCode::Dropped(0)
}
};
if result == ReturnCode::Blocked && !self.options(store.0, options).async_ {
result = self.wait_for_write(store.0, transmit_handle)?;
}
if result != ReturnCode::Blocked {
*self.id().get_mut(store.0).get_mut_by_index(ty, handle)?.1 =
TransmitLocalState::Write {
done: matches!(
(result, ty),
(ReturnCode::Dropped(_), TransmitIndex::Stream(_))
),
};
}
log::trace!(
"guest_write result for {transmit_handle:?} (handle {handle}; state {transmit_id:?}): {result:?}",
);
Ok(result)
}
/// Read from the specified stream or future from the guest.
pub(super) fn guest_read<T: 'static>(
self,
mut store: StoreContextMut<T>,
caller: RuntimeComponentInstanceIndex,
ty: TransmitIndex,
options: OptionsIndex,
flat_abi: Option<FlatAbi>,
handle: u32,
address: u32,
count: u32,
) -> Result<ReturnCode> {
if !self.options(store.0, options).async_ {
// The caller may only sync call `{stream,future}.read` from an
// async task (i.e. a task created via a call to an async export).
// Otherwise, we'll trap.
store.0.check_blocking()?;
}
let address = usize::try_from(address).unwrap();
let count = usize::try_from(count).unwrap();
self.check_bounds(store.0, options, ty, address, count)?;
let (rep, state) = self.id().get_mut(store.0).get_mut_by_index(ty, handle)?;
let TransmitLocalState::Read { done } = *state else {
bail!("invalid handle {handle}; expected `Read`; got {:?}", *state);
};
if done {
bail!("cannot read from stream after being notified that the writable end dropped");
}
*state = TransmitLocalState::Busy;
let transmit_handle = TableId::<TransmitHandle>::new(rep);
let concurrent_state = store.0.concurrent_state_mut();
let transmit_id = concurrent_state.get_mut(transmit_handle)?.state;
let transmit = concurrent_state.get_mut(transmit_id)?;
log::trace!(
"guest_read {count} from {transmit_handle:?} (handle {handle}; state {transmit_id:?}); {:?}",
transmit.write
);
if transmit.done {
bail!("cannot read from future after previous read succeeded");
}
let new_state = if let WriteState::Dropped = &transmit.write {
WriteState::Dropped
} else {
WriteState::Open
};
let set_guest_ready = |me: &mut ConcurrentState| {
let transmit = me.get_mut(transmit_id)?;
assert!(
matches!(&transmit.read, ReadState::Open),
"expected `ReadState::Open`; got `{:?}`",
transmit.read
);
transmit.read = ReadState::GuestReady {
ty,
flat_abi,
options,
address,
count,
handle,
instance: self,
caller,
};
Ok::<_, crate::Error>(())
};
let mut result = match mem::replace(&mut transmit.write, new_state) {
WriteState::GuestReady {
instance: _,
ty: write_ty,
flat_abi: write_flat_abi,
options: write_options,
address: write_address,
count: write_count,
handle: write_handle,
caller: write_caller,
} => {
assert_eq!(flat_abi, write_flat_abi);
if let TransmitIndex::Future(_) = ty {
transmit.done = true;
}
let write_handle_rep = transmit.write_handle.rep();
// See the comment in `guest_write` for the
// `ReadState::GuestReady` case concerning zero-length reads and
// writes.
let write_complete = write_count == 0 || count > 0;
let read_complete = write_count > 0;
let write_buffer_remaining = count < write_count;
let count = count.min(write_count);
self.copy(
store.as_context_mut(),
flat_abi,
write_caller,
write_ty,
write_options,
write_address,
caller,
ty,
options,
address,
count,
rep,
)?;
let instance = self.id().get_mut(store.0);
let types = instance.component().types();
let item_size = payload(ty, types)
.map(|ty| usize::try_from(types.canonical_abi(&ty).size32).unwrap())
.unwrap_or(0);
let concurrent_state = store.0.concurrent_state_mut();
if write_complete {
let count = u32::try_from(count).unwrap();
let total = if let Some(Event::StreamWrite {
code: ReturnCode::Completed(old_total),
..
}) = concurrent_state.take_event(write_handle_rep)?
{
count + old_total
} else {
count
};
let code = ReturnCode::completed(ty.kind(), total);
concurrent_state.send_write_result(
write_ty,
transmit_id,
write_handle,
code,
)?;
}
if write_buffer_remaining {
let transmit = concurrent_state.get_mut(transmit_id)?;
transmit.write = WriteState::GuestReady {
instance: self,
caller: write_caller,
ty: write_ty,
flat_abi: write_flat_abi,
options: write_options,
address: write_address + (count * item_size),
count: write_count - count,
handle: write_handle,
};
}
if read_complete {
ReturnCode::completed(ty.kind(), count.try_into().unwrap())
} else {
set_guest_ready(concurrent_state)?;
ReturnCode::Blocked
}
}
WriteState::HostReady {
produce,
try_into,
guest_offset,
cancel,
cancel_waker,
} => {
assert!(cancel_waker.is_none());
assert!(!cancel);
assert_eq!(0, guest_offset);
set_guest_ready(concurrent_state)?;
let code =
self.produce(store.0, ty.kind(), transmit_id, produce, try_into, 0, false)?;
if let (TransmitIndex::Future(_), ReturnCode::Completed(_)) = (ty, code) {
store.0.concurrent_state_mut().get_mut(transmit_id)?.done = true;
}
code
}
WriteState::Open => {
set_guest_ready(concurrent_state)?;
ReturnCode::Blocked
}
WriteState::Dropped => ReturnCode::Dropped(0),
};
if result == ReturnCode::Blocked && !self.options(store.0, options).async_ {
result = self.wait_for_read(store.0, transmit_handle)?;
}
if result != ReturnCode::Blocked {
*self.id().get_mut(store.0).get_mut_by_index(ty, handle)?.1 =
TransmitLocalState::Read {
done: matches!(
(result, ty),
(ReturnCode::Dropped(_), TransmitIndex::Stream(_))
),
};
}
log::trace!(
"guest_read result for {transmit_handle:?} (handle {handle}; state {transmit_id:?}): {result:?}",
);
Ok(result)
}
fn wait_for_write(
self,
store: &mut StoreOpaque,
handle: TableId<TransmitHandle>,
) -> Result<ReturnCode> {
let waitable = Waitable::Transmit(handle);
store.wait_for_event(waitable)?;
let event = waitable.take_event(store.concurrent_state_mut())?;
if let Some(event @ (Event::StreamWrite { code, .. } | Event::FutureWrite { code, .. })) =
event
{
waitable.on_delivery(store, self, event);
Ok(code)
} else {
unreachable!()
}
}
/// Cancel a pending stream or future write.
fn cancel_write(
self,
store: &mut StoreOpaque,
transmit_id: TableId<TransmitState>,
async_: bool,
) -> Result<ReturnCode> {
let state = store.concurrent_state_mut();
let transmit = state.get_mut(transmit_id)?;
log::trace!(
"host_cancel_write state {transmit_id:?}; write state {:?} read state {:?}",
transmit.read,
transmit.write
);
let code = if let Some(event) =
Waitable::Transmit(transmit.write_handle).take_event(state)?
{
let (Event::FutureWrite { code, .. } | Event::StreamWrite { code, .. }) = event else {
unreachable!();
};
match (code, event) {
(ReturnCode::Completed(count), Event::StreamWrite { .. }) => {
ReturnCode::Cancelled(count)
}
(ReturnCode::Dropped(_) | ReturnCode::Completed(_), _) => code,
_ => unreachable!(),
}
} else if let ReadState::HostReady {
cancel,
cancel_waker,
..
} = &mut state.get_mut(transmit_id)?.read
{
*cancel = true;
if let Some(waker) = cancel_waker.take() {
waker.wake();
}
if async_ {
ReturnCode::Blocked
} else {
let handle = store
.concurrent_state_mut()
.get_mut(transmit_id)?
.write_handle;
self.wait_for_write(store, handle)?
}
} else {
ReturnCode::Cancelled(0)
};
let transmit = store.concurrent_state_mut().get_mut(transmit_id)?;
match &transmit.write {
WriteState::GuestReady { .. } => {
transmit.write = WriteState::Open;
}
WriteState::HostReady { .. } => todo!("support host write cancellation"),
WriteState::Open | WriteState::Dropped => {}
}
log::trace!("cancelled write {transmit_id:?}: {code:?}");
Ok(code)
}
fn wait_for_read(
self,
store: &mut StoreOpaque,
handle: TableId<TransmitHandle>,
) -> Result<ReturnCode> {
let waitable = Waitable::Transmit(handle);
store.wait_for_event(waitable)?;
let event = waitable.take_event(store.concurrent_state_mut())?;
if let Some(event @ (Event::StreamRead { code, .. } | Event::FutureRead { code, .. })) =
event
{
waitable.on_delivery(store, self, event);
Ok(code)
} else {
unreachable!()
}
}
/// Cancel a pending stream or future read.
fn cancel_read(
self,
store: &mut StoreOpaque,
transmit_id: TableId<TransmitState>,
async_: bool,
) -> Result<ReturnCode> {
let state = store.concurrent_state_mut();
let transmit = state.get_mut(transmit_id)?;
log::trace!(
"host_cancel_read state {transmit_id:?}; read state {:?} write state {:?}",
transmit.read,
transmit.write
);
let code = if let Some(event) =
Waitable::Transmit(transmit.read_handle).take_event(state)?
{
let (Event::FutureRead { code, .. } | Event::StreamRead { code, .. }) = event else {
unreachable!();
};
match (code, event) {
(ReturnCode::Completed(count), Event::StreamRead { .. }) => {
ReturnCode::Cancelled(count)
}
(ReturnCode::Dropped(_) | ReturnCode::Completed(_), _) => code,
_ => unreachable!(),
}
} else if let WriteState::HostReady {
cancel,
cancel_waker,
..
} = &mut state.get_mut(transmit_id)?.write
{
*cancel = true;
if let Some(waker) = cancel_waker.take() {
waker.wake();
}
if async_ {
ReturnCode::Blocked
} else {
let handle = store
.concurrent_state_mut()
.get_mut(transmit_id)?
.read_handle;
self.wait_for_read(store, handle)?
}
} else {
ReturnCode::Cancelled(0)
};
let transmit = store.concurrent_state_mut().get_mut(transmit_id)?;
match &transmit.read {
ReadState::GuestReady { .. } => {
transmit.read = ReadState::Open;
}
ReadState::HostReady { .. } | ReadState::HostToHost { .. } => {
todo!("support host read cancellation")
}
ReadState::Open | ReadState::Dropped => {}
}
log::trace!("cancelled read {transmit_id:?}: {code:?}");
Ok(code)
}
/// Cancel a pending write for the specified stream or future from the guest.
fn guest_cancel_write(
self,
store: &mut StoreOpaque,
ty: TransmitIndex,
async_: bool,
writer: u32,
) -> Result<ReturnCode> {
if !async_ {
// The caller may only sync call `{stream,future}.cancel-write` from
// an async task (i.e. a task created via a call to an async
// export). Otherwise, we'll trap.
store.check_blocking()?;
}
let (rep, state) =
get_mut_by_index_from(self.id().get_mut(store).table_for_transmit(ty), ty, writer)?;
let id = TableId::<TransmitHandle>::new(rep);
log::trace!("guest cancel write {id:?} (handle {writer})");
match state {
TransmitLocalState::Write { .. } => {
bail!("stream or future write cancelled when no write is pending")
}
TransmitLocalState::Read { .. } => {
bail!("passed read end to `{{stream|future}}.cancel-write`")
}
TransmitLocalState::Busy => {}
}
let transmit_id = store.concurrent_state_mut().get_mut(id)?.state;
let code = self.cancel_write(store, transmit_id, async_)?;
if !matches!(code, ReturnCode::Blocked) {
let state =
get_mut_by_index_from(self.id().get_mut(store).table_for_transmit(ty), ty, writer)?
.1;
if let TransmitLocalState::Busy = state {
*state = TransmitLocalState::Write { done: false };
}
}
Ok(code)
}
/// Cancel a pending read for the specified stream or future from the guest.
fn guest_cancel_read(
self,
store: &mut StoreOpaque,
ty: TransmitIndex,
async_: bool,
reader: u32,
) -> Result<ReturnCode> {
if !async_ {
// The caller may only sync call `{stream,future}.cancel-read` from
// an async task (i.e. a task created via a call to an async
// export). Otherwise, we'll trap.
store.check_blocking()?;
}
let (rep, state) =
get_mut_by_index_from(self.id().get_mut(store).table_for_transmit(ty), ty, reader)?;
let id = TableId::<TransmitHandle>::new(rep);
log::trace!("guest cancel read {id:?} (handle {reader})");
match state {
TransmitLocalState::Read { .. } => {
bail!("stream or future read cancelled when no read is pending")
}
TransmitLocalState::Write { .. } => {
bail!("passed write end to `{{stream|future}}.cancel-read`")
}
TransmitLocalState::Busy => {}
}
let transmit_id = store.concurrent_state_mut().get_mut(id)?.state;
let code = self.cancel_read(store, transmit_id, async_)?;
if !matches!(code, ReturnCode::Blocked) {
let state =
get_mut_by_index_from(self.id().get_mut(store).table_for_transmit(ty), ty, reader)?
.1;
if let TransmitLocalState::Busy = state {
*state = TransmitLocalState::Read { done: false };
}
}
Ok(code)
}
/// Drop the readable end of the specified stream or future from the guest.
fn guest_drop_readable(
self,
store: &mut StoreOpaque,
ty: TransmitIndex,
reader: u32,
) -> Result<()> {
let table = self.id().get_mut(store).table_for_transmit(ty);
let (rep, _is_done) = match ty {
TransmitIndex::Stream(ty) => table.stream_remove_readable(ty, reader)?,
TransmitIndex::Future(ty) => table.future_remove_readable(ty, reader)?,
};
let kind = match ty {
TransmitIndex::Stream(_) => TransmitKind::Stream,
TransmitIndex::Future(_) => TransmitKind::Future,
};
let id = TableId::<TransmitHandle>::new(rep);
log::trace!("guest_drop_readable: drop reader {id:?}");
store.host_drop_reader(id, kind)
}
/// Create a new error context for the given component.
pub(crate) fn error_context_new(
self,
store: &mut StoreOpaque,
ty: TypeComponentLocalErrorContextTableIndex,
options: OptionsIndex,
debug_msg_address: u32,
debug_msg_len: u32,
) -> Result<u32> {
let lift_ctx = &mut LiftContext::new(store, options, self);
let debug_msg = String::linear_lift_from_flat(
lift_ctx,
InterfaceType::String,
&[ValRaw::u32(debug_msg_address), ValRaw::u32(debug_msg_len)],
)?;
// Create a new ErrorContext that is tracked along with other concurrent state
let err_ctx = ErrorContextState { debug_msg };
let state = store.concurrent_state_mut();
let table_id = state.push(err_ctx)?;
let global_ref_count_idx =
TypeComponentGlobalErrorContextTableIndex::from_u32(table_id.rep());
// Add to the global error context ref counts
let _ = state
.global_error_context_ref_counts
.insert(global_ref_count_idx, GlobalErrorContextRefCount(1));
// Error context are tracked both locally (to a single component instance) and globally
// the counts for both must stay in sync.
//
// Here we reflect the newly created global concurrent error context state into the
// component instance's locally tracked count, along with the appropriate key into the global
// ref tracking data structures to enable later lookup
let local_idx = self
.id()
.get_mut(store)
.table_for_error_context(ty)
.error_context_insert(table_id.rep())?;
Ok(local_idx)
}
/// Retrieve the debug message from the specified error context.
pub(super) fn error_context_debug_message<T>(
self,
store: StoreContextMut<T>,
ty: TypeComponentLocalErrorContextTableIndex,
options: OptionsIndex,
err_ctx_handle: u32,
debug_msg_address: u32,
) -> Result<()> {
// Retrieve the error context and internal debug message
let handle_table_id_rep = self
.id()
.get_mut(store.0)
.table_for_error_context(ty)
.error_context_rep(err_ctx_handle)?;
let state = store.0.concurrent_state_mut();
// Get the state associated with the error context
let ErrorContextState { debug_msg } =
state.get_mut(TableId::<ErrorContextState>::new(handle_table_id_rep))?;
let debug_msg = debug_msg.clone();
let lower_cx = &mut LowerContext::new(store, options, self);
let debug_msg_address = usize::try_from(debug_msg_address)?;
// Lower the string into the component's memory
let offset = lower_cx
.as_slice_mut()
.get(debug_msg_address..)
.and_then(|b| b.get(..debug_msg.bytes().len()))
.map(|_| debug_msg_address)
.ok_or_else(|| crate::format_err!("invalid debug message pointer: out of bounds"))?;
debug_msg
.as_str()
.linear_lower_to_memory(lower_cx, InterfaceType::String, offset)?;
Ok(())
}
/// Implements the `future.cancel-read` intrinsic.
pub(crate) fn future_cancel_read(
self,
store: &mut StoreOpaque,
ty: TypeFutureTableIndex,
async_: bool,
reader: u32,
) -> Result<u32> {
self.guest_cancel_read(store, TransmitIndex::Future(ty), async_, reader)
.map(|v| v.encode())
}
/// Implements the `future.cancel-write` intrinsic.
pub(crate) fn future_cancel_write(
self,
store: &mut StoreOpaque,
ty: TypeFutureTableIndex,
async_: bool,
writer: u32,
) -> Result<u32> {
self.guest_cancel_write(store, TransmitIndex::Future(ty), async_, writer)
.map(|v| v.encode())
}
/// Implements the `stream.cancel-read` intrinsic.
pub(crate) fn stream_cancel_read(
self,
store: &mut StoreOpaque,
ty: TypeStreamTableIndex,
async_: bool,
reader: u32,
) -> Result<u32> {
self.guest_cancel_read(store, TransmitIndex::Stream(ty), async_, reader)
.map(|v| v.encode())
}
/// Implements the `stream.cancel-write` intrinsic.
pub(crate) fn stream_cancel_write(
self,
store: &mut StoreOpaque,
ty: TypeStreamTableIndex,
async_: bool,
writer: u32,
) -> Result<u32> {
self.guest_cancel_write(store, TransmitIndex::Stream(ty), async_, writer)
.map(|v| v.encode())
}
/// Implements the `future.drop-readable` intrinsic.
pub(crate) fn future_drop_readable(
self,
store: &mut StoreOpaque,
ty: TypeFutureTableIndex,
reader: u32,
) -> Result<()> {
self.guest_drop_readable(store, TransmitIndex::Future(ty), reader)
}
/// Implements the `stream.drop-readable` intrinsic.
pub(crate) fn stream_drop_readable(
self,
store: &mut StoreOpaque,
ty: TypeStreamTableIndex,
reader: u32,
) -> Result<()> {
self.guest_drop_readable(store, TransmitIndex::Stream(ty), reader)
}
/// Allocate a new future or stream and grant ownership of both the read and
/// write ends to the (sub-)component instance to which the specified
/// `TransmitIndex` belongs.
fn guest_new(self, store: &mut StoreOpaque, ty: TransmitIndex) -> Result<ResourcePair> {
let (write, read) = store
.concurrent_state_mut()
.new_transmit(TransmitOrigin::guest(self.id().instance(), ty))?;
let table = self.id().get_mut(store).table_for_transmit(ty);
let (read_handle, write_handle) = match ty {
TransmitIndex::Future(ty) => (
table.future_insert_read(ty, read.rep())?,
table.future_insert_write(ty, write.rep())?,
),
TransmitIndex::Stream(ty) => (
table.stream_insert_read(ty, read.rep())?,
table.stream_insert_write(ty, write.rep())?,
),
};
let state = store.concurrent_state_mut();
state.get_mut(read)?.common.handle = Some(read_handle);
state.get_mut(write)?.common.handle = Some(write_handle);
Ok(ResourcePair {
write: write_handle,
read: read_handle,
})
}
/// Drop the specified error context.
pub(crate) fn error_context_drop(
self,
store: &mut StoreOpaque,
ty: TypeComponentLocalErrorContextTableIndex,
error_context: u32,
) -> Result<()> {
let instance = self.id().get_mut(store);
let local_handle_table = instance.table_for_error_context(ty);
let rep = local_handle_table.error_context_drop(error_context)?;
let global_ref_count_idx = TypeComponentGlobalErrorContextTableIndex::from_u32(rep);
let state = store.concurrent_state_mut();
let GlobalErrorContextRefCount(global_ref_count) = state
.global_error_context_ref_counts
.get_mut(&global_ref_count_idx)
.expect("retrieve concurrent state for error context during drop");
// Reduce the component-global ref count, removing tracking if necessary
assert!(*global_ref_count >= 1);
*global_ref_count -= 1;
if *global_ref_count == 0 {
state
.global_error_context_ref_counts
.remove(&global_ref_count_idx);
state
.delete(TableId::<ErrorContextState>::new(rep))
.context("deleting component-global error context data")?;
}
Ok(())
}
/// Transfer ownership of the specified stream or future read end from one
/// guest to another.
fn guest_transfer(
self,
store: &mut StoreOpaque,
src_idx: u32,
src: TransmitIndex,
dst: TransmitIndex,
) -> Result<u32> {
let mut instance = self.id().get_mut(store);
let src_table = instance.as_mut().table_for_transmit(src);
let (rep, is_done) = match src {
TransmitIndex::Future(idx) => src_table.future_remove_readable(idx, src_idx)?,
TransmitIndex::Stream(idx) => src_table.stream_remove_readable(idx, src_idx)?,
};
if is_done {
bail!("cannot lift after being notified that the writable end dropped");
}
let dst_table = instance.table_for_transmit(dst);
let handle = match dst {
TransmitIndex::Future(idx) => dst_table.future_insert_read(idx, rep),
TransmitIndex::Stream(idx) => dst_table.stream_insert_read(idx, rep),
}?;
store
.concurrent_state_mut()
.get_mut(TableId::<TransmitHandle>::new(rep))?
.common
.handle = Some(handle);
Ok(handle)
}
/// Implements the `future.new` intrinsic.
pub(crate) fn future_new(
self,
store: &mut StoreOpaque,
ty: TypeFutureTableIndex,
) -> Result<ResourcePair> {
self.guest_new(store, TransmitIndex::Future(ty))
}
/// Implements the `stream.new` intrinsic.
pub(crate) fn stream_new(
self,
store: &mut StoreOpaque,
ty: TypeStreamTableIndex,
) -> Result<ResourcePair> {
self.guest_new(store, TransmitIndex::Stream(ty))
}
/// Transfer ownership of the specified future read end from one guest to
/// another.
pub(crate) fn future_transfer(
self,
store: &mut StoreOpaque,
src_idx: u32,
src: TypeFutureTableIndex,
dst: TypeFutureTableIndex,
) -> Result<u32> {
self.guest_transfer(
store,
src_idx,
TransmitIndex::Future(src),
TransmitIndex::Future(dst),
)
}
/// Transfer ownership of the specified stream read end from one guest to
/// another.
pub(crate) fn stream_transfer(
self,
store: &mut StoreOpaque,
src_idx: u32,
src: TypeStreamTableIndex,
dst: TypeStreamTableIndex,
) -> Result<u32> {
self.guest_transfer(
store,
src_idx,
TransmitIndex::Stream(src),
TransmitIndex::Stream(dst),
)
}
/// Copy the specified error context from one component to another.
pub(crate) fn error_context_transfer(
self,
store: &mut StoreOpaque,
src_idx: u32,
src: TypeComponentLocalErrorContextTableIndex,
dst: TypeComponentLocalErrorContextTableIndex,
) -> Result<u32> {
let mut instance = self.id().get_mut(store);
let rep = instance
.as_mut()
.table_for_error_context(src)
.error_context_rep(src_idx)?;
let dst_idx = instance
.table_for_error_context(dst)
.error_context_insert(rep)?;
// Update the global (cross-subcomponent) count for error contexts
// as the new component has essentially created a new reference that will
// be dropped/handled independently
let global_ref_count = store
.concurrent_state_mut()
.global_error_context_ref_counts
.get_mut(&TypeComponentGlobalErrorContextTableIndex::from_u32(rep))
.context("global ref count present for existing (sub)component error context")?;
global_ref_count.0 += 1;
Ok(dst_idx)
}
}
impl ComponentInstance {
fn table_for_transmit(self: Pin<&mut Self>, ty: TransmitIndex) -> &mut HandleTable {
let (states, types) = self.instance_states();
let runtime_instance = match ty {
TransmitIndex::Stream(ty) => types[ty].instance,
TransmitIndex::Future(ty) => types[ty].instance,
};
states[runtime_instance].handle_table()
}
fn table_for_error_context(
self: Pin<&mut Self>,
ty: TypeComponentLocalErrorContextTableIndex,
) -> &mut HandleTable {
let (states, types) = self.instance_states();
let runtime_instance = types[ty].instance;
states[runtime_instance].handle_table()
}
fn get_mut_by_index(
self: Pin<&mut Self>,
ty: TransmitIndex,
index: u32,
) -> Result<(u32, &mut TransmitLocalState)> {
get_mut_by_index_from(self.table_for_transmit(ty), ty, index)
}
}
impl ConcurrentState {
fn send_write_result(
&mut self,
ty: TransmitIndex,
id: TableId<TransmitState>,
handle: u32,
code: ReturnCode,
) -> Result<()> {
let write_handle = self.get_mut(id)?.write_handle.rep();
self.set_event(
write_handle,
match ty {
TransmitIndex::Future(ty) => Event::FutureWrite {
code,
pending: Some((ty, handle)),
},
TransmitIndex::Stream(ty) => Event::StreamWrite {
code,
pending: Some((ty, handle)),
},
},
)
}
fn send_read_result(
&mut self,
ty: TransmitIndex,
id: TableId<TransmitState>,
handle: u32,
code: ReturnCode,
) -> Result<()> {
let read_handle = self.get_mut(id)?.read_handle.rep();
self.set_event(
read_handle,
match ty {
TransmitIndex::Future(ty) => Event::FutureRead {
code,
pending: Some((ty, handle)),
},
TransmitIndex::Stream(ty) => Event::StreamRead {
code,
pending: Some((ty, handle)),
},
},
)
}
fn take_event(&mut self, waitable: u32) -> Result<Option<Event>> {
Waitable::Transmit(TableId::<TransmitHandle>::new(waitable)).take_event(self)
}
fn set_event(&mut self, waitable: u32, event: Event) -> Result<()> {
Waitable::Transmit(TableId::<TransmitHandle>::new(waitable)).set_event(self, Some(event))
}
/// Set or update the event for the specified waitable.
///
/// If there is already an event set for this waitable, we assert that it is
/// of the same variant as the new one and reuse the `ReturnCode` count and
/// the `pending` field if applicable.
// TODO: This is a bit awkward due to how
// `Event::{Stream,Future}{Write,Read}` and
// `ReturnCode::{Completed,Dropped,Cancelled}` are currently represented.
// Consider updating those representations in a way that allows this
// function to be simplified.
fn update_event(&mut self, waitable: u32, event: Event) -> Result<()> {
let waitable = Waitable::Transmit(TableId::<TransmitHandle>::new(waitable));
fn update_code(old: ReturnCode, new: ReturnCode) -> ReturnCode {
let (ReturnCode::Completed(count)
| ReturnCode::Dropped(count)
| ReturnCode::Cancelled(count)) = old
else {
unreachable!()
};
match new {
ReturnCode::Dropped(0) => ReturnCode::Dropped(count),
ReturnCode::Cancelled(0) => ReturnCode::Cancelled(count),
_ => unreachable!(),
}
}
let event = match (waitable.take_event(self)?, event) {
(None, _) => event,
(Some(old @ Event::FutureWrite { .. }), Event::FutureWrite { .. }) => old,
(Some(old @ Event::FutureRead { .. }), Event::FutureRead { .. }) => old,
(
Some(Event::StreamWrite {
code: old_code,
pending: old_pending,
}),
Event::StreamWrite { code, pending },
) => Event::StreamWrite {
code: update_code(old_code, code),
pending: old_pending.or(pending),
},
(
Some(Event::StreamRead {
code: old_code,
pending: old_pending,
}),
Event::StreamRead { code, pending },
) => Event::StreamRead {
code: update_code(old_code, code),
pending: old_pending.or(pending),
},
_ => unreachable!(),
};
waitable.set_event(self, Some(event))
}
/// Allocate a new future or stream, including the `TransmitState` and the
/// `TransmitHandle`s corresponding to the read and write ends.
fn new_transmit(
&mut self,
origin: TransmitOrigin,
) -> Result<(TableId<TransmitHandle>, TableId<TransmitHandle>)> {
let state_id = self.push(TransmitState::new(origin))?;
let write = self.push(TransmitHandle::new(state_id))?;
let read = self.push(TransmitHandle::new(state_id))?;
let state = self.get_mut(state_id)?;
state.write_handle = write;
state.read_handle = read;
log::trace!("new transmit: state {state_id:?}; write {write:?}; read {read:?}",);
Ok((write, read))
}
/// Delete the specified future or stream, including the read and write ends.
fn delete_transmit(&mut self, state_id: TableId<TransmitState>) -> Result<()> {
let state = self.delete(state_id)?;
self.delete(state.write_handle)?;
self.delete(state.read_handle)?;
log::trace!(
"delete transmit: state {state_id:?}; write {:?}; read {:?}",
state.write_handle,
state.read_handle,
);
Ok(())
}
}
pub(crate) struct ResourcePair {
pub(crate) write: u32,
pub(crate) read: u32,
}
impl Waitable {
/// Handle the imminent delivery of the specified event, e.g. by updating
/// the state of the stream or future.
pub(super) fn on_delivery(&self, store: &mut StoreOpaque, instance: Instance, event: Event) {
match event {
Event::FutureRead {
pending: Some((ty, handle)),
..
}
| Event::FutureWrite {
pending: Some((ty, handle)),
..
} => {
let instance = instance.id().get_mut(store);
let runtime_instance = instance.component().types()[ty].instance;
let (rep, state) = instance.instance_states().0[runtime_instance]
.handle_table()
.future_rep(ty, handle)
.unwrap();
assert_eq!(rep, self.rep());
assert_eq!(*state, TransmitLocalState::Busy);
*state = match event {
Event::FutureRead { .. } => TransmitLocalState::Read { done: false },
Event::FutureWrite { .. } => TransmitLocalState::Write { done: false },
_ => unreachable!(),
};
}
Event::StreamRead {
pending: Some((ty, handle)),
code,
}
| Event::StreamWrite {
pending: Some((ty, handle)),
code,
} => {
let instance = instance.id().get_mut(store);
let runtime_instance = instance.component().types()[ty].instance;
let (rep, state) = instance.instance_states().0[runtime_instance]
.handle_table()
.stream_rep(ty, handle)
.unwrap();
assert_eq!(rep, self.rep());
assert_eq!(*state, TransmitLocalState::Busy);
let done = matches!(code, ReturnCode::Dropped(_));
*state = match event {
Event::StreamRead { .. } => TransmitLocalState::Read { done },
Event::StreamWrite { .. } => TransmitLocalState::Write { done },
_ => unreachable!(),
};
let transmit_handle = TableId::<TransmitHandle>::new(rep);
let state = store.concurrent_state_mut();
let transmit_id = state.get_mut(transmit_handle).unwrap().state;
let transmit = state.get_mut(transmit_id).unwrap();
match event {
Event::StreamRead { .. } => {
transmit.read = ReadState::Open;
}
Event::StreamWrite { .. } => transmit.write = WriteState::Open,
_ => unreachable!(),
};
}
_ => {}
}
}
}
/// Determine whether an intra-component read/write is allowed for the specified
/// `stream` or `future` payload type according to the component model
/// specification.
fn allow_intra_component_read_write(ty: Option<InterfaceType>) -> bool {
matches!(
ty,
None | Some(
InterfaceType::S8
| InterfaceType::U8
| InterfaceType::S16
| InterfaceType::U16
| InterfaceType::S32
| InterfaceType::U32
| InterfaceType::S64
| InterfaceType::U64
| InterfaceType::Float32
| InterfaceType::Float64
)
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Engine, Store};
use core::future::pending;
use core::pin::pin;
use std::sync::LazyLock;
static ENGINE: LazyLock<Engine> = LazyLock::new(Engine::default);
fn poll_future_producer<T>(rx: Pin<&mut T>, finish: bool) -> Poll<Result<Option<T::Item>>>
where
T: FutureProducer<()>,
{
rx.poll_produce(
&mut Context::from_waker(Waker::noop()),
Store::new(&ENGINE, ()).as_context_mut(),
finish,
)
}
#[test]
fn future_producer() {
let mut fut = pin!(async { crate::error::Ok(()) });
assert!(matches!(
poll_future_producer(fut.as_mut(), false),
Poll::Ready(Ok(Some(()))),
));
let mut fut = pin!(async { crate::error::Ok(()) });
assert!(matches!(
poll_future_producer(fut.as_mut(), true),
Poll::Ready(Ok(Some(()))),
));
let mut fut = pin!(pending::<Result<()>>());
assert!(matches!(
poll_future_producer(fut.as_mut(), false),
Poll::Pending,
));
assert!(matches!(
poll_future_producer(fut.as_mut(), true),
Poll::Ready(Ok(None)),
));
let (tx, rx) = oneshot::channel();
let mut rx = pin!(rx);
assert!(matches!(
poll_future_producer(rx.as_mut(), false),
Poll::Pending,
));
assert!(matches!(
poll_future_producer(rx.as_mut(), true),
Poll::Ready(Ok(None)),
));
tx.send(()).unwrap();
assert!(matches!(
poll_future_producer(rx.as_mut(), true),
Poll::Ready(Ok(Some(()))),
));
let (tx, rx) = oneshot::channel();
let mut rx = pin!(rx);
tx.send(()).unwrap();
assert!(matches!(
poll_future_producer(rx.as_mut(), false),
Poll::Ready(Ok(Some(()))),
));
let (tx, rx) = oneshot::channel::<()>();
let mut rx = pin!(rx);
drop(tx);
assert!(matches!(
poll_future_producer(rx.as_mut(), false),
Poll::Ready(Err(..)),
));
let (tx, rx) = oneshot::channel::<()>();
let mut rx = pin!(rx);
drop(tx);
assert!(matches!(
poll_future_producer(rx.as_mut(), true),
Poll::Ready(Err(..)),
));
}
}