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
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
*
* Copyright 2016 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "wasm/WasmJS.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/EndianUtils.h"
#include "mozilla/Maybe.h"
#include "mozilla/RangedPtr.h"
#include <algorithm>
#include "gc/FreeOp.h"
#include "jit/AtomicOperations.h"
#include "jit/JitOptions.h"
#include "jit/JitRuntime.h"
#include "jit/Simulator.h"
#if defined(JS_CODEGEN_X64) // Assembler::HasSSE41
# include "jit/x64/Assembler-x64.h"
# include "jit/x86-shared/Architecture-x86-shared.h"
# include "jit/x86-shared/Assembler-x86-shared.h"
#endif
#include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
#include "js/Printf.h"
#include "js/PropertySpec.h" // JS_{PS,FN}{,_END}
#include "util/StringBuffer.h"
#include "util/Text.h"
#include "vm/ErrorObject.h"
#include "vm/FunctionFlags.h" // js::FunctionFlags
#include "vm/GlobalObject.h" // js::GlobalObject
#include "vm/HelperThreadState.h" // js::PromiseHelperTask
#include "vm/Interpreter.h"
#include "vm/PlainObject.h" // js::PlainObject
#include "vm/PromiseObject.h" // js::PromiseObject
#include "vm/StringType.h"
#include "vm/Warnings.h" // js::WarnNumberASCII
#include "wasm/WasmBaselineCompile.h"
#include "wasm/WasmBuiltins.h"
#include "wasm/WasmCompile.h"
#include "wasm/WasmCraneliftCompile.h"
#include "wasm/WasmInstance.h"
#include "wasm/WasmIonCompile.h"
#include "wasm/WasmModule.h"
#include "wasm/WasmProcess.h"
#include "wasm/WasmSignalHandlers.h"
#include "wasm/WasmStubs.h"
#include "wasm/WasmValidate.h"
#include "vm/ArrayBufferObject-inl.h"
#include "vm/JSObject-inl.h"
#include "vm/NativeObject-inl.h"
using namespace js;
using namespace js::jit;
using namespace js::wasm;
using mozilla::CheckedInt;
using mozilla::Nothing;
using mozilla::RangedPtr;
using mozilla::Span;
extern mozilla::Atomic<bool> fuzzingSafe;
// About the fuzzer intercession points: If fuzzing has been selected and only a
// single compiler has been selected then we will disable features that are not
// supported by that single compiler. This is strictly a concession to the
// fuzzer infrastructure.
static inline bool IsFuzzing() {
#ifdef FUZZING
return true;
#else
return fuzzingSafe;
#endif
}
static inline bool IsFuzzingIon(JSContext* cx) {
return IsFuzzing() && !cx->options().wasmBaseline() &&
cx->options().wasmIon() && !cx->options().wasmCranelift();
}
static inline bool IsFuzzingCranelift(JSContext* cx) {
return IsFuzzing() && !cx->options().wasmBaseline() &&
!cx->options().wasmIon() && cx->options().wasmCranelift();
}
// These functions read flags and apply fuzzing intercession policies. Never go
// directly to the flags in code below, always go via these accessors.
static inline bool WasmMultiValueFlag(JSContext* cx) {
#ifdef ENABLE_WASM_MULTI_VALUE
return cx->options().wasmMultiValue();
#else
return false;
#endif
}
static inline bool WasmSimdFlag(JSContext* cx) {
#ifdef ENABLE_WASM_SIMD
if (IsFuzzingCranelift(cx)) {
return false;
}
return cx->options().wasmSimd() && js::jit::JitSupportsWasmSimd();
#else
return false;
#endif
}
static inline bool WasmSimdWormholeFlag(JSContext* cx) {
#ifdef ENABLE_WASM_SIMD_WORMHOLE
return cx->options().wasmSimdWormhole();
#else
return false;
#endif
}
static inline bool WasmReftypesFlag(JSContext* cx) {
#ifdef ENABLE_WASM_REFTYPES
return cx->options().wasmReftypes();
#else
return false;
#endif
}
static inline bool WasmFunctionReferencesFlag(JSContext* cx) {
if (IsFuzzingIon(cx) || IsFuzzingCranelift(cx)) {
return false;
}
#ifdef ENABLE_WASM_FUNCTION_REFERENCES
return WasmReftypesFlag(cx) && cx->options().wasmFunctionReferences();
#else
return false;
#endif
}
static inline bool WasmGcFlag(JSContext* cx) {
if (IsFuzzingIon(cx) || IsFuzzingCranelift(cx)) {
return false;
}
#ifdef ENABLE_WASM_GC
return WasmFunctionReferencesFlag(cx) && cx->options().wasmGc();
#else
return false;
#endif
}
static inline bool WasmThreadsFlag(JSContext* cx) {
return cx->realm() &&
cx->realm()->creationOptions().getSharedMemoryAndAtomicsEnabled();
}
static inline bool WasmExceptionsFlag(JSContext* cx) {
#ifdef ENABLE_WASM_EXCEPTIONS
return cx->options().wasmExceptions();
#else
return false;
#endif
}
static inline bool WasmDebuggerActive(JSContext* cx) {
if (IsFuzzingIon(cx) || IsFuzzingCranelift(cx)) {
return false;
}
return cx->realm() && cx->realm()->debuggerObservesAsmJS();
}
/*
* [SMDOC] Compiler and feature selection; compiler and feature availability.
*
* In order to make the computation of whether a wasm feature or wasm compiler
* is available predictable, we have established some rules, and implemented
* those rules.
*
* Code elsewhere should use the predicates below to test for features and
* compilers, it should never try to compute feature and compiler availability
* in other ways.
*
* At the outset, there is a set of selected compilers C containing at most one
* baseline compiler [*] and at most one optimizing compiler [**], and a set of
* selected features F. These selections come from defaults and from overrides
* by command line switches in the shell and javascript.option.wasm_X in the
* browser. Defaults for both features and compilers may be platform specific,
* for example, some compilers may not be available on some platforms because
* they do not support the architecture at all or they do not support features
* that must be enabled by default on the platform.
*
* [*] Currently we have only one, "baseline" aka "Rabaldr", but other
* implementations have additional baseline translators, eg from wasm
* bytecode to an internal code processed by an interpreter.
*
* [**] Currently we have two, "ion" aka "Baldr", and "Cranelift".
*
*
* Compiler availability:
*
* The set of features F induces a set of available compilers A: these are the
* compilers that all support all the features in F. (Some of these compilers
* may not be in the set C.)
*
* The sets C and A are intersected, yielding a set of enabled compilers E.
* Notably, the set E may be empty, in which case wasm is effectively disabled
* (though the WebAssembly object is still present in the global environment).
*
* An important consequence is that selecting a feature that is not supported by
* a particular compiler disables that compiler completely -- there is no notion
* of a compiler being available but suddenly failing when an unsupported
* feature is used by a program. If a compiler is available, it supports all
* the features that have been selected.
*
* Equally important, a feature cannot be enabled by default on a platform if
* the feature is not supported by all the compilers we wish to have enabled by
* default on the platform. We MUST by-default disable features on a platform
* that are not supported by all the compilers on the platform.
*
* As an example:
*
* On ARM64 the default compilers are Baseline and Cranelift. Say Cranelift
* does not support feature X. Thus X cannot be enabled by default on ARM64.
* However, X support can be compiled-in to SpiderMonkey, and the user can opt
* to enable X. Doing so will disable Cranelift.
*
* In contrast, X can be enabled by default on x64, where the default
* compilers are Baseline and Ion, both of which support X.
*
* A subtlety is worth noting: on x64, enabling Cranelift (thus disabling Ion)
* will not disable X. Instead, the presence of X in the selected feature set
* will disable Cranelift, leaving only Baseline. This follows from the logic
* described above.
*
* In a shell build, the testing functions wasmCompilersPresent,
* wasmCompileMode, wasmCraneliftDisabledByFeatures, and
* wasmIonDisabledByFeatures can be used to probe compiler availability and the
* reasons for a compiler being unavailable.
*
*
* Feature availability:
*
* A feature is available if it is selected and there is at least one available
* compiler that implements it.
*
* For example, --wasm-gc selects the GC feature, and if Baseline is available
* then the feature is available.
*
* In a shell build, there are per-feature testing functions (of the form
* wasmFeatureEnabled) to probe whether specific features are available.
*/
// Compiler availability predicates. These must be kept in sync with the
// feature predicates in the next section below.
//
// These can't call the feature predicates since the feature predicates call
// back to these predicates. So there will be a small amount of duplicated
// logic here, but as compilers reach feature parity that duplication will go
// away.
//
// There's a static precedence order between the optimizing compilers. This
// order currently ranks Cranelift over Ion on all platforms because Cranelift
// is disabled by default on all platforms: anyone who has enabled Cranelift
// will wish to use it instead of Ion.
//
// The precedence order is implemented by guards in IonAvailable() and
// CraneliftAvailable(). We expect that it will become more complex as the
// default settings change. But it should remain static.
bool wasm::BaselineAvailable(JSContext* cx) {
// Baseline supports every feature supported by any compiler.
return cx->options().wasmBaseline() && BaselinePlatformSupport();
}
bool wasm::IonAvailable(JSContext* cx) {
if (!cx->options().wasmIon() || !IonPlatformSupport()) {
return false;
}
bool isDisabled = false;
MOZ_ALWAYS_TRUE(IonDisabledByFeatures(cx, &isDisabled));
return !isDisabled && !CraneliftAvailable(cx);
}
template <size_t ArrayLength>
static inline bool Append(JSStringBuilder* reason, const char (&s)[ArrayLength],
char* sep) {
if ((*sep && !reason->append(*sep)) || !reason->append(s)) {
return false;
}
*sep = ',';
return true;
}
bool wasm::IonDisabledByFeatures(JSContext* cx, bool* isDisabled,
JSStringBuilder* reason) {
// Ion has no debugging support, no gc support.
bool debug = WasmDebuggerActive(cx);
bool functionReferences = WasmFunctionReferencesFlag(cx);
bool gc = WasmGcFlag(cx);
bool exn = WasmExceptionsFlag(cx);
if (reason) {
char sep = 0;
if (debug && !Append(reason, "debug", &sep)) {
return false;
}
if (functionReferences && !Append(reason, "function-references", &sep)) {
return false;
}
if (gc && !Append(reason, "gc", &sep)) {
return false;
}
if (exn && !Append(reason, "exceptions", &sep)) {
return false;
}
}
*isDisabled = debug || functionReferences || gc || exn;
return true;
}
bool wasm::CraneliftAvailable(JSContext* cx) {
if (!cx->options().wasmCranelift() || !CraneliftPlatformSupport()) {
return false;
}
bool isDisabled = false;
MOZ_ALWAYS_TRUE(CraneliftDisabledByFeatures(cx, &isDisabled));
return !isDisabled;
}
bool wasm::CraneliftDisabledByFeatures(JSContext* cx, bool* isDisabled,
JSStringBuilder* reason) {
// Cranelift has no debugging support, no gc support, no simd, and
// no exceptions support.
bool debug = WasmDebuggerActive(cx);
bool functionReferences = WasmFunctionReferencesFlag(cx);
bool gc = WasmGcFlag(cx);
#ifdef JS_CODEGEN_ARM64
// Cranelift aarch64 has full SIMD support.
bool simdOnNonAarch64 = false;
#else
bool simdOnNonAarch64 = WasmSimdFlag(cx);
#endif
bool exn = WasmExceptionsFlag(cx);
if (reason) {
char sep = 0;
if (debug && !Append(reason, "debug", &sep)) {
return false;
}
if (functionReferences && !Append(reason, "function-references", &sep)) {
return false;
}
if (gc && !Append(reason, "gc", &sep)) {
return false;
}
if (simdOnNonAarch64 && !Append(reason, "simd", &sep)) {
return false;
}
if (exn && !Append(reason, "exceptions", &sep)) {
return false;
}
}
*isDisabled = debug || functionReferences || gc || simdOnNonAarch64 || exn;
return true;
}
bool wasm::AnyCompilerAvailable(JSContext* cx) {
return wasm::BaselineAvailable(cx) || wasm::IonAvailable(cx) ||
wasm::CraneliftAvailable(cx);
}
// Feature predicates. These must be kept in sync with the predicates in the
// section above.
//
// The meaning of these predicates is tricky: A predicate is true for a feature
// if the feature is enabled and/or compiled-in *and* we have *at least one*
// compiler that can support the feature. Subsequent compiler selection must
// ensure that only compilers that actually support the feature are used.
bool wasm::ReftypesAvailable(JSContext* cx) {
// All compilers support reference types.
return WasmReftypesFlag(cx) && AnyCompilerAvailable(cx);
}
bool wasm::FunctionReferencesAvailable(JSContext* cx) {
// Cranelift and Ion do not support function-references.
return WasmFunctionReferencesFlag(cx) && BaselineAvailable(cx);
}
bool wasm::GcTypesAvailable(JSContext* cx) {
// Cranelift and Ion do not support GC.
return WasmGcFlag(cx) && BaselineAvailable(cx);
}
bool wasm::MultiValuesAvailable(JSContext* cx) {
return WasmMultiValueFlag(cx) && AnyCompilerAvailable(cx);
}
bool wasm::SimdAvailable(JSContext* cx) {
return WasmSimdFlag(cx) &&
(BaselineAvailable(cx) || IonAvailable(cx) || CraneliftAvailable(cx));
}
bool wasm::SimdWormholeAvailable(JSContext* cx) {
return WasmSimdWormholeFlag(cx) && SimdAvailable(cx) && IonAvailable(cx) &&
!BaselineAvailable(cx) && !CraneliftAvailable(cx);
}
bool wasm::ThreadsAvailable(JSContext* cx) {
return WasmThreadsFlag(cx) && AnyCompilerAvailable(cx);
}
bool wasm::ExceptionsAvailable(JSContext* cx) {
// Ion & Cranelift do not support Exceptions (for now).
// Exceptions require multi-value.
return WasmExceptionsFlag(cx) && MultiValuesAvailable(cx) &&
BaselineAvailable(cx);
}
bool wasm::HasPlatformSupport(JSContext* cx) {
#if !MOZ_LITTLE_ENDIAN() || defined(JS_CODEGEN_NONE)
return false;
#endif
if (gc::SystemPageSize() > wasm::PageSize) {
return false;
}
if (!JitOptions.supportsFloatingPoint) {
return false;
}
if (!JitOptions.supportsUnalignedAccesses) {
return false;
}
if (!wasm::EnsureFullSignalHandlers(cx)) {
return false;
}
if (!jit::JitSupportsAtomics()) {
return false;
}
// Wasm threads require 8-byte lock-free atomics.
if (!jit::AtomicOperations::isLockfree8()) {
return false;
}
// Lazily initialize the global type context
if (!cx->wasm().ensureTypeContext(cx)) {
return false;
}
// Test only whether the compilers are supported on the hardware, not whether
// they are enabled.
return BaselinePlatformSupport() || IonPlatformSupport() ||
CraneliftPlatformSupport();
}
bool wasm::HasSupport(JSContext* cx) {
// If the general wasm pref is on, it's on for everything.
bool prefEnabled = cx->options().wasm();
// If the general pref is off, check trusted principals.
if (MOZ_UNLIKELY(!prefEnabled)) {
prefEnabled = cx->options().wasmForTrustedPrinciples() && cx->realm() &&
cx->realm()->principals() &&
cx->realm()->principals()->isSystemOrAddonPrincipal();
}
// Do not check for compiler availability, as that may be run-time variant.
// For HasSupport() we want a stable answer depending only on prefs.
return prefEnabled && HasPlatformSupport(cx);
}
bool wasm::StreamingCompilationAvailable(JSContext* cx) {
// This should match EnsureStreamSupport().
return HasSupport(cx) && AnyCompilerAvailable(cx) &&
cx->runtime()->offThreadPromiseState.ref().initialized() &&
CanUseExtraThreads() && cx->runtime()->consumeStreamCallback &&
cx->runtime()->reportStreamErrorCallback;
}
bool wasm::CodeCachingAvailable(JSContext* cx) {
// At the moment, we require Ion support for code caching. The main reason
// for this is that wasm::CompileAndSerialize() does not have access to
// information about which optimizing compiler it should use. See comments in
// CompileAndSerialize(), below.
return StreamingCompilationAvailable(cx) && IonAvailable(cx);
}
// As the return values from the underlying buffer accessors will become size_t
// before long, they are captured as size_t here.
uint32_t wasm::ByteLength32(Handle<ArrayBufferObjectMaybeShared*> buffer) {
size_t len = buffer->byteLength().get();
MOZ_ASSERT(len <= size_t(MaxMemory32Pages) * PageSize);
return uint32_t(len);
}
uint32_t wasm::ByteLength32(const ArrayBufferObjectMaybeShared& buffer) {
size_t len = buffer.byteLength().get();
MOZ_ASSERT(len <= size_t(MaxMemory32Pages) * PageSize);
return uint32_t(len);
}
uint32_t wasm::ByteLength32(const WasmArrayRawBuffer* buffer) {
size_t len = buffer->byteLength().get();
MOZ_ASSERT(len <= size_t(MaxMemory32Pages) * PageSize);
return uint32_t(len);
}
uint32_t wasm::ByteLength32(const ArrayBufferObject& buffer) {
size_t len = buffer.byteLength().get();
MOZ_ASSERT(len <= size_t(MaxMemory32Pages) * PageSize);
return uint32_t(len);
}
uint32_t wasm::VolatileByteLength32(const SharedArrayRawBuffer* buffer) {
size_t len = buffer->volatileByteLength().get();
MOZ_ASSERT(len <= size_t(MaxMemory32Pages) * PageSize);
return uint32_t(len);
}
// ============================================================================
// Imports
static bool ThrowBadImportArg(JSContext* cx) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_IMPORT_ARG);
return false;
}
static bool ThrowBadImportType(JSContext* cx, const char* field,
const char* str) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_IMPORT_TYPE, field, str);
return false;
}
static bool GetProperty(JSContext* cx, HandleObject obj, const char* chars,
MutableHandleValue v) {
JSAtom* atom = AtomizeUTF8Chars(cx, chars, strlen(chars));
if (!atom) {
return false;
}
RootedId id(cx, AtomToId(atom));
return GetProperty(cx, obj, obj, id, v);
}
bool js::wasm::GetImports(JSContext* cx, const Module& module,
HandleObject importObj, ImportValues* imports) {
if (!module.imports().empty() && !importObj) {
return ThrowBadImportArg(cx);
}
const Metadata& metadata = module.metadata();
#ifdef ENABLE_WASM_EXCEPTIONS
uint32_t eventIndex = 0;
const EventDescVector& events = metadata.events;
#endif
uint32_t globalIndex = 0;
const GlobalDescVector& globals = metadata.globals;
uint32_t tableIndex = 0;
const TableDescVector& tables = metadata.tables;
for (const Import& import : module.imports()) {
RootedValue v(cx);
if (!GetProperty(cx, importObj, import.module.get(), &v)) {
return false;
}
if (!v.isObject()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_IMPORT_FIELD,
import.module.get());
return false;
}
RootedObject obj(cx, &v.toObject());
if (!GetProperty(cx, obj, import.field.get(), &v)) {
return false;
}
switch (import.kind) {
case DefinitionKind::Function: {
if (!IsFunctionObject(v)) {
return ThrowBadImportType(cx, import.field.get(), "Function");
}
if (!imports->funcs.append(&v.toObject().as<JSFunction>())) {
return false;
}
break;
}
case DefinitionKind::Table: {
const uint32_t index = tableIndex++;
if (!v.isObject() || !v.toObject().is<WasmTableObject>()) {
return ThrowBadImportType(cx, import.field.get(), "Table");
}
RootedWasmTableObject obj(cx, &v.toObject().as<WasmTableObject>());
if (obj->table().elemType() != tables[index].elemType) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_TBL_TYPE_LINK);
return false;
}
if (!imports->tables.append(obj)) {
return false;
}
break;
}
case DefinitionKind::Memory: {
if (!v.isObject() || !v.toObject().is<WasmMemoryObject>()) {
return ThrowBadImportType(cx, import.field.get(), "Memory");
}
MOZ_ASSERT(!imports->memory);
imports->memory = &v.toObject().as<WasmMemoryObject>();
break;
}
#ifdef ENABLE_WASM_EXCEPTIONS
case DefinitionKind::Event: {
const uint32_t index = eventIndex++;
if (!v.isObject() || !v.toObject().is<WasmExceptionObject>()) {
return ThrowBadImportType(cx, import.field.get(), "Exception");
}
RootedWasmExceptionObject obj(cx,
&v.toObject().as<WasmExceptionObject>());
// Checks whether the signature of the imported exception object matches
// the signature declared in the exception import's EventDesc.
if (obj->resultType() != events[index].resultType()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_EXN_SIG, import.module.get(),
import.field.get());
return false;
}
if (!imports->exceptionObjs.append(obj)) {
ReportOutOfMemory(cx);
return false;
}
break;
}
#endif
case DefinitionKind::Global: {
const uint32_t index = globalIndex++;
const GlobalDesc& global = globals[index];
MOZ_ASSERT(global.importIndex() == index);
RootedVal val(cx);
if (v.isObject() && v.toObject().is<WasmGlobalObject>()) {
RootedWasmGlobalObject obj(cx, &v.toObject().as<WasmGlobalObject>());
if (obj->isMutable() != global.isMutable()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_GLOB_MUT_LINK);
return false;
}
if (obj->type() != global.type()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_GLOB_TYPE_LINK);
return false;
}
if (imports->globalObjs.length() <= index &&
!imports->globalObjs.resize(index + 1)) {
ReportOutOfMemory(cx);
return false;
}
imports->globalObjs[index] = obj;
val = obj->val();
} else {
if (IsNumberType(global.type())) {
if (global.type() == ValType::I64 && !v.isBigInt()) {
return ThrowBadImportType(cx, import.field.get(), "BigInt");
}
if (global.type() != ValType::I64 && !v.isNumber()) {
return ThrowBadImportType(cx, import.field.get(), "Number");
}
} else {
MOZ_ASSERT(global.type().isReference());
if (!global.type().isExternRef() && !v.isObjectOrNull()) {
return ThrowBadImportType(cx, import.field.get(),
"Object-or-null value required for "
"non-externref reference type");
}
}
if (global.isMutable()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_GLOB_MUT_LINK);
return false;
}
if (!Val::fromJSValue(cx, global.type(), v, &val)) {
return false;
}
}
if (!imports->globalValues.append(val)) {
return false;
}
break;
}
}
}
MOZ_ASSERT(globalIndex == globals.length() ||
!globals[globalIndex].isImport());
return true;
}
static bool DescribeScriptedCaller(JSContext* cx, ScriptedCaller* caller,
const char* introducer) {
// Note: JS::DescribeScriptedCaller returns whether a scripted caller was
// found, not whether an error was thrown. This wrapper function converts
// back to the more ordinary false-if-error form.
JS::AutoFilename af;
if (JS::DescribeScriptedCaller(cx, &af, &caller->line)) {
caller->filename =
FormatIntroducedFilename(cx, af.get(), caller->line, introducer);
if (!caller->filename) {
return false;
}
}
return true;
}
// ============================================================================
// Testing / Fuzzing support
bool wasm::Eval(JSContext* cx, Handle<TypedArrayObject*> code,
HandleObject importObj,
MutableHandleWasmInstanceObject instanceObj) {
if (!GlobalObject::ensureConstructor(cx, cx->global(), JSProto_WebAssembly)) {
return false;
}
MutableBytes bytecode = cx->new_<ShareableBytes>();
if (!bytecode) {
return false;
}
if (!bytecode->append((uint8_t*)code->dataPointerEither().unwrap(),
code->byteLength().get())) {
ReportOutOfMemory(cx);
return false;
}
ScriptedCaller scriptedCaller;
if (!DescribeScriptedCaller(cx, &scriptedCaller, "wasm_eval")) {
return false;
}
SharedCompileArgs compileArgs =
CompileArgs::build(cx, std::move(scriptedCaller));
if (!compileArgs) {
return false;
}
UniqueChars error;
UniqueCharsVector warnings;
JSTelemetrySender sender(cx->runtime());
SharedModule module = CompileBuffer(*compileArgs, *bytecode, &error,
&warnings, nullptr, sender);
if (!module) {
if (error) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_COMPILE_ERROR, error.get());
return false;
}
ReportOutOfMemory(cx);
return false;
}
Rooted<ImportValues> imports(cx);
if (!GetImports(cx, *module, importObj, imports.address())) {
return false;
}
return module->instantiate(cx, imports.get(), nullptr, instanceObj);
}
struct MOZ_STACK_CLASS SerializeListener : JS::OptimizedEncodingListener {
// MOZ_STACK_CLASS means these can be nops.
MozExternalRefCountType MOZ_XPCOM_ABI AddRef() override { return 0; }
MozExternalRefCountType MOZ_XPCOM_ABI Release() override { return 0; }
DebugOnly<bool> called = false;
Bytes* serialized;
explicit SerializeListener(Bytes* serialized) : serialized(serialized) {}
void storeOptimizedEncoding(JS::UniqueOptimizedEncodingBytes bytes) override {
MOZ_ASSERT(!called);
called = true;
if (serialized->resize(bytes->length())) {
memcpy(serialized->begin(), bytes->begin(), bytes->length());
}
}
};
bool wasm::CompileAndSerialize(const ShareableBytes& bytecode,
Bytes* serialized) {
MutableCompileArgs compileArgs = js_new<CompileArgs>(ScriptedCaller());
if (!compileArgs) {
return false;
}
// The caller has ensured CodeCachingAvailable(). Moreover, we want to ensure
// we go straight to tier-2 so that we synchronously call
// JS::OptimizedEncodingListener::storeOptimizedEncoding().
compileArgs->baselineEnabled = false;
// We always pick Ion here, and we depend on CodeCachingAvailable() having
// determined that Ion is available, see comments at CodeCachingAvailable().
// To do better, we need to pass information about which compiler that should
// be used into CompileAndSerialize().
compileArgs->ionEnabled = true;
// The caller must ensure that huge memory support is configured the same in
// the receiving process of this serialized module.
compileArgs->features.hugeMemory = wasm::IsHugeMemoryEnabled();
SerializeListener listener(serialized);
UniqueChars error;
UniqueCharsVector warnings;
SharedModule module =
CompileBuffer(*compileArgs, bytecode, &error, &warnings, &listener);
if (!module) {
fprintf(stderr, "Compilation error: %s\n", error ? error.get() : "oom");
return false;
}
MOZ_ASSERT(module->code().hasTier(Tier::Serialized));
MOZ_ASSERT(listener.called);
return !listener.serialized->empty();
}
bool wasm::DeserializeModule(JSContext* cx, const Bytes& serialized,
MutableHandleObject moduleObj) {
MutableModule module =
Module::deserialize(serialized.begin(), serialized.length());
if (!module) {
ReportOutOfMemory(cx);
return false;
}
moduleObj.set(module->createObject(cx));
return !!moduleObj;
}
// ============================================================================
// Common functions
// '[EnforceRange] unsigned long' types are coerced with
// ConvertToInt(v, 32, 'unsigned')
// defined in Web IDL Section 3.2.4.9.
static bool EnforceRangeU32(JSContext* cx, HandleValue v, const char* kind,
const char* noun, uint32_t* u32) {
// Step 4.
double x;
if (!ToNumber(cx, v, &x)) {
return false;
}
// Step 5.
if (mozilla::IsNegativeZero(x)) {
x = 0.0;
}
// Step 6.1.
if (!mozilla::IsFinite(x)) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_UINT32, kind, noun);
return false;
}
// Step 6.2.
x = JS::ToInteger(x);
// Step 6.3.
if (x < 0 || x > double(UINT32_MAX)) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_UINT32, kind, noun);
return false;
}
*u32 = uint32_t(x);
MOZ_ASSERT(double(*u32) == x);
return true;
}
static bool GetLimits(JSContext* cx, HandleObject obj, uint32_t maximumField,
const char* kind, Limits* limits, Shareable allowShared) {
JSAtom* initialAtom = Atomize(cx, "initial", strlen("initial"));
if (!initialAtom) {
return false;
}
RootedId initialId(cx, AtomToId(initialAtom));
RootedValue initialVal(cx);
if (!GetProperty(cx, obj, obj, initialId, &initialVal)) {
return false;
}
uint32_t initial = 0;
if (!initialVal.isUndefined() &&
!EnforceRangeU32(cx, initialVal, kind, "initial size", &initial)) {
return false;
}
limits->initial = initial;
if (limits->initial > maximumField) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_WASM_BAD_RANGE,
kind, "initial size");
return false;
}
#ifdef ENABLE_WASM_TYPE_REFLECTIONS
// Get minimum parameter.
JSAtom* minimumAtom = Atomize(cx, "minimum", strlen("minimum"));
if (!minimumAtom) {
return false;
}
RootedId minimumId(cx, AtomToId(minimumAtom));
RootedValue minimumVal(cx);
if (!GetProperty(cx, obj, obj, minimumId, &minimumVal)) {
return false;
}
uint32_t minimum = 0;
if (!minimumVal.isUndefined() &&
!EnforceRangeU32(cx, minimumVal, kind, "initial size", &minimum)) {
return false;
}
if (!minimumVal.isUndefined()) {
limits->initial = minimum;
}
#endif
// Get maximum parameter.
JSAtom* maximumAtom = Atomize(cx, "maximum", strlen("maximum"));
if (!maximumAtom) {
return false;
}
RootedId maximumId(cx, AtomToId(maximumAtom));
RootedValue maxVal(cx);
if (!GetProperty(cx, obj, obj, maximumId, &maxVal)) {
return false;
}
// maxVal does not have a default value.
if (!maxVal.isUndefined()) {
uint32_t maximum = 0;
if (!EnforceRangeU32(cx, maxVal, kind, "maximum size", &maximum)) {
return false;
}
limits->maximum = Some(maximum);
if (*limits->maximum > maximumField || limits->initial > *limits->maximum) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_RANGE, kind, "maximum size");
return false;
}
}
limits->shared = Shareable::False;
if (allowShared == Shareable::True) {
JSAtom* sharedAtom = Atomize(cx, "shared", strlen("shared"));
if (!sharedAtom) {
return false;
}
RootedId sharedId(cx, AtomToId(sharedAtom));
RootedValue sharedVal(cx);
if (!GetProperty(cx, obj, obj, sharedId, &sharedVal)) {
return false;
}
// shared's default value is false, which is already the value set above.
if (!sharedVal.isUndefined()) {
limits->shared =
ToBoolean(sharedVal) ? Shareable::True : Shareable::False;
if (limits->shared == Shareable::True) {
if (maxVal.isUndefined()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_WASM_MISSING_MAXIMUM, kind);
return false;
}
if (!cx->realm()
->creationOptions()
.getSharedMemoryAndAtomicsEnabled()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_WASM_NO_SHMEM_LINK);
return false;
}
}
}
}
#ifdef ENABLE_WASM_TYPE_REFLECTIONS
// Check both minimum and initial are not supplied.
if (minimumVal.isUndefined() == initialVal.isUndefined()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_SUPPLY_ONLY_ONE, "minimum", "initial");
return false;
}
#else
if (initialVal.isUndefined()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_MISSING_REQUIRED, "initial");
return false;
}
#endif
return true;
}
template <class Class, const char* name>
static JSObject* CreateWasmConstructor(JSContext* cx, JSProtoKey key) {
RootedAtom className(cx, Atomize(cx, name, strlen(name)));
if (!className) {
return nullptr;
}
return NewNativeConstructor(cx, Class::construct, 1, className);
}
// ============================================================================
// WebAssembly.Module class and methods
const JSClassOps WasmModuleObject::classOps_ = {
nullptr, // addProperty
nullptr, // delProperty
nullptr, // enumerate
nullptr, // newEnumerate
nullptr, // resolve
nullptr, // mayResolve
WasmModuleObject::finalize, // finalize
nullptr, // call
nullptr, // hasInstance
nullptr, // construct
nullptr, // trace
};
const JSClass WasmModuleObject::class_ = {
"WebAssembly.Module",
JSCLASS_DELAY_METADATA_BUILDER |
JSCLASS_HAS_RESERVED_SLOTS(WasmModuleObject::RESERVED_SLOTS) |
JSCLASS_FOREGROUND_FINALIZE,
&WasmModuleObject::classOps_,
&WasmModuleObject::classSpec_,
};
const JSClass& WasmModuleObject::protoClass_ = PlainObject::class_;
static constexpr char WasmModuleName[] = "Module";
const ClassSpec WasmModuleObject::classSpec_ = {
CreateWasmConstructor<WasmModuleObject, WasmModuleName>,
GenericCreatePrototype<WasmModuleObject>,
WasmModuleObject::static_methods,
nullptr,
WasmModuleObject::methods,
WasmModuleObject::properties,
nullptr,
ClassSpec::DontDefineConstructor};
const JSPropertySpec WasmModuleObject::properties[] = {
JS_STRING_SYM_PS(toStringTag, "WebAssembly.Module", JSPROP_READONLY),
JS_PS_END};
const JSFunctionSpec WasmModuleObject::methods[] = {JS_FS_END};
const JSFunctionSpec WasmModuleObject::static_methods[] = {
JS_FN("imports", WasmModuleObject::imports, 1, JSPROP_ENUMERATE),
JS_FN("exports", WasmModuleObject::exports, 1, JSPROP_ENUMERATE),
JS_FN("customSections", WasmModuleObject::customSections, 2,
JSPROP_ENUMERATE),
JS_FS_END};
/* static */
void WasmModuleObject::finalize(JSFreeOp* fop, JSObject* obj) {
const Module& module = obj->as<WasmModuleObject>().module();
obj->zone()->decJitMemory(module.codeLength(module.code().stableTier()));
fop->release(obj, &module, module.gcMallocBytesExcludingCode(),
MemoryUse::WasmModule);
}
static bool IsModuleObject(JSObject* obj, const Module** module) {
WasmModuleObject* mobj = obj->maybeUnwrapIf<WasmModuleObject>();
if (!mobj) {
return false;
}
*module = &mobj->module();
return true;
}
static bool GetModuleArg(JSContext* cx, CallArgs args, uint32_t numRequired,
const char* name, const Module** module) {
if (!args.requireAtLeast(cx, name, numRequired)) {
return false;
}
if (!args[0].isObject() || !IsModuleObject(&args[0].toObject(), module)) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_MOD_ARG);
return false;
}
return true;
}
struct KindNames {
RootedPropertyName kind;
RootedPropertyName table;
RootedPropertyName memory;
RootedPropertyName event;
RootedPropertyName signature;
explicit KindNames(JSContext* cx)
: kind(cx), table(cx), memory(cx), event(cx), signature(cx) {}
};
static bool InitKindNames(JSContext* cx, KindNames* names) {
JSAtom* kind = Atomize(cx, "kind", strlen("kind"));
if (!kind) {
return false;
}
names->kind = kind->asPropertyName();
JSAtom* table = Atomize(cx, "table", strlen("table"));
if (!table) {
return false;
}
names->table = table->asPropertyName();
JSAtom* memory = Atomize(cx, "memory", strlen("memory"));
if (!memory) {
return false;
}
names->memory = memory->asPropertyName();
#ifdef ENABLE_WASM_EXCEPTIONS
JSAtom* event = Atomize(cx, "event", strlen("event"));
if (!event) {
return false;
}
names->event = event->asPropertyName();
#endif
JSAtom* signature = Atomize(cx, "signature", strlen("signature"));
if (!signature) {
return false;
}
names->signature = signature->asPropertyName();
return true;
}
static JSString* KindToString(JSContext* cx, const KindNames& names,
DefinitionKind kind) {
switch (kind) {
case DefinitionKind::Function:
return cx->names().function;
case DefinitionKind::Table:
return names.table;
case DefinitionKind::Memory:
return names.memory;
case DefinitionKind::Global:
return cx->names().global;
#ifdef ENABLE_WASM_EXCEPTIONS
case DefinitionKind::Event:
return names.event;
#endif
}
MOZ_CRASH("invalid kind");
}
static JSString* FuncTypeToString(JSContext* cx, const FuncType& funcType) {
JSStringBuilder buf(cx);
if (!buf.append('(')) {
return nullptr;
}
bool first = true;
for (ValType arg : funcType.args()) {
if (!first && !buf.append(", ", strlen(", "))) {
return nullptr;
}
UniqueChars argStr = ToString(arg);
if (!argStr) {
return nullptr;
}
if (!buf.append(argStr.get(), strlen(argStr.get()))) {
return nullptr;
}
first = false;
}
if (!buf.append(") -> (", strlen(") -> ("))) {
return nullptr;
}
first = true;
for (ValType result : funcType.results()) {
if (!first && !buf.append(", ", strlen(", "))) {
return nullptr;
}
UniqueChars resultStr = ToString(result);
if (!resultStr) {
return nullptr;
}
if (!buf.append(resultStr.get(), strlen(resultStr.get()))) {
return nullptr;
}
first = false;
}
if (!buf.append(')')) {
return nullptr;
}
return buf.finishString();
}
static JSString* UTF8CharsToString(JSContext* cx, const char* chars) {
return NewStringCopyUTF8Z<CanGC>(cx,
JS::ConstUTF8CharsZ(chars, strlen(chars)));
}
/* static */
bool WasmModuleObject::imports(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
const Module* module;
if (!GetModuleArg(cx, args, 1, "WebAssembly.Module.imports", &module)) {
return false;
}
KindNames names(cx);
if (!InitKindNames(cx, &names)) {
return false;
}
RootedValueVector elems(cx);
if (!elems.reserve(module->imports().length())) {
return false;
}
const FuncImportVector& funcImports =
module->metadata(module->code().stableTier()).funcImports;
size_t numFuncImport = 0;
for (const Import& import : module->imports()) {
Rooted<IdValueVector> props(cx, IdValueVector(cx));
if (!props.reserve(3)) {
return false;
}
JSString* moduleStr = UTF8CharsToString(cx, import.module.get());
if (!moduleStr) {
return false;
}
props.infallibleAppend(
IdValuePair(NameToId(cx->names().module), StringValue(moduleStr)));
JSString* nameStr = UTF8CharsToString(cx, import.field.get());
if (!nameStr) {
return false;
}
props.infallibleAppend(
IdValuePair(NameToId(cx->names().name), StringValue(nameStr)));
JSString* kindStr = KindToString(cx, names, import.kind);
if (!kindStr) {
return false;
}
props.infallibleAppend(
IdValuePair(NameToId(names.kind), StringValue(kindStr)));
if (fuzzingSafe && import.kind == DefinitionKind::Function) {
JSString* ftStr =
FuncTypeToString(cx, funcImports[numFuncImport++].funcType());
if (!ftStr) {
return false;
}
if (!props.append(
IdValuePair(NameToId(names.signature), StringValue(ftStr)))) {
return false;
}
}
JSObject* obj = NewPlainObjectWithProperties(cx, props.begin(),
props.length(), GenericObject);
if (!obj) {
return false;
}
elems.infallibleAppend(ObjectValue(*obj));
}
JSObject* arr = NewDenseCopiedArray(cx, elems.length(), elems.begin());
if (!arr) {
return false;
}
args.rval().setObject(*arr);
return true;
}
/* static */
bool WasmModuleObject::exports(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
const Module* module;
if (!GetModuleArg(cx, args, 1, "WebAssembly.Module.exports", &module)) {
return false;
}
KindNames names(cx);
if (!InitKindNames(cx, &names)) {
return false;
}
RootedValueVector elems(cx);
if (!elems.reserve(module->exports().length())) {
return false;
}
for (const Export& exp : module->exports()) {
Rooted<IdValueVector> props(cx, IdValueVector(cx));
if (!props.reserve(2)) {
return false;
}
JSString* nameStr = UTF8CharsToString(cx, exp.fieldName());
if (!nameStr) {
return false;
}
props.infallibleAppend(
IdValuePair(NameToId(cx->names().name), StringValue(nameStr)));
JSString* kindStr = KindToString(cx, names, exp.kind());
if (!kindStr) {
return false;
}
props.infallibleAppend(
IdValuePair(NameToId(names.kind), StringValue(kindStr)));
if (fuzzingSafe && exp.kind() == DefinitionKind::Function) {
const FuncExport& fe = module->metadata(module->code().stableTier())
.lookupFuncExport(exp.funcIndex());
JSString* ftStr = FuncTypeToString(cx, fe.funcType());
if (!ftStr) {
return false;
}
if (!props.append(
IdValuePair(NameToId(names.signature), StringValue(ftStr)))) {
return false;
}
}
JSObject* obj = NewPlainObjectWithProperties(cx, props.begin(),
props.length(), GenericObject);
if (!obj) {
return false;
}
elems.infallibleAppend(ObjectValue(*obj));
}
JSObject* arr = NewDenseCopiedArray(cx, elems.length(), elems.begin());
if (!arr) {
return false;
}
args.rval().setObject(*arr);
return true;
}
/* static */
bool WasmModuleObject::customSections(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
const Module* module;
if (!GetModuleArg(cx, args, 2, "WebAssembly.Module.customSections",
&module)) {
return false;
}
Vector<char, 8> name(cx);
{
RootedString str(cx, ToString(cx, args.get(1)));
if (!str) {
return false;
}
Rooted<JSLinearString*> linear(cx, str->ensureLinear(cx));
if (!linear) {
return false;
}
if (!name.initLengthUninitialized(
JS::GetDeflatedUTF8StringLength(linear))) {
return false;
}
mozilla::Unused << JS::DeflateStringToUTF8Buffer(
linear, Span(name.begin(), name.length()));
}
RootedValueVector elems(cx);
RootedArrayBufferObject buf(cx);
for (const CustomSection& cs : module->customSections()) {
if (name.length() != cs.name.length()) {
continue;
}
if (memcmp(name.begin(), cs.name.begin(), name.length())) {
continue;
}
buf = ArrayBufferObject::createZeroed(cx, BufferSize(cs.payload->length()));
if (!buf) {
return false;
}
memcpy(buf->dataPointer(), cs.payload->begin(), cs.payload->length());
if (!elems.append(ObjectValue(*buf))) {
return false;
}
}
JSObject* arr = NewDenseCopiedArray(cx, elems.length(), elems.begin());
if (!arr) {
return false;
}
args.rval().setObject(*arr);
return true;
}
/* static */
WasmModuleObject* WasmModuleObject::create(JSContext* cx, const Module& module,
HandleObject proto) {
AutoSetNewObjectMetadata metadata(cx);
auto* obj = NewObjectWithGivenProto<WasmModuleObject>(cx, proto);
if (!obj) {
return nullptr;
}
// This accounts for module allocation size (excluding code which is handled
// separately - see below). This assumes that the size of associated data
// doesn't change for the life of the WasmModuleObject. The size is counted
// once per WasmModuleObject referencing a Module.
InitReservedSlot(obj, MODULE_SLOT, const_cast<Module*>(&module),
module.gcMallocBytesExcludingCode(), MemoryUse::WasmModule);
module.AddRef();
// Bug 1569888: We account for the first tier here; the second tier, if
// different, also needs to be accounted for.
cx->zone()->incJitMemory(module.codeLength(module.code().stableTier()));
return obj;
}
static bool GetBufferSource(JSContext* cx, JSObject* obj, unsigned errorNumber,
MutableBytes* bytecode) {
*bytecode = cx->new_<ShareableBytes>();
if (!*bytecode) {
return false;
}
JSObject* unwrapped = CheckedUnwrapStatic(obj);
SharedMem<uint8_t*> dataPointer;
size_t byteLength;
if (!unwrapped || !IsBufferSource(unwrapped, &dataPointer, &byteLength)) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, errorNumber);
return false;
}
if (!(*bytecode)->append(dataPointer.unwrap(), byteLength)) {
ReportOutOfMemory(cx);
return false;
}
return true;
}
static SharedCompileArgs InitCompileArgs(JSContext* cx,
const char* introducer) {
ScriptedCaller scriptedCaller;
if (!DescribeScriptedCaller(cx, &scriptedCaller, introducer)) {
return nullptr;
}
return CompileArgs::build(cx, std::move(scriptedCaller));
}
static bool ReportCompileWarnings(JSContext* cx,
const UniqueCharsVector& warnings) {
// Avoid spamming the console.
size_t numWarnings = std::min<size_t>(warnings.length(), 3);
for (size_t i = 0; i < numWarnings; i++) {
if (!WarnNumberASCII(cx, JSMSG_WASM_COMPILE_WARNING, warnings[i].get())) {
return false;
}
}
if (warnings.length() > numWarnings) {
if (!WarnNumberASCII(cx, JSMSG_WASM_COMPILE_WARNING,
"other warnings suppressed")) {
return false;
}
}
return true;
}
/* static */
bool WasmModuleObject::construct(JSContext* cx, unsigned argc, Value* vp) {
CallArgs callArgs = CallArgsFromVp(argc, vp);
Log(cx, "sync new Module() started");
if (!ThrowIfNotConstructing(cx, callArgs, "Module")) {
return false;
}
if (!callArgs.requireAtLeast(cx, "WebAssembly.Module", 1)) {
return false;
}
if (!callArgs[0].isObject()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_BUF_ARG);
return false;
}
MutableBytes bytecode;
if (!GetBufferSource(cx, &callArgs[0].toObject(), JSMSG_WASM_BAD_BUF_ARG,
&bytecode)) {
return false;
}
SharedCompileArgs compileArgs = InitCompileArgs(cx, "WebAssembly.Module");
if (!compileArgs) {
return false;
}
UniqueChars error;
UniqueCharsVector warnings;
JSTelemetrySender sender(cx->runtime());
SharedModule module = CompileBuffer(*compileArgs, *bytecode, &error,
&warnings, nullptr, sender);
if (!module) {
if (error) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_COMPILE_ERROR, error.get());
return false;
}
ReportOutOfMemory(cx);
return false;
}
if (!ReportCompileWarnings(cx, warnings)) {
return false;
}
RootedObject proto(cx);
if (!GetPrototypeFromBuiltinConstructor(cx, callArgs, JSProto_WasmModule,
&proto)) {
return false;
}
if (!proto) {
proto = GlobalObject::getOrCreatePrototype(cx, JSProto_WasmModule);
}
RootedObject moduleObj(cx, WasmModuleObject::create(cx, *module, proto));
if (!moduleObj) {
return false;
}
Log(cx, "sync new Module() succeded");
callArgs.rval().setObject(*moduleObj);
return true;
}
const Module& WasmModuleObject::module() const {
MOZ_ASSERT(is<WasmModuleObject>());
return *(const Module*)getReservedSlot(MODULE_SLOT).toPrivate();
}
// ============================================================================
// WebAssembly.Instance class and methods
const JSClassOps WasmInstanceObject::classOps_ = {
nullptr, // addProperty
nullptr, // delProperty
nullptr, // enumerate
nullptr, // newEnumerate
nullptr, // resolve
nullptr, // mayResolve
WasmInstanceObject::finalize, // finalize
nullptr, // call
nullptr, // hasInstance
nullptr, // construct
WasmInstanceObject::trace, // trace
};
const JSClass WasmInstanceObject::class_ = {
"WebAssembly.Instance",
JSCLASS_DELAY_METADATA_BUILDER |
JSCLASS_HAS_RESERVED_SLOTS(WasmInstanceObject::RESERVED_SLOTS) |
JSCLASS_FOREGROUND_FINALIZE,
&WasmInstanceObject::classOps_,
&WasmInstanceObject::classSpec_,
};
const JSClass& WasmInstanceObject::protoClass_ = PlainObject::class_;
static constexpr char WasmInstanceName[] = "Instance";
const ClassSpec WasmInstanceObject::classSpec_ = {
CreateWasmConstructor<WasmInstanceObject, WasmInstanceName>,
GenericCreatePrototype<WasmInstanceObject>,
WasmInstanceObject::static_methods,
nullptr,
WasmInstanceObject::methods,
WasmInstanceObject::properties,
nullptr,
ClassSpec::DontDefineConstructor};
static bool IsInstance(HandleValue v) {
return v.isObject() && v.toObject().is<WasmInstanceObject>();
}
/* static */
bool WasmInstanceObject::exportsGetterImpl(JSContext* cx,
const CallArgs& args) {
args.rval().setObject(
args.thisv().toObject().as<WasmInstanceObject>().exportsObj());
return true;
}
/* static */
bool WasmInstanceObject::exportsGetter(JSContext* cx, unsigned argc,
Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsInstance, exportsGetterImpl>(cx, args);
}
const JSPropertySpec WasmInstanceObject::properties[] = {
JS_PSG("exports", WasmInstanceObject::exportsGetter, JSPROP_ENUMERATE),
JS_STRING_SYM_PS(toStringTag, "WebAssembly.Instance", JSPROP_READONLY),
JS_PS_END};
const JSFunctionSpec WasmInstanceObject::methods[] = {JS_FS_END};
const JSFunctionSpec WasmInstanceObject::static_methods[] = {JS_FS_END};
bool WasmInstanceObject::isNewborn() const {
MOZ_ASSERT(is<WasmInstanceObject>());
return getReservedSlot(INSTANCE_SLOT).isUndefined();
}
// WeakScopeMap maps from function index to js::Scope. This maps is weak
// to avoid holding scope objects alive. The scopes are normally created
// during debugging.
//
// This is defined here in order to avoid recursive dependency between
// WasmJS.h and Scope.h.
using WasmFunctionScopeMap =
JS::WeakCache<GCHashMap<uint32_t, WeakHeapPtr<WasmFunctionScope*>,
DefaultHasher<uint32_t>, ZoneAllocPolicy>>;
class WasmInstanceObject::UnspecifiedScopeMap {
public:
WasmFunctionScopeMap& asWasmFunctionScopeMap() {
return *(WasmFunctionScopeMap*)this;
}
};
/* static */
void WasmInstanceObject::finalize(JSFreeOp* fop, JSObject* obj) {
WasmInstanceObject& instance = obj->as<WasmInstanceObject>();
fop->delete_(obj, &instance.exports(), MemoryUse::WasmInstanceExports);
fop->delete_(obj, &instance.scopes().asWasmFunctionScopeMap(),
MemoryUse::WasmInstanceScopes);
fop->delete_(obj, &instance.indirectGlobals(),
MemoryUse::WasmInstanceGlobals);
if (!instance.isNewborn()) {
if (instance.instance().debugEnabled()) {
instance.instance().debug().finalize(fop);
}
fop->delete_(obj, &instance.instance(), MemoryUse::WasmInstanceInstance);
}
}
/* static */
void WasmInstanceObject::trace(JSTracer* trc, JSObject* obj) {
WasmInstanceObject& instanceObj = obj->as<WasmInstanceObject>();
instanceObj.exports().trace(trc);
instanceObj.indirectGlobals().trace(trc);
if (!instanceObj.isNewborn()) {
instanceObj.instance().tracePrivate(trc);
}
}
/* static */
WasmInstanceObject* WasmInstanceObject::create(
JSContext* cx, SharedCode code, const DataSegmentVector& dataSegments,
const ElemSegmentVector& elemSegments, UniqueTlsData tlsData,
HandleWasmMemoryObject memory, SharedExceptionTagVector&& exceptionTags,
SharedTableVector&& tables, const JSFunctionVector& funcImports,
const GlobalDescVector& globals, const ValVector& globalImportValues,
const WasmGlobalObjectVector& globalObjs, HandleObject proto,
UniqueDebugState maybeDebug) {
UniquePtr<ExportMap> exports = js::MakeUnique<ExportMap>(cx->zone());
if (!exports) {
ReportOutOfMemory(cx);
return nullptr;
}
UniquePtr<WasmFunctionScopeMap> scopes =
js::MakeUnique<WasmFunctionScopeMap>(cx->zone(), cx->zone());
if (!scopes) {
ReportOutOfMemory(cx);
return nullptr;
}
uint32_t indirectGlobals = 0;
for (uint32_t i = 0; i < globalObjs.length(); i++) {
if (globalObjs[i] && globals[i].isIndirect()) {
indirectGlobals++;
}
}
Rooted<UniquePtr<GlobalObjectVector>> indirectGlobalObjs(
cx, js::MakeUnique<GlobalObjectVector>(cx->zone()));
if (!indirectGlobalObjs || !indirectGlobalObjs->resize(indirectGlobals)) {
ReportOutOfMemory(cx);
return nullptr;
}
{
uint32_t next = 0;
for (uint32_t i = 0; i < globalObjs.length(); i++) {
if (globalObjs[i] && globals[i].isIndirect()) {
(*indirectGlobalObjs)[next++] = globalObjs[i];
}
}
}
Instance* instance = nullptr;
RootedWasmInstanceObject obj(cx);
{
// We must delay creating metadata for this object until after all its
// slots have been initialized. We must also create the metadata before
// calling Instance::init as that may allocate new objects.
AutoSetNewObjectMetadata metadata(cx);
obj = NewObjectWithGivenProto<WasmInstanceObject>(cx, proto);
if (!obj) {
return nullptr;
}
MOZ_ASSERT(obj->isTenured(), "assumed by WasmTableObject write barriers");
// Finalization assumes these slots are always initialized:
InitReservedSlot(obj, EXPORTS_SLOT, exports.release(),
MemoryUse::WasmInstanceExports);
InitReservedSlot(obj, SCOPES_SLOT, scopes.release(),
MemoryUse::WasmInstanceScopes);
InitReservedSlot(obj, GLOBALS_SLOT, indirectGlobalObjs.release(),
MemoryUse::WasmInstanceGlobals);
obj->initReservedSlot(INSTANCE_SCOPE_SLOT, UndefinedValue());
// The INSTANCE_SLOT may not be initialized if Instance allocation fails,
// leading to an observable "newborn" state in tracing/finalization.
MOZ_ASSERT(obj->isNewborn());
// Root the Instance via WasmInstanceObject before any possible GC.
instance = cx->new_<Instance>(cx, obj, code, std::move(tlsData), memory,
std::move(exceptionTags), std::move(tables),
std::move(maybeDebug));
if (!instance) {
return nullptr;
}
InitReservedSlot(obj, INSTANCE_SLOT, instance,
MemoryUse::WasmInstanceInstance);
MOZ_ASSERT(!obj->isNewborn());
}
if (!instance->init(cx, funcImports, globalImportValues, globalObjs,
dataSegments, elemSegments)) {
return nullptr;
}
return obj;
}
void WasmInstanceObject::initExportsObj(JSObject& exportsObj) {
MOZ_ASSERT(getReservedSlot(EXPORTS_OBJ_SLOT).isUndefined());
setReservedSlot(EXPORTS_OBJ_SLOT, ObjectValue(exportsObj));
}
static bool GetImportArg(JSContext* cx, CallArgs callArgs,
MutableHandleObject importObj) {
if (!callArgs.get(1).isUndefined()) {
if (!callArgs[1].isObject()) {
return ThrowBadImportArg(cx);
}
importObj.set(&callArgs[1].toObject());
}
return true;
}
/* static */
bool WasmInstanceObject::construct(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
Log(cx, "sync new Instance() started");
if (!ThrowIfNotConstructing(cx, args, "Instance")) {
return false;
}
if (!args.requireAtLeast(cx, "WebAssembly.Instance", 1)) {
return false;
}
const Module* module;
if (!args[0].isObject() || !IsModuleObject(&args[0].toObject(), &module)) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_MOD_ARG);
return false;
}
RootedObject importObj(cx);
if (!GetImportArg(cx, args, &importObj)) {
return false;
}
RootedObject instanceProto(cx);
if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_WasmInstance,
&instanceProto)) {
return false;
}
if (!instanceProto) {
instanceProto =
GlobalObject::getOrCreatePrototype(cx, JSProto_WasmInstance);
}
Rooted<ImportValues> imports(cx);
if (!GetImports(cx, *module, importObj, imports.address())) {
return false;
}
RootedWasmInstanceObject instanceObj(cx);
if (!module->instantiate(cx, imports.get(), instanceProto, &instanceObj)) {
return false;
}
Log(cx, "sync new Instance() succeeded");
args.rval().setObject(*instanceObj);
return true;
}
Instance& WasmInstanceObject::instance() const {
MOZ_ASSERT(!isNewborn());
return *(Instance*)getReservedSlot(INSTANCE_SLOT).toPrivate();
}
JSObject& WasmInstanceObject::exportsObj() const {
return getReservedSlot(EXPORTS_OBJ_SLOT).toObject();
}
WasmInstanceObject::ExportMap& WasmInstanceObject::exports() const {
return *(ExportMap*)getReservedSlot(EXPORTS_SLOT).toPrivate();
}
WasmInstanceObject::UnspecifiedScopeMap& WasmInstanceObject::scopes() const {
return *(UnspecifiedScopeMap*)(getReservedSlot(SCOPES_SLOT).toPrivate());
}
WasmInstanceObject::GlobalObjectVector& WasmInstanceObject::indirectGlobals()
const {
return *(GlobalObjectVector*)getReservedSlot(GLOBALS_SLOT).toPrivate();
}
static bool WasmCall(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
RootedFunction callee(cx, &args.callee().as<JSFunction>());
Instance& instance = ExportedFunctionToInstance(callee);
uint32_t funcIndex = ExportedFunctionToFuncIndex(callee);
return instance.callExport(cx, funcIndex, args);
}
/* static */
bool WasmInstanceObject::getExportedFunction(
JSContext* cx, HandleWasmInstanceObject instanceObj, uint32_t funcIndex,
MutableHandleFunction fun) {
if (ExportMap::Ptr p = instanceObj->exports().lookup(funcIndex)) {
fun.set(p->value());
return true;
}
const Instance& instance = instanceObj->instance();
const FuncExport& funcExport =
instance.metadata(instance.code().bestTier()).lookupFuncExport(funcIndex);
unsigned numArgs = funcExport.funcType().args().length();
if (instance.isAsmJS()) {
// asm.js needs to act like a normal JS function which means having the
// name from the original source and being callable as a constructor.
RootedAtom name(cx, instance.getFuncDisplayAtom(cx, funcIndex));
if (!name) {
return false;
}
fun.set(NewNativeConstructor(cx, WasmCall, numArgs, name,
gc::AllocKind::FUNCTION_EXTENDED,
TenuredObject, FunctionFlags::ASMJS_CTOR));
if (!fun) {
return false;
}
// asm.js does not support jit entries.
fun->setWasmFuncIndex(funcIndex);
} else {
RootedAtom name(cx, NumberToAtom(cx, funcIndex));
if (!name) {
return false;
}
fun.set(NewNativeFunction(cx, WasmCall, numArgs, name,
gc::AllocKind::FUNCTION_EXTENDED, TenuredObject,
FunctionFlags::WASM));
if (!fun) {
return false;
}
// Some applications eagerly access all table elements which currently
// triggers worst-case behavior for lazy stubs, since each will allocate a
// separate 4kb code page. Most eagerly-accessed functions are not called,
// so use a shared, provisional (and slow) stub as JitEntry and wait until
// Instance::callExport() to create the fast entry stubs.
if (funcExport.canHaveJitEntry()) {
if (!funcExport.hasEagerStubs()) {
if (!EnsureBuiltinThunksInitialized()) {
return false;
}
void* provisionalJitEntryStub = ProvisionalJitEntryStub();
MOZ_ASSERT(provisionalJitEntryStub);
instance.code().setJitEntryIfNull(funcIndex, provisionalJitEntryStub);
}
fun->setWasmJitEntry(instance.code().getAddressOfJitEntry(funcIndex));
} else {
fun->setWasmFuncIndex(funcIndex);
}
}
fun->setExtendedSlot(FunctionExtended::WASM_INSTANCE_SLOT,
ObjectValue(*instanceObj));
void* tlsData = instanceObj->instance().tlsData();
fun->setExtendedSlot(FunctionExtended::WASM_TLSDATA_SLOT,
PrivateValue(tlsData));
if (!instanceObj->exports().putNew(funcIndex, fun)) {
ReportOutOfMemory(cx);
return false;
}
return true;
}
const CodeRange& WasmInstanceObject::getExportedFunctionCodeRange(
JSFunction* fun, Tier tier) {
uint32_t funcIndex = ExportedFunctionToFuncIndex(fun);
MOZ_ASSERT(exports().lookup(funcIndex)->value() == fun);
const MetadataTier& metadata = instance().metadata(tier);
return metadata.codeRange(metadata.lookupFuncExport(funcIndex));
}
/* static */
WasmInstanceScope* WasmInstanceObject::getScope(
JSContext* cx, HandleWasmInstanceObject instanceObj) {
if (!instanceObj->getReservedSlot(INSTANCE_SCOPE_SLOT).isUndefined()) {
return (WasmInstanceScope*)instanceObj->getReservedSlot(INSTANCE_SCOPE_SLOT)
.toGCThing();
}
Rooted<WasmInstanceScope*> instanceScope(
cx, WasmInstanceScope::create(cx, instanceObj));
if (!instanceScope) {
return nullptr;
}
instanceObj->setReservedSlot(INSTANCE_SCOPE_SLOT,
PrivateGCThingValue(instanceScope));
return instanceScope;
}
/* static */
WasmFunctionScope* WasmInstanceObject::getFunctionScope(
JSContext* cx, HandleWasmInstanceObject instanceObj, uint32_t funcIndex) {
if (auto p =
instanceObj->scopes().asWasmFunctionScopeMap().lookup(funcIndex)) {
return p->value();
}
Rooted<WasmInstanceScope*> instanceScope(
cx, WasmInstanceObject::getScope(cx, instanceObj));
if (!instanceScope) {
return nullptr;
}
Rooted<WasmFunctionScope*> funcScope(
cx, WasmFunctionScope::create(cx, instanceScope, funcIndex));
if (!funcScope) {
return nullptr;
}
if (!instanceObj->scopes().asWasmFunctionScopeMap().putNew(funcIndex,
funcScope)) {
ReportOutOfMemory(cx);
return nullptr;
}
return funcScope;
}
bool wasm::IsWasmExportedFunction(JSFunction* fun) {
return fun->kind() == FunctionFlags::Wasm;
}
Instance& wasm::ExportedFunctionToInstance(JSFunction* fun) {
return ExportedFunctionToInstanceObject(fun)->instance();
}
WasmInstanceObject* wasm::ExportedFunctionToInstanceObject(JSFunction* fun) {
MOZ_ASSERT(fun->kind() == FunctionFlags::Wasm ||
fun->kind() == FunctionFlags::AsmJS);
const Value& v = fun->getExtendedSlot(FunctionExtended::WASM_INSTANCE_SLOT);
return &v.toObject().as<WasmInstanceObject>();
}
uint32_t wasm::ExportedFunctionToFuncIndex(JSFunction* fun) {
Instance& instance = ExportedFunctionToInstanceObject(fun)->instance();
return instance.code().getFuncIndex(fun);
}
// ============================================================================
// WebAssembly.Memory class and methods
const JSClassOps WasmMemoryObject::classOps_ = {
nullptr, // addProperty
nullptr, // delProperty
nullptr, // enumerate
nullptr, // newEnumerate
nullptr, // resolve
nullptr, // mayResolve
WasmMemoryObject::finalize, // finalize
nullptr, // call
nullptr, // hasInstance
nullptr, // construct
nullptr, // trace
};
const JSClass WasmMemoryObject::class_ = {
"WebAssembly.Memory",
JSCLASS_DELAY_METADATA_BUILDER |
JSCLASS_HAS_RESERVED_SLOTS(WasmMemoryObject::RESERVED_SLOTS) |
JSCLASS_FOREGROUND_FINALIZE,
&WasmMemoryObject::classOps_, &WasmMemoryObject::classSpec_};
const JSClass& WasmMemoryObject::protoClass_ = PlainObject::class_;
static constexpr char WasmMemoryName[] = "Memory";
const ClassSpec WasmMemoryObject::classSpec_ = {
CreateWasmConstructor<WasmMemoryObject, WasmMemoryName>,
GenericCreatePrototype<WasmMemoryObject>,
WasmMemoryObject::static_methods,
nullptr,
WasmMemoryObject::methods,
WasmMemoryObject::properties,
nullptr,
ClassSpec::DontDefineConstructor};
/* static */
void WasmMemoryObject::finalize(JSFreeOp* fop, JSObject* obj) {
WasmMemoryObject& memory = obj->as<WasmMemoryObject>();
if (memory.hasObservers()) {
fop->delete_(obj, &memory.observers(), MemoryUse::WasmMemoryObservers);
}
}
/* static */
WasmMemoryObject* WasmMemoryObject::create(
JSContext* cx, HandleArrayBufferObjectMaybeShared buffer,
HandleObject proto) {
AutoSetNewObjectMetadata metadata(cx);
auto* obj = NewObjectWithGivenProto<WasmMemoryObject>(cx, proto);
if (!obj) {
return nullptr;
}
obj->initReservedSlot(BUFFER_SLOT, ObjectValue(*buffer));
MOZ_ASSERT(!obj->hasObservers());
return obj;
}
/* static */
bool WasmMemoryObject::construct(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
if (!ThrowIfNotConstructing(cx, args, "Memory")) {
return false;
}
if (!args.requireAtLeast(cx, "WebAssembly.Memory", 1)) {
return false;
}
if (!args.get(0).isObject()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_DESC_ARG, "memory");
return false;
}
RootedObject obj(cx, &args[0].toObject());
Limits limits;
if (!GetLimits(cx, obj, MaxMemory32LimitField, "Memory", &limits,
Shareable::True)) {
return false;
}
if (limits.initial > MaxMemory32Pages) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_MEM_IMP_LIMIT);
return false;
}
ConvertMemoryPagesToBytes(&limits);
RootedArrayBufferObjectMaybeShared buffer(cx);
if (!CreateWasmBuffer(cx, MemoryKind::Memory32, limits, &buffer)) {
return false;
}
RootedObject proto(cx);
if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_WasmMemory,
&proto)) {
return false;
}
if (!proto) {
proto = GlobalObject::getOrCreatePrototype(cx, JSProto_WasmMemory);
}
RootedWasmMemoryObject memoryObj(cx,
WasmMemoryObject::create(cx, buffer, proto));
if (!memoryObj) {
return false;
}
args.rval().setObject(*memoryObj);
return true;
}
static bool IsMemory(HandleValue v) {
return v.isObject() && v.toObject().is<WasmMemoryObject>();
}
/* static */
bool WasmMemoryObject::bufferGetterImpl(JSContext* cx, const CallArgs& args) {
RootedWasmMemoryObject memoryObj(
cx, &args.thisv().toObject().as<WasmMemoryObject>());
RootedArrayBufferObjectMaybeShared buffer(cx, &memoryObj->buffer());
if (memoryObj->isShared()) {
uint32_t memoryLength = memoryObj->volatileMemoryLength32();
MOZ_ASSERT(memoryLength >= ByteLength32(buffer));
if (memoryLength > ByteLength32(buffer)) {
RootedSharedArrayBufferObject newBuffer(
cx,
SharedArrayBufferObject::New(cx, memoryObj->sharedArrayRawBuffer(),
BufferSize(memoryLength)));
if (!newBuffer) {
return false;
}
// OK to addReference after we try to allocate because the memoryObj
// keeps the rawBuffer alive.
if (!memoryObj->sharedArrayRawBuffer()->addReference()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_SC_SAB_REFCNT_OFLO);
return false;
}
buffer = newBuffer;
memoryObj->setReservedSlot(BUFFER_SLOT, ObjectValue(*newBuffer));
}
}
args.rval().setObject(*buffer);
return true;
}
/* static */
bool WasmMemoryObject::bufferGetter(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsMemory, bufferGetterImpl>(cx, args);
}
const JSPropertySpec WasmMemoryObject::properties[] = {
JS_PSG("buffer", WasmMemoryObject::bufferGetter, JSPROP_ENUMERATE),
JS_STRING_SYM_PS(toStringTag, "WebAssembly.Memory", JSPROP_READONLY),
JS_PS_END};
/* static */
bool WasmMemoryObject::growImpl(JSContext* cx, const CallArgs& args) {
RootedWasmMemoryObject memory(
cx, &args.thisv().toObject().as<WasmMemoryObject>());
if (!args.requireAtLeast(cx, "WebAssembly.Memory.grow", 1)) {
return false;
}
uint32_t delta;
if (!EnforceRangeU32(cx, args.get(0), "Memory", "grow delta", &delta)) {
return false;
}
uint32_t ret = grow(memory, delta, cx);
if (ret == uint32_t(-1)) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_WASM_BAD_GROW,
"memory");
return false;
}
args.rval().setInt32(ret);
return true;
}
/* static */
bool WasmMemoryObject::grow(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsMemory, growImpl>(cx, args);
}
const JSFunctionSpec WasmMemoryObject::methods[] = {
#ifdef ENABLE_WASM_TYPE_REFLECTIONS
JS_FN("type", WasmMemoryObject::type, 0, JSPROP_ENUMERATE),
#endif
JS_FN("grow", WasmMemoryObject::grow, 1, JSPROP_ENUMERATE), JS_FS_END};
const JSFunctionSpec WasmMemoryObject::static_methods[] = {JS_FS_END};
ArrayBufferObjectMaybeShared& WasmMemoryObject::buffer() const {
return getReservedSlot(BUFFER_SLOT)
.toObject()
.as<ArrayBufferObjectMaybeShared>();
}
SharedArrayRawBuffer* WasmMemoryObject::sharedArrayRawBuffer() const {
MOZ_ASSERT(isShared());
return buffer().as<SharedArrayBufferObject>().rawBufferObject();
}
#ifdef ENABLE_WASM_TYPE_REFLECTIONS
bool WasmMemoryObject::typeImpl(JSContext* cx, const CallArgs& args) {
RootedWasmMemoryObject memoryObj(
cx, &args.thisv().toObject().as<WasmMemoryObject>());
Rooted<IdValueVector> props(cx, IdValueVector(cx));
Maybe<uint32_t> bufferMaxSize = memoryObj->buffer().wasmMaxSize();
if (bufferMaxSize.isSome()) {
uint32_t maximumPages = bufferMaxSize.value() / wasm::PageSize;
if (!props.append(IdValuePair(NameToId(cx->names().maximum),
Int32Value(maximumPages)))) {
return false;
}
}
uint32_t minimumPages = mozilla::AssertedCast<uint32_t>(
memoryObj->volatileMemoryLength32() / wasm::PageSize);
if (!props.append(IdValuePair(NameToId(cx->names().minimum),
Int32Value(minimumPages)))) {
return false;
}
if (!props.append(IdValuePair(NameToId(cx->names().shared),
BooleanValue(memoryObj->isShared())))) {
return false;
}
JSObject* memoryType = NewPlainObjectWithProperties(
cx, props.begin(), props.length(), GenericObject);
if (!memoryType) {
return false;
}
args.rval().setObject(*memoryType);
return true;
}
bool WasmMemoryObject::type(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsMemory, typeImpl>(cx, args);
}
#endif
uint32_t WasmMemoryObject::volatileMemoryLength32() const {
if (isShared()) {
return VolatileByteLength32(sharedArrayRawBuffer());
}
return ByteLength32(buffer());
}
bool WasmMemoryObject::isShared() const {
return buffer().is<SharedArrayBufferObject>();
}
bool WasmMemoryObject::hasObservers() const {
return !getReservedSlot(OBSERVERS_SLOT).isUndefined();
}
WasmMemoryObject::InstanceSet& WasmMemoryObject::observers() const {
MOZ_ASSERT(hasObservers());
return *reinterpret_cast<InstanceSet*>(
getReservedSlot(OBSERVERS_SLOT).toPrivate());
}
WasmMemoryObject::InstanceSet* WasmMemoryObject::getOrCreateObservers(
JSContext* cx) {
if (!hasObservers()) {
auto observers = MakeUnique<InstanceSet>(cx->zone(), cx->zone());
if (!observers) {
ReportOutOfMemory(cx);
return nullptr;
}
InitReservedSlot(this, OBSERVERS_SLOT, observers.release(),
MemoryUse::WasmMemoryObservers);
}
return &observers();
}
bool WasmMemoryObject::isHuge() const {
#ifdef WASM_SUPPORTS_HUGE_MEMORY
static_assert(MaxMemory32Bytes < HugeMappedSize,
"Non-huge buffer may be confused as huge");
return buffer().wasmMappedSize() >= HugeMappedSize;
#else
return false;
#endif
}
bool WasmMemoryObject::movingGrowable() const {
return !isHuge() && !buffer().wasmMaxSize();
}
uint32_t WasmMemoryObject::boundsCheckLimit32() const {
if (!buffer().isWasm() || isHuge()) {
return ByteLength32(buffer());
}
size_t mappedSize = buffer().wasmMappedSize();
MOZ_ASSERT(mappedSize <= UINT32_MAX);
MOZ_ASSERT(mappedSize >= wasm::GuardSize);
MOZ_ASSERT(wasm::IsValidBoundsCheckImmediate(mappedSize - wasm::GuardSize));
return mappedSize - wasm::GuardSize;
}
bool WasmMemoryObject::addMovingGrowObserver(JSContext* cx,
WasmInstanceObject* instance) {
MOZ_ASSERT(movingGrowable());
InstanceSet* observers = getOrCreateObservers(cx);
if (!observers) {
return false;
}
if (!observers->putNew(instance)) {
ReportOutOfMemory(cx);
return false;
}
return true;
}
/* static */
uint32_t WasmMemoryObject::growShared(HandleWasmMemoryObject memory,
uint32_t delta) {
SharedArrayRawBuffer* rawBuf = memory->sharedArrayRawBuffer();
SharedArrayRawBuffer::Lock lock(rawBuf);
MOZ_ASSERT(VolatileByteLength32(rawBuf) % PageSize == 0);
uint32_t oldNumPages = VolatileByteLength32(rawBuf) / PageSize;
CheckedInt<uint32_t> newSize = oldNumPages;
newSize += delta;
newSize *= PageSize;
if (!newSize.isValid()) {
return -1;
}
if (newSize.value() > rawBuf->maxSize()) {
return -1;
}
if (!rawBuf->wasmGrowToSizeInPlace(lock, BufferSize(newSize.value()))) {
return -1;
}
// New buffer objects will be created lazily in all agents (including in
// this agent) by bufferGetterImpl, above, so no more work to do here.
return oldNumPages;
}
/* static */
uint32_t WasmMemoryObject::grow(HandleWasmMemoryObject memory, uint32_t delta,
JSContext* cx) {
if (memory->isShared()) {
return growShared(memory, delta);
}
RootedArrayBufferObject oldBuf(cx, &memory->buffer().as<ArrayBufferObject>());
MOZ_ASSERT(ByteLength32(oldBuf) % PageSize == 0);
uint32_t oldNumPages = ByteLength32(oldBuf) / PageSize;
// FIXME (large ArrayBuffer): This does not allow 65536 pages, which is
// technically the max. That may be a webcompat problem. We can fix this
// once wasmMovingGrowToSize and wasmGrowToSizeInPlace accept size_t rather
// than uint32_t. See the FIXME in WasmConstants.h for additional
// information.
static_assert(MaxMemory32Pages <= UINT32_MAX / PageSize, "Avoid overflows");
CheckedInt<uint32_t> newSize = oldNumPages;
newSize += delta;
newSize *= PageSize;
if (!newSize.isValid()) {
return -1;
}
// Always check against the max here, do not rely on the buffer resizers to
// use the correct limit, they don't have enough context.
if (newSize.value() > MaxMemory32Pages * PageSize) {
return -1;
}
RootedArrayBufferObject newBuf(cx);
if (memory->movingGrowable()) {
MOZ_ASSERT(!memory->isHuge());
if (!ArrayBufferObject::wasmMovingGrowToSize(BufferSize(newSize.value()),
oldBuf, &newBuf, cx)) {
return -1;
}
} else {
if (Maybe<uint64_t> maxSize = oldBuf->wasmMaxSize()) {
if (newSize.value() > maxSize.value()) {
return -1;
}
}
if (!ArrayBufferObject::wasmGrowToSizeInPlace(BufferSize(newSize.value()),
oldBuf, &newBuf, cx)) {
return -1;
}
}
memory->setReservedSlot(BUFFER_SLOT, ObjectValue(*newBuf));
// Only notify moving-grow-observers after the BUFFER_SLOT has been updated
// since observers will call buffer().
if (memory->hasObservers()) {
for (InstanceSet::Range r = memory->observers().all(); !r.empty();
r.popFront()) {
r.front()->instance().onMovingGrowMemory();
}
}
return oldNumPages;
}
bool js::wasm::IsSharedWasmMemoryObject(JSObject* obj) {
WasmMemoryObject* mobj = obj->maybeUnwrapIf<WasmMemoryObject>();
return mobj && mobj->isShared();
}
// ============================================================================
// WebAssembly.Table class and methods
const JSClassOps WasmTableObject::classOps_ = {
nullptr, // addProperty
nullptr, // delProperty
nullptr, // enumerate
nullptr, // newEnumerate
nullptr, // resolve
nullptr, // mayResolve
WasmTableObject::finalize, // finalize
nullptr, // call
nullptr, // hasInstance
nullptr, // construct
WasmTableObject::trace, // trace
};
const JSClass WasmTableObject::class_ = {
"WebAssembly.Table",
JSCLASS_DELAY_METADATA_BUILDER |
JSCLASS_HAS_RESERVED_SLOTS(WasmTableObject::RESERVED_SLOTS) |
JSCLASS_FOREGROUND_FINALIZE,
&WasmTableObject::classOps_, &WasmTableObject::classSpec_};
const JSClass& WasmTableObject::protoClass_ = PlainObject::class_;
static constexpr char WasmTableName[] = "Table";
const ClassSpec WasmTableObject::classSpec_ = {
CreateWasmConstructor<WasmTableObject, WasmTableName>,
GenericCreatePrototype<WasmTableObject>,
WasmTableObject::static_methods,
nullptr,
WasmTableObject::methods,
WasmTableObject::properties,
nullptr,
ClassSpec::DontDefineConstructor};
bool WasmTableObject::isNewborn() const {
MOZ_ASSERT(is<WasmTableObject>());
return getReservedSlot(TABLE_SLOT).isUndefined();
}
/* static */
void WasmTableObject::finalize(JSFreeOp* fop, JSObject* obj) {
WasmTableObject& tableObj = obj->as<WasmTableObject>();
if (!tableObj.isNewborn()) {
auto& table = tableObj.table();
fop->release(obj, &table, table.gcMallocBytes(), MemoryUse::WasmTableTable);
}
}
/* static */
void WasmTableObject::trace(JSTracer* trc, JSObject* obj) {
WasmTableObject& tableObj = obj->as<WasmTableObject>();
if (!tableObj.isNewborn()) {
tableObj.table().tracePrivate(trc);
}
}
// Return the JS value to use when a parameter to a function requiring a table
// value is omitted. An implementation of [1].
//
// [1]
// https://webassembly.github.io/reference-types/js-api/index.html#defaultvalue
static Value TableDefaultValue(wasm::RefType tableType) {
return tableType.isExtern() ? UndefinedValue() : NullValue();
}
/* static */
WasmTableObject* WasmTableObject::create(JSContext* cx, uint32_t initialLength,
Maybe<uint32_t> maximumLength,
wasm::RefType tableType,
HandleObject proto) {
AutoSetNewObjectMetadata metadata(cx);
RootedWasmTableObject obj(
cx, NewObjectWithGivenProto<WasmTableObject>(cx, proto));
if (!obj) {
return nullptr;
}
MOZ_ASSERT(obj->isNewborn());
TableDesc td(tableType, initialLength, maximumLength, /*isAsmJS*/ false,
/*importedOrExported=*/true);
SharedTable table = Table::create(cx, td, obj);
if (!table) {
ReportOutOfMemory(cx);
return nullptr;
}
size_t size = table->gcMallocBytes();
InitReservedSlot(obj, TABLE_SLOT, table.forget().take(), size,
MemoryUse::WasmTableTable);
MOZ_ASSERT(!obj->isNewborn());
return obj;
}
/* static */
bool WasmTableObject::construct(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
if (!ThrowIfNotConstructing(cx, args, "Table")) {
return false;
}
if (!args.requireAtLeast(cx, "WebAssembly.Table", 1)) {
return false;
}
if (!args.get(0).isObject()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_DESC_ARG, "table");
return false;
}
RootedObject obj(cx, &args[0].toObject());
JSAtom* elementAtom = Atomize(cx, "element", strlen("element"));
if (!elementAtom) {
return false;
}
RootedId elementId(cx, AtomToId(elementAtom));
RootedValue elementVal(cx);
if (!GetProperty(cx, obj, obj, elementId, &elementVal)) {
return false;
}
RootedString elementStr(cx, ToString(cx, elementVal));
if (!elementStr) {
return false;
}
RootedLinearString elementLinearStr(cx, elementStr->ensureLinear(cx));
if (!elementLinearStr) {
return false;
}
RefType tableType;
if (StringEqualsLiteral(elementLinearStr, "anyfunc") ||
StringEqualsLiteral(elementLinearStr, "funcref")) {
tableType = RefType::func();
#ifdef ENABLE_WASM_REFTYPES
} else if (StringEqualsLiteral(elementLinearStr, "externref")) {
if (!ReftypesAvailable(cx)) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_ELEMENT);
return false;
}
tableType = RefType::extern_();
#endif
#ifdef ENABLE_WASM_GC
} else if (StringEqualsLiteral(elementLinearStr, "eqref")) {
if (!GcTypesAvailable(cx)) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_ELEMENT);
return false;
}
tableType = RefType::eq();
#endif
} else {
#ifdef ENABLE_WASM_REFTYPES
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_ELEMENT_GENERALIZED);
#else
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_ELEMENT);
#endif
return false;
}
Limits limits;
if (!GetLimits(cx, obj, MaxTableLimitField, "Table", &limits,
Shareable::False)) {
return false;
}
if (limits.initial > MaxTableLength) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_TABLE_IMP_LIMIT);
return false;
}
RootedObject proto(cx);
if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_WasmTable,
&proto)) {
return false;
}
if (!proto) {
proto = GlobalObject::getOrCreatePrototype(cx, JSProto_WasmTable);
}
// The rest of the runtime expects table limits to be within a 32-bit range.
static_assert(MaxTableLimitField <= UINT32_MAX, "invariant");
uint32_t initialLength = uint32_t(limits.initial);
Maybe<uint32_t> maximumLength;
if (limits.maximum) {
maximumLength = Some(uint32_t(*limits.maximum));
}
RootedWasmTableObject table(
cx, WasmTableObject::create(cx, initialLength, maximumLength, tableType,
proto));
if (!table) {
return false;
}
// Initialize the table to a default value
RootedValue initValue(
cx, args.length() < 2 ? TableDefaultValue(tableType) : args[1]);
// Skip initializing the table if the fill value is null, as that is the
// default value.
if (!initValue.isNull() &&
!table->fillRange(cx, 0, initialLength, initValue)) {
return false;
}
#ifdef DEBUG
// Assert that null is the default value of a new table.
if (initValue.isNull()) {
table->assertRangeNull(0, initialLength);
}
#endif
args.rval().setObject(*table);
return true;
}
static bool IsTable(HandleValue v) {
return v.isObject() && v.toObject().is<WasmTableObject>();
}
/* static */
bool WasmTableObject::lengthGetterImpl(JSContext* cx, const CallArgs& args) {
args.rval().setNumber(
args.thisv().toObject().as<WasmTableObject>().table().length());
return true;
}
/* static */
bool WasmTableObject::lengthGetter(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsTable, lengthGetterImpl>(cx, args);
}
const JSPropertySpec WasmTableObject::properties[] = {
JS_PSG("length", WasmTableObject::lengthGetter, JSPROP_ENUMERATE),
JS_STRING_SYM_PS(toStringTag, "WebAssembly.Table", JSPROP_READONLY),
JS_PS_END};
static bool ToTableIndex(JSContext* cx, HandleValue v, const Table& table,
const char* noun, uint32_t* index) {
if (!EnforceRangeU32(cx, v, "Table", noun, index)) {
return false;
}
if (*index >= table.length()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_RANGE, "Table", noun);
return false;
}
return true;
}
#ifdef ENABLE_WASM_TYPE_REFLECTIONS
/* static */
bool WasmTableObject::typeImpl(JSContext* cx, const CallArgs& args) {
Rooted<IdValueVector> props(cx, IdValueVector(cx));
Table& table = args.thisv().toObject().as<WasmTableObject>().table();
const char* elementValue;
switch (table.repr()) {
case TableRepr::Func:
elementValue = "funcref";
break;
case TableRepr::Ref:
elementValue = "externref";
break;
default:
MOZ_CRASH("Should not happen");
}
JSString* elementString = UTF8CharsToString(cx, elementValue);
if (!elementString) {
return false;
}
if (!props.append(IdValuePair(NameToId(cx->names().element),
StringValue(elementString)))) {
return false;
}
if (table.maximum().isSome()) {
if (!props.append(IdValuePair(NameToId(cx->names().maximum),
Int32Value(table.maximum().value())))) {
return false;
}
}
if (!props.append(IdValuePair(NameToId(cx->names().minimum),
Int32Value(table.length())))) {
return false;
}
JSObject* tableType = NewPlainObjectWithProperties(
cx, props.begin(), props.length(), GenericObject);
if (!tableType) {
return false;
}
args.rval().setObject(*tableType);
return true;
}
/* static */
bool WasmTableObject::type(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsTable, typeImpl>(cx, args);
}
#endif
/* static */
bool WasmTableObject::getImpl(JSContext* cx, const CallArgs& args) {
RootedWasmTableObject tableObj(
cx, &args.thisv().toObject().as<WasmTableObject>());
const Table& table = tableObj->table();
if (!args.requireAtLeast(cx, "WebAssembly.Table.get", 1)) {
return false;
}
uint32_t index;
if (!ToTableIndex(cx, args.get(0), table, "get index", &index)) {
return false;
}
switch (table.repr()) {
case TableRepr::Func: {
MOZ_RELEASE_ASSERT(!table.isAsmJS());
RootedFunction fun(cx);
if (!table.getFuncRef(cx, index, &fun)) {
return false;
}
args.rval().setObjectOrNull(fun);
break;
}
case TableRepr::Ref: {
args.rval().set(UnboxAnyRef(table.getAnyRef(index)));
break;
}
}
return true;
}
/* static */
bool WasmTableObject::get(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsTable, getImpl>(cx, args);
}
/* static */
bool WasmTableObject::setImpl(JSContext* cx, const CallArgs& args) {
RootedWasmTableObject tableObj(
cx, &args.thisv().toObject().as<WasmTableObject>());
Table& table = tableObj->table();
if (!args.requireAtLeast(cx, "WebAssembly.Table.set", 1)) {
return false;
}
uint32_t index;
if (!ToTableIndex(cx, args.get(0), table, "set index", &index)) {
return false;
}
RootedValue fillValue(
cx, args.length() < 2 ? TableDefaultValue(table.elemType()) : args[1]);
if (!tableObj->fillRange(cx, index, 1, fillValue)) {
return false;
}
args.rval().setUndefined();
return true;
}
/* static */
bool WasmTableObject::set(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsTable, setImpl>(cx, args);
}
/* static */
bool WasmTableObject::growImpl(JSContext* cx, const CallArgs& args) {
RootedWasmTableObject tableObj(
cx, &args.thisv().toObject().as<WasmTableObject>());
Table& table = tableObj->table();
if (!args.requireAtLeast(cx, "WebAssembly.Table.grow", 1)) {
return false;
}
uint32_t delta;
if (!EnforceRangeU32(cx, args.get(0), "Table", "grow delta", &delta)) {
return false;
}
uint32_t oldLength = table.grow(delta);
if (oldLength == uint32_t(-1)) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_WASM_BAD_GROW,
"table");
return false;
}
// Fill the grown range of the table
RootedValue fillValue(
cx, args.length() < 2 ? TableDefaultValue(table.elemType()) : args[1]);
// Skip filling the grown range of the table if the fill value is null, as
// that is the default value.
if (!fillValue.isNull() &&
!tableObj->fillRange(cx, oldLength, delta, fillValue)) {
return false;
}
#ifdef DEBUG
// Assert that null is the default value of the grown range.
if (fillValue.isNull()) {
tableObj->assertRangeNull(oldLength, delta);
}
#endif
args.rval().setInt32(oldLength);
return true;
}
/* static */
bool WasmTableObject::grow(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsTable, growImpl>(cx, args);
}
const JSFunctionSpec WasmTableObject::methods[] = {
#ifdef ENABLE_WASM_TYPE_REFLECTIONS
JS_FN("type", WasmTableObject::type, 0, JSPROP_ENUMERATE),
#endif
JS_FN("get", WasmTableObject::get, 1, JSPROP_ENUMERATE),
JS_FN("set", WasmTableObject::set, 2, JSPROP_ENUMERATE),
JS_FN("grow", WasmTableObject::grow, 1, JSPROP_ENUMERATE), JS_FS_END};
const JSFunctionSpec WasmTableObject::static_methods[] = {JS_FS_END};
Table& WasmTableObject::table() const {
return *(Table*)getReservedSlot(TABLE_SLOT).toPrivate();
}
bool WasmTableObject::fillRange(JSContext* cx, uint32_t index, uint32_t length,
HandleValue value) const {
Table& tab = table();
// All consumers are required to either bounds check or statically be in
// bounds
MOZ_ASSERT(uint64_t(index) + uint64_t(length) <= tab.length());
RootedFunction fun(cx);
RootedAnyRef any(cx, AnyRef::null());
if (!CheckRefType(cx, tab.elemType(), value, &fun, &any)) {
return false;
}
switch (tab.repr()) {
case TableRepr::Func:
MOZ_RELEASE_ASSERT(!tab.isAsmJS());
tab.fillFuncRef(index, length, FuncRef::fromJSFunction(fun), cx);
break;
case TableRepr::Ref:
tab.fillAnyRef(index, length, any);
break;
}
return true;
}
#ifdef DEBUG
void WasmTableObject::assertRangeNull(uint32_t index, uint32_t length) const {
Table& tab = table();
switch (tab.repr()) {
case TableRepr::Func:
for (uint32_t i = index; i < index + length; i++) {
MOZ_ASSERT(tab.getFuncRef(i).code == nullptr);
}
break;
case TableRepr::Ref:
for (uint32_t i = index; i < index + length; i++) {
MOZ_ASSERT(tab.getAnyRef(i).isNull());
}
break;
}
}
#endif
// ============================================================================
// WebAssembly.global class and methods
const JSClassOps WasmGlobalObject::classOps_ = {
nullptr, // addProperty
nullptr, // delProperty
nullptr, // enumerate
nullptr, // newEnumerate
nullptr, // resolve
nullptr, // mayResolve
WasmGlobalObject::finalize, // finalize
nullptr, // call
nullptr, // hasInstance
nullptr, // construct
WasmGlobalObject::trace, // trace
};
const JSClass WasmGlobalObject::class_ = {
"WebAssembly.Global",
JSCLASS_HAS_RESERVED_SLOTS(WasmGlobalObject::RESERVED_SLOTS) |
JSCLASS_BACKGROUND_FINALIZE,
&WasmGlobalObject::classOps_, &WasmGlobalObject::classSpec_};
const JSClass& WasmGlobalObject::protoClass_ = PlainObject::class_;
static constexpr char WasmGlobalName[] = "Global";
const ClassSpec WasmGlobalObject::classSpec_ = {
CreateWasmConstructor<WasmGlobalObject, WasmGlobalName>,
GenericCreatePrototype<WasmGlobalObject>,
WasmGlobalObject::static_methods,
nullptr,
WasmGlobalObject::methods,
WasmGlobalObject::properties,
nullptr,
ClassSpec::DontDefineConstructor};
/* static */
void WasmGlobalObject::trace(JSTracer* trc, JSObject* obj) {
WasmGlobalObject* global = reinterpret_cast<WasmGlobalObject*>(obj);
if (global->isNewborn()) {
// This can happen while we're allocating the object, in which case
// every single slot of the object is not defined yet. In particular,
// there's nothing to trace yet.
return;
}
global->val().get().trace(trc);
}
/* static */
void WasmGlobalObject::finalize(JSFreeOp* fop, JSObject* obj) {
WasmGlobalObject* global = reinterpret_cast<WasmGlobalObject*>(obj);
if (!global->isNewborn()) {
fop->delete_(obj, &global->val(), MemoryUse::WasmGlobalCell);
}
}
/* static */
WasmGlobalObject* WasmGlobalObject::create(JSContext* cx, HandleVal hval,
bool isMutable, HandleObject proto) {
AutoSetNewObjectMetadata metadata(cx);
RootedWasmGlobalObject obj(
cx, NewObjectWithGivenProto<WasmGlobalObject>(cx, proto));
if (!obj) {
return nullptr;
}
MOZ_ASSERT(obj->isNewborn());
MOZ_ASSERT(obj->isTenured(), "assumed by global.set post barriers");
GCPtrVal* val = js_new<GCPtrVal>(Val(hval.get().type()));
if (!val) {
ReportOutOfMemory(cx);
return nullptr;
}
obj->initReservedSlot(MUTABLE_SLOT, JS::BooleanValue(isMutable));
InitReservedSlot(obj, VAL_SLOT, val, MemoryUse::WasmGlobalCell);
// It's simpler to initialize the cell after the object has been created,
// to avoid needing to root the cell before the object creation.
obj->val() = hval.get();
MOZ_ASSERT(!obj->isNewborn());
return obj;
}
/* static */
bool WasmGlobalObject::construct(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
if (!ThrowIfNotConstructing(cx, args, "Global")) {
return false;
}
if (!args.requireAtLeast(cx, "WebAssembly.Global", 1)) {
return false;
}
if (!args.get(0).isObject()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_DESC_ARG, "global");
return false;
}
RootedObject obj(cx, &args[0].toObject());
// Extract properties in lexicographic order per spec.
RootedValue mutableVal(cx);
if (!JS_GetProperty(cx, obj, "mutable", &mutableVal)) {
return false;
}
RootedValue typeVal(cx);
if (!JS_GetProperty(cx, obj, "value", &typeVal)) {
return false;
}
RootedString typeStr(cx, ToString(cx, typeVal));
if (!typeStr) {
return false;
}
RootedLinearString typeLinearStr(cx, typeStr->ensureLinear(cx));
if (!typeLinearStr) {
return false;
}
ValType globalType;
if (StringEqualsLiteral(typeLinearStr, "i32")) {
globalType = ValType::I32;
} else if (StringEqualsLiteral(typeLinearStr, "i64")) {
globalType = ValType::I64;
} else if (StringEqualsLiteral(typeLinearStr, "f32")) {
globalType = ValType::F32;
} else if (StringEqualsLiteral(typeLinearStr, "f64")) {
globalType = ValType::F64;
#ifdef ENABLE_WASM_SIMD
} else if (SimdAvailable(cx) && StringEqualsLiteral(typeLinearStr, "v128")) {
globalType = ValType::V128;
#endif
#ifdef ENABLE_WASM_REFTYPES
} else if (ReftypesAvailable(cx) &&
StringEqualsLiteral(typeLinearStr, "funcref")) {
globalType = RefType::func();
} else if (ReftypesAvailable(cx) &&
StringEqualsLiteral(typeLinearStr, "externref")) {
globalType = RefType::extern_();
#endif
#ifdef ENABLE_WASM_GC
} else if (GcTypesAvailable(cx) &&
StringEqualsLiteral(typeLinearStr, "eqref")) {
globalType = RefType::eq();
#endif
} else {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_GLOBAL_TYPE);
return false;
}
bool isMutable = ToBoolean(mutableVal);
// Extract the initial value, or provide a suitable default.
RootedVal globalVal(cx, globalType);
// Override with non-undefined value, if provided.
RootedValue valueVal(cx, args.get(1));
if (!valueVal.isUndefined() ||
(args.length() >= 2 && globalType.isReference())) {
if (!Val::fromJSValue(cx, globalType, valueVal, &globalVal)) {
return false;
}
}
RootedObject proto(cx);
if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_WasmGlobal,
&proto)) {
return false;
}
if (!proto) {
proto = GlobalObject::getOrCreatePrototype(cx, JSProto_WasmGlobal);
}
WasmGlobalObject* global =
WasmGlobalObject::create(cx, globalVal, isMutable, proto);
if (!global) {
return false;
}
args.rval().setObject(*global);
return true;
}
static bool IsGlobal(HandleValue v) {
return v.isObject() && v.toObject().is<WasmGlobalObject>();
}
/* static */
bool WasmGlobalObject::valueGetterImpl(JSContext* cx, const CallArgs& args) {
const WasmGlobalObject& globalObj =
args.thisv().toObject().as<WasmGlobalObject>();
if (!globalObj.type().isExposable()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_VAL_TYPE);
return false;
}
return globalObj.val().get().toJSValue(cx, args.rval());
}
/* static */
bool WasmGlobalObject::valueGetter(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsGlobal, valueGetterImpl>(cx, args);
}
/* static */
bool WasmGlobalObject::valueSetterImpl(JSContext* cx, const CallArgs& args) {
if (!args.requireAtLeast(cx, "WebAssembly.Global setter", 1)) {
return false;
}
RootedWasmGlobalObject global(
cx, &args.thisv().toObject().as<WasmGlobalObject>());
if (!global->isMutable()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_GLOBAL_IMMUTABLE);
return false;
}
RootedVal val(cx);
if (!Val::fromJSValue(cx, global->type(), args.get(0), &val)) {
return false;
}
global->val() = val.get();
args.rval().setUndefined();
return true;
}
/* static */
bool WasmGlobalObject::valueSetter(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsGlobal, valueSetterImpl>(cx, args);
}
const JSPropertySpec WasmGlobalObject::properties[] = {
JS_PSGS("value", WasmGlobalObject::valueGetter,
WasmGlobalObject::valueSetter, JSPROP_ENUMERATE),
JS_STRING_SYM_PS(toStringTag, "WebAssembly.Global", JSPROP_READONLY),
JS_PS_END};
const JSFunctionSpec WasmGlobalObject::methods[] = {
#ifdef ENABLE_WASM_TYPE_REFLECTIONS
JS_FN("type", WasmGlobalObject::type, 0, JSPROP_ENUMERATE),
#endif
JS_FN(js_valueOf_str, WasmGlobalObject::valueGetter, 0, JSPROP_ENUMERATE),
JS_FS_END};
const JSFunctionSpec WasmGlobalObject::static_methods[] = {JS_FS_END};
bool WasmGlobalObject::isMutable() const {
return getReservedSlot(MUTABLE_SLOT).toBoolean();
}
ValType WasmGlobalObject::type() const { return val().get().type(); }
GCPtrVal& WasmGlobalObject::val() const {
return *reinterpret_cast<GCPtrVal*>(getReservedSlot(VAL_SLOT).toPrivate());
}
#ifdef ENABLE_WASM_TYPE_REFLECTIONS
/* static */
bool WasmGlobalObject::typeImpl(JSContext* cx, const CallArgs& args) {
RootedWasmGlobalObject global(
cx, &args.thisv().toObject().as<WasmGlobalObject>());
Rooted<IdValueVector> props(cx, IdValueVector(cx));
if (!props.append(IdValuePair(NameToId(cx->names().mutable_),
BooleanValue(global->isMutable())))) {
return false;
}
JSString* valueType = UTF8CharsToString(cx, ToString(global->type()).get());
if (!valueType) {
return false;
}
if (!props.append(
IdValuePair(NameToId(cx->names().value), StringValue(valueType)))) {
return false;
}
JSObject* globalType = NewPlainObjectWithProperties(
cx, props.begin(), props.length(), GenericObject);
if (!globalType) {
return false;
}
args.rval().setObject(*globalType);
return true;
}
/* static */
bool WasmGlobalObject::type(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsGlobal, typeImpl>(cx, args);
}
#endif
// ============================================================================
// WebAssembly.Exception class and methods
const JSClassOps WasmExceptionObject::classOps_ = {
nullptr, // addProperty
nullptr, // delProperty
nullptr, // enumerate
nullptr, // newEnumerate
nullptr, // resolve
nullptr, // mayResolve
WasmExceptionObject::finalize, // finalize
nullptr, // call
nullptr, // hasInstance
nullptr, // construct
nullptr, // trace
};
const JSClass WasmExceptionObject::class_ = {
"WebAssembly.Exception",
JSCLASS_HAS_RESERVED_SLOTS(WasmExceptionObject::RESERVED_SLOTS) |
JSCLASS_FOREGROUND_FINALIZE,
&WasmExceptionObject::classOps_, &WasmExceptionObject::classSpec_};
const JSClass& WasmExceptionObject::protoClass_ = PlainObject::class_;
static constexpr char WasmExceptionName[] = "Exception";
const ClassSpec WasmExceptionObject::classSpec_ = {
CreateWasmConstructor<WasmExceptionObject, WasmExceptionName>,
GenericCreatePrototype<WasmExceptionObject>,
WasmExceptionObject::static_methods,
nullptr,
WasmExceptionObject::methods,
WasmExceptionObject::properties,
nullptr,
ClassSpec::DontDefineConstructor};
/* static */
void WasmExceptionObject::finalize(JSFreeOp* fop, JSObject* obj) {
WasmExceptionObject& exnObj = obj->as<WasmExceptionObject>();
if (!exnObj.isNewborn()) {
fop->release(obj, &exnObj.tag(), MemoryUse::WasmExceptionTag);
fop->delete_(obj, &exnObj.valueTypes(), MemoryUse::WasmExceptionType);
}
}
bool WasmExceptionObject::construct(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
if (!ThrowIfNotConstructing(cx, args, "Exception")) {
return false;
}
// FIXME: The JS API is not finalized and may specify a different behavior
// here.
// For now, we implement the same behavior as V8 and error when called.
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_EXN_CONSTRUCTOR);
return false;
}
/* static */
WasmExceptionObject* WasmExceptionObject::create(JSContext* cx,
const ValTypeVector& type,
HandleObject proto) {
AutoSetNewObjectMetadata metadata(cx);
RootedWasmExceptionObject obj(
cx, NewObjectWithGivenProto<WasmExceptionObject>(cx, proto));
if (!obj) {
return nullptr;
}
MOZ_ASSERT(obj->isNewborn());
SharedExceptionTag tag = SharedExceptionTag(cx->new_<ExceptionTag>());
if (!tag) {
ReportOutOfMemory(cx);
return nullptr;
}
InitReservedSlot(obj, TAG_SLOT, tag.forget().take(),
MemoryUse::WasmExceptionTag);
wasm::ValTypeVector* newValueTypes = js_new<ValTypeVector>();
for (uint32_t i = 0; i < type.length(); i++) {
if (!newValueTypes->append(type[i])) {
return nullptr;
}
}
InitReservedSlot(obj, TYPE_SLOT, newValueTypes, MemoryUse::WasmExceptionType);
MOZ_ASSERT(!obj->isNewborn());
return obj;
}
bool WasmExceptionObject::isNewborn() const {
MOZ_ASSERT(is<WasmExceptionObject>());
return getReservedSlot(TYPE_SLOT).isUndefined();
}
const JSPropertySpec WasmExceptionObject::properties[] = {
JS_STRING_SYM_PS(toStringTag, "WebAssembly.Exception", JSPROP_READONLY),
JS_PS_END};
const JSFunctionSpec WasmExceptionObject::methods[] = {JS_FS_END};
const JSFunctionSpec WasmExceptionObject::static_methods[] = {JS_FS_END};
wasm::ValTypeVector& WasmExceptionObject::valueTypes() const {
return *(ValTypeVector*)getFixedSlot(TYPE_SLOT).toPrivate();
};
wasm::ResultType WasmExceptionObject::resultType() const {
return wasm::ResultType::Vector(valueTypes());
}
ExceptionTag& WasmExceptionObject::tag() const {
return *(ExceptionTag*)getReservedSlot(TAG_SLOT).toPrivate();
}
// ============================================================================
// WebAssembly class and static methods
static bool WebAssembly_toSource(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
args.rval().setString(cx->names().WebAssembly);
return true;
}
static bool RejectWithPendingException(JSContext* cx,
Handle<PromiseObject*> promise) {
if (!cx->isExceptionPending()) {
return false;
}
RootedValue rejectionValue(cx);
if (!GetAndClearException(cx, &rejectionValue)) {
return false;
}
return PromiseObject::reject(cx, promise, rejectionValue);
}
static bool Reject(JSContext* cx, const CompileArgs& args,
Handle<PromiseObject*> promise, const UniqueChars& error) {
if (!error) {
ReportOutOfMemory(cx);
return RejectWithPendingException(cx, promise);
}
RootedObject stack(cx, promise->allocationSite());
RootedString filename(
cx, JS_NewStringCopyZ(cx, args.scriptedCaller.filename.get()));
if (!filename) {
return false;
}
unsigned line = args.scriptedCaller.line;
// Ideally we'd report a JSMSG_WASM_COMPILE_ERROR here, but there's no easy
// way to create an ErrorObject for an arbitrary error code with multiple
// replacements.
UniqueChars str(JS_smprintf("wasm validation error: %s", error.get()));
if (!str) {
return false;
}
size_t len = strlen(str.get());
RootedString message(cx, NewStringCopyN<CanGC>(cx, str.get(), len));
if (!message) {
return false;
}
RootedObject errorObj(
cx, ErrorObject::create(cx, JSEXN_WASMCOMPILEERROR, stack, filename, 0,
line, 0, nullptr, message));
if (!errorObj) {
return false;
}
RootedValue rejectionValue(cx, ObjectValue(*errorObj));
return PromiseObject::reject(cx, promise, rejectionValue);
}
static void LogAsync(JSContext* cx, const char* funcName,
const Module& module) {
Log(cx, "async %s succeeded%s", funcName,
module.loggingDeserialized() ? " (loaded from cache)" : "");
}
enum class Ret { Pair, Instance };
class AsyncInstantiateTask : public OffThreadPromiseTask {
SharedModule module_;
PersistentRooted<ImportValues> imports_;
Ret ret_;
public:
AsyncInstantiateTask(JSContext* cx, const Module& module, Ret ret,
Handle<PromiseObject*> promise)
: OffThreadPromiseTask(cx, promise),
module_(&module),
imports_(cx),
ret_(ret) {}
ImportValues& imports() { return imports_.get(); }
bool resolve(JSContext* cx, Handle<PromiseObject*> promise) override {
RootedObject instanceProto(
cx, &cx->global()->getPrototype(JSProto_WasmInstance).toObject());
RootedWasmInstanceObject instanceObj(cx);
if (!module_->instantiate(cx, imports_.get(), instanceProto,
&instanceObj)) {
return RejectWithPendingException(cx, promise);
}
RootedValue resolutionValue(cx);
if (ret_ == Ret::Instance) {
resolutionValue = ObjectValue(*instanceObj);
} else {
RootedObject resultObj(cx, JS_NewPlainObject(cx));
if (!resultObj) {
return RejectWithPendingException(cx, promise);
}
RootedObject moduleProto(
cx, &cx->global()->getPrototype(JSProto_WasmModule).toObject());
RootedObject moduleObj(
cx, WasmModuleObject::create(cx, *module_, moduleProto));
if (!moduleObj) {
return RejectWithPendingException(cx, promise);
}
RootedValue val(cx, ObjectValue(*moduleObj));
if (!JS_DefineProperty(cx, resultObj, "module", val, JSPROP_ENUMERATE)) {
return RejectWithPendingException(cx, promise);
}
val = ObjectValue(*instanceObj);
if (!JS_DefineProperty(cx, resultObj, "instance", val,
JSPROP_ENUMERATE)) {
return RejectWithPendingException(cx, promise);
}
resolutionValue = ObjectValue(*resultObj);
}
if (!PromiseObject::resolve(cx, promise, resolutionValue)) {
return RejectWithPendingException(cx, promise);
}
LogAsync(cx, "instantiate", *module_);
return true;
}
};
static bool AsyncInstantiate(JSContext* cx, const Module& module,
HandleObject importObj, Ret ret,
Handle<PromiseObject*> promise) {
auto task = js::MakeUnique<AsyncInstantiateTask>(cx, module, ret, promise);
if (!task || !task->init(cx)) {
return false;
}
if (!GetImports(cx, module, importObj, &task->imports())) {
return RejectWithPendingException(cx, promise);
}
task.release()->dispatchResolveAndDestroy();
return true;
}
static bool ResolveCompile(JSContext* cx, const Module& module,
Handle<PromiseObject*> promise) {
RootedObject proto(
cx, &cx->global()->getPrototype(JSProto_WasmModule).toObject());
RootedObject moduleObj(cx, WasmModuleObject::create(cx, module, proto));
if (!moduleObj) {
return RejectWithPendingException(cx, promise);
}
RootedValue resolutionValue(cx, ObjectValue(*moduleObj));
if (!PromiseObject::resolve(cx, promise, resolutionValue)) {
return RejectWithPendingException(cx, promise);
}
LogAsync(cx, "compile", module);
return true;
}
struct CompileBufferTask : PromiseHelperTask {
MutableBytes bytecode;
SharedCompileArgs compileArgs;
UniqueChars error;
UniqueCharsVector warnings;
SharedModule module;
bool instantiate;
PersistentRootedObject importObj;
JSTelemetrySender sender;
CompileBufferTask(JSContext* cx, Handle<PromiseObject*> promise,
HandleObject importObj)
: PromiseHelperTask(cx, promise),
instantiate(true),
importObj(cx, importObj),
sender(cx->runtime()) {}
CompileBufferTask(JSContext* cx, Handle<PromiseObject*> promise)
: PromiseHelperTask(cx, promise), instantiate(false) {}
bool init(JSContext* cx, const char* introducer) {
compileArgs = InitCompileArgs(cx, introducer);
if (!compileArgs) {
return false;
}
return PromiseHelperTask::init(cx);
}
void execute() override {
module = CompileBuffer(*compileArgs, *bytecode, &error, &warnings, nullptr,
sender);
}
bool resolve(JSContext* cx, Handle<PromiseObject*> promise) override {
if (!module) {
return Reject(cx, *compileArgs, promise, error);
}
if (!ReportCompileWarnings(cx, warnings)) {
return false;
}
if (instantiate) {
return AsyncInstantiate(cx, *module, importObj, Ret::Pair, promise);
}
return ResolveCompile(cx, *module, promise);
}
};
static bool RejectWithPendingException(JSContext* cx,
Handle<PromiseObject*> promise,
CallArgs& callArgs) {
if (!RejectWithPendingException(cx, promise)) {
return false;
}
callArgs.rval().setObject(*promise);
return true;
}
static bool EnsurePromiseSupport(JSContext* cx) {
if (!cx->runtime()->offThreadPromiseState.ref().initialized()) {
JS_ReportErrorASCII(
cx, "WebAssembly Promise APIs not supported in this runtime.");
return false;
}
return true;
}
static bool GetBufferSource(JSContext* cx, CallArgs callArgs, const char* name,
MutableBytes* bytecode) {
if (!callArgs.requireAtLeast(cx, name, 1)) {
return false;
}
if (!callArgs[0].isObject()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_BUF_ARG);
return false;
}
return GetBufferSource(cx, &callArgs[0].toObject(), JSMSG_WASM_BAD_BUF_ARG,
bytecode);
}
static bool WebAssembly_compile(JSContext* cx, unsigned argc, Value* vp) {
if (!EnsurePromiseSupport(cx)) {
return false;
}
Log(cx, "async compile() started");
Rooted<PromiseObject*> promise(cx, PromiseObject::createSkippingExecutor(cx));
if (!promise) {
return false;
}
auto task = cx->make_unique<CompileBufferTask>(cx, promise);
if (!task || !task->init(cx, "WebAssembly.compile")) {
return false;
}
CallArgs callArgs = CallArgsFromVp(argc, vp);
if (!GetBufferSource(cx, callArgs, "WebAssembly.compile", &task->bytecode)) {
return RejectWithPendingException(cx, promise, callArgs);
}
if (!StartOffThreadPromiseHelperTask(cx, std::move(task))) {
return false;
}
callArgs.rval().setObject(*promise);
return true;
}
static bool GetInstantiateArgs(JSContext* cx, CallArgs callArgs,
MutableHandleObject firstArg,
MutableHandleObject importObj) {
if (!callArgs.requireAtLeast(cx, "WebAssembly.instantiate", 1)) {
return false;
}
if (!callArgs[0].isObject()) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_WASM_BAD_BUF_MOD_ARG);
return false;
}
firstArg.set(&callArgs[0].toObject());
return GetImportArg(cx, callArgs, importObj);
}
static bool WebAssembly_instantiate(JSContext* cx, unsigned argc, Value* vp) {
if (!EnsurePromiseSupport(cx)) {
return false;
}
Log(cx, "async instantiate() started");
Rooted<PromiseObject*> promise(cx, PromiseObject::createSkippingExecutor(cx));
if (!promise) {
return false;
}
CallArgs callArgs = CallArgsFromVp(argc, vp);
RootedObject firstArg(cx);
RootedObject importObj(cx);
if (!GetInstantiateArgs(cx, callArgs, &firstArg, &importObj)) {
return RejectWithPendingException(cx, promise, callArgs);
}
const Module* module;
if (IsModuleObject(firstArg, &module)) {
if (!AsyncInstantiate(cx, *module, importObj, Ret::Instance, promise)) {
return false;
}
} else {
auto task = cx->make_unique<CompileBufferTask>(cx, promise, importObj);
if (!task || !task->init(cx, "WebAssembly.instantiate")) {
return false;
}
if (!GetBufferSource(cx, firstArg, JSMSG_WASM_BAD_BUF_MOD_ARG,
&task->bytecode)) {
return RejectWithPendingException(cx, promise, callArgs);
}
if (!StartOffThreadPromiseHelperTask(cx, std::move(task))) {
return false;
}
}
callArgs.rval().setObject(*promise);
return true;
}
static bool WebAssembly_validate(JSContext* cx, unsigned argc, Value* vp) {
CallArgs callArgs = CallArgsFromVp(argc, vp);
MutableBytes bytecode;
if (!GetBufferSource(cx, callArgs, "WebAssembly.validate", &bytecode)) {
return false;
}
UniqueChars error;
bool validated = Validate(cx, *bytecode, &error);
// If the reason for validation failure was OOM (signalled by null error
// message), report out-of-memory so that validate's return is always
// correct.
if (!validated && !error) {
ReportOutOfMemory(cx);
return false;
}
if (error) {
MOZ_ASSERT(!validated);
Log(cx, "validate() failed with: %s", error.get());
}
callArgs.rval().setBoolean(validated);
return true;
}
static bool EnsureStreamSupport(JSContext* cx) {
// This should match wasm::StreamingCompilationAvailable().
if (!EnsurePromiseSupport(cx)) {
return false;
}
if (!CanUseExtraThreads()) {
JS_ReportErrorASCII(
cx, "WebAssembly.compileStreaming not supported with --no-threads");
return false;
}
if (!cx->runtime()->consumeStreamCallback) {
JS_ReportErrorASCII(cx,
"WebAssembly streaming not supported in this runtime");
return false;
}
return true;
}
// This value is chosen and asserted to be disjoint from any host error code.
static const size_t StreamOOMCode = 0;
static bool RejectWithStreamErrorNumber(JSContext* cx, size_t errorCode,
Handle<PromiseObject*> promise) {
if (errorCode == StreamOOMCode) {
ReportOutOfMemory(cx);
return false;
}
cx->runtime()->reportStreamErrorCallback(cx, errorCode);
return RejectWithPendingException(cx, promise);
}
class CompileStreamTask : public PromiseHelperTask, public JS::StreamConsumer {
// The stream progresses monotonically through these states; the helper
// thread wait()s for streamState_ to reach Closed.
enum StreamState { Env, Code, Tail, Closed };
ExclusiveWaitableData<StreamState> streamState_;
// Immutable:
const bool instantiate_;
const PersistentRootedObject importObj_;
// Immutable after noteResponseURLs() which is called at most once before
// first call on stream thread:
const MutableCompileArgs compileArgs_;
// Immutable after Env state:
Bytes envBytes_;
SectionRange codeSection_;
// The code section vector is resized once during the Env state and filled
// in chunk by chunk during the Code state, updating the end-pointer after
// each chunk:
Bytes codeBytes_;
uint8_t* codeBytesEnd_;
ExclusiveBytesPtr exclusiveCodeBytesEnd_;
// Immutable after Tail state:
Bytes tailBytes_;
ExclusiveStreamEndData exclusiveStreamEnd_;
// Written once before Closed state and read in Closed state on main thread:
SharedModule module_;
Maybe<size_t> streamError_;
UniqueChars compileError_;
UniqueCharsVector warnings_;
// Set on stream thread and read racily on helper thread to abort compilation:
Atomic<bool> streamFailed_;
JSTelemetrySender sender_;
// Called on some thread before consumeChunk(), streamEnd(), streamError()):
void noteResponseURLs(const char* url, const char* sourceMapUrl) override {
if (url) {
compileArgs_->scriptedCaller.filename = DuplicateString(url);
compileArgs_->scriptedCaller.filenameIsURL = true;
}
if (sourceMapUrl) {
compileArgs_->sourceMapURL = DuplicateString(sourceMapUrl);
}
}
// Called on a stream thread:
// Until StartOffThreadPromiseHelperTask succeeds, we are responsible for
// dispatching ourselves back to the JS thread.
//
// Warning: After this function returns, 'this' can be deleted at any time, so
// the caller must immediately return from the stream callback.
void setClosedAndDestroyBeforeHelperThreadStarted() {
streamState_.lock().get() = Closed;
dispatchResolveAndDestroy();
}
// See setClosedAndDestroyBeforeHelperThreadStarted() comment.
bool rejectAndDestroyBeforeHelperThreadStarted(size_t errorNumber) {
MOZ_ASSERT(streamState_.lock() == Env);
MOZ_ASSERT(!streamError_);
streamError_ = Some(errorNumber);
setClosedAndDestroyBeforeHelperThreadStarted();
return false;
}
// Once StartOffThreadPromiseHelperTask succeeds, the helper thread will
// dispatchResolveAndDestroy() after execute() returns, but execute()
// wait()s for state to be Closed.
//
// Warning: After this function returns, 'this' can be deleted at any time, so
// the caller must immediately return from the stream callback.
void setClosedAndDestroyAfterHelperThreadStarted() {
auto streamState = streamState_.lock();
MOZ_ASSERT(streamState != Closed);
streamState.get() = Closed;
streamState.notify_one(/* stream closed */);
}
// See setClosedAndDestroyAfterHelperThreadStarted() comment.
bool rejectAndDestroyAfterHelperThreadStarted(size_t errorNumber) {
MOZ_ASSERT(!streamError_);
streamError_ = Some(errorNumber);
streamFailed_ = true;
exclusiveCodeBytesEnd_.lock().notify_one();
exclusiveStreamEnd_.lock().notify_one();
setClosedAndDestroyAfterHelperThreadStarted();
return false;
}
bool consumeChunk(const uint8_t* begin, size_t length) override {
switch (streamState_.lock().get()) {
case Env: {
if (!envBytes_.append(begin, length)) {
return rejectAndDestroyBeforeHelperThreadStarted(StreamOOMCode);
}
if (!StartsCodeSection(envBytes_.begin(), envBytes_.end(),
&codeSection_)) {
return true;
}
uint32_t extraBytes = envBytes_.length() - codeSection_.start;
if (extraBytes) {
envBytes_.shrinkTo(codeSection_.start);
}
if (codeSection_.size > MaxCodeSectionBytes) {
return rejectAndDestroyBeforeHelperThreadStarted(StreamOOMCode);
}
if (!codeBytes_.resize(codeSection_.size)) {
return rejectAndDestroyBeforeHelperThreadStarted(StreamOOMCode);
}
codeBytesEnd_ = codeBytes_.begin();
exclusiveCodeBytesEnd_.lock().get() = codeBytesEnd_;
if (!StartOffThreadPromiseHelperTask(this)) {
return rejectAndDestroyBeforeHelperThreadStarted(StreamOOMCode);
}
// Set the state to Code iff StartOffThreadPromiseHelperTask()
// succeeds so that the state tells us whether we are before or
// after the helper thread started.
streamState_.lock().get() = Code;
if (extraBytes) {
return consumeChunk(begin + length - extraBytes, extraBytes);
}
return true;
}
case Code: {
size_t copyLength =
std::min<size_t>(length, codeBytes_.end() - codeBytesEnd_);
memcpy(codeBytesEnd_, begin, copyLength);
codeBytesEnd_ += copyLength;
{
auto codeStreamEnd = exclusiveCodeBytesEnd_.lock();
codeStreamEnd.get() = codeBytesEnd_;
codeStreamEnd.notify_one();
}
if (codeBytesEnd_ != codeBytes_.end()) {
return true;
}
streamState_.lock().get() = Tail;
if (uint32_t extraBytes = length - copyLength) {
return consumeChunk(begin + copyLength, extraBytes);
}
return true;
}
case Tail: {
if (!tailBytes_.append(begin, length)) {
return rejectAndDestroyAfterHelperThreadStarted(StreamOOMCode);
}
return true;
}
case Closed:
MOZ_CRASH("consumeChunk() in Closed state");
}
MOZ_CRASH("unreachable");
}
void streamEnd(JS::OptimizedEncodingListener* tier2Listener) override {
switch (streamState_.lock().get()) {
case Env: {
SharedBytes bytecode = js_new<ShareableBytes>(std::move(envBytes_));
if (!bytecode) {
rejectAndDestroyBeforeHelperThreadStarted(StreamOOMCode);
return;
}
module_ = CompileBuffer(*compileArgs_, *bytecode, &compileError_,
&warnings_, nullptr, sender_);
setClosedAndDestroyBeforeHelperThreadStarted();
return;
}
case Code:
case Tail:
// Unlock exclusiveStreamEnd_ before locking streamState_.
{
auto streamEnd = exclusiveStreamEnd_.lock();
MOZ_ASSERT(!streamEnd->reached);
streamEnd->reached = true;
streamEnd->tailBytes = &tailBytes_;
streamEnd->tier2Listener = tier2Listener;
streamEnd.notify_one();
}
setClosedAndDestroyAfterHelperThreadStarted();
return;
case Closed:
MOZ_CRASH("streamEnd() in Closed state");
}
}
void streamError(size_t errorCode) override {
MOZ_ASSERT(errorCode != StreamOOMCode);
switch (streamState_.lock().get()) {
case Env:
rejectAndDestroyBeforeHelperThreadStarted(errorCode);
return;
case Tail:
case Code:
rejectAndDestroyAfterHelperThreadStarted(errorCode);
return;
case Closed:
MOZ_CRASH("streamError() in Closed state");
}
}
void consumeOptimizedEncoding(const uint8_t* begin, size_t length) override {
module_ = Module::deserialize(begin, length);
MOZ_ASSERT(streamState_.lock().get() == Env);
setClosedAndDestroyBeforeHelperThreadStarted();
}
// Called on a helper thread:
void execute() override {
module_ =
CompileStreaming(*compileArgs_, envBytes_, codeBytes_,
exclusiveCodeBytesEnd_, exclusiveStreamEnd_,
streamFailed_, &compileError_, &warnings_, sender_);
// When execute() returns, the CompileStreamTask will be dispatched
// back to its JS thread to call resolve() and then be destroyed. We
// can't let this happen until the stream has been closed lest
// consumeChunk() or streamEnd() be called on a dead object.
auto streamState = streamState_.lock();
while (streamState != Closed) {
streamState.wait(/* stream closed */);
}
}
// Called on a JS thread after streaming compilation completes/errors:
bool resolve(JSContext* cx, Handle<PromiseObject*> promise) override {
MOZ_ASSERT(streamState_.lock() == Closed);
if (module_) {
MOZ_ASSERT(!streamFailed_ && !streamError_ && !compileError_);
if (!ReportCompileWarnings(cx, warnings_)) {
return false;
}
if (instantiate_) {
return AsyncInstantiate(cx, *module_, importObj_, Ret::Pair, promise);
}
return ResolveCompile(cx, *module_, promise);
}
if (streamError_) {
return RejectWithStreamErrorNumber(cx, *streamError_, promise);
}
return Reject(cx, *compileArgs_, promise, compileError_);
}
public:
CompileStreamTask(JSContext* cx, Handle<PromiseObject*> promise,
CompileArgs& compileArgs, bool instantiate,
HandleObject importObj)
: PromiseHelperTask(cx, promise),
streamState_(mutexid::WasmStreamStatus, Env),
instantiate_(instantiate),
importObj_(cx, importObj),
compileArgs_(&compileArgs),
codeSection_{},
codeBytesEnd_(nullptr),
exclusiveCodeBytesEnd_(mutexid::WasmCodeBytesEnd, nullptr),
exclusiveStreamEnd_(mutexid::WasmStreamEnd),
streamFailed_(false),
sender_(cx->runtime()) {
MOZ_ASSERT_IF(importObj_, instantiate_);
}
};
// A short-lived object that captures the arguments of a
// WebAssembly.{compileStreaming,instantiateStreaming} while waiting for
// the Promise<Response> to resolve to a (hopefully) Promise.
class ResolveResponseClosure : public NativeObject {
static const unsigned COMPILE_ARGS_SLOT = 0;
static const unsigned PROMISE_OBJ_SLOT = 1;
static const unsigned INSTANTIATE_SLOT = 2;
static const unsigned IMPORT_OBJ_SLOT = 3;
static const JSClassOps classOps_;
static void finalize(JSFreeOp* fop, JSObject* obj) {
auto& closure = obj->as<ResolveResponseClosure>();
fop->release(obj, &closure.compileArgs(),
MemoryUse::WasmResolveResponseClosure);
}
public:
static const unsigned RESERVED_SLOTS = 4;
static const JSClass class_;
static ResolveResponseClosure* create(JSContext* cx, const CompileArgs& args,
HandleObject promise, bool instantiate,
HandleObject importObj) {
MOZ_ASSERT_IF(importObj, instantiate);
AutoSetNewObjectMetadata metadata(cx);
auto* obj = NewObjectWithGivenProto<ResolveResponseClosure>(cx, nullptr);
if (!obj) {
return nullptr;
}
args.AddRef();
InitReservedSlot(obj, COMPILE_ARGS_SLOT, const_cast<CompileArgs*>(&args),
MemoryUse::WasmResolveResponseClosure);
obj->setReservedSlot(PROMISE_OBJ_SLOT, ObjectValue(*promise));
obj->setReservedSlot(INSTANTIATE_SLOT, BooleanValue(instantiate));
obj->setReservedSlot(IMPORT_OBJ_SLOT, ObjectOrNullValue(importObj));
return obj;
}
CompileArgs& compileArgs() const {
return *(CompileArgs*)getReservedSlot(COMPILE_ARGS_SLOT).toPrivate();
}
PromiseObject& promise() const {
return getReservedSlot(PROMISE_OBJ_SLOT).toObject().as<PromiseObject>();
}
bool instantiate() const {
return getReservedSlot(INSTANTIATE_SLOT).toBoolean();
}
JSObject* importObj() const {
return getReservedSlot(IMPORT_OBJ_SLOT).toObjectOrNull();
}
};
const JSClassOps ResolveResponseClosure::classOps_ = {
nullptr, // addProperty
nullptr, // delProperty
nullptr, // enumerate
nullptr, // newEnumerate
nullptr, // resolve
nullptr, // mayResolve
ResolveResponseClosure::finalize, // finalize
nullptr, // call
nullptr, // hasInstance
nullptr, // construct
nullptr, // trace
};
const JSClass ResolveResponseClosure::class_ = {
"WebAssembly ResolveResponseClosure",
JSCLASS_DELAY_METADATA_BUILDER |
JSCLASS_HAS_RESERVED_SLOTS(ResolveResponseClosure::RESERVED_SLOTS) |
JSCLASS_FOREGROUND_FINALIZE,
&ResolveResponseClosure::classOps_,
};
static ResolveResponseClosure* ToResolveResponseClosure(CallArgs args) {
return &args.callee()
.as<JSFunction>()
.getExtendedSlot(0)
.toObject()
.as<ResolveResponseClosure>();
}
static bool RejectWithErrorNumber(JSContext* cx, uint32_t errorNumber,
Handle<PromiseObject*> promise) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, errorNumber);
return RejectWithPendingException(cx, promise);
}
static bool ResolveResponse_OnFulfilled(JSContext* cx, unsigned argc,
Value* vp) {
CallArgs callArgs = CallArgsFromVp(argc, vp);
Rooted<ResolveResponseClosure*> closure(cx,
ToResolveResponseClosure(callArgs));
Rooted<PromiseObject*> promise(cx, &closure->promise());
CompileArgs& compileArgs = closure->compileArgs();
bool instantiate = closure->instantiate();
Rooted<JSObject*> importObj(cx, closure->importObj());
auto task = cx->make_unique<CompileStreamTask>(cx, promise, compileArgs,
instantiate, importObj);
if (!task || !task->init(cx)) {
return false;
}
if (!callArgs.get(0).isObject()) {
return RejectWithErrorNumber(cx, JSMSG_WASM_BAD_RESPONSE_VALUE, promise);
}
RootedObject response(cx, &callArgs.get(0).toObject());
if (!cx->runtime()->consumeStreamCallback(cx, response, JS::MimeType::Wasm,
task.get())) {
return RejectWithPendingException(cx, promise);
}
Unused << task.release();
callArgs.rval().setUndefined();
return true;
}
static bool ResolveResponse_OnRejected(JSContext* cx, unsigned argc,
Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
Rooted<ResolveResponseClosure*> closure(cx, ToResolveResponseClosure(args));
Rooted<PromiseObject*> promise(cx, &closure->promise());
if (!PromiseObject::reject(cx, promise, args.get(0))) {
return false;
}
args.rval().setUndefined();
return true;
}
static bool ResolveResponse(JSContext* cx, CallArgs callArgs,
Handle<PromiseObject*> promise,
bool instantiate = false,
HandleObject importObj = nullptr) {
MOZ_ASSERT_IF(importObj, instantiate);
const char* introducer = instantiate ? "WebAssembly.instantiateStreaming"
: "WebAssembly.compileStreaming";
SharedCompileArgs compileArgs = InitCompileArgs(cx, introducer);
if (!compileArgs) {
return false;
}
RootedObject closure(
cx, ResolveResponseClosure::create(cx, *compileArgs, promise, instantiate,
importObj));
if (!closure) {
return false;
}
RootedFunction onResolved(
cx, NewNativeFunction(cx, ResolveResponse_OnFulfilled, 1, nullptr,
gc::AllocKind::FUNCTION_EXTENDED, GenericObject));
if (!onResolved) {
return false;
}
RootedFunction onRejected(
cx, NewNativeFunction(cx, ResolveResponse_OnRejected, 1, nullptr,
gc::AllocKind::FUNCTION_EXTENDED, GenericObject));
if (!onRejected) {
return false;
}
onResolved->setExtendedSlot(0, ObjectValue(*closure));
onRejected->setExtendedSlot(0, ObjectValue(*closure));
RootedObject resolve(cx,
PromiseObject::unforgeableResolve(cx, callArgs.get(0)));
if (!resolve) {
return false;
}
return JS::AddPromiseReactions(cx, resolve, onResolved, onRejected);
}
static bool WebAssembly_compileStreaming(JSContext* cx, unsigned argc,
Value* vp) {
if (!EnsureStreamSupport(cx)) {
return false;
}
Log(cx, "async compileStreaming() started");
Rooted<PromiseObject*> promise(cx, PromiseObject::createSkippingExecutor(cx));
if (!promise) {
return false;
}
CallArgs callArgs = CallArgsFromVp(argc, vp);
if (!ResolveResponse(cx, callArgs, promise)) {
return RejectWithPendingException(cx, promise, callArgs);
}
callArgs.rval().setObject(*promise);
return true;
}
static bool WebAssembly_instantiateStreaming(JSContext* cx, unsigned argc,
Value* vp) {
if (!EnsureStreamSupport(cx)) {
return false;
}
Log(cx, "async instantiateStreaming() started");
Rooted<PromiseObject*> promise(cx, PromiseObject::createSkippingExecutor(cx));
if (!promise) {
return false;
}
CallArgs callArgs = CallArgsFromVp(argc, vp);
RootedObject firstArg(cx);
RootedObject importObj(cx);
if (!GetInstantiateArgs(cx, callArgs, &firstArg, &importObj)) {
return RejectWithPendingException(cx, promise, callArgs);
}
if (!ResolveResponse(cx, callArgs, promise, true, importObj)) {
return RejectWithPendingException(cx, promise, callArgs);
}
callArgs.rval().setObject(*promise);
return true;
}
static const JSFunctionSpec WebAssembly_static_methods[] = {
JS_FN(js_toSource_str, WebAssembly_toSource, 0, 0),
JS_FN("compile", WebAssembly_compile, 1, JSPROP_ENUMERATE),
JS_FN("instantiate", WebAssembly_instantiate, 1, JSPROP_ENUMERATE),
JS_FN("validate", WebAssembly_validate, 1, JSPROP_ENUMERATE),
JS_FN("compileStreaming", WebAssembly_compileStreaming, 1,
JSPROP_ENUMERATE),
JS_FN("instantiateStreaming", WebAssembly_instantiateStreaming, 1,
JSPROP_ENUMERATE),
JS_FS_END};
static JSObject* CreateWebAssemblyObject(JSContext* cx, JSProtoKey key) {
MOZ_RELEASE_ASSERT(HasSupport(cx));
Handle<GlobalObject*> global = cx->global();
RootedObject proto(cx, GlobalObject::getOrCreateObjectPrototype(cx, global));
if (!proto) {
return nullptr;
}
return NewTenuredObjectWithGivenProto(cx, &WasmNamespaceObject::class_,
proto);
}
static bool WebAssemblyClassFinish(JSContext* cx, HandleObject object,
HandleObject proto) {
Handle<WasmNamespaceObject*> wasm = object.as<WasmNamespaceObject>();
struct NameAndProtoKey {
const char* const name;
JSProtoKey key;
};
constexpr NameAndProtoKey entries[] = {
{"Module", JSProto_WasmModule},
{"Instance", JSProto_WasmInstance},
{"Memory", JSProto_WasmMemory},
{"Table", JSProto_WasmTable},
{"Global", JSProto_WasmGlobal},
#ifdef ENABLE_WASM_EXCEPTIONS
{"Exception", JSProto_WasmException},
#endif
{"CompileError", GetExceptionProtoKey(JSEXN_WASMCOMPILEERROR)},
{"LinkError", GetExceptionProtoKey(JSEXN_WASMLINKERROR)},
{"RuntimeError", GetExceptionProtoKey(JSEXN_WASMRUNTIMEERROR)},
};
RootedValue ctorValue(cx);
RootedId id(cx);
for (const auto& entry : entries) {
const char* name = entry.name;
JSProtoKey key = entry.key;
JSObject* ctor = GlobalObject::getOrCreateConstructor(cx, key);
if (!ctor) {
return false;
}
ctorValue.setObject(*ctor);
JSAtom* className = Atomize(cx, name, strlen(name));
if (!className) {
return false;
}
id.set(AtomToId(className));
if (!DefineDataProperty(cx, wasm, id, ctorValue, 0)) {
return false;
}
}
return true;
}
static const ClassSpec WebAssemblyClassSpec = {CreateWebAssemblyObject,
nullptr,
WebAssembly_static_methods,
nullptr,
nullptr,
nullptr,
WebAssemblyClassFinish};
const JSClass js::WasmNamespaceObject::class_ = {
js_WebAssembly_str, JSCLASS_HAS_CACHED_PROTO(JSProto_WebAssembly),
JS_NULL_CLASS_OPS, &WebAssemblyClassSpec};
|