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
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "BindingUtils.h"
#include <algorithm>
#include <stdarg.h>
#include "mozilla/Assertions.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/Encoding.h"
#include "mozilla/FloatingPoint.h"
#include "mozilla/Preferences.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/Unused.h"
#include "mozilla/UseCounter.h"
#include "AccessCheck.h"
#include "js/experimental/JitInfo.h" // JSJit{Getter,Setter,Method}CallArgs, JSJit{Getter,Setter}Op, JSJitInfo
#include "js/friend/StackLimits.h" // js::CheckRecursionLimitConservative
#include "js/Id.h"
#include "js/JSON.h"
#include "js/Object.h" // JS::GetClass, JS::GetCompartment, JS::GetReservedSlot, JS::SetReservedSlot
#include "js/StableStringChars.h"
#include "js/String.h" // JS::GetStringLength, JS::MaxStringLength, JS::StringHasLatin1Chars
#include "js/Symbol.h"
#include "jsfriendapi.h"
#include "nsContentCreatorFunctions.h"
#include "nsContentUtils.h"
#include "nsGlobalWindow.h"
#include "nsHTMLTags.h"
#include "nsIDOMGlobalPropertyInitializer.h"
#include "nsINode.h"
#include "nsIOService.h"
#include "nsIPrincipal.h"
#include "nsIXPConnect.h"
#include "nsUTF8Utils.h"
#include "WorkerPrivate.h"
#include "WorkerRunnable.h"
#include "WrapperFactory.h"
#include "xpcprivate.h"
#include "XrayWrapper.h"
#include "nsPrintfCString.h"
#include "mozilla/Sprintf.h"
#include "nsReadableUtils.h"
#include "nsWrapperCacheInlines.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/CustomElementRegistry.h"
#include "mozilla/dom/DeprecationReportBody.h"
#include "mozilla/dom/DOMException.h"
#include "mozilla/dom/ElementBinding.h"
#include "mozilla/dom/Exceptions.h"
#include "mozilla/dom/HTMLObjectElement.h"
#include "mozilla/dom/HTMLObjectElementBinding.h"
#include "mozilla/dom/HTMLEmbedElement.h"
#include "mozilla/dom/HTMLElementBinding.h"
#include "mozilla/dom/HTMLEmbedElementBinding.h"
#include "mozilla/dom/MaybeCrossOriginObject.h"
#include "mozilla/dom/ReportingUtils.h"
#include "mozilla/dom/XULElementBinding.h"
#include "mozilla/dom/XULFrameElementBinding.h"
#include "mozilla/dom/XULMenuElementBinding.h"
#include "mozilla/dom/XULPopupElementBinding.h"
#include "mozilla/dom/XULTextElementBinding.h"
#include "mozilla/dom/XULTreeElementBinding.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/WebIDLGlobalNameHash.h"
#include "mozilla/dom/WorkerPrivate.h"
#include "mozilla/dom/WorkerScope.h"
#include "mozilla/dom/XrayExpandoClass.h"
#include "mozilla/dom/WindowProxyHolder.h"
#include "ipc/ErrorIPCUtils.h"
#include "mozilla/UseCounter.h"
#include "mozilla/dom/DocGroup.h"
#include "nsXULElement.h"
namespace mozilla {
namespace dom {
// Forward declare GetConstructorObject methods.
#define HTML_TAG(_tag, _classname, _interfacename) \
namespace HTML##_interfacename##Element_Binding { \
JSObject* GetConstructorObject(JSContext*); \
}
#define HTML_OTHER(_tag)
#include "nsHTMLTagList.h"
#undef HTML_TAG
#undef HTML_OTHER
typedef JSObject* (*constructorGetterCallback)(JSContext*);
// Mapping of html tag and GetConstructorObject methods.
#define HTML_TAG(_tag, _classname, _interfacename) \
HTML##_interfacename##Element_Binding::GetConstructorObject,
#define HTML_OTHER(_tag) nullptr,
// We use eHTMLTag_foo (where foo is the tag) which is defined in nsHTMLTags.h
// to index into this array.
static const constructorGetterCallback sConstructorGetterCallback[] = {
HTMLUnknownElement_Binding::GetConstructorObject,
#include "nsHTMLTagList.h"
#undef HTML_TAG
#undef HTML_OTHER
};
static const JSErrorFormatString ErrorFormatString[] = {
#define MSG_DEF(_name, _argc, _has_context, _exn, _str) \
{#_name, _str, _argc, _exn},
#include "mozilla/dom/Errors.msg"
#undef MSG_DEF
};
#define MSG_DEF(_name, _argc, _has_context, _exn, _str) \
static_assert( \
(_argc) < JS::MaxNumErrorArguments, #_name \
" must only have as many error arguments as the JS engine can support");
#include "mozilla/dom/Errors.msg"
#undef MSG_DEF
static const JSErrorFormatString* GetErrorMessage(void* aUserRef,
const unsigned aErrorNumber) {
MOZ_ASSERT(aErrorNumber < ArrayLength(ErrorFormatString));
return &ErrorFormatString[aErrorNumber];
}
uint16_t GetErrorArgCount(const ErrNum aErrorNumber) {
return GetErrorMessage(nullptr, aErrorNumber)->argCount;
}
// aErrorNumber needs to be unsigned, not an ErrNum, because the latter makes
// va_start have undefined behavior, and we do not want undefined behavior.
void binding_detail::ThrowErrorMessage(JSContext* aCx,
const unsigned aErrorNumber, ...) {
va_list ap;
va_start(ap, aErrorNumber);
if (!ErrorFormatHasContext[aErrorNumber]) {
JS_ReportErrorNumberUTF8VA(aCx, GetErrorMessage, nullptr, aErrorNumber, ap);
va_end(ap);
return;
}
// Our first arg is the context arg. We want to replace nullptr with empty
// string, leave empty string alone, and for anything else append ": " to the
// end. See also the behavior of
// TErrorResult::SetPendingExceptionWithMessage, which this is mirroring for
// exceptions that are thrown directly, not via an ErrorResult.
const char* args[JS::MaxNumErrorArguments + 1];
size_t argCount = GetErrorArgCount(static_cast<ErrNum>(aErrorNumber));
MOZ_ASSERT(argCount > 0, "We have a context arg!");
nsAutoCString firstArg;
for (size_t i = 0; i < argCount; ++i) {
args[i] = va_arg(ap, const char*);
if (i == 0) {
if (args[0] && *args[0]) {
firstArg.Append(args[0]);
firstArg.AppendLiteral(": ");
}
args[0] = firstArg.get();
}
}
JS_ReportErrorNumberUTF8Array(aCx, GetErrorMessage, nullptr, aErrorNumber,
args);
va_end(ap);
}
static bool ThrowInvalidThis(JSContext* aCx, const JS::CallArgs& aArgs,
bool aSecurityError, const char* aInterfaceName) {
NS_ConvertASCIItoUTF16 ifaceName(aInterfaceName);
// This should only be called for DOM methods/getters/setters, which
// are JSNative-backed functions, so we can assume that
// JS_ValueToFunction and JS_GetFunctionDisplayId will both return
// non-null and that JS_GetStringCharsZ returns non-null.
JS::Rooted<JSFunction*> func(aCx, JS_ValueToFunction(aCx, aArgs.calleev()));
MOZ_ASSERT(func);
JS::Rooted<JSString*> funcName(aCx, JS_GetFunctionDisplayId(func));
MOZ_ASSERT(funcName);
nsAutoJSString funcNameStr;
if (!funcNameStr.init(aCx, funcName)) {
return false;
}
if (aSecurityError) {
return Throw(aCx, NS_ERROR_DOM_SECURITY_ERR,
nsPrintfCString("Permission to call '%s' denied.",
NS_ConvertUTF16toUTF8(funcNameStr).get()));
}
const ErrNum errorNumber = MSG_METHOD_THIS_DOES_NOT_IMPLEMENT_INTERFACE;
MOZ_RELEASE_ASSERT(GetErrorArgCount(errorNumber) == 2);
JS_ReportErrorNumberUC(aCx, GetErrorMessage, nullptr,
static_cast<unsigned>(errorNumber), funcNameStr.get(),
ifaceName.get());
return false;
}
bool ThrowInvalidThis(JSContext* aCx, const JS::CallArgs& aArgs,
bool aSecurityError, prototypes::ID aProtoId) {
return ThrowInvalidThis(aCx, aArgs, aSecurityError,
NamesOfInterfacesWithProtos(aProtoId));
}
bool ThrowNoSetterArg(JSContext* aCx, const JS::CallArgs& aArgs,
prototypes::ID aProtoId) {
nsPrintfCString errorMessage("%s attribute setter",
NamesOfInterfacesWithProtos(aProtoId));
return aArgs.requireAtLeast(aCx, errorMessage.get(), 1);
}
} // namespace dom
namespace binding_danger {
template <typename CleanupPolicy>
struct TErrorResult<CleanupPolicy>::Message {
Message() : mErrorNumber(dom::Err_Limit) {
MOZ_COUNT_CTOR(TErrorResult::Message);
}
~Message() { MOZ_COUNT_DTOR(TErrorResult::Message); }
// UTF-8 strings (probably ASCII in most cases) in mArgs.
nsTArray<nsCString> mArgs;
dom::ErrNum mErrorNumber;
bool HasCorrectNumberOfArguments() {
return GetErrorArgCount(mErrorNumber) == mArgs.Length();
}
bool operator==(const TErrorResult<CleanupPolicy>::Message& aRight) const {
return mErrorNumber == aRight.mErrorNumber && mArgs == aRight.mArgs;
}
};
template <typename CleanupPolicy>
nsTArray<nsCString>& TErrorResult<CleanupPolicy>::CreateErrorMessageHelper(
const dom::ErrNum errorNumber, nsresult errorType) {
AssertInOwningThread();
mResult = errorType;
Message* message = InitMessage(new Message());
message->mErrorNumber = errorNumber;
return message->mArgs;
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::SerializeMessage(IPC::Message* aMsg) const {
using namespace IPC;
AssertInOwningThread();
MOZ_ASSERT(mUnionState == HasMessage);
MOZ_ASSERT(mExtra.mMessage);
WriteParam(aMsg, mExtra.mMessage->mArgs);
WriteParam(aMsg, mExtra.mMessage->mErrorNumber);
}
template <typename CleanupPolicy>
bool TErrorResult<CleanupPolicy>::DeserializeMessage(const IPC::Message* aMsg,
PickleIterator* aIter) {
using namespace IPC;
AssertInOwningThread();
auto readMessage = MakeUnique<Message>();
if (!ReadParam(aMsg, aIter, &readMessage->mArgs) ||
!ReadParam(aMsg, aIter, &readMessage->mErrorNumber)) {
return false;
}
if (!readMessage->HasCorrectNumberOfArguments()) {
return false;
}
MOZ_ASSERT(mUnionState == HasNothing);
InitMessage(readMessage.release());
#ifdef DEBUG
mUnionState = HasMessage;
#endif // DEBUG
return true;
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::SetPendingExceptionWithMessage(
JSContext* aCx, const char* context) {
AssertInOwningThread();
MOZ_ASSERT(mUnionState == HasMessage);
MOZ_ASSERT(mExtra.mMessage,
"SetPendingExceptionWithMessage() can be called only once");
Message* message = mExtra.mMessage;
MOZ_RELEASE_ASSERT(message->HasCorrectNumberOfArguments());
if (dom::ErrorFormatHasContext[message->mErrorNumber]) {
MOZ_ASSERT(!message->mArgs.IsEmpty(), "How could we have no args here?");
MOZ_ASSERT(message->mArgs[0].IsEmpty(), "Context should not be set yet!");
if (context) {
// Prepend our context and ": "; see API documentation.
message->mArgs[0].AssignASCII(context);
message->mArgs[0].AppendLiteral(": ");
}
}
const uint32_t argCount = message->mArgs.Length();
const char* args[JS::MaxNumErrorArguments + 1];
for (uint32_t i = 0; i < argCount; ++i) {
args[i] = message->mArgs.ElementAt(i).get();
}
args[argCount] = nullptr;
JS_ReportErrorNumberUTF8Array(aCx, dom::GetErrorMessage, nullptr,
static_cast<unsigned>(message->mErrorNumber),
argCount > 0 ? args : nullptr);
ClearMessage();
mResult = NS_OK;
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::ClearMessage() {
AssertInOwningThread();
MOZ_ASSERT(IsErrorWithMessage());
MOZ_ASSERT(mUnionState == HasMessage);
delete mExtra.mMessage;
mExtra.mMessage = nullptr;
#ifdef DEBUG
mUnionState = HasNothing;
#endif // DEBUG
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::ThrowJSException(JSContext* cx,
JS::Handle<JS::Value> exn) {
AssertInOwningThread();
MOZ_ASSERT(mMightHaveUnreportedJSException,
"Why didn't you tell us you planned to throw a JS exception?");
ClearUnionData();
// Make sure mExtra.mJSException is initialized _before_ we try to root it.
// But don't set it to exn yet, because we don't want to do that until after
// we root.
JS::Value& exc = InitJSException();
if (!js::AddRawValueRoot(cx, &exc, "TErrorResult::mExtra::mJSException")) {
// Don't use NS_ERROR_INTERNAL_ERRORRESULT_JS_EXCEPTION, because that
// indicates we have in fact rooted mExtra.mJSException.
mResult = NS_ERROR_OUT_OF_MEMORY;
} else {
exc = exn;
mResult = NS_ERROR_INTERNAL_ERRORRESULT_JS_EXCEPTION;
#ifdef DEBUG
mUnionState = HasJSException;
#endif // DEBUG
}
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::SetPendingJSException(JSContext* cx) {
AssertInOwningThread();
MOZ_ASSERT(!mMightHaveUnreportedJSException,
"Why didn't you tell us you planned to handle JS exceptions?");
MOZ_ASSERT(mUnionState == HasJSException);
JS::Rooted<JS::Value> exception(cx, mExtra.mJSException);
if (JS_WrapValue(cx, &exception)) {
JS_SetPendingException(cx, exception);
}
mExtra.mJSException = exception;
// If JS_WrapValue failed, not much we can do about it... No matter
// what, go ahead and unroot mExtra.mJSException.
js::RemoveRawValueRoot(cx, &mExtra.mJSException);
mResult = NS_OK;
#ifdef DEBUG
mUnionState = HasNothing;
#endif // DEBUG
}
template <typename CleanupPolicy>
struct TErrorResult<CleanupPolicy>::DOMExceptionInfo {
DOMExceptionInfo(nsresult rv, const nsACString& message)
: mMessage(message), mRv(rv) {}
nsCString mMessage;
nsresult mRv;
bool operator==(
const TErrorResult<CleanupPolicy>::DOMExceptionInfo& aRight) const {
return mRv == aRight.mRv && mMessage == aRight.mMessage;
}
};
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::SerializeDOMExceptionInfo(
IPC::Message* aMsg) const {
using namespace IPC;
AssertInOwningThread();
MOZ_ASSERT(mUnionState == HasDOMExceptionInfo);
MOZ_ASSERT(mExtra.mDOMExceptionInfo);
WriteParam(aMsg, mExtra.mDOMExceptionInfo->mMessage);
WriteParam(aMsg, mExtra.mDOMExceptionInfo->mRv);
}
template <typename CleanupPolicy>
bool TErrorResult<CleanupPolicy>::DeserializeDOMExceptionInfo(
const IPC::Message* aMsg, PickleIterator* aIter) {
using namespace IPC;
AssertInOwningThread();
nsCString message;
nsresult rv;
if (!ReadParam(aMsg, aIter, &message) || !ReadParam(aMsg, aIter, &rv)) {
return false;
}
MOZ_ASSERT(mUnionState == HasNothing);
MOZ_ASSERT(IsDOMException());
InitDOMExceptionInfo(new DOMExceptionInfo(rv, message));
#ifdef DEBUG
mUnionState = HasDOMExceptionInfo;
#endif // DEBUG
return true;
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::ThrowDOMException(nsresult rv,
const nsACString& message) {
AssertInOwningThread();
ClearUnionData();
mResult = NS_ERROR_INTERNAL_ERRORRESULT_DOMEXCEPTION;
InitDOMExceptionInfo(new DOMExceptionInfo(rv, message));
#ifdef DEBUG
mUnionState = HasDOMExceptionInfo;
#endif
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::SetPendingDOMException(JSContext* cx,
const char* context) {
AssertInOwningThread();
MOZ_ASSERT(mUnionState == HasDOMExceptionInfo);
MOZ_ASSERT(mExtra.mDOMExceptionInfo,
"SetPendingDOMException() can be called only once");
if (context && !mExtra.mDOMExceptionInfo->mMessage.IsEmpty()) {
// Prepend our context and ": "; see API documentation.
nsAutoCString prefix(context);
prefix.AppendLiteral(": ");
mExtra.mDOMExceptionInfo->mMessage.Insert(prefix, 0);
}
dom::Throw(cx, mExtra.mDOMExceptionInfo->mRv,
mExtra.mDOMExceptionInfo->mMessage);
ClearDOMExceptionInfo();
mResult = NS_OK;
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::ClearDOMExceptionInfo() {
AssertInOwningThread();
MOZ_ASSERT(IsDOMException());
MOZ_ASSERT(mUnionState == HasDOMExceptionInfo);
delete mExtra.mDOMExceptionInfo;
mExtra.mDOMExceptionInfo = nullptr;
#ifdef DEBUG
mUnionState = HasNothing;
#endif // DEBUG
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::ClearUnionData() {
AssertInOwningThread();
if (IsJSException()) {
JSContext* cx = dom::danger::GetJSContext();
MOZ_ASSERT(cx);
mExtra.mJSException.setUndefined();
js::RemoveRawValueRoot(cx, &mExtra.mJSException);
#ifdef DEBUG
mUnionState = HasNothing;
#endif // DEBUG
} else if (IsErrorWithMessage()) {
ClearMessage();
} else if (IsDOMException()) {
ClearDOMExceptionInfo();
}
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::SetPendingGenericErrorException(
JSContext* cx) {
AssertInOwningThread();
MOZ_ASSERT(!IsErrorWithMessage());
MOZ_ASSERT(!IsJSException());
MOZ_ASSERT(!IsDOMException());
dom::Throw(cx, ErrorCode());
mResult = NS_OK;
}
template <typename CleanupPolicy>
TErrorResult<CleanupPolicy>& TErrorResult<CleanupPolicy>::operator=(
TErrorResult<CleanupPolicy>&& aRHS) {
AssertInOwningThread();
aRHS.AssertInOwningThread();
// Clear out any union members we may have right now, before we
// start writing to it.
ClearUnionData();
#ifdef DEBUG
mMightHaveUnreportedJSException = aRHS.mMightHaveUnreportedJSException;
aRHS.mMightHaveUnreportedJSException = false;
#endif
if (aRHS.IsErrorWithMessage()) {
InitMessage(aRHS.mExtra.mMessage);
aRHS.mExtra.mMessage = nullptr;
} else if (aRHS.IsJSException()) {
JSContext* cx = dom::danger::GetJSContext();
MOZ_ASSERT(cx);
JS::Value& exn = InitJSException();
if (!js::AddRawValueRoot(cx, &exn, "TErrorResult::mExtra::mJSException")) {
MOZ_CRASH("Could not root mExtra.mJSException, we're about to OOM");
}
mExtra.mJSException = aRHS.mExtra.mJSException;
aRHS.mExtra.mJSException.setUndefined();
js::RemoveRawValueRoot(cx, &aRHS.mExtra.mJSException);
} else if (aRHS.IsDOMException()) {
InitDOMExceptionInfo(aRHS.mExtra.mDOMExceptionInfo);
aRHS.mExtra.mDOMExceptionInfo = nullptr;
} else {
// Null out the union on both sides for hygiene purposes. This is purely
// precautionary, so InitMessage/placement-new is unnecessary.
mExtra.mMessage = aRHS.mExtra.mMessage = nullptr;
}
#ifdef DEBUG
mUnionState = aRHS.mUnionState;
aRHS.mUnionState = HasNothing;
#endif // DEBUG
// Note: It's important to do this last, since this affects the condition
// checks above!
mResult = aRHS.mResult;
aRHS.mResult = NS_OK;
return *this;
}
template <typename CleanupPolicy>
bool TErrorResult<CleanupPolicy>::operator==(const ErrorResult& aRight) const {
auto right = reinterpret_cast<const TErrorResult<CleanupPolicy>*>(&aRight);
if (mResult != right->mResult) {
return false;
}
if (IsJSException()) {
// js exceptions are always non-equal
return false;
}
if (IsErrorWithMessage()) {
return *mExtra.mMessage == *right->mExtra.mMessage;
}
if (IsDOMException()) {
return *mExtra.mDOMExceptionInfo == *right->mExtra.mDOMExceptionInfo;
}
return true;
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::CloneTo(TErrorResult& aRv) const {
AssertInOwningThread();
aRv.AssertInOwningThread();
aRv.ClearUnionData();
aRv.mResult = mResult;
#ifdef DEBUG
aRv.mMightHaveUnreportedJSException = mMightHaveUnreportedJSException;
#endif
if (IsErrorWithMessage()) {
#ifdef DEBUG
aRv.mUnionState = HasMessage;
#endif
Message* message = aRv.InitMessage(new Message());
message->mArgs = mExtra.mMessage->mArgs.Clone();
message->mErrorNumber = mExtra.mMessage->mErrorNumber;
} else if (IsDOMException()) {
#ifdef DEBUG
aRv.mUnionState = HasDOMExceptionInfo;
#endif
auto* exnInfo = new DOMExceptionInfo(mExtra.mDOMExceptionInfo->mRv,
mExtra.mDOMExceptionInfo->mMessage);
aRv.InitDOMExceptionInfo(exnInfo);
} else if (IsJSException()) {
#ifdef DEBUG
aRv.mUnionState = HasJSException;
#endif
JSContext* cx = dom::danger::GetJSContext();
JS::Rooted<JS::Value> exception(cx, mExtra.mJSException);
aRv.ThrowJSException(cx, exception);
}
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::SuppressException() {
AssertInOwningThread();
WouldReportJSException();
ClearUnionData();
// We don't use AssignErrorCode, because we want to override existing error
// states, which AssignErrorCode is not allowed to do.
mResult = NS_OK;
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::SetPendingException(JSContext* cx,
const char* context) {
AssertInOwningThread();
if (IsUncatchableException()) {
// Nuke any existing exception on cx, to make sure we're uncatchable.
JS_ClearPendingException(cx);
// Don't do any reporting. Just return, to create an
// uncatchable exception.
mResult = NS_OK;
return;
}
if (IsJSContextException()) {
// Whatever we need to throw is on the JSContext already.
MOZ_ASSERT(JS_IsExceptionPending(cx));
mResult = NS_OK;
return;
}
if (IsErrorWithMessage()) {
SetPendingExceptionWithMessage(cx, context);
return;
}
if (IsJSException()) {
SetPendingJSException(cx);
return;
}
if (IsDOMException()) {
SetPendingDOMException(cx, context);
return;
}
SetPendingGenericErrorException(cx);
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::StealExceptionFromJSContext(JSContext* cx) {
AssertInOwningThread();
MOZ_ASSERT(mMightHaveUnreportedJSException,
"Why didn't you tell us you planned to throw a JS exception?");
JS::Rooted<JS::Value> exn(cx);
if (!JS_GetPendingException(cx, &exn)) {
ThrowUncatchableException();
return;
}
ThrowJSException(cx, exn);
JS_ClearPendingException(cx);
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::NoteJSContextException(JSContext* aCx) {
AssertInOwningThread();
if (JS_IsExceptionPending(aCx)) {
mResult = NS_ERROR_INTERNAL_ERRORRESULT_EXCEPTION_ON_JSCONTEXT;
} else {
mResult = NS_ERROR_UNCATCHABLE_EXCEPTION;
}
}
/* static */
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::EnsureUTF8Validity(nsCString& aValue,
size_t aValidUpTo) {
nsCString valid;
if (NS_SUCCEEDED(UTF_8_ENCODING->DecodeWithoutBOMHandling(aValue, valid,
aValidUpTo))) {
aValue = valid;
} else {
aValue.SetLength(aValidUpTo);
}
}
template class TErrorResult<JustAssertCleanupPolicy>;
template class TErrorResult<AssertAndSuppressCleanupPolicy>;
template class TErrorResult<JustSuppressCleanupPolicy>;
template class TErrorResult<ThreadSafeJustSuppressCleanupPolicy>;
} // namespace binding_danger
namespace dom {
bool DefineConstants(JSContext* cx, JS::Handle<JSObject*> obj,
const ConstantSpec* cs) {
JS::Rooted<JS::Value> value(cx);
for (; cs->name; ++cs) {
value = cs->value;
bool ok = JS_DefineProperty(
cx, obj, cs->name, value,
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
if (!ok) {
return false;
}
}
return true;
}
static inline bool Define(JSContext* cx, JS::Handle<JSObject*> obj,
const JSFunctionSpec* spec) {
return JS_DefineFunctions(cx, obj, spec);
}
static inline bool Define(JSContext* cx, JS::Handle<JSObject*> obj,
const JSPropertySpec* spec) {
return JS_DefineProperties(cx, obj, spec);
}
static inline bool Define(JSContext* cx, JS::Handle<JSObject*> obj,
const ConstantSpec* spec) {
return DefineConstants(cx, obj, spec);
}
template <typename T>
bool DefinePrefable(JSContext* cx, JS::Handle<JSObject*> obj,
const Prefable<T>* props) {
MOZ_ASSERT(props);
MOZ_ASSERT(props->specs);
do {
// Define if enabled
if (props->isEnabled(cx, obj)) {
if (!Define(cx, obj, props->specs)) {
return false;
}
}
} while ((++props)->specs);
return true;
}
bool DefineUnforgeableMethods(JSContext* cx, JS::Handle<JSObject*> obj,
const Prefable<const JSFunctionSpec>* props) {
return DefinePrefable(cx, obj, props);
}
bool DefineUnforgeableAttributes(JSContext* cx, JS::Handle<JSObject*> obj,
const Prefable<const JSPropertySpec>* props) {
return DefinePrefable(cx, obj, props);
}
// We should use JSFunction objects for interface objects, but we need a custom
// hasInstance hook because we have new interface objects on prototype chains of
// old (XPConnect-based) bindings. We also need Xrays and arbitrary numbers of
// reserved slots (e.g. for named constructors). So we define a custom
// funToString ObjectOps member for interface objects.
JSString* InterfaceObjectToString(JSContext* aCx, JS::Handle<JSObject*> aObject,
bool /* isToSource */) {
const JSClass* clasp = JS::GetClass(aObject);
MOZ_ASSERT(IsDOMIfaceAndProtoClass(clasp));
const DOMIfaceAndProtoJSClass* ifaceAndProtoJSClass =
DOMIfaceAndProtoJSClass::FromJSClass(clasp);
return JS_NewStringCopyZ(aCx, ifaceAndProtoJSClass->mFunToString);
}
bool Constructor(JSContext* cx, unsigned argc, JS::Value* vp) {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
const JS::Value& v = js::GetFunctionNativeReserved(
&args.callee(), CONSTRUCTOR_NATIVE_HOLDER_RESERVED_SLOT);
const JSNativeHolder* nativeHolder =
static_cast<const JSNativeHolder*>(v.toPrivate());
return (nativeHolder->mNative)(cx, argc, vp);
}
static JSObject* CreateConstructor(JSContext* cx, JS::Handle<JSObject*> global,
const char* name,
const JSNativeHolder* nativeHolder,
unsigned ctorNargs) {
JSFunction* fun = js::NewFunctionWithReserved(cx, Constructor, ctorNargs,
JSFUN_CONSTRUCTOR, name);
if (!fun) {
return nullptr;
}
JSObject* constructor = JS_GetFunctionObject(fun);
js::SetFunctionNativeReserved(
constructor, CONSTRUCTOR_NATIVE_HOLDER_RESERVED_SLOT,
JS::PrivateValue(const_cast<JSNativeHolder*>(nativeHolder)));
return constructor;
}
static bool DefineConstructor(JSContext* cx, JS::Handle<JSObject*> global,
const char* name,
JS::Handle<JSObject*> constructor) {
bool alreadyDefined;
if (!JS_AlreadyHasOwnProperty(cx, global, name, &alreadyDefined)) {
return false;
}
// This is Enumerable: False per spec.
return alreadyDefined ||
JS_DefineProperty(cx, global, name, constructor, JSPROP_RESOLVING);
}
static JSObject* CreateInterfaceObject(
JSContext* cx, JS::Handle<JSObject*> global,
JS::Handle<JSObject*> constructorProto, const JSClass* constructorClass,
unsigned ctorNargs, const NamedConstructor* namedConstructors,
JS::Handle<JSObject*> proto, const NativeProperties* properties,
const NativeProperties* chromeOnlyProperties, const char* name,
bool isChrome, bool defineOnGlobal,
const char* const* legacyWindowAliases) {
JS::Rooted<JSObject*> constructor(cx);
MOZ_ASSERT(constructorProto);
MOZ_ASSERT(constructorClass);
constructor =
JS_NewObjectWithGivenProto(cx, constructorClass, constructorProto);
if (!constructor) {
return nullptr;
}
if (!JS_DefineProperty(cx, constructor, "length", ctorNargs,
JSPROP_READONLY)) {
return nullptr;
}
// Might as well intern, since we're going to need an atomized
// version of name anyway when we stick our constructor on the
// global.
JS::Rooted<JSString*> nameStr(cx, JS_AtomizeAndPinString(cx, name));
if (!nameStr) {
return nullptr;
}
if (!JS_DefineProperty(cx, constructor, "name", nameStr, JSPROP_READONLY)) {
return nullptr;
}
if (DOMIfaceAndProtoJSClass::FromJSClass(constructorClass)
->wantsInterfaceHasInstance) {
JS::Rooted<jsid> hasInstanceId(cx, SYMBOL_TO_JSID(JS::GetWellKnownSymbol(
cx, JS::SymbolCode::hasInstance)));
if (!JS_DefineFunctionById(
cx, constructor, hasInstanceId, InterfaceHasInstance, 1,
// Flags match those of Function[Symbol.hasInstance]
JSPROP_READONLY | JSPROP_PERMANENT)) {
return nullptr;
}
if (isChrome && !JS_DefineFunction(cx, constructor, "isInstance",
InterfaceIsInstance, 1,
// Don't bother making it enumerable
0)) {
return nullptr;
}
}
if (properties) {
if (properties->HasStaticMethods() &&
!DefinePrefable(cx, constructor, properties->StaticMethods())) {
return nullptr;
}
if (properties->HasStaticAttributes() &&
!DefinePrefable(cx, constructor, properties->StaticAttributes())) {
return nullptr;
}
if (properties->HasConstants() &&
!DefinePrefable(cx, constructor, properties->Constants())) {
return nullptr;
}
}
if (chromeOnlyProperties && isChrome) {
if (chromeOnlyProperties->HasStaticMethods() &&
!DefinePrefable(cx, constructor,
chromeOnlyProperties->StaticMethods())) {
return nullptr;
}
if (chromeOnlyProperties->HasStaticAttributes() &&
!DefinePrefable(cx, constructor,
chromeOnlyProperties->StaticAttributes())) {
return nullptr;
}
if (chromeOnlyProperties->HasConstants() &&
!DefinePrefable(cx, constructor, chromeOnlyProperties->Constants())) {
return nullptr;
}
}
if (proto && !JS_LinkConstructorAndPrototype(cx, constructor, proto)) {
return nullptr;
}
if (defineOnGlobal && !DefineConstructor(cx, global, name, constructor)) {
return nullptr;
}
if (legacyWindowAliases && NS_IsMainThread()) {
for (; *legacyWindowAliases; ++legacyWindowAliases) {
if (!DefineConstructor(cx, global, *legacyWindowAliases, constructor)) {
return nullptr;
}
}
}
if (namedConstructors) {
int namedConstructorSlot = DOM_INTERFACE_SLOTS_BASE;
while (namedConstructors->mName) {
JS::Rooted<JSObject*> namedConstructor(
cx, CreateConstructor(cx, global, namedConstructors->mName,
&namedConstructors->mHolder,
namedConstructors->mNargs));
if (!namedConstructor ||
!JS_DefineProperty(cx, namedConstructor, "prototype", proto,
JSPROP_PERMANENT | JSPROP_READONLY) ||
(defineOnGlobal &&
!DefineConstructor(cx, global, namedConstructors->mName,
namedConstructor))) {
return nullptr;
}
JS::SetReservedSlot(constructor, namedConstructorSlot++,
JS::ObjectValue(*namedConstructor));
++namedConstructors;
}
}
return constructor;
}
static JSObject* CreateInterfacePrototypeObject(
JSContext* cx, JS::Handle<JSObject*> global,
JS::Handle<JSObject*> parentProto, const JSClass* protoClass,
const NativeProperties* properties,
const NativeProperties* chromeOnlyProperties,
const char* const* unscopableNames, bool isGlobal) {
JS::Rooted<JSObject*> ourProto(
cx, JS_NewObjectWithGivenProto(cx, protoClass, parentProto));
if (!ourProto ||
// We don't try to define properties on the global's prototype; those
// properties go on the global itself.
(!isGlobal &&
!DefineProperties(cx, ourProto, properties, chromeOnlyProperties))) {
return nullptr;
}
if (unscopableNames) {
JS::Rooted<JSObject*> unscopableObj(
cx, JS_NewObjectWithGivenProto(cx, nullptr, nullptr));
if (!unscopableObj) {
return nullptr;
}
for (; *unscopableNames; ++unscopableNames) {
if (!JS_DefineProperty(cx, unscopableObj, *unscopableNames,
JS::TrueHandleValue, JSPROP_ENUMERATE)) {
return nullptr;
}
}
JS::Rooted<jsid> unscopableId(cx, SYMBOL_TO_JSID(JS::GetWellKnownSymbol(
cx, JS::SymbolCode::unscopables)));
// Readonly and non-enumerable to match Array.prototype.
if (!JS_DefinePropertyById(cx, ourProto, unscopableId, unscopableObj,
JSPROP_READONLY)) {
return nullptr;
}
}
return ourProto;
}
bool DefineProperties(JSContext* cx, JS::Handle<JSObject*> obj,
const NativeProperties* properties,
const NativeProperties* chromeOnlyProperties) {
if (properties) {
if (properties->HasMethods() &&
!DefinePrefable(cx, obj, properties->Methods())) {
return false;
}
if (properties->HasAttributes() &&
!DefinePrefable(cx, obj, properties->Attributes())) {
return false;
}
if (properties->HasConstants() &&
!DefinePrefable(cx, obj, properties->Constants())) {
return false;
}
}
if (chromeOnlyProperties) {
if (chromeOnlyProperties->HasMethods() &&
!DefinePrefable(cx, obj, chromeOnlyProperties->Methods())) {
return false;
}
if (chromeOnlyProperties->HasAttributes() &&
!DefinePrefable(cx, obj, chromeOnlyProperties->Attributes())) {
return false;
}
if (chromeOnlyProperties->HasConstants() &&
!DefinePrefable(cx, obj, chromeOnlyProperties->Constants())) {
return false;
}
}
return true;
}
void CreateInterfaceObjects(
JSContext* cx, JS::Handle<JSObject*> global,
JS::Handle<JSObject*> protoProto, const JSClass* protoClass,
JS::Heap<JSObject*>* protoCache, JS::Handle<JSObject*> constructorProto,
const JSClass* constructorClass, unsigned ctorNargs,
const NamedConstructor* namedConstructors,
JS::Heap<JSObject*>* constructorCache, const NativeProperties* properties,
const NativeProperties* chromeOnlyProperties, const char* name,
bool defineOnGlobal, const char* const* unscopableNames, bool isGlobal,
const char* const* legacyWindowAliases) {
MOZ_ASSERT(protoClass || constructorClass, "Need at least one class!");
MOZ_ASSERT(
!((properties &&
(properties->HasMethods() || properties->HasAttributes())) ||
(chromeOnlyProperties && (chromeOnlyProperties->HasMethods() ||
chromeOnlyProperties->HasAttributes()))) ||
protoClass,
"Methods or properties but no protoClass!");
MOZ_ASSERT(!((properties && (properties->HasStaticMethods() ||
properties->HasStaticAttributes())) ||
(chromeOnlyProperties &&
(chromeOnlyProperties->HasStaticMethods() ||
chromeOnlyProperties->HasStaticAttributes()))) ||
constructorClass,
"Static methods but no constructorClass!");
MOZ_ASSERT(bool(name) == bool(constructorClass),
"Must have name precisely when we have an interface object");
MOZ_ASSERT(!protoClass == !protoCache,
"If, and only if, there is an interface prototype object we need "
"to cache it");
MOZ_ASSERT(bool(constructorClass) == bool(constructorCache),
"If, and only if, there is an interface object we need to cache "
"it");
MOZ_ASSERT(constructorProto || !constructorClass,
"Must have a constructor proto if we plan to create a constructor "
"object");
bool isChrome = nsContentUtils::ThreadsafeIsSystemCaller(cx);
JS::Rooted<JSObject*> proto(cx);
if (protoClass) {
proto = CreateInterfacePrototypeObject(
cx, global, protoProto, protoClass, properties,
isChrome ? chromeOnlyProperties : nullptr, unscopableNames, isGlobal);
if (!proto) {
return;
}
*protoCache = proto;
} else {
MOZ_ASSERT(!proto);
}
JSObject* interface;
if (constructorClass) {
interface = CreateInterfaceObject(
cx, global, constructorProto, constructorClass, ctorNargs,
namedConstructors, proto, properties, chromeOnlyProperties, name,
isChrome, defineOnGlobal, legacyWindowAliases);
if (!interface) {
if (protoCache) {
// If we fail we need to make sure to clear the value of protoCache we
// set above.
*protoCache = nullptr;
}
return;
}
*constructorCache = interface;
}
}
// Only set aAllowNativeWrapper to false if you really know you need it; if in
// doubt use true. Setting it to false disables security wrappers.
static bool NativeInterface2JSObjectAndThrowIfFailed(
JSContext* aCx, JS::Handle<JSObject*> aScope,
JS::MutableHandle<JS::Value> aRetval, xpcObjectHelper& aHelper,
const nsIID* aIID, bool aAllowNativeWrapper) {
js::AssertSameCompartment(aCx, aScope);
nsresult rv;
// Inline some logic from XPCConvert::NativeInterfaceToJSObject that we need
// on all threads.
nsWrapperCache* cache = aHelper.GetWrapperCache();
if (cache) {
JS::Rooted<JSObject*> obj(aCx, cache->GetWrapper());
if (!obj) {
obj = cache->WrapObject(aCx, nullptr);
if (!obj) {
return Throw(aCx, NS_ERROR_UNEXPECTED);
}
}
if (aAllowNativeWrapper && !JS_WrapObject(aCx, &obj)) {
return false;
}
aRetval.setObject(*obj);
return true;
}
MOZ_ASSERT(NS_IsMainThread());
if (!XPCConvert::NativeInterface2JSObject(aCx, aRetval, aHelper, aIID,
aAllowNativeWrapper, &rv)) {
// I can't tell if NativeInterface2JSObject throws JS exceptions
// or not. This is a sloppy stab at the right semantics; the
// method really ought to be fixed to behave consistently.
if (!JS_IsExceptionPending(aCx)) {
Throw(aCx, NS_FAILED(rv) ? rv : NS_ERROR_UNEXPECTED);
}
return false;
}
return true;
}
bool TryPreserveWrapper(JS::Handle<JSObject*> obj) {
MOZ_ASSERT(IsDOMObject(obj));
// nsISupports objects are special cased because DOM proxies are nsISupports
// and have addProperty hooks that do more than wrapper preservation (so we
// don't want to call them).
if (nsISupports* native = UnwrapDOMObjectToISupports(obj)) {
nsWrapperCache* cache = nullptr;
CallQueryInterface(native, &cache);
if (cache) {
cache->PreserveWrapper(native);
}
return true;
}
// The addProperty hook for WebIDL classes does wrapper preservation, and
// nothing else, so call it, if present.
const DOMJSClass* domClass = GetDOMClass(obj);
const JSClass* clasp = domClass->ToJSClass();
JSAddPropertyOp addProperty = clasp->getAddProperty();
// We expect all proxies to be nsISupports.
MOZ_RELEASE_ASSERT(!clasp->isProxy(),
"Should not call addProperty for proxies.");
if (!addProperty) {
return true;
}
// The class should have an addProperty hook iff it is a CC participant.
MOZ_RELEASE_ASSERT(domClass->mParticipant);
JS::Rooted<jsid> dummyId(RootingCx());
JS::Rooted<JS::Value> dummyValue(RootingCx());
return addProperty(nullptr, obj, dummyId, dummyValue);
}
bool HasReleasedWrapper(JS::Handle<JSObject*> obj) {
MOZ_ASSERT(obj);
MOZ_ASSERT(IsDOMObject(obj));
nsWrapperCache* cache = nullptr;
if (nsISupports* native = UnwrapDOMObjectToISupports(obj)) {
CallQueryInterface(native, &cache);
} else {
const DOMJSClass* domClass = GetDOMClass(obj);
// We expect all proxies to be nsISupports.
MOZ_RELEASE_ASSERT(!domClass->ToJSClass()->isProxy(),
"Should not call getWrapperCache for proxies.");
WrapperCacheGetter getter = domClass->mWrapperCacheGetter;
if (getter) {
// If the class has a wrapper cache getter it must be a CC participant.
MOZ_RELEASE_ASSERT(domClass->mParticipant);
cache = getter(obj);
}
}
return cache && !cache->PreservingWrapper();
}
// Can only be called with a DOM JSClass.
bool InstanceClassHasProtoAtDepth(const JSClass* clasp, uint32_t protoID,
uint32_t depth) {
const DOMJSClass* domClass = DOMJSClass::FromJSClass(clasp);
return static_cast<uint32_t>(domClass->mInterfaceChain[depth]) == protoID;
}
// Only set allowNativeWrapper to false if you really know you need it; if in
// doubt use true. Setting it to false disables security wrappers.
bool XPCOMObjectToJsval(JSContext* cx, JS::Handle<JSObject*> scope,
xpcObjectHelper& helper, const nsIID* iid,
bool allowNativeWrapper,
JS::MutableHandle<JS::Value> rval) {
return NativeInterface2JSObjectAndThrowIfFailed(cx, scope, rval, helper, iid,
allowNativeWrapper);
}
bool VariantToJsval(JSContext* aCx, nsIVariant* aVariant,
JS::MutableHandle<JS::Value> aRetval) {
nsresult rv;
if (!XPCVariant::VariantDataToJS(aCx, aVariant, &rv, aRetval)) {
// Does it throw? Who knows
if (!JS_IsExceptionPending(aCx)) {
Throw(aCx, NS_FAILED(rv) ? rv : NS_ERROR_UNEXPECTED);
}
return false;
}
return true;
}
bool WrapObject(JSContext* cx, const WindowProxyHolder& p,
JS::MutableHandle<JS::Value> rval) {
return ToJSValue(cx, p, rval);
}
static int CompareIdsAtIndices(const void* aElement1, const void* aElement2,
void* aClosure) {
const uint16_t index1 = *static_cast<const uint16_t*>(aElement1);
const uint16_t index2 = *static_cast<const uint16_t*>(aElement2);
const PropertyInfo* infos = static_cast<PropertyInfo*>(aClosure);
MOZ_ASSERT(JSID_BITS(infos[index1].Id()) != JSID_BITS(infos[index2].Id()));
return JSID_BITS(infos[index1].Id()) < JSID_BITS(infos[index2].Id()) ? -1 : 1;
}
// {JSPropertySpec,JSFunctionSpec} use {JSPropertySpec,JSFunctionSpec}::Name
// and ConstantSpec uses `const char*` for name field.
static inline JSPropertySpec::Name ToPropertySpecName(
JSPropertySpec::Name name) {
return name;
}
static inline JSPropertySpec::Name ToPropertySpecName(const char* name) {
return JSPropertySpec::Name(name);
}
template <typename SpecT>
static bool InitIdsInternal(JSContext* cx, const Prefable<SpecT>* pref,
PropertyInfo* infos, PropertyType type) {
MOZ_ASSERT(pref);
MOZ_ASSERT(pref->specs);
// Index of the Prefable that contains the id for the current PropertyInfo.
uint32_t prefIndex = 0;
do {
// We ignore whether the set of ids is enabled and just intern all the IDs,
// because this is only done once per application runtime.
const SpecT* spec = pref->specs;
// Index of the property/function/constant spec for our current PropertyInfo
// in the "specs" array of the relevant Prefable.
uint32_t specIndex = 0;
do {
jsid id;
if (!JS::PropertySpecNameToPermanentId(cx, ToPropertySpecName(spec->name),
&id)) {
return false;
}
infos->SetId(id);
infos->type = type;
infos->prefIndex = prefIndex;
infos->specIndex = specIndex++;
++infos;
} while ((++spec)->name);
++prefIndex;
} while ((++pref)->specs);
return true;
}
#define INIT_IDS_IF_DEFINED(TypeName) \
{ \
if (nativeProperties->Has##TypeName##s() && \
!InitIdsInternal(cx, nativeProperties->TypeName##s(), \
nativeProperties->TypeName##PropertyInfos(), \
e##TypeName)) { \
return false; \
} \
}
bool InitIds(JSContext* cx, const NativeProperties* nativeProperties) {
INIT_IDS_IF_DEFINED(StaticMethod);
INIT_IDS_IF_DEFINED(StaticAttribute);
INIT_IDS_IF_DEFINED(Method);
INIT_IDS_IF_DEFINED(Attribute);
INIT_IDS_IF_DEFINED(UnforgeableMethod);
INIT_IDS_IF_DEFINED(UnforgeableAttribute);
INIT_IDS_IF_DEFINED(Constant);
// Initialize and sort the index array.
uint16_t* indices = nativeProperties->sortedPropertyIndices;
for (unsigned int i = 0; i < nativeProperties->propertyInfoCount; ++i) {
indices[i] = i;
}
// CompareIdsAtIndices() doesn't actually modify the PropertyInfo array, so
// the const_cast here is OK in spite of the signature of NS_QuickSort().
NS_QuickSort(indices, nativeProperties->propertyInfoCount, sizeof(uint16_t),
CompareIdsAtIndices,
const_cast<PropertyInfo*>(nativeProperties->PropertyInfos()));
return true;
}
#undef INIT_IDS_IF_DEFINED
void GetInterfaceImpl(JSContext* aCx, nsIInterfaceRequestor* aRequestor,
nsWrapperCache* aCache, JS::Handle<JS::Value> aIID,
JS::MutableHandle<JS::Value> aRetval,
ErrorResult& aError) {
Maybe<nsIID> iid = xpc::JSValue2ID(aCx, aIID);
if (!iid) {
aError.Throw(NS_ERROR_XPC_BAD_CONVERT_JS);
return;
}
RefPtr<nsISupports> result;
aError = aRequestor->GetInterface(*iid, getter_AddRefs(result));
if (aError.Failed()) {
return;
}
if (!WrapObject(aCx, result, iid.ptr(), aRetval)) {
aError.Throw(NS_ERROR_FAILURE);
}
}
bool ThrowingConstructor(JSContext* cx, unsigned argc, JS::Value* vp) {
return ThrowErrorMessage<MSG_ILLEGAL_CONSTRUCTOR>(cx, nullptr);
}
bool ThrowConstructorWithoutNew(JSContext* cx, const char* name) {
return ThrowErrorMessage<MSG_CONSTRUCTOR_WITHOUT_NEW>(cx, name);
}
inline const NativePropertyHooks* GetNativePropertyHooksFromConstructorFunction(
JS::Handle<JSObject*> obj) {
MOZ_ASSERT(JS_IsNativeFunction(obj, Constructor));
const JS::Value& v = js::GetFunctionNativeReserved(
obj, CONSTRUCTOR_NATIVE_HOLDER_RESERVED_SLOT);
const JSNativeHolder* nativeHolder =
static_cast<const JSNativeHolder*>(v.toPrivate());
return nativeHolder->mPropertyHooks;
}
inline const NativePropertyHooks* GetNativePropertyHooks(
JSContext* cx, JS::Handle<JSObject*> obj, DOMObjectType& type) {
const JSClass* clasp = JS::GetClass(obj);
const DOMJSClass* domClass = GetDOMClass(clasp);
if (domClass) {
bool isGlobal = (clasp->flags & JSCLASS_DOM_GLOBAL) != 0;
type = isGlobal ? eGlobalInstance : eInstance;
return domClass->mNativeHooks;
}
if (JS_ObjectIsFunction(obj)) {
type = eInterface;
return GetNativePropertyHooksFromConstructorFunction(obj);
}
MOZ_ASSERT(IsDOMIfaceAndProtoClass(JS::GetClass(obj)));
const DOMIfaceAndProtoJSClass* ifaceAndProtoJSClass =
DOMIfaceAndProtoJSClass::FromJSClass(JS::GetClass(obj));
type = ifaceAndProtoJSClass->mType;
return ifaceAndProtoJSClass->mNativeHooks;
}
static JSObject* XrayCreateFunction(JSContext* cx,
JS::Handle<JSObject*> wrapper,
JSNativeWrapper native, unsigned nargs,
JS::Handle<jsid> id) {
JSFunction* fun;
if (JSID_IS_STRING(id)) {
fun = js::NewFunctionByIdWithReserved(cx, native.op, nargs, 0, id);
} else {
// Can't pass this id (probably a symbol) to NewFunctionByIdWithReserved;
// just use an empty name for lack of anything better.
fun = js::NewFunctionWithReserved(cx, native.op, nargs, 0, nullptr);
}
if (!fun) {
return nullptr;
}
SET_JITINFO(fun, native.info);
JSObject* obj = JS_GetFunctionObject(fun);
js::SetFunctionNativeReserved(obj, XRAY_DOM_FUNCTION_PARENT_WRAPPER_SLOT,
JS::ObjectValue(*wrapper));
#ifdef DEBUG
js::SetFunctionNativeReserved(obj, XRAY_DOM_FUNCTION_NATIVE_SLOT_FOR_SELF,
JS::ObjectValue(*obj));
#endif
return obj;
}
struct IdToIndexComparator {
// The id we're searching for.
const jsid& mId;
// The list of ids we're searching in.
const PropertyInfo* mInfos;
explicit IdToIndexComparator(const jsid& aId, const PropertyInfo* aInfos)
: mId(aId), mInfos(aInfos) {}
int operator()(const uint16_t aIndex) const {
if (JSID_BITS(mId) == JSID_BITS(mInfos[aIndex].Id())) {
return 0;
}
return JSID_BITS(mId) < JSID_BITS(mInfos[aIndex].Id()) ? -1 : 1;
}
};
static const PropertyInfo* XrayFindOwnPropertyInfo(
JSContext* cx, JS::Handle<jsid> id,
const NativeProperties* nativeProperties) {
if (MOZ_UNLIKELY(nativeProperties->iteratorAliasMethodIndex >= 0) &&
id.isWellKnownSymbol(JS::SymbolCode::iterator)) {
return nativeProperties->MethodPropertyInfos() +
nativeProperties->iteratorAliasMethodIndex;
}
size_t idx;
const uint16_t* sortedPropertyIndices =
nativeProperties->sortedPropertyIndices;
const PropertyInfo* propertyInfos = nativeProperties->PropertyInfos();
if (BinarySearchIf(sortedPropertyIndices, 0,
nativeProperties->propertyInfoCount,
IdToIndexComparator(id, propertyInfos), &idx)) {
return propertyInfos + sortedPropertyIndices[idx];
}
return nullptr;
}
static bool XrayResolveAttribute(JSContext* cx, JS::Handle<JSObject*> wrapper,
JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
const Prefable<const JSPropertySpec>& pref,
const JSPropertySpec& attrSpec,
JS::MutableHandle<JS::PropertyDescriptor> desc,
bool& cacheOnHolder) {
if (!pref.isEnabled(cx, obj)) {
return true;
}
if (!attrSpec.isAccessor()) {
MOZ_ASSERT(id.isWellKnownSymbol(JS::SymbolCode::toStringTag));
desc.setAttributes(attrSpec.attributes());
desc.object().set(wrapper);
return attrSpec.getValue(cx, desc.value());
}
MOZ_ASSERT(
!attrSpec.isSelfHosted(),
"Bad JSPropertySpec declaration: unsupported self-hosted accessor");
cacheOnHolder = true;
// Because of centralization, we need to make sure we fault in the JitInfos as
// well. At present, until the JSAPI changes, the easiest way to do this is
// wrap them up as functions ourselves.
desc.setAttributes(attrSpec.attributes());
// They all have getters, so we can just make it.
JS::Rooted<JSObject*> funobj(
cx, XrayCreateFunction(cx, wrapper, attrSpec.u.accessors.getter.native, 0,
id));
if (!funobj) return false;
desc.setGetterObject(funobj);
desc.attributesRef() |= JSPROP_GETTER;
if (attrSpec.u.accessors.setter.native.op) {
// We have a setter! Make it.
funobj = XrayCreateFunction(cx, wrapper, attrSpec.u.accessors.setter.native,
1, id);
if (!funobj) return false;
desc.setSetterObject(funobj);
desc.attributesRef() |= JSPROP_SETTER;
} else {
desc.setSetter(nullptr);
}
desc.object().set(wrapper);
desc.value().setUndefined();
return true;
}
static bool XrayResolveMethod(JSContext* cx, JS::Handle<JSObject*> wrapper,
JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
const Prefable<const JSFunctionSpec>& pref,
const JSFunctionSpec& methodSpec,
JS::MutableHandle<JS::PropertyDescriptor> desc,
bool& cacheOnHolder) {
if (!pref.isEnabled(cx, obj)) {
return true;
}
cacheOnHolder = true;
JSObject* funobj;
if (methodSpec.selfHostedName) {
JSFunction* fun = JS::GetSelfHostedFunction(cx, methodSpec.selfHostedName,
id, methodSpec.nargs);
if (!fun) {
return false;
}
MOZ_ASSERT(!methodSpec.call.op,
"Bad FunctionSpec declaration: non-null native");
MOZ_ASSERT(!methodSpec.call.info,
"Bad FunctionSpec declaration: non-null jitinfo");
funobj = JS_GetFunctionObject(fun);
} else {
funobj =
XrayCreateFunction(cx, wrapper, methodSpec.call, methodSpec.nargs, id);
if (!funobj) {
return false;
}
}
desc.value().setObject(*funobj);
desc.setAttributes(methodSpec.flags);
desc.object().set(wrapper);
desc.setSetter(nullptr);
desc.setGetter(nullptr);
return true;
}
static bool XrayResolveConstant(JSContext* cx, JS::Handle<JSObject*> wrapper,
JS::Handle<JSObject*> obj, JS::Handle<jsid>,
const Prefable<const ConstantSpec>& pref,
const ConstantSpec& constantSpec,
JS::MutableHandle<JS::PropertyDescriptor> desc,
bool& cacheOnHolder) {
if (!pref.isEnabled(cx, obj)) {
return true;
}
cacheOnHolder = true;
desc.setAttributes(JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
desc.object().set(wrapper);
desc.value().set(constantSpec.value);
return true;
}
#define RESOLVE_CASE(PropType, SpecType, Resolver) \
case e##PropType: { \
MOZ_ASSERT(nativeProperties->Has##PropType##s()); \
const Prefable<const SpecType>& pref = \
nativeProperties->PropType##s()[propertyInfo.prefIndex]; \
return Resolver(cx, wrapper, obj, id, pref, \
pref.specs[propertyInfo.specIndex], desc, cacheOnHolder); \
}
static bool XrayResolveProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
JS::MutableHandle<JS::PropertyDescriptor> desc,
bool& cacheOnHolder, DOMObjectType type,
const NativeProperties* nativeProperties,
const PropertyInfo& propertyInfo) {
MOZ_ASSERT(type != eGlobalInterfacePrototype);
// Make sure we resolve for matched object type.
switch (propertyInfo.type) {
case eStaticMethod:
case eStaticAttribute:
if (type != eInterface) {
return true;
}
break;
case eMethod:
case eAttribute:
if (type != eGlobalInstance && type != eInterfacePrototype) {
return true;
}
break;
case eUnforgeableMethod:
case eUnforgeableAttribute:
if (!IsInstance(type)) {
return true;
}
break;
case eConstant:
if (IsInstance(type)) {
return true;
}
break;
}
switch (propertyInfo.type) {
RESOLVE_CASE(StaticMethod, JSFunctionSpec, XrayResolveMethod)
RESOLVE_CASE(StaticAttribute, JSPropertySpec, XrayResolveAttribute)
RESOLVE_CASE(Method, JSFunctionSpec, XrayResolveMethod)
RESOLVE_CASE(Attribute, JSPropertySpec, XrayResolveAttribute)
RESOLVE_CASE(UnforgeableMethod, JSFunctionSpec, XrayResolveMethod)
RESOLVE_CASE(UnforgeableAttribute, JSPropertySpec, XrayResolveAttribute)
RESOLVE_CASE(Constant, ConstantSpec, XrayResolveConstant)
}
return true;
}
#undef RESOLVE_CASE
static bool ResolvePrototypeOrConstructor(
JSContext* cx, JS::Handle<JSObject*> wrapper, JS::Handle<JSObject*> obj,
size_t protoAndIfaceCacheIndex, unsigned attrs,
JS::MutableHandle<JS::PropertyDescriptor> desc, bool& cacheOnHolder) {
JS::Rooted<JSObject*> global(cx, JS::GetNonCCWObjectGlobal(obj));
{
JSAutoRealm ar(cx, global);
ProtoAndIfaceCache& protoAndIfaceCache = *GetProtoAndIfaceCache(global);
// This function is called when resolving the "constructor" and "prototype"
// properties of Xrays for DOM prototypes and constructors respectively.
// This means the relevant Xray exists, which means its _target_ exists.
// And that means we managed to successfullly create the prototype or
// constructor, respectively, and hence must have managed to create the
// thing it's pointing to as well. So our entry slot must exist.
JSObject* protoOrIface =
protoAndIfaceCache.EntrySlotMustExist(protoAndIfaceCacheIndex);
MOZ_RELEASE_ASSERT(protoOrIface, "How can this object not exist?");
cacheOnHolder = true;
desc.object().set(wrapper);
desc.setAttributes(attrs);
desc.setGetter(nullptr);
desc.setSetter(nullptr);
desc.value().set(JS::ObjectValue(*protoOrIface));
}
return JS_WrapPropertyDescriptor(cx, desc);
}
/* static */ bool XrayResolveOwnProperty(
JSContext* cx, JS::Handle<JSObject*> wrapper, JS::Handle<JSObject*> obj,
JS::Handle<jsid> id, JS::MutableHandle<JS::PropertyDescriptor> desc,
bool& cacheOnHolder) {
cacheOnHolder = false;
DOMObjectType type;
const NativePropertyHooks* nativePropertyHooks =
GetNativePropertyHooks(cx, obj, type);
ResolveOwnProperty resolveOwnProperty =
nativePropertyHooks->mResolveOwnProperty;
if (type == eNamedPropertiesObject) {
MOZ_ASSERT(!resolveOwnProperty,
"Shouldn't have any Xray-visible properties");
return true;
}
const NativePropertiesHolder& nativePropertiesHolder =
nativePropertyHooks->mNativeProperties;
const NativeProperties* nativeProperties = nullptr;
const PropertyInfo* found = nullptr;
if ((nativeProperties = nativePropertiesHolder.regular)) {
found = XrayFindOwnPropertyInfo(cx, id, nativeProperties);
}
if (!found && (nativeProperties = nativePropertiesHolder.chromeOnly) &&
xpc::AccessCheck::isChrome(JS::GetCompartment(wrapper))) {
found = XrayFindOwnPropertyInfo(cx, id, nativeProperties);
}
if (IsInstance(type)) {
// Check for unforgeable properties first to prevent names provided by
// resolveOwnProperty callback from shadowing them.
if (found && (found->type == eUnforgeableMethod ||
found->type == eUnforgeableAttribute)) {
if (!XrayResolveProperty(cx, wrapper, obj, id, desc, cacheOnHolder, type,
nativeProperties, *found)) {
return false;
}
if (desc.object()) {
return true;
}
}
if (resolveOwnProperty) {
if (!resolveOwnProperty(cx, wrapper, obj, id, desc)) {
return false;
}
if (desc.object()) {
// None of these should be cached on the holder, since they're dynamic.
return true;
}
}
// For non-global instance Xrays there are no other properties, so return
// here for them.
if (type != eGlobalInstance) {
return true;
}
} else if (type == eInterface) {
if (id.get() == GetJSIDByIndex(cx, XPCJSContext::IDX_PROTOTYPE)) {
return nativePropertyHooks->mPrototypeID == prototypes::id::_ID_Count ||
ResolvePrototypeOrConstructor(
cx, wrapper, obj, nativePropertyHooks->mPrototypeID,
JSPROP_PERMANENT | JSPROP_READONLY, desc, cacheOnHolder);
}
if (id.get() == GetJSIDByIndex(cx, XPCJSContext::IDX_ISINSTANCE)) {
const JSClass* objClass = JS::GetClass(obj);
if (IsDOMIfaceAndProtoClass(objClass) &&
DOMIfaceAndProtoJSClass::FromJSClass(objClass)
->wantsInterfaceHasInstance) {
cacheOnHolder = true;
JSNativeWrapper interfaceIsInstanceWrapper = {InterfaceIsInstance,
nullptr};
JSObject* funObj =
XrayCreateFunction(cx, wrapper, interfaceIsInstanceWrapper, 1, id);
if (!funObj) {
return false;
}
desc.value().setObject(*funObj);
desc.setAttributes(0);
desc.object().set(wrapper);
desc.setSetter(nullptr);
desc.setGetter(nullptr);
return true;
}
}
if (id.isWellKnownSymbol(JS::SymbolCode::hasInstance)) {
const JSClass* objClass = JS::GetClass(obj);
if (IsDOMIfaceAndProtoClass(objClass) &&
DOMIfaceAndProtoJSClass::FromJSClass(objClass)
->wantsInterfaceHasInstance) {
cacheOnHolder = true;
JSNativeWrapper interfaceHasInstanceWrapper = {InterfaceHasInstance,
nullptr};
JSObject* funObj =
XrayCreateFunction(cx, wrapper, interfaceHasInstanceWrapper, 1, id);
if (!funObj) {
return false;
}
desc.value().setObject(*funObj);
desc.setAttributes(JSPROP_READONLY | JSPROP_PERMANENT);
desc.object().set(wrapper);
desc.setSetter(nullptr);
desc.setGetter(nullptr);
return true;
}
}
} else {
MOZ_ASSERT(IsInterfacePrototype(type));
if (id.get() == GetJSIDByIndex(cx, XPCJSContext::IDX_CONSTRUCTOR)) {
return nativePropertyHooks->mConstructorID ==
constructors::id::_ID_Count ||
ResolvePrototypeOrConstructor(cx, wrapper, obj,
nativePropertyHooks->mConstructorID,
0, desc, cacheOnHolder);
}
// The properties for globals live on the instance, so return here as there
// are no properties on their interface prototype object.
if (type == eGlobalInterfacePrototype) {
return true;
}
}
if (found && !XrayResolveProperty(cx, wrapper, obj, id, desc, cacheOnHolder,
type, nativeProperties, *found)) {
return false;
}
return true;
}
bool XrayDefineProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
JS::Handle<JS::PropertyDescriptor> desc,
JS::ObjectOpResult& result, bool* done) {
if (!js::IsProxy(obj)) return true;
const DOMProxyHandler* handler = GetDOMProxyHandler(obj);
return handler->defineProperty(cx, wrapper, id, desc, result, done);
}
template <typename SpecType>
bool XrayAppendPropertyKeys(JSContext* cx, JS::Handle<JSObject*> obj,
const Prefable<const SpecType>* pref,
const PropertyInfo* infos, unsigned flags,
JS::MutableHandleVector<jsid> props) {
do {
bool prefIsEnabled = pref->isEnabled(cx, obj);
if (prefIsEnabled) {
const SpecType* spec = pref->specs;
do {
const jsid id = infos++->Id();
if (((flags & JSITER_HIDDEN) ||
(spec->attributes() & JSPROP_ENUMERATE)) &&
((flags & JSITER_SYMBOLS) || !JSID_IS_SYMBOL(id)) &&
!props.append(id)) {
return false;
}
} while ((++spec)->name);
}
// Break if we have reached the end of pref.
if (!(++pref)->specs) {
break;
}
// Advance infos if the previous pref is disabled. The -1 is required
// because there is an end-of-list terminator between pref->specs and
// (pref - 1)->specs.
if (!prefIsEnabled) {
infos += pref->specs - (pref - 1)->specs - 1;
}
} while (1);
return true;
}
template <>
bool XrayAppendPropertyKeys<ConstantSpec>(
JSContext* cx, JS::Handle<JSObject*> obj,
const Prefable<const ConstantSpec>* pref, const PropertyInfo* infos,
unsigned flags, JS::MutableHandleVector<jsid> props) {
do {
bool prefIsEnabled = pref->isEnabled(cx, obj);
if (prefIsEnabled) {
const ConstantSpec* spec = pref->specs;
do {
if (!props.append(infos++->Id())) {
return false;
}
} while ((++spec)->name);
}
// Break if we have reached the end of pref.
if (!(++pref)->specs) {
break;
}
// Advance infos if the previous pref is disabled. The -1 is required
// because there is an end-of-list terminator between pref->specs and
// (pref - 1)->specs.
if (!prefIsEnabled) {
infos += pref->specs - (pref - 1)->specs - 1;
}
} while (1);
return true;
}
#define ADD_KEYS_IF_DEFINED(FieldName) \
{ \
if (nativeProperties->Has##FieldName##s() && \
!XrayAppendPropertyKeys(cx, obj, nativeProperties->FieldName##s(), \
nativeProperties->FieldName##PropertyInfos(), \
flags, props)) { \
return false; \
} \
}
bool XrayOwnPropertyKeys(JSContext* cx, JS::Handle<JSObject*> wrapper,
JS::Handle<JSObject*> obj, unsigned flags,
JS::MutableHandleVector<jsid> props,
DOMObjectType type,
const NativeProperties* nativeProperties) {
MOZ_ASSERT(type != eNamedPropertiesObject);
if (IsInstance(type)) {
ADD_KEYS_IF_DEFINED(UnforgeableMethod);
ADD_KEYS_IF_DEFINED(UnforgeableAttribute);
if (type == eGlobalInstance) {
ADD_KEYS_IF_DEFINED(Method);
ADD_KEYS_IF_DEFINED(Attribute);
}
} else {
MOZ_ASSERT(type != eGlobalInterfacePrototype);
if (type == eInterface) {
ADD_KEYS_IF_DEFINED(StaticMethod);
ADD_KEYS_IF_DEFINED(StaticAttribute);
} else {
MOZ_ASSERT(type == eInterfacePrototype);
ADD_KEYS_IF_DEFINED(Method);
ADD_KEYS_IF_DEFINED(Attribute);
}
ADD_KEYS_IF_DEFINED(Constant);
}
return true;
}
#undef ADD_KEYS_IF_DEFINED
bool XrayOwnNativePropertyKeys(JSContext* cx, JS::Handle<JSObject*> wrapper,
const NativePropertyHooks* nativePropertyHooks,
DOMObjectType type, JS::Handle<JSObject*> obj,
unsigned flags,
JS::MutableHandleVector<jsid> props) {
MOZ_ASSERT(type != eNamedPropertiesObject);
if (type == eInterface &&
nativePropertyHooks->mPrototypeID != prototypes::id::_ID_Count &&
!AddStringToIDVector(cx, props, "prototype")) {
return false;
}
if (IsInterfacePrototype(type) &&
nativePropertyHooks->mConstructorID != constructors::id::_ID_Count &&
(flags & JSITER_HIDDEN) &&
!AddStringToIDVector(cx, props, "constructor")) {
return false;
}
const NativePropertiesHolder& nativeProperties =
nativePropertyHooks->mNativeProperties;
if (nativeProperties.regular &&
!XrayOwnPropertyKeys(cx, wrapper, obj, flags, props, type,
nativeProperties.regular)) {
return false;
}
if (nativeProperties.chromeOnly &&
xpc::AccessCheck::isChrome(JS::GetCompartment(wrapper)) &&
!XrayOwnPropertyKeys(cx, wrapper, obj, flags, props, type,
nativeProperties.chromeOnly)) {
return false;
}
return true;
}
bool XrayOwnPropertyKeys(JSContext* cx, JS::Handle<JSObject*> wrapper,
JS::Handle<JSObject*> obj, unsigned flags,
JS::MutableHandleVector<jsid> props) {
DOMObjectType type;
const NativePropertyHooks* nativePropertyHooks =
GetNativePropertyHooks(cx, obj, type);
EnumerateOwnProperties enumerateOwnProperties =
nativePropertyHooks->mEnumerateOwnProperties;
if (type == eNamedPropertiesObject) {
MOZ_ASSERT(!enumerateOwnProperties,
"Shouldn't have any Xray-visible properties");
return true;
}
if (IsInstance(type)) {
// FIXME https://bugzilla.mozilla.org/show_bug.cgi?id=1071189
// Should do something about XBL properties too.
if (enumerateOwnProperties &&
!enumerateOwnProperties(cx, wrapper, obj, props)) {
return false;
}
}
return type == eGlobalInterfacePrototype ||
XrayOwnNativePropertyKeys(cx, wrapper, nativePropertyHooks, type, obj,
flags, props);
}
const JSClass* XrayGetExpandoClass(JSContext* cx, JS::Handle<JSObject*> obj) {
DOMObjectType type;
const NativePropertyHooks* nativePropertyHooks =
GetNativePropertyHooks(cx, obj, type);
if (!IsInstance(type)) {
// Non-instances don't need any special expando classes.
return &DefaultXrayExpandoObjectClass;
}
return nativePropertyHooks->mXrayExpandoClass;
}
bool XrayDeleteNamedProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
JS::ObjectOpResult& opresult) {
DOMObjectType type;
const NativePropertyHooks* nativePropertyHooks =
GetNativePropertyHooks(cx, obj, type);
if (!IsInstance(type) || !nativePropertyHooks->mDeleteNamedProperty) {
return opresult.succeed();
}
return nativePropertyHooks->mDeleteNamedProperty(cx, wrapper, obj, id,
opresult);
}
JSObject* GetCachedSlotStorageObjectSlow(JSContext* cx,
JS::Handle<JSObject*> obj,
bool* isXray) {
if (!xpc::WrapperFactory::IsXrayWrapper(obj)) {
JSObject* retval =
js::UncheckedUnwrap(obj, /* stopAtWindowProxy = */ false);
MOZ_ASSERT(IsDOMObject(retval));
*isXray = false;
return retval;
}
*isXray = true;
return xpc::EnsureXrayExpandoObject(cx, obj);
}
DEFINE_XRAY_EXPANDO_CLASS(, DefaultXrayExpandoObjectClass, 0);
NativePropertyHooks sEmptyNativePropertyHooks = {nullptr,
nullptr,
nullptr,
{nullptr, nullptr},
prototypes::id::_ID_Count,
constructors::id::_ID_Count,
nullptr};
const JSClassOps sBoringInterfaceObjectClassClassOps = {
nullptr, /* addProperty */
nullptr, /* delProperty */
nullptr, /* enumerate */
nullptr, /* newEnumerate */
nullptr, /* resolve */
nullptr, /* mayResolve */
nullptr, /* finalize */
ThrowingConstructor, /* call */
nullptr, /* hasInstance */
ThrowingConstructor, /* construct */
nullptr, /* trace */
};
const js::ObjectOps sInterfaceObjectClassObjectOps = {
nullptr, /* lookupProperty */
nullptr, /* defineProperty */
nullptr, /* hasProperty */
nullptr, /* getProperty */
nullptr, /* setProperty */
nullptr, /* getOwnPropertyDescriptor */
nullptr, /* deleteProperty */
nullptr, /* getElements */
InterfaceObjectToString, /* funToString */
};
bool GetPropertyOnPrototype(JSContext* cx, JS::Handle<JSObject*> proxy,
JS::Handle<JS::Value> receiver, JS::Handle<jsid> id,
bool* found, JS::MutableHandle<JS::Value> vp) {
JS::Rooted<JSObject*> proto(cx);
if (!js::GetObjectProto(cx, proxy, &proto)) {
return false;
}
if (!proto) {
*found = false;
return true;
}
if (!JS_HasPropertyById(cx, proto, id, found)) {
return false;
}
if (!*found) {
return true;
}
return JS_ForwardGetPropertyTo(cx, proto, id, receiver, vp);
}
bool HasPropertyOnPrototype(JSContext* cx, JS::Handle<JSObject*> proxy,
JS::Handle<jsid> id, bool* has) {
JS::Rooted<JSObject*> proto(cx);
if (!js::GetObjectProto(cx, proxy, &proto)) {
return false;
}
if (!proto) {
*has = false;
return true;
}
return JS_HasPropertyById(cx, proto, id, has);
}
bool AppendNamedPropertyIds(JSContext* cx, JS::Handle<JSObject*> proxy,
nsTArray<nsString>& names,
bool shadowPrototypeProperties,
JS::MutableHandleVector<jsid> props) {
for (uint32_t i = 0; i < names.Length(); ++i) {
JS::Rooted<JS::Value> v(cx);
if (!xpc::NonVoidStringToJsval(cx, names[i], &v)) {
return false;
}
JS::Rooted<jsid> id(cx);
if (!JS_ValueToId(cx, v, &id)) {
return false;
}
bool shouldAppend = shadowPrototypeProperties;
if (!shouldAppend) {
bool has;
if (!HasPropertyOnPrototype(cx, proxy, id, &has)) {
return false;
}
shouldAppend = !has;
}
if (shouldAppend) {
if (!props.append(id)) {
return false;
}
}
}
return true;
}
bool DictionaryBase::ParseJSON(JSContext* aCx, const nsAString& aJSON,
JS::MutableHandle<JS::Value> aVal) {
if (aJSON.IsEmpty()) {
return true;
}
return JS_ParseJSON(aCx, aJSON.BeginReading(), aJSON.Length(), aVal);
}
bool DictionaryBase::StringifyToJSON(JSContext* aCx, JS::Handle<JSObject*> aObj,
nsAString& aJSON) const {
return JS::ToJSONMaybeSafely(aCx, aObj, AppendJSONToString, &aJSON);
}
/* static */
bool DictionaryBase::AppendJSONToString(const char16_t* aJSONData,
uint32_t aDataLength, void* aString) {
nsAString* string = static_cast<nsAString*>(aString);
string->Append(aJSONData, aDataLength);
return true;
}
void UpdateReflectorGlobal(JSContext* aCx, JS::Handle<JSObject*> aObjArg,
ErrorResult& aError) {
js::AssertSameCompartment(aCx, aObjArg);
aError.MightThrowJSException();
// Check if we're anywhere near the stack limit before we reach the
// transplanting code, since it has no good way to handle errors. This uses
// the untrusted script limit, which is not strictly necessary since no
// actual script should run.
if (!js::CheckRecursionLimitConservative(aCx)) {
aError.StealExceptionFromJSContext(aCx);
return;
}
JS::Rooted<JSObject*> aObj(aCx, aObjArg);
MOZ_ASSERT(IsDOMObject(aObj));
const DOMJSClass* domClass = GetDOMClass(aObj);
JS::Rooted<JSObject*> oldGlobal(aCx, JS::GetNonCCWObjectGlobal(aObj));
MOZ_ASSERT(JS_IsGlobalObject(oldGlobal));
JS::Rooted<JSObject*> newGlobal(aCx,
domClass->mGetAssociatedGlobal(aCx, aObj));
MOZ_ASSERT(JS_IsGlobalObject(newGlobal));
JSAutoRealm oldAr(aCx, oldGlobal);
if (oldGlobal == newGlobal) {
return;
}
nsISupports* native = UnwrapDOMObjectToISupports(aObj);
if (!native) {
return;
}
bool isProxy = js::IsProxy(aObj);
JS::Rooted<JSObject*> expandoObject(aCx);
if (isProxy) {
expandoObject = DOMProxyHandler::GetAndClearExpandoObject(aObj);
}
JSAutoRealm newAr(aCx, newGlobal);
// First we clone the reflector. We get a copy of its properties and clone its
// expando chain.
JS::Handle<JSObject*> proto = (domClass->mGetProto)(aCx);
if (!proto) {
aError.StealExceptionFromJSContext(aCx);
return;
}
JS::Rooted<JSObject*> newobj(aCx, JS_CloneObject(aCx, aObj, proto));
if (!newobj) {
aError.StealExceptionFromJSContext(aCx);
return;
}
// Assert it's possible to create wrappers when |aObj| and |newobj| are in
// different compartments.
MOZ_ASSERT_IF(JS::GetCompartment(aObj) != JS::GetCompartment(newobj),
js::AllowNewWrapper(JS::GetCompartment(aObj), newobj));
JS::Rooted<JSObject*> propertyHolder(aCx);
JS::Rooted<JSObject*> copyFrom(aCx, isProxy ? expandoObject : aObj);
if (copyFrom) {
propertyHolder = JS_NewObjectWithGivenProto(aCx, nullptr, nullptr);
if (!propertyHolder) {
aError.StealExceptionFromJSContext(aCx);
return;
}
if (!JS_CopyOwnPropertiesAndPrivateFields(aCx, propertyHolder, copyFrom)) {
aError.StealExceptionFromJSContext(aCx);
return;
}
} else {
propertyHolder = nullptr;
}
// We've set up |newobj|, so we make it own the native by setting its reserved
// slot and nulling out the reserved slot of |obj|.
//
// NB: It's important to do this _after_ copying the properties to
// propertyHolder. Otherwise, an object with |foo.x === foo| will
// crash when JS_CopyOwnPropertiesAndPrivateFields tries to call wrap() on
// foo.x.
JS::SetReservedSlot(newobj, DOM_OBJECT_SLOT,
JS::GetReservedSlot(aObj, DOM_OBJECT_SLOT));
JS::SetReservedSlot(aObj, DOM_OBJECT_SLOT, JS::PrivateValue(nullptr));
aObj = xpc::TransplantObjectRetainingXrayExpandos(aCx, aObj, newobj);
if (!aObj) {
MOZ_CRASH();
}
nsWrapperCache* cache = nullptr;
CallQueryInterface(native, &cache);
cache->UpdateWrapperForNewGlobal(native, aObj);
if (propertyHolder) {
JS::Rooted<JSObject*> copyTo(aCx);
if (isProxy) {
copyTo = DOMProxyHandler::EnsureExpandoObject(aCx, aObj);
} else {
copyTo = aObj;
}
if (!copyTo ||
!JS_CopyOwnPropertiesAndPrivateFields(aCx, copyTo, propertyHolder)) {
MOZ_CRASH();
}
}
JS::Rooted<JSObject*> maybeObjLC(aCx, aObj);
nsObjectLoadingContent* htmlobject;
nsresult rv = UNWRAP_OBJECT(HTMLObjectElement, &maybeObjLC, htmlobject);
if (NS_FAILED(rv)) {
rv = UNWRAP_OBJECT(HTMLEmbedElement, &maybeObjLC, htmlobject);
if (NS_FAILED(rv)) {
htmlobject = nullptr;
}
}
if (htmlobject) {
htmlobject->SetupProtoChain(aCx, aObj);
}
}
GlobalObject::GlobalObject(JSContext* aCx, JSObject* aObject)
: mGlobalJSObject(aCx), mCx(aCx), mGlobalObject(nullptr) {
MOZ_ASSERT(mCx);
JS::Rooted<JSObject*> obj(aCx, aObject);
if (js::IsWrapper(obj)) {
// aCx correctly represents the current global here.
obj = js::CheckedUnwrapDynamic(obj, aCx, /* stopAtWindowProxy = */ false);
if (!obj) {
// We should never end up here on a worker thread, since there shouldn't
// be any security wrappers to worry about.
if (!MOZ_LIKELY(NS_IsMainThread())) {
MOZ_CRASH();
}
Throw(aCx, NS_ERROR_XPC_SECURITY_MANAGER_VETO);
return;
}
}
mGlobalJSObject = JS::GetNonCCWObjectGlobal(obj);
}
nsISupports* GlobalObject::GetAsSupports() const {
if (mGlobalObject) {
return mGlobalObject;
}
MOZ_ASSERT(!js::IsWrapper(mGlobalJSObject));
// Most of our globals are DOM objects. Try that first. Note that this
// assumes that either the first nsISupports in the object is the canonical
// one or that we don't care about the canonical nsISupports here.
mGlobalObject = UnwrapDOMObjectToISupports(mGlobalJSObject);
if (mGlobalObject) {
return mGlobalObject;
}
MOZ_ASSERT(NS_IsMainThread(), "All our worker globals are DOM objects");
// Remove everything below here once all our global objects are using new
// bindings. If that ever happens; it would need to include Sandbox and
// BackstagePass.
// See whether mGlobalJSObject is an XPCWrappedNative. This will redo the
// IsWrapper bit above and the UnwrapDOMObjectToISupports in the case when
// we're not actually an XPCWrappedNative, but this should be a rare-ish case
// anyway.
//
// It's OK to use ReflectorToISupportsStatic, because we know we don't have a
// cross-compartment wrapper.
nsCOMPtr<nsISupports> supp = xpc::ReflectorToISupportsStatic(mGlobalJSObject);
if (supp) {
// See documentation for mGlobalJSObject for why this assignment is OK.
mGlobalObject = supp;
return mGlobalObject;
}
// And now a final hack. Sandbox is not a reflector, but it does have an
// nsIGlobalObject hanging out in its private slot. Handle that case here,
// (though again, this will do the useless UnwrapDOMObjectToISupports if we
// got here for something that is somehow not a DOM object, not an
// XPCWrappedNative _and_ not a Sandbox).
if (XPCConvert::GetISupportsFromJSObject(mGlobalJSObject, &mGlobalObject)) {
return mGlobalObject;
}
MOZ_ASSERT(!mGlobalObject);
Throw(mCx, NS_ERROR_XPC_BAD_CONVERT_JS);
return nullptr;
}
nsIPrincipal* GlobalObject::GetSubjectPrincipal() const {
if (!NS_IsMainThread()) {
return nullptr;
}
JS::Realm* realm = js::GetContextRealm(mCx);
MOZ_ASSERT(realm);
JSPrincipals* principals = JS::GetRealmPrincipals(realm);
return nsJSPrincipals::get(principals);
}
CallerType GlobalObject::CallerType() const {
return nsContentUtils::ThreadsafeIsSystemCaller(mCx)
? dom::CallerType::System
: dom::CallerType::NonSystem;
}
static bool CallOrdinaryHasInstance(JSContext* cx, JS::CallArgs& args) {
JS::Rooted<JSObject*> thisObj(cx, &args.thisv().toObject());
bool isInstance;
if (!JS::OrdinaryHasInstance(cx, thisObj, args.get(0), &isInstance)) {
return false;
}
args.rval().setBoolean(isInstance);
return true;
}
bool InterfaceHasInstance(JSContext* cx, unsigned argc, JS::Value* vp) {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
// If the thing we were passed is not an object, return false like
// OrdinaryHasInstance does.
if (!args.get(0).isObject()) {
args.rval().setBoolean(false);
return true;
}
// If "this" is not an object, likewise return false (again, like
// OrdinaryHasInstance).
if (!args.thisv().isObject()) {
args.rval().setBoolean(false);
return true;
}
// If "this" doesn't have a DOMIfaceAndProtoJSClass, it's not a DOM
// constructor, so just fall back to OrdinaryHasInstance. But note that we
// should CheckedUnwrapStatic here, because otherwise we won't get the right
// answers. The static version is OK, because we're looking for DOM
// constructors, which are not cross-origin objects.
JS::Rooted<JSObject*> thisObj(
cx, js::CheckedUnwrapStatic(&args.thisv().toObject()));
if (!thisObj) {
// Just fall back on the normal thing, in case it still happens to work.
return CallOrdinaryHasInstance(cx, args);
}
const JSClass* thisClass = JS::GetClass(thisObj);
if (!IsDOMIfaceAndProtoClass(thisClass)) {
return CallOrdinaryHasInstance(cx, args);
}
const DOMIfaceAndProtoJSClass* clasp =
DOMIfaceAndProtoJSClass::FromJSClass(thisClass);
// If "this" isn't a DOM constructor or is a constructor for an interface
// without a prototype, just fall back to OrdinaryHasInstance.
if (clasp->mType != eInterface ||
clasp->mPrototypeID == prototypes::id::_ID_Count) {
return CallOrdinaryHasInstance(cx, args);
}
JS::Rooted<JSObject*> instance(cx, &args[0].toObject());
const DOMJSClass* domClass = GetDOMClass(
js::UncheckedUnwrap(instance, /* stopAtWindowProxy = */ false));
if (domClass &&
domClass->mInterfaceChain[clasp->mDepth] == clasp->mPrototypeID) {
args.rval().setBoolean(true);
return true;
}
if (IsRemoteObjectProxy(instance, clasp->mPrototypeID)) {
args.rval().setBoolean(true);
return true;
}
return CallOrdinaryHasInstance(cx, args);
}
bool InterfaceHasInstance(JSContext* cx, int prototypeID, int depth,
JS::Handle<JSObject*> instance, bool* bp) {
const DOMJSClass* domClass = GetDOMClass(js::UncheckedUnwrap(instance));
MOZ_ASSERT(!domClass || prototypeID != prototypes::id::_ID_Count,
"Why do we have a hasInstance hook if we don't have a prototype "
"ID?");
*bp = (domClass && domClass->mInterfaceChain[depth] == prototypeID);
return true;
}
bool InterfaceIsInstance(JSContext* cx, unsigned argc, JS::Value* vp) {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
// If the thing we were passed is not an object, return false.
if (!args.get(0).isObject()) {
args.rval().setBoolean(false);
return true;
}
// If "this" isn't a DOM constructor or is a constructor for an interface
// without a prototype, return false.
if (!args.thisv().isObject()) {
args.rval().setBoolean(false);
return true;
}
// CheckedUnwrapStatic is fine, since we're just interested in finding out
// whether this is a DOM constructor.
JS::Rooted<JSObject*> thisObj(
cx, js::CheckedUnwrapStatic(&args.thisv().toObject()));
if (!thisObj) {
args.rval().setBoolean(false);
return true;
}
const JSClass* thisClass = JS::GetClass(thisObj);
if (!IsDOMIfaceAndProtoClass(thisClass)) {
args.rval().setBoolean(false);
return true;
}
const DOMIfaceAndProtoJSClass* clasp =
DOMIfaceAndProtoJSClass::FromJSClass(thisClass);
if (clasp->mType != eInterface ||
clasp->mPrototypeID == prototypes::id::_ID_Count) {
args.rval().setBoolean(false);
return true;
}
JS::Rooted<JSObject*> instance(cx, &args[0].toObject());
const DOMJSClass* domClass = GetDOMClass(
js::UncheckedUnwrap(instance, /* stopAtWindowProxy = */ false));
bool isInstance = domClass && domClass->mInterfaceChain[clasp->mDepth] ==
clasp->mPrototypeID;
args.rval().setBoolean(isInstance);
return true;
}
bool ReportLenientThisUnwrappingFailure(JSContext* cx, JSObject* obj) {
JS::Rooted<JSObject*> rootedObj(cx, obj);
GlobalObject global(cx, rootedObj);
if (global.Failed()) {
return false;
}
nsCOMPtr<nsPIDOMWindowInner> window =
do_QueryInterface(global.GetAsSupports());
if (window && window->GetDoc()) {
window->GetDoc()->WarnOnceAbout(DeprecatedOperations::eLenientThis);
}
return true;
}
bool GetContentGlobalForJSImplementedObject(BindingCallContext& cx,
JS::Handle<JSObject*> obj,
nsIGlobalObject** globalObj) {
// Be very careful to not get tricked here.
MOZ_ASSERT(NS_IsMainThread());
if (!xpc::AccessCheck::isChrome(JS::GetCompartment(obj))) {
MOZ_CRASH("Should have a chrome object here");
}
// Look up the content-side object.
JS::Rooted<JS::Value> domImplVal(cx);
if (!JS_GetProperty(cx, obj, "__DOM_IMPL__", &domImplVal)) {
return false;
}
if (!domImplVal.isObject()) {
cx.ThrowErrorMessage<MSG_NOT_OBJECT>("Value");
return false;
}
// Go ahead and get the global from it. GlobalObject will handle
// doing unwrapping as needed.
GlobalObject global(cx, &domImplVal.toObject());
if (global.Failed()) {
return false;
}
DebugOnly<nsresult> rv =
CallQueryInterface(global.GetAsSupports(), globalObj);
MOZ_ASSERT(NS_SUCCEEDED(rv));
MOZ_ASSERT(*globalObj);
return true;
}
void ConstructJSImplementation(const char* aContractId,
nsIGlobalObject* aGlobal,
JS::MutableHandle<JSObject*> aObject,
ErrorResult& aRv) {
MOZ_ASSERT(NS_IsMainThread());
// Make sure to divorce ourselves from the calling JS while creating and
// initializing the object, so exceptions from that will get reported
// properly, since those are never exceptions that a spec wants to be thrown.
{
AutoNoJSAPI nojsapi;
nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(aGlobal);
if (!window->IsCurrentInnerWindow()) {
aRv.ThrowInvalidStateError("Window no longer active");
return;
}
// Get the XPCOM component containing the JS implementation.
nsresult rv;
nsCOMPtr<nsISupports> implISupports = do_CreateInstance(aContractId, &rv);
if (!implISupports) {
nsPrintfCString msg("Failed to get JS implementation for contract \"%s\"",
aContractId);
NS_WARNING(msg.get());
aRv.Throw(rv);
return;
}
// Initialize the object, if it implements nsIDOMGlobalPropertyInitializer
// and our global is a window.
nsCOMPtr<nsIDOMGlobalPropertyInitializer> gpi =
do_QueryInterface(implISupports);
if (gpi) {
JS::Rooted<JS::Value> initReturn(RootingCx());
rv = gpi->Init(window, &initReturn);
if (NS_FAILED(rv)) {
aRv.Throw(rv);
return;
}
// With JS-implemented WebIDL, the return value of init() is not used to
// determine if init() failed, so init() should only return undefined. Any
// kind of permission or pref checking must happen by adding an attribute
// to the WebIDL interface.
if (!initReturn.isUndefined()) {
MOZ_ASSERT(false,
"The init() method for JS-implemented WebIDL should not "
"return anything");
MOZ_CRASH();
}
}
// Extract the JS implementation from the XPCOM object.
nsCOMPtr<nsIXPConnectWrappedJS> implWrapped =
do_QueryInterface(implISupports, &rv);
MOZ_ASSERT(implWrapped, "Failed to get wrapped JS from XPCOM component.");
if (!implWrapped) {
aRv.Throw(rv);
return;
}
aObject.set(implWrapped->GetJSObject());
if (!aObject) {
aRv.Throw(NS_ERROR_FAILURE);
}
}
}
bool NonVoidByteStringToJsval(JSContext* cx, const nsACString& str,
JS::MutableHandle<JS::Value> rval) {
// ByteStrings are not UTF-8 encoded.
JSString* jsStr = JS_NewStringCopyN(cx, str.Data(), str.Length());
if (!jsStr) {
return false;
}
rval.setString(jsStr);
return true;
}
bool NormalizeUSVString(nsAString& aString) {
return EnsureUTF16Validity(aString);
}
bool NormalizeUSVString(binding_detail::FakeString<char16_t>& aString) {
uint32_t upTo = Utf16ValidUpTo(aString);
uint32_t len = aString.Length();
if (upTo == len) {
return true;
}
// This is the part that's different from EnsureUTF16Validity with an
// nsAString& argument, because we don't want to ensure mutability in our
// BeginWriting() in the common case and nsAString's EnsureMutable is not
// public. This is a little annoying; I wish we could just share the more or
// less identical code!
if (!aString.EnsureMutable()) {
return false;
}
char16_t* ptr = aString.BeginWriting();
auto span = Span(ptr, len);
span[upTo] = 0xFFFD;
EnsureUtf16ValiditySpan(span.From(upTo + 1));
return true;
}
bool ConvertJSValueToByteString(BindingCallContext& cx, JS::Handle<JS::Value> v,
bool nullable, const char* sourceDescription,
nsACString& result) {
JS::Rooted<JSString*> s(cx);
if (v.isString()) {
s = v.toString();
} else {
if (nullable && v.isNullOrUndefined()) {
result.SetIsVoid(true);
return true;
}
s = JS::ToString(cx, v);
if (!s) {
return false;
}
}
// Conversion from Javascript string to ByteString is only valid if all
// characters < 256. This is always the case for Latin1 strings.
size_t length;
if (!JS::StringHasLatin1Chars(s)) {
// ThrowErrorMessage can GC, so we first scan the string for bad chars
// and report the error outside the AutoCheckCannotGC scope.
bool foundBadChar = false;
size_t badCharIndex;
char16_t badChar;
{
JS::AutoCheckCannotGC nogc;
const char16_t* chars =
JS_GetTwoByteStringCharsAndLength(cx, nogc, s, &length);
if (!chars) {
return false;
}
for (size_t i = 0; i < length; i++) {
if (chars[i] > 255) {
badCharIndex = i;
badChar = chars[i];
foundBadChar = true;
break;
}
}
}
if (foundBadChar) {
MOZ_ASSERT(badCharIndex < length);
MOZ_ASSERT(badChar > 255);
// The largest unsigned 64 bit number (18,446,744,073,709,551,615) has
// 20 digits, plus one more for the null terminator.
char index[21];
static_assert(sizeof(size_t) <= 8, "index array too small");
SprintfLiteral(index, "%zu", badCharIndex);
// A char16_t is 16 bits long. The biggest unsigned 16 bit
// number (65,535) has 5 digits, plus one more for the null
// terminator.
char badCharArray[6];
static_assert(sizeof(char16_t) <= 2, "badCharArray too small");
SprintfLiteral(badCharArray, "%d", badChar);
cx.ThrowErrorMessage<MSG_INVALID_BYTESTRING>(sourceDescription, index,
badCharArray);
return false;
}
} else {
length = JS::GetStringLength(s);
}
static_assert(JS::MaxStringLength < UINT32_MAX,
"length+1 shouldn't overflow");
if (!result.SetLength(length, fallible)) {
return false;
}
if (!JS_EncodeStringToBuffer(cx, s, result.BeginWriting(), length)) {
return false;
}
return true;
}
void FinalizeGlobal(JSFreeOp* aFreeOp, JSObject* aObj) {
MOZ_ASSERT(JS::GetClass(aObj)->flags & JSCLASS_DOM_GLOBAL);
mozilla::dom::DestroyProtoAndIfaceCache(aObj);
}
bool ResolveGlobal(JSContext* aCx, JS::Handle<JSObject*> aObj,
JS::Handle<jsid> aId, bool* aResolvedp) {
MOZ_ASSERT(JS_IsGlobalObject(aObj),
"Should have a global here, since we plan to resolve standard "
"classes!");
return JS_ResolveStandardClass(aCx, aObj, aId, aResolvedp);
}
bool MayResolveGlobal(const JSAtomState& aNames, jsid aId,
JSObject* aMaybeObj) {
return JS_MayResolveStandardClass(aNames, aId, aMaybeObj);
}
bool EnumerateGlobal(JSContext* aCx, JS::HandleObject aObj,
JS::MutableHandleVector<jsid> aProperties,
bool aEnumerableOnly) {
MOZ_ASSERT(JS_IsGlobalObject(aObj),
"Should have a global here, since we plan to enumerate standard "
"classes!");
return JS_NewEnumerateStandardClasses(aCx, aObj, aProperties,
aEnumerableOnly);
}
bool IsNonExposedGlobal(JSContext* aCx, JSObject* aGlobal,
uint32_t aNonExposedGlobals) {
MOZ_ASSERT(aNonExposedGlobals, "Why did we get called?");
MOZ_ASSERT(
(aNonExposedGlobals & ~(GlobalNames::Window | GlobalNames::BackstagePass |
GlobalNames::DedicatedWorkerGlobalScope |
GlobalNames::SharedWorkerGlobalScope |
GlobalNames::ServiceWorkerGlobalScope |
GlobalNames::WorkerDebuggerGlobalScope |
GlobalNames::WorkletGlobalScope |
GlobalNames::AudioWorkletGlobalScope)) == 0,
"Unknown non-exposed global type");
const char* name = JS::GetClass(aGlobal)->name;
if ((aNonExposedGlobals & GlobalNames::Window) && !strcmp(name, "Window")) {
return true;
}
if ((aNonExposedGlobals & GlobalNames::BackstagePass) &&
!strcmp(name, "BackstagePass")) {
return true;
}
if ((aNonExposedGlobals & GlobalNames::DedicatedWorkerGlobalScope) &&
!strcmp(name, "DedicatedWorkerGlobalScope")) {
return true;
}
if ((aNonExposedGlobals & GlobalNames::SharedWorkerGlobalScope) &&
!strcmp(name, "SharedWorkerGlobalScope")) {
return true;
}
if ((aNonExposedGlobals & GlobalNames::ServiceWorkerGlobalScope) &&
!strcmp(name, "ServiceWorkerGlobalScope")) {
return true;
}
if ((aNonExposedGlobals & GlobalNames::WorkerDebuggerGlobalScope) &&
!strcmp(name, "WorkerDebuggerGlobalScopex")) {
return true;
}
if ((aNonExposedGlobals & GlobalNames::WorkletGlobalScope) &&
!strcmp(name, "WorkletGlobalScope")) {
return true;
}
if ((aNonExposedGlobals & GlobalNames::AudioWorkletGlobalScope) &&
!strcmp(name, "AudioWorkletGlobalScope")) {
return true;
}
return false;
}
namespace binding_detail {
/**
* A ThisPolicy struct needs to provide the following methods:
*
* HasValidThisValue: Takes a CallArgs and returns a boolean indicating whether
* the thisv() is valid in the sense of being the right type
* of Value. It does not check whether it's the right sort
* of object if the Value is a JSObject*.
*
* ExtractThisObject: Takes a CallArgs for which HasValidThisValue was true and
* returns the JSObject* to use for getting |this|.
*
* MaybeUnwrapThisObject: If our |this| is a JSObject* that this policy wants to
* allow unchecked access to for this
* getter/setter/method, unwrap it. Otherwise just
* return the given object.
*
* UnwrapThisObject: Takes a MutableHandle for a JSObject which contains the
* this object (which the caller probably got from
* MaybeUnwrapThisObject). It will try to get the right native
* out of aObj. In some cases there are 2 possible types for
* the native (which is why aSelf is a reference to a void*).
* The ThisPolicy user should use the this JSObject* to
* determine what C++ class aSelf contains. aObj is used to
* keep the reflector object alive while self is being used,
* so its value before and after the UnwrapThisObject call
* could be different (if aObj was wrapped). The return value
* is an nsresult, which will signal if an error occurred.
*
* This is passed a JSContext for dynamic unwrapping purposes,
* but should not throw exceptions on that JSContext.
*
* HandleInvalidThis: If the |this| is not valid (wrong type of value, wrong
* object, etc), decide what to do about it. Returns a
* boolean to return from the JSNative (false for failure,
* true for succcess).
*/
struct NormalThisPolicy {
// This needs to be inlined because it's called on no-exceptions fast-paths.
static MOZ_ALWAYS_INLINE bool HasValidThisValue(const JS::CallArgs& aArgs) {
// Per WebIDL spec, all getters/setters/methods allow null/undefined "this"
// and coerce it to the global. Then the "is this the right interface?"
// check fails if the interface involved is not one that the global
// implements.
//
// As an optimization, we skip doing the null/undefined stuff if we know our
// interface is not implemented by the global.
return aArgs.thisv().isObject();
}
static MOZ_ALWAYS_INLINE JSObject* ExtractThisObject(
const JS::CallArgs& aArgs) {
return &aArgs.thisv().toObject();
}
static MOZ_ALWAYS_INLINE JSObject* MaybeUnwrapThisObject(JSObject* aObj) {
return aObj;
}
static MOZ_ALWAYS_INLINE nsresult UnwrapThisObject(
JS::MutableHandle<JSObject*> aObj, JSContext* aCx, void*& aSelf,
prototypes::ID aProtoID, uint32_t aProtoDepth) {
binding_detail::MutableObjectHandleWrapper wrapper(aObj);
return binding_detail::UnwrapObjectInternal<void, true>(
wrapper, aSelf, aProtoID, aProtoDepth, aCx);
}
static bool HandleInvalidThis(JSContext* aCx, const JS::CallArgs& aArgs,
bool aSecurityError, prototypes::ID aProtoId) {
return ThrowInvalidThis(aCx, aArgs, aSecurityError, aProtoId);
}
};
struct MaybeGlobalThisPolicy : public NormalThisPolicy {
static MOZ_ALWAYS_INLINE bool HasValidThisValue(const JS::CallArgs& aArgs) {
// Here we have to allow null/undefined.
return aArgs.thisv().isObject() || aArgs.thisv().isNullOrUndefined();
}
static MOZ_ALWAYS_INLINE JSObject* ExtractThisObject(
const JS::CallArgs& aArgs) {
return aArgs.thisv().isObject()
? &aArgs.thisv().toObject()
: JS::GetNonCCWObjectGlobal(&aArgs.callee());
}
// We want the MaybeUnwrapThisObject of NormalThisPolicy.
// We want the HandleInvalidThis of NormalThisPolicy.
};
// Shared LenientThis behavior for our two different LenientThis policies.
struct LenientThisPolicyMixin {
static bool HandleInvalidThis(JSContext* aCx, const JS::CallArgs& aArgs,
bool aSecurityError, prototypes::ID aProtoId) {
if (aSecurityError) {
return NormalThisPolicy::HandleInvalidThis(aCx, aArgs, aSecurityError,
aProtoId);
}
MOZ_ASSERT(!JS_IsExceptionPending(aCx));
if (!ReportLenientThisUnwrappingFailure(aCx, &aArgs.callee())) {
return false;
}
aArgs.rval().set(JS::UndefinedValue());
return true;
}
};
// There are some LenientThis things on globals, so we inherit from
// MaybeGlobalThisPolicy.
struct LenientThisPolicy : public MaybeGlobalThisPolicy,
public LenientThisPolicyMixin {
// We want the HasValidThisValue of MaybeGlobalThisPolicy.
// We want the ExtractThisObject of MaybeGlobalThisPolicy.
// We want the MaybeUnwrapThisObject of MaybeGlobalThisPolicy.
// We want HandleInvalidThis from LenientThisPolicyMixin
using LenientThisPolicyMixin::HandleInvalidThis;
};
// There are some cross-origin things on globals, so we inherit from
// MaybeGlobalThisPolicy.
struct CrossOriginThisPolicy : public MaybeGlobalThisPolicy {
// We want the HasValidThisValue of MaybeGlobalThisPolicy.
// We want the ExtractThisObject of MaybeGlobalThisPolicy.
static MOZ_ALWAYS_INLINE JSObject* MaybeUnwrapThisObject(JSObject* aObj) {
if (xpc::WrapperFactory::IsCrossOriginWrapper(aObj)) {
return js::UncheckedUnwrap(aObj);
}
// Else just return aObj; our UnwrapThisObject call will try to
// CheckedUnwrap it, and either succeed or get a security error as needed.
return aObj;
}
// After calling UnwrapThisObject aSelf can contain one of 2 types, depending
// on whether aObj is a proxy with a RemoteObjectProxy handler or a (maybe
// wrapped) normal WebIDL reflector. The generated binding code relies on this
// and uses IsRemoteObjectProxy to determine what type aSelf points to.
static MOZ_ALWAYS_INLINE nsresult UnwrapThisObject(
JS::MutableHandle<JSObject*> aObj, JSContext* aCx, void*& aSelf,
prototypes::ID aProtoID, uint32_t aProtoDepth) {
binding_detail::MutableObjectHandleWrapper wrapper(aObj);
// We need to pass false here, because if aObj doesn't have a DOMJSClass
// it might be a remote proxy object, and we don't want to throw in that
// case (even though unwrapping would fail).
nsresult rv = binding_detail::UnwrapObjectInternal<void, false>(
wrapper, aSelf, aProtoID, aProtoDepth, nullptr);
if (NS_SUCCEEDED(rv)) {
return rv;
}
if (js::IsWrapper(wrapper)) {
// We want CheckedUnwrapDynamic here: aCx represents the Realm we are in
// right now, so we want to check whether that Realm should be able to
// access the object. And this object can definitely be a WindowProxy, so
// we need he dynamic check.
JSObject* unwrappedObj = js::CheckedUnwrapDynamic(
wrapper, aCx, /* stopAtWindowProxy = */ false);
if (!unwrappedObj) {
return NS_ERROR_XPC_SECURITY_MANAGER_VETO;
}
// At this point we want to keep "unwrappedObj" alive, because we don't
// hold a strong reference in "aSelf".
wrapper = unwrappedObj;
return binding_detail::UnwrapObjectInternal<void, false>(
wrapper, aSelf, aProtoID, aProtoDepth, nullptr);
}
if (!IsRemoteObjectProxy(wrapper, aProtoID)) {
return NS_ERROR_XPC_BAD_CONVERT_JS;
}
aSelf = RemoteObjectProxyBase::GetNative(wrapper);
return NS_OK;
}
// We want the HandleInvalidThis of MaybeGlobalThisPolicy.
};
// Some objects that can be cross-origin objects are globals, so we inherit
// from MaybeGlobalThisPolicy.
struct MaybeCrossOriginObjectThisPolicy : public MaybeGlobalThisPolicy {
// We want the HasValidThisValue of MaybeGlobalThisPolicy.
// We want the ExtractThisObject of MaybeGlobalThisPolicy.
// We want the MaybeUnwrapThisObject of MaybeGlobalThisPolicy
static MOZ_ALWAYS_INLINE nsresult UnwrapThisObject(
JS::MutableHandle<JSObject*> aObj, JSContext* aCx, void*& aSelf,
prototypes::ID aProtoID, uint32_t aProtoDepth) {
// There are two cases at this point: either aObj is a cross-compartment
// wrapper (CCW) or it's not. If it is, we don't need to do anything
// special compared to MaybeGlobalThisPolicy: the CCW will do the relevant
// security checks. Which is good, because if we tried to do the
// cross-origin object check _before_ unwrapping it would always come back
// as "same-origin" and if we tried to do it after unwrapping it would be
// completely wrong: the checks rely on the two sides of the comparison
// being symmetric (can access each other or cannot access each other), but
// if we have a CCW we could have an Xray, which is asymmetric. And then
// we'd think we should deny access, whereas we should actually allow
// access.
//
// If we do _not_ have a CCW here, then we need to check whether it's a
// cross-origin-accessible object, and if it is check whether it's
// same-origin-domain with our current callee.
if (!js::IsCrossCompartmentWrapper(aObj) &&
xpc::IsCrossOriginAccessibleObject(aObj) &&
!MaybeCrossOriginObjectMixins::IsPlatformObjectSameOrigin(aCx, aObj)) {
return NS_ERROR_XPC_SECURITY_MANAGER_VETO;
}
return MaybeGlobalThisPolicy::UnwrapThisObject(aObj, aCx, aSelf, aProtoID,
aProtoDepth);
}
// We want the HandleInvalidThis of MaybeGlobalThisPolicy.
};
// And in some cases we are dealing with a maybe-cross-origin object _and_ need
// [LenientThis] behavior.
struct MaybeCrossOriginObjectLenientThisPolicy
: public MaybeCrossOriginObjectThisPolicy,
public LenientThisPolicyMixin {
// We want to get all of our behavior from
// MaybeCrossOriginObjectLenientThisPolicy, except for HandleInvalidThis,
// which should come from LenientThisPolicyMixin.
using LenientThisPolicyMixin::HandleInvalidThis;
};
/**
* An ExceptionPolicy struct provides a single HandleException method which is
* used to handle an exception, if any. The method is given the current
* success/failure boolean so it can decide whether there is in fact an
* exception involved.
*/
struct ThrowExceptions {
// This needs to be inlined because it's called even on no-exceptions
// fast-paths.
static MOZ_ALWAYS_INLINE bool HandleException(JSContext* aCx,
JS::CallArgs& aArgs,
const JSJitInfo* aInfo,
bool aOK) {
return aOK;
}
};
struct ConvertExceptionsToPromises {
// This needs to be inlined because it's called even on no-exceptions
// fast-paths.
static MOZ_ALWAYS_INLINE bool HandleException(JSContext* aCx,
JS::CallArgs& aArgs,
const JSJitInfo* aInfo,
bool aOK) {
// Promise-returning getters/methods always return objects.
MOZ_ASSERT(aInfo->returnType() == JSVAL_TYPE_OBJECT);
if (aOK) {
return true;
}
return ConvertExceptionToPromise(aCx, aArgs.rval());
}
};
template <typename ThisPolicy, typename ExceptionPolicy>
bool GenericGetter(JSContext* cx, unsigned argc, JS::Value* vp) {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
const JSJitInfo* info = FUNCTION_VALUE_TO_JITINFO(args.calleev());
prototypes::ID protoID = static_cast<prototypes::ID>(info->protoID);
if (!ThisPolicy::HasValidThisValue(args)) {
bool ok = ThisPolicy::HandleInvalidThis(cx, args, false, protoID);
return ExceptionPolicy::HandleException(cx, args, info, ok);
}
JS::Rooted<JSObject*> obj(cx, ThisPolicy::ExtractThisObject(args));
// NOTE: we want to leave obj in its initial compartment, so don't want to
// pass it to UnwrapObjectInternal. Also, the thing we pass to
// UnwrapObjectInternal may be affected by our ThisPolicy.
JS::Rooted<JSObject*> rootSelf(cx, ThisPolicy::MaybeUnwrapThisObject(obj));
void* self;
{
nsresult rv =
ThisPolicy::UnwrapThisObject(&rootSelf, cx, self, protoID, info->depth);
if (NS_FAILED(rv)) {
bool ok = ThisPolicy::HandleInvalidThis(
cx, args, rv == NS_ERROR_XPC_SECURITY_MANAGER_VETO, protoID);
return ExceptionPolicy::HandleException(cx, args, info, ok);
}
}
MOZ_ASSERT(info->type() == JSJitInfo::Getter);
JSJitGetterOp getter = info->getter;
bool ok = getter(cx, obj, self, JSJitGetterCallArgs(args));
#ifdef DEBUG
if (ok) {
AssertReturnTypeMatchesJitinfo(info, args.rval());
}
#endif
return ExceptionPolicy::HandleException(cx, args, info, ok);
}
// Force instantiation of the specializations of GenericGetter we need here.
template bool GenericGetter<NormalThisPolicy, ThrowExceptions>(JSContext* cx,
unsigned argc,
JS::Value* vp);
template bool GenericGetter<NormalThisPolicy, ConvertExceptionsToPromises>(
JSContext* cx, unsigned argc, JS::Value* vp);
template bool GenericGetter<MaybeGlobalThisPolicy, ThrowExceptions>(
JSContext* cx, unsigned argc, JS::Value* vp);
template bool GenericGetter<MaybeGlobalThisPolicy, ConvertExceptionsToPromises>(
JSContext* cx, unsigned argc, JS::Value* vp);
template bool GenericGetter<LenientThisPolicy, ThrowExceptions>(JSContext* cx,
unsigned argc,
JS::Value* vp);
// There aren't any [LenientThis] Promise-returning getters, so don't
// bother instantiating that specialization.
template bool GenericGetter<CrossOriginThisPolicy, ThrowExceptions>(
JSContext* cx, unsigned argc, JS::Value* vp);
// There aren't any cross-origin Promise-returning getters, so don't
// bother instantiating that specialization.
template bool GenericGetter<MaybeCrossOriginObjectThisPolicy, ThrowExceptions>(
JSContext* cx, unsigned argc, JS::Value* vp);
// There aren't any maybe-cross-origin-object Promise-returning getters, so
// don't bother instantiating that specialization.
template bool GenericGetter<MaybeCrossOriginObjectLenientThisPolicy,
ThrowExceptions>(JSContext* cx, unsigned argc,
JS::Value* vp);
// There aren't any maybe-cross-origin-object Promise-returning lenient-this
// getters, so don't bother instantiating that specialization.
template <typename ThisPolicy>
bool GenericSetter(JSContext* cx, unsigned argc, JS::Value* vp) {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
const JSJitInfo* info = FUNCTION_VALUE_TO_JITINFO(args.calleev());
prototypes::ID protoID = static_cast<prototypes::ID>(info->protoID);
if (!ThisPolicy::HasValidThisValue(args)) {
return ThisPolicy::HandleInvalidThis(cx, args, false, protoID);
}
JS::Rooted<JSObject*> obj(cx, ThisPolicy::ExtractThisObject(args));
// NOTE: we want to leave obj in its initial compartment, so don't want to
// pass it to UnwrapObject. Also the thing we pass to UnwrapObjectInternal
// may be affected by our ThisPolicy.
JS::Rooted<JSObject*> rootSelf(cx, ThisPolicy::MaybeUnwrapThisObject(obj));
void* self;
{
nsresult rv =
ThisPolicy::UnwrapThisObject(&rootSelf, cx, self, protoID, info->depth);
if (NS_FAILED(rv)) {
return ThisPolicy::HandleInvalidThis(
cx, args, rv == NS_ERROR_XPC_SECURITY_MANAGER_VETO, protoID);
}
}
if (args.length() == 0) {
return ThrowNoSetterArg(cx, args, protoID);
}
MOZ_ASSERT(info->type() == JSJitInfo::Setter);
JSJitSetterOp setter = info->setter;
if (!setter(cx, obj, self, JSJitSetterCallArgs(args))) {
return false;
}
args.rval().setUndefined();
#ifdef DEBUG
AssertReturnTypeMatchesJitinfo(info, args.rval());
#endif
return true;
}
// Force instantiation of the specializations of GenericSetter we need here.
template bool GenericSetter<NormalThisPolicy>(JSContext* cx, unsigned argc,
JS::Value* vp);
template bool GenericSetter<MaybeGlobalThisPolicy>(JSContext* cx, unsigned argc,
JS::Value* vp);
template bool GenericSetter<LenientThisPolicy>(JSContext* cx, unsigned argc,
JS::Value* vp);
template bool GenericSetter<CrossOriginThisPolicy>(JSContext* cx, unsigned argc,
JS::Value* vp);
template bool GenericSetter<MaybeCrossOriginObjectThisPolicy>(JSContext* cx,
unsigned argc,
JS::Value* vp);
template bool GenericSetter<MaybeCrossOriginObjectLenientThisPolicy>(
JSContext* cx, unsigned argc, JS::Value* vp);
template <typename ThisPolicy, typename ExceptionPolicy>
bool GenericMethod(JSContext* cx, unsigned argc, JS::Value* vp) {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
const JSJitInfo* info = FUNCTION_VALUE_TO_JITINFO(args.calleev());
prototypes::ID protoID = static_cast<prototypes::ID>(info->protoID);
if (!ThisPolicy::HasValidThisValue(args)) {
bool ok = ThisPolicy::HandleInvalidThis(cx, args, false, protoID);
return ExceptionPolicy::HandleException(cx, args, info, ok);
}
JS::Rooted<JSObject*> obj(cx, ThisPolicy::ExtractThisObject(args));
// NOTE: we want to leave obj in its initial compartment, so don't want to
// pass it to UnwrapObjectInternal. Also, the thing we pass to
// UnwrapObjectInternal may be affected by our ThisPolicy.
JS::Rooted<JSObject*> rootSelf(cx, ThisPolicy::MaybeUnwrapThisObject(obj));
void* self;
{
nsresult rv =
ThisPolicy::UnwrapThisObject(&rootSelf, cx, self, protoID, info->depth);
if (NS_FAILED(rv)) {
bool ok = ThisPolicy::HandleInvalidThis(
cx, args, rv == NS_ERROR_XPC_SECURITY_MANAGER_VETO, protoID);
return ExceptionPolicy::HandleException(cx, args, info, ok);
}
}
MOZ_ASSERT(info->type() == JSJitInfo::Method);
JSJitMethodOp method = info->method;
bool ok = method(cx, obj, self, JSJitMethodCallArgs(args));
#ifdef DEBUG
if (ok) {
AssertReturnTypeMatchesJitinfo(info, args.rval());
}
#endif
return ExceptionPolicy::HandleException(cx, args, info, ok);
}
// Force instantiation of the specializations of GenericMethod we need here.
template bool GenericMethod<NormalThisPolicy, ThrowExceptions>(JSContext* cx,
unsigned argc,
JS::Value* vp);
template bool GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>(
JSContext* cx, unsigned argc, JS::Value* vp);
template bool GenericMethod<MaybeGlobalThisPolicy, ThrowExceptions>(
JSContext* cx, unsigned argc, JS::Value* vp);
template bool GenericMethod<MaybeGlobalThisPolicy, ConvertExceptionsToPromises>(
JSContext* cx, unsigned argc, JS::Value* vp);
template bool GenericMethod<CrossOriginThisPolicy, ThrowExceptions>(
JSContext* cx, unsigned argc, JS::Value* vp);
// There aren't any cross-origin Promise-returning methods, so don't
// bother instantiating that specialization.
template bool GenericMethod<MaybeCrossOriginObjectThisPolicy, ThrowExceptions>(
JSContext* cx, unsigned argc, JS::Value* vp);
template bool GenericMethod<MaybeCrossOriginObjectThisPolicy,
ConvertExceptionsToPromises>(JSContext* cx,
unsigned argc,
JS::Value* vp);
} // namespace binding_detail
bool StaticMethodPromiseWrapper(JSContext* cx, unsigned argc, JS::Value* vp) {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
const JSJitInfo* info = FUNCTION_VALUE_TO_JITINFO(args.calleev());
MOZ_ASSERT(info);
MOZ_ASSERT(info->type() == JSJitInfo::StaticMethod);
bool ok = info->staticMethod(cx, argc, vp);
if (ok) {
return true;
}
return ConvertExceptionToPromise(cx, args.rval());
}
bool ConvertExceptionToPromise(JSContext* cx,
JS::MutableHandle<JS::Value> rval) {
JS::Rooted<JS::Value> exn(cx);
if (!JS_GetPendingException(cx, &exn)) {
// This is very important: if there is no pending exception here but we're
// ending up in this code, that means the callee threw an uncatchable
// exception. Just propagate that out as-is.
return false;
}
JS_ClearPendingException(cx);
JSObject* promise = JS::CallOriginalPromiseReject(cx, exn);
if (!promise) {
// We just give up. Put the exception back.
JS_SetPendingException(cx, exn);
return false;
}
rval.setObject(*promise);
return true;
}
/* static */
void CreateGlobalOptionsWithXPConnect::TraceGlobal(JSTracer* aTrc,
JSObject* aObj) {
xpc::TraceXPCGlobal(aTrc, aObj);
}
/* static */
bool CreateGlobalOptionsWithXPConnect::PostCreateGlobal(
JSContext* aCx, JS::Handle<JSObject*> aGlobal) {
JSPrincipals* principals =
JS::GetRealmPrincipals(js::GetNonCCWObjectRealm(aGlobal));
nsIPrincipal* principal = nsJSPrincipals::get(principals);
SiteIdentifier site;
nsresult rv = BasePrincipal::Cast(principal)->GetSiteIdentifier(site);
NS_ENSURE_SUCCESS(rv, false);
xpc::RealmPrivate::Init(aGlobal, site);
return true;
}
uint64_t GetWindowID(void* aGlobal) { return 0; }
uint64_t GetWindowID(nsGlobalWindowInner* aGlobal) {
return aGlobal->WindowID();
}
uint64_t GetWindowID(DedicatedWorkerGlobalScope* aGlobal) {
return aGlobal->WindowID();
}
#ifdef DEBUG
void AssertReturnTypeMatchesJitinfo(const JSJitInfo* aJitInfo,
JS::Handle<JS::Value> aValue) {
switch (aJitInfo->returnType()) {
case JSVAL_TYPE_UNKNOWN:
// Any value is good.
break;
case JSVAL_TYPE_DOUBLE:
// The value could actually be an int32 value as well.
MOZ_ASSERT(aValue.isNumber());
break;
case JSVAL_TYPE_INT32:
MOZ_ASSERT(aValue.isInt32());
break;
case JSVAL_TYPE_UNDEFINED:
MOZ_ASSERT(aValue.isUndefined());
break;
case JSVAL_TYPE_BOOLEAN:
MOZ_ASSERT(aValue.isBoolean());
break;
case JSVAL_TYPE_STRING:
MOZ_ASSERT(aValue.isString());
break;
case JSVAL_TYPE_NULL:
MOZ_ASSERT(aValue.isNull());
break;
case JSVAL_TYPE_OBJECT:
MOZ_ASSERT(aValue.isObject());
break;
default:
// Someone messed up their jitinfo type.
MOZ_ASSERT(false, "Unexpected JSValueType stored in jitinfo");
break;
}
}
#endif
bool CallerSubsumes(JSObject* aObject) {
// Remote object proxies are not CCWs, so unwrapping them does not get you
// their "real" principal, but we want to treat them like cross-origin objects
// when considering them as WebIDL arguments, for consistency.
if (IsRemoteObjectProxy(aObject)) {
return false;
}
nsIPrincipal* objPrin =
nsContentUtils::ObjectPrincipal(js::UncheckedUnwrap(aObject));
return nsContentUtils::SubjectPrincipal()->Subsumes(objPrin);
}
nsresult UnwrapArgImpl(JSContext* cx, JS::Handle<JSObject*> src,
const nsIID& iid, void** ppArg) {
if (!NS_IsMainThread()) {
return NS_ERROR_NOT_AVAILABLE;
}
// The JSContext represents the "who is unwrapping" realm, so we want to use
// it for ReflectorToISupportsDynamic here.
nsCOMPtr<nsISupports> iface = xpc::ReflectorToISupportsDynamic(src, cx);
if (iface) {
if (NS_FAILED(iface->QueryInterface(iid, ppArg))) {
return NS_ERROR_XPC_BAD_CONVERT_JS;
}
return NS_OK;
}
// Only allow XPCWrappedJS stuff in system code. Ideally we would remove this
// even there, but that involves converting some things to WebIDL callback
// interfaces and making some other things builtinclass...
if (!nsContentUtils::IsSystemCaller(cx)) {
return NS_ERROR_XPC_BAD_CONVERT_JS;
}
RefPtr<nsXPCWrappedJS> wrappedJS;
nsresult rv =
nsXPCWrappedJS::GetNewOrUsed(cx, src, iid, getter_AddRefs(wrappedJS));
if (NS_FAILED(rv) || !wrappedJS) {
return rv;
}
// We need to go through the QueryInterface logic to make this return
// the right thing for the various 'special' interfaces; e.g.
// nsIPropertyBag. We must use AggregatedQueryInterface in cases where
// there is an outer to avoid nasty recursion.
return wrappedJS->QueryInterface(iid, ppArg);
}
nsresult UnwrapWindowProxyArg(JSContext* cx, JS::Handle<JSObject*> src,
WindowProxyHolder& ppArg) {
if (IsRemoteObjectProxy(src, prototypes::id::Window)) {
ppArg =
static_cast<BrowsingContext*>(RemoteObjectProxyBase::GetNative(src));
return NS_OK;
}
nsCOMPtr<nsPIDOMWindowInner> inner;
nsresult rv = UnwrapArg<nsPIDOMWindowInner>(cx, src, getter_AddRefs(inner));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsPIDOMWindowOuter> outer = inner->GetOuterWindow();
RefPtr<BrowsingContext> bc = outer ? outer->GetBrowsingContext() : nullptr;
ppArg = std::move(bc);
return NS_OK;
}
template <decltype(JS::NewMapObject) Method>
bool GetMaplikeSetlikeBackingObject(JSContext* aCx, JS::Handle<JSObject*> aObj,
size_t aSlotIndex,
JS::MutableHandle<JSObject*> aBackingObj,
bool* aBackingObjCreated) {
JS::Rooted<JSObject*> reflector(aCx);
reflector = IsDOMObject(aObj)
? aObj
: js::UncheckedUnwrap(aObj,
/* stopAtWindowProxy = */ false);
// Retrieve the backing object from the reserved slot on the maplike/setlike
// object. If it doesn't exist yet, create it.
JS::Rooted<JS::Value> slotValue(aCx);
slotValue = JS::GetReservedSlot(reflector, aSlotIndex);
if (slotValue.isUndefined()) {
// Since backing object access can happen in non-originating realms,
// make sure to create the backing object in reflector realm.
{
JSAutoRealm ar(aCx, reflector);
JS::Rooted<JSObject*> newBackingObj(aCx);
newBackingObj.set(Method(aCx));
if (NS_WARN_IF(!newBackingObj)) {
return false;
}
JS::SetReservedSlot(reflector, aSlotIndex,
JS::ObjectValue(*newBackingObj));
}
slotValue = JS::GetReservedSlot(reflector, aSlotIndex);
*aBackingObjCreated = true;
} else {
*aBackingObjCreated = false;
}
if (!MaybeWrapNonDOMObjectValue(aCx, &slotValue)) {
return false;
}
aBackingObj.set(&slotValue.toObject());
return true;
}
bool GetMaplikeBackingObject(JSContext* aCx, JS::Handle<JSObject*> aObj,
size_t aSlotIndex,
JS::MutableHandle<JSObject*> aBackingObj,
bool* aBackingObjCreated) {
return GetMaplikeSetlikeBackingObject<JS::NewMapObject>(
aCx, aObj, aSlotIndex, aBackingObj, aBackingObjCreated);
}
bool GetSetlikeBackingObject(JSContext* aCx, JS::Handle<JSObject*> aObj,
size_t aSlotIndex,
JS::MutableHandle<JSObject*> aBackingObj,
bool* aBackingObjCreated) {
return GetMaplikeSetlikeBackingObject<JS::NewSetObject>(
aCx, aObj, aSlotIndex, aBackingObj, aBackingObjCreated);
}
bool ForEachHandler(JSContext* aCx, unsigned aArgc, JS::Value* aVp) {
JS::CallArgs args = CallArgsFromVp(aArgc, aVp);
// Unpack callback and object from slots
JS::Rooted<JS::Value> callbackFn(
aCx,
js::GetFunctionNativeReserved(&args.callee(), FOREACH_CALLBACK_SLOT));
JS::Rooted<JS::Value> maplikeOrSetlikeObj(
aCx, js::GetFunctionNativeReserved(&args.callee(),
FOREACH_MAPLIKEORSETLIKEOBJ_SLOT));
MOZ_ASSERT(aArgc == 3);
JS::RootedVector<JS::Value> newArgs(aCx);
// Arguments are passed in as value, key, object. Keep value and key, replace
// object with the maplike/setlike object.
if (!newArgs.append(args.get(0))) {
return false;
}
if (!newArgs.append(args.get(1))) {
return false;
}
if (!newArgs.append(maplikeOrSetlikeObj)) {
return false;
}
JS::Rooted<JS::Value> rval(aCx, JS::UndefinedValue());
// Now actually call the user specified callback
return JS::Call(aCx, args.thisv(), callbackFn, newArgs, &rval);
}
static inline prototypes::ID GetProtoIdForNewtarget(
JS::Handle<JSObject*> aNewTarget) {
const JSClass* newTargetClass = JS::GetClass(aNewTarget);
if (IsDOMIfaceAndProtoClass(newTargetClass)) {
const DOMIfaceAndProtoJSClass* newTargetIfaceClass =
DOMIfaceAndProtoJSClass::FromJSClass(newTargetClass);
if (newTargetIfaceClass->mType == eInterface) {
return newTargetIfaceClass->mPrototypeID;
}
} else if (JS_IsNativeFunction(aNewTarget, Constructor)) {
return GetNativePropertyHooksFromConstructorFunction(aNewTarget)
->mPrototypeID;
}
return prototypes::id::_ID_Count;
}
bool GetDesiredProto(JSContext* aCx, const JS::CallArgs& aCallArgs,
prototypes::id::ID aProtoId,
CreateInterfaceObjectsMethod aCreator,
JS::MutableHandle<JSObject*> aDesiredProto) {
// This basically implements
// https://heycam.github.io/webidl/#internally-create-a-new-object-implementing-the-interface
// step 3.
MOZ_ASSERT(aCallArgs.isConstructing(), "How did we end up here?");
// The desired prototype depends on the actual constructor that was invoked,
// which is passed to us as the newTarget in the callargs. We want to do
// something akin to the ES6 specification's GetProtototypeFromConstructor (so
// get .prototype on the newTarget, with a fallback to some sort of default).
// First, a fast path for the case when the the constructor is in fact one of
// our DOM constructors. This is safe because on those the "constructor"
// property is non-configurable and non-writable, so we don't have to do the
// slow JS_GetProperty call.
JS::Rooted<JSObject*> newTarget(aCx, &aCallArgs.newTarget().toObject());
MOZ_ASSERT(JS::IsCallable(newTarget));
JS::Rooted<JSObject*> originalNewTarget(aCx, newTarget);
// See whether we have a known DOM constructor here, such that we can take a
// fast path.
prototypes::ID protoID = GetProtoIdForNewtarget(newTarget);
if (protoID == prototypes::id::_ID_Count) {
// We might still have a cross-compartment wrapper for a known DOM
// constructor. CheckedUnwrapStatic is fine here, because we're looking for
// DOM constructors and those can't be cross-origin objects.
newTarget = js::CheckedUnwrapStatic(newTarget);
if (newTarget && newTarget != originalNewTarget) {
protoID = GetProtoIdForNewtarget(newTarget);
}
}
if (protoID != prototypes::id::_ID_Count) {
ProtoAndIfaceCache& protoAndIfaceCache =
*GetProtoAndIfaceCache(JS::GetNonCCWObjectGlobal(newTarget));
aDesiredProto.set(protoAndIfaceCache.EntrySlotMustExist(protoID));
if (newTarget != originalNewTarget) {
return JS_WrapObject(aCx, aDesiredProto);
}
return true;
}
// Slow path. This basically duplicates the ES6 spec's
// GetPrototypeFromConstructor except that instead of taking a string naming
// the fallback prototype we determine the fallback based on the proto id we
// were handed.
//
// Note that it's very important to do this property get on originalNewTarget,
// not our unwrapped newTarget, since we want to get Xray behavior here as
// needed.
// XXXbz for speed purposes, using a preinterned id here sure would be nice.
// We can't use GetJSIDByIndex, because that only works on the main thread,
// not workers.
JS::Rooted<JS::Value> protoVal(aCx);
if (!JS_GetProperty(aCx, originalNewTarget, "prototype", &protoVal)) {
return false;
}
if (protoVal.isObject()) {
aDesiredProto.set(&protoVal.toObject());
return true;
}
// Fall back to getting the proto for our given proto id in the realm that
// GetFunctionRealm(newTarget) returns.
JS::Rooted<JS::Realm*> realm(aCx, JS::GetFunctionRealm(aCx, newTarget));
if (!realm) {
return false;
}
{
// JS::GetRealmGlobalOrNull should not be returning null here, because we
// have live objects in the Realm.
JSAutoRealm ar(aCx, JS::GetRealmGlobalOrNull(realm));
aDesiredProto.set(
GetPerInterfaceObjectHandle(aCx, aProtoId, aCreator, true));
if (!aDesiredProto) {
return false;
}
}
return MaybeWrapObject(aCx, aDesiredProto);
}
namespace {
class MOZ_RAII AutoConstructionDepth final {
public:
MOZ_IMPLICIT AutoConstructionDepth(CustomElementDefinition* aDefinition)
: mDefinition(aDefinition) {
MOZ_ASSERT(mDefinition->mConstructionStack.IsEmpty());
mDefinition->mConstructionDepth++;
// If the mConstructionDepth isn't matched with the length of mPrefixStack,
// this means the constructor is called directly from JS, i.e.
// 'new CustomElementConstructor()', we have to push a dummy prefix into
// stack.
if (mDefinition->mConstructionDepth > mDefinition->mPrefixStack.Length()) {
mDidPush = true;
mDefinition->mPrefixStack.AppendElement(nullptr);
}
MOZ_ASSERT(mDefinition->mConstructionDepth ==
mDefinition->mPrefixStack.Length());
}
~AutoConstructionDepth() {
MOZ_ASSERT(mDefinition->mConstructionDepth > 0);
MOZ_ASSERT(mDefinition->mConstructionDepth ==
mDefinition->mPrefixStack.Length());
if (mDidPush) {
MOZ_ASSERT(mDefinition->mPrefixStack.LastElement() == nullptr);
mDefinition->mPrefixStack.RemoveLastElement();
}
mDefinition->mConstructionDepth--;
}
private:
CustomElementDefinition* mDefinition;
bool mDidPush = false;
};
} // anonymous namespace
// https://html.spec.whatwg.org/multipage/dom.html#htmlconstructor
namespace binding_detail {
bool HTMLConstructor(JSContext* aCx, unsigned aArgc, JS::Value* aVp,
constructors::id::ID aConstructorId,
prototypes::id::ID aProtoId,
CreateInterfaceObjectsMethod aCreator) {
JS::CallArgs args = JS::CallArgsFromVp(aArgc, aVp);
// Per spec, this is technically part of step 3, but doing the check
// directly lets us provide a better error message. And then in
// step 2 we can work with newTarget in a simpler way because we
// know it's an object.
if (!args.isConstructing()) {
return ThrowConstructorWithoutNew(aCx,
NamesOfInterfacesWithProtos(aProtoId));
}
JS::Rooted<JSObject*> callee(aCx, &args.callee());
// 'callee' is not a function here; it's either an Xray for our interface
// object or the interface object itself. So caling XrayAwareCalleeGlobal on
// it is not safe. But since in the Xray case it's a wrapper for our
// interface object, we can just construct our GlobalObject from it and end
// up with the right thing.
GlobalObject global(aCx, callee);
if (global.Failed()) {
return false;
}
// Now we start the [HTMLConstructor] algorithm steps from
// https://html.spec.whatwg.org/multipage/dom.html#htmlconstructor
ErrorResult rv;
auto scopeExit =
MakeScopeExit([&]() { Unused << rv.MaybeSetPendingException(aCx); });
// Step 1.
nsCOMPtr<nsPIDOMWindowInner> window =
do_QueryInterface(global.GetAsSupports());
if (!window) {
// This means we ended up with an HTML Element interface object defined in
// a non-Window scope. That's ... pretty unexpected.
rv.Throw(NS_ERROR_UNEXPECTED);
return false;
}
RefPtr<mozilla::dom::CustomElementRegistry> registry(
window->CustomElements());
// Technically, per spec, a window always has a document. In Gecko, a
// sufficiently torn-down window might not, so check for that case. We're
// going to need a document to create an element.
Document* doc = window->GetExtantDoc();
if (!doc) {
rv.Throw(NS_ERROR_UNEXPECTED);
return false;
}
// Step 2.
// The newTarget might be a cross-compartment wrapper. Get the underlying
// object so we can do the spec's object-identity checks. If we ever stop
// unwrapping here, carefully audit uses of newTarget below!
//
// Note that the ES spec enforces that newTarget is always a constructor (in
// the sense of having a [[Construct]]), so it's not a cross-origin object and
// we can use CheckedUnwrapStatic.
JS::Rooted<JSObject*> newTarget(
aCx, js::CheckedUnwrapStatic(&args.newTarget().toObject()));
if (!newTarget) {
rv.ThrowTypeError<MSG_ILLEGAL_CONSTRUCTOR>();
return false;
}
// Enter the compartment of our underlying newTarget object, so we end
// up comparing to the constructor object for our interface from that global.
// XXXbz This is not what the spec says to do, and it's not super-clear to me
// at this point why we're doing it. Why not just compare |newTarget| and
// |callee| if the intent is just to prevent registration of HTML interface
// objects as constructors? Of course it's not clear that the spec check
// makes sense to start with: https://github.com/whatwg/html/issues/3575
{
JSAutoRealm ar(aCx, newTarget);
JS::Handle<JSObject*> constructor =
GetPerInterfaceObjectHandle(aCx, aConstructorId, aCreator, true);
if (!constructor) {
return false;
}
if (newTarget == constructor) {
rv.ThrowTypeError<MSG_ILLEGAL_CONSTRUCTOR>();
return false;
}
}
// Step 3.
CustomElementDefinition* definition =
registry->LookupCustomElementDefinition(aCx, newTarget);
if (!definition) {
rv.ThrowTypeError<MSG_ILLEGAL_CONSTRUCTOR>();
return false;
}
// Steps 4, 5, 6 do some sanity checks on our callee. We add to those a
// determination of what sort of element we're planning to construct.
// Technically, this should happen (implicitly) in step 8, but this
// determination is side-effect-free, so it's OK.
int32_t ns = definition->mNamespaceID;
constructorGetterCallback cb = nullptr;
if (ns == kNameSpaceID_XUL) {
if (definition->mLocalName == nsGkAtoms::description ||
definition->mLocalName == nsGkAtoms::label) {
cb = XULTextElement_Binding::GetConstructorObject;
} else if (definition->mLocalName == nsGkAtoms::menupopup ||
definition->mLocalName == nsGkAtoms::popup ||
definition->mLocalName == nsGkAtoms::panel ||
definition->mLocalName == nsGkAtoms::tooltip) {
cb = XULPopupElement_Binding::GetConstructorObject;
} else if (definition->mLocalName == nsGkAtoms::iframe ||
definition->mLocalName == nsGkAtoms::browser ||
definition->mLocalName == nsGkAtoms::editor) {
cb = XULFrameElement_Binding::GetConstructorObject;
} else if (definition->mLocalName == nsGkAtoms::menu ||
definition->mLocalName == nsGkAtoms::menulist) {
cb = XULMenuElement_Binding::GetConstructorObject;
} else if (definition->mLocalName == nsGkAtoms::tree) {
cb = XULTreeElement_Binding::GetConstructorObject;
} else {
cb = XULElement_Binding::GetConstructorObject;
}
}
int32_t tag = eHTMLTag_userdefined;
if (!definition->IsCustomBuiltIn()) {
// Step 4.
// If the definition is for an autonomous custom element, the active
// function should be HTMLElement or extend from XULElement.
if (!cb) {
cb = HTMLElement_Binding::GetConstructorObject;
}
// We want to get the constructor from our global's realm, not the
// caller realm.
JSAutoRealm ar(aCx, global.Get());
JS::Rooted<JSObject*> constructor(aCx, cb(aCx));
// CheckedUnwrapStatic is OK here, since our callee is callable, hence not a
// cross-origin object.
if (constructor != js::CheckedUnwrapStatic(callee)) {
rv.ThrowTypeError<MSG_ILLEGAL_CONSTRUCTOR>();
return false;
}
} else {
if (ns == kNameSpaceID_XHTML) {
// Step 5.
// If the definition is for a customized built-in element, the localName
// should be one of the ones defined in the specification for this
// interface.
tag = nsHTMLTags::CaseSensitiveAtomTagToId(definition->mLocalName);
if (tag == eHTMLTag_userdefined) {
rv.ThrowTypeError<MSG_ILLEGAL_CONSTRUCTOR>();
return false;
}
MOZ_ASSERT(tag <= NS_HTML_TAG_MAX, "tag is out of bounds");
// If the definition is for a customized built-in element, the active
// function should be the localname's element interface.
cb = sConstructorGetterCallback[tag];
}
if (!cb) {
rv.ThrowTypeError<MSG_ILLEGAL_CONSTRUCTOR>();
return false;
}
// We want to get the constructor from our global's realm, not the
// caller realm.
JSAutoRealm ar(aCx, global.Get());
JS::Rooted<JSObject*> constructor(aCx, cb(aCx));
if (!constructor) {
return false;
}
// CheckedUnwrapStatic is OK here, since our callee is callable, hence not a
// cross-origin object.
if (constructor != js::CheckedUnwrapStatic(callee)) {
rv.ThrowTypeError<MSG_ILLEGAL_CONSTRUCTOR>();
return false;
}
}
// Steps 7 and 8.
JS::Rooted<JSObject*> desiredProto(aCx);
if (!GetDesiredProto(aCx, args, aProtoId, aCreator, &desiredProto)) {
return false;
}
MOZ_ASSERT(desiredProto, "How could we not have a prototype by now?");
// We need to do some work to actually return an Element, so we do step 8 on
// one branch and steps 9-12 on another branch, then common up the "return
// element" work.
RefPtr<Element> element;
nsTArray<RefPtr<Element>>& constructionStack = definition->mConstructionStack;
if (constructionStack.IsEmpty()) {
// Step 8.
// Now we go to construct an element. We want to do this in global's
// realm, not caller realm (the normal constructor behavior),
// just in case those elements create JS things.
JSAutoRealm ar(aCx, global.Get());
AutoConstructionDepth acd(definition);
RefPtr<NodeInfo> nodeInfo = doc->NodeInfoManager()->GetNodeInfo(
definition->mLocalName, definition->mPrefixStack.LastElement(), ns,
nsINode::ELEMENT_NODE);
MOZ_ASSERT(nodeInfo);
if (ns == kNameSpaceID_XUL) {
element = nsXULElement::Construct(nodeInfo.forget());
} else {
if (tag == eHTMLTag_userdefined) {
// Autonomous custom element.
element = NS_NewHTMLElement(nodeInfo.forget());
} else {
// Customized built-in element.
element = CreateHTMLElement(tag, nodeInfo.forget(), NOT_FROM_PARSER);
}
}
element->SetCustomElementData(new CustomElementData(
definition->mType, CustomElementData::State::eCustom));
element->SetCustomElementDefinition(definition);
} else {
// Step 9.
element = constructionStack.LastElement();
// Step 10.
if (element == ALREADY_CONSTRUCTED_MARKER) {
rv.ThrowTypeError(
"Cannot instantiate a custom element inside its own constructor "
"during upgrades");
return false;
}
// Step 11.
// Do prototype swizzling for upgrading a custom element here, for cases
// when we have a reflector already. If we don't have one yet, we will
// create it with the right proto (by calling GetOrCreateDOMReflector with
// that proto), and will preserve it by means of the proto != canonicalProto
// check).
JS::Rooted<JSObject*> reflector(aCx, element->GetWrapper());
if (reflector) {
// reflector might be in different realm.
JSAutoRealm ar(aCx, reflector);
JS::Rooted<JSObject*> givenProto(aCx, desiredProto);
if (!JS_WrapObject(aCx, &givenProto) ||
!JS_SetPrototype(aCx, reflector, givenProto)) {
return false;
}
PreserveWrapper(element.get());
}
// Step 12.
constructionStack.LastElement() = ALREADY_CONSTRUCTED_MARKER;
}
// Tail end of step 8 and step 13: returning the element. We want to do this
// part in the global's realm, though in practice it won't matter much
// because Element always knows which realm it should be created in.
JSAutoRealm ar(aCx, global.Get());
if (!js::IsObjectInContextCompartment(desiredProto, aCx) &&
!JS_WrapObject(aCx, &desiredProto)) {
return false;
}
return GetOrCreateDOMReflector(aCx, element, args.rval(), desiredProto);
}
} // namespace binding_detail
#ifdef DEBUG
namespace binding_detail {
void AssertReflectorHasGivenProto(JSContext* aCx, JSObject* aReflector,
JS::Handle<JSObject*> aGivenProto) {
if (!aGivenProto) {
// Nothing to assert here
return;
}
JS::Rooted<JSObject*> reflector(aCx, aReflector);
JSAutoRealm ar(aCx, reflector);
JS::Rooted<JSObject*> reflectorProto(aCx);
bool ok = JS_GetPrototype(aCx, reflector, &reflectorProto);
MOZ_ASSERT(ok);
// aGivenProto may not be in the right realm here, so we
// have to wrap it to compare.
JS::Rooted<JSObject*> givenProto(aCx, aGivenProto);
ok = JS_WrapObject(aCx, &givenProto);
MOZ_ASSERT(ok);
MOZ_ASSERT(givenProto == reflectorProto,
"How are we supposed to change the proto now?");
}
} // namespace binding_detail
#endif // DEBUG
void SetUseCounter(JSObject* aObject, UseCounter aUseCounter) {
nsGlobalWindowInner* win =
xpc::WindowGlobalOrNull(js::UncheckedUnwrap(aObject));
if (win && win->GetDocument()) {
win->GetDocument()->SetUseCounter(aUseCounter);
}
}
void SetUseCounter(UseCounterWorker aUseCounter) {
// If this is called from Worklet thread, workerPrivate will be null.
WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate();
if (workerPrivate) {
workerPrivate->SetUseCounter(aUseCounter);
}
}
namespace {
#define DEPRECATED_OPERATION(_op) #_op,
static const char* kDeprecatedOperations[] = {
#include "nsDeprecatedOperationList.h"
nullptr};
#undef DEPRECATED_OPERATION
class GetLocalizedStringRunnable final : public WorkerMainThreadRunnable {
public:
GetLocalizedStringRunnable(WorkerPrivate* aWorkerPrivate,
const nsAutoCString& aKey,
nsAutoString& aLocalizedString)
: WorkerMainThreadRunnable(aWorkerPrivate,
"GetLocalizedStringRunnable"_ns),
mKey(aKey),
mLocalizedString(aLocalizedString) {
MOZ_ASSERT(aWorkerPrivate);
aWorkerPrivate->AssertIsOnWorkerThread();
}
bool MainThreadRun() override {
AssertIsOnMainThread();
nsresult rv = nsContentUtils::GetLocalizedString(
nsContentUtils::eDOM_PROPERTIES, mKey.get(), mLocalizedString);
Unused << NS_WARN_IF(NS_FAILED(rv));
return true;
}
private:
const nsAutoCString& mKey;
nsAutoString& mLocalizedString;
};
void ReportDeprecation(nsIGlobalObject* aGlobal, nsIURI* aURI,
DeprecatedOperations aOperation,
const nsAString& aFileName,
const Nullable<uint32_t>& aLineNumber,
const Nullable<uint32_t>& aColumnNumber) {
MOZ_ASSERT(aURI);
// Anonymize the URL.
// Strip the URL of any possible username/password and make it ready to be
// presented in the UI.
nsCOMPtr<nsIURI> exposableURI = net::nsIOService::CreateExposableURI(aURI);
nsAutoCString spec;
nsresult rv = exposableURI->GetSpec(spec);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
nsAutoString type;
type.AssignASCII(kDeprecatedOperations[static_cast<size_t>(aOperation)]);
nsAutoCString key;
key.AssignASCII(kDeprecatedOperations[static_cast<size_t>(aOperation)]);
key.AppendASCII("Warning");
nsAutoString msg;
if (NS_IsMainThread()) {
rv = nsContentUtils::GetLocalizedString(nsContentUtils::eDOM_PROPERTIES,
key.get(), msg);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
} else {
// nsIStringBundle is thread-safe but its creation is not, and in particular
// nsContentUtils doesn't create and store nsIStringBundle objects in a
// thread-safe way. Better to call GetLocalizedString() on the main thread.
WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate();
if (!workerPrivate) {
return;
}
RefPtr<GetLocalizedStringRunnable> runnable =
new GetLocalizedStringRunnable(workerPrivate, key, msg);
IgnoredErrorResult ignoredRv;
runnable->Dispatch(Canceling, ignoredRv);
if (NS_WARN_IF(ignoredRv.Failed())) {
return;
}
if (msg.IsEmpty()) {
return;
}
}
RefPtr<DeprecationReportBody> body =
new DeprecationReportBody(aGlobal, type, nullptr /* date */, msg,
aFileName, aLineNumber, aColumnNumber);
ReportingUtils::Report(aGlobal, nsGkAtoms::deprecation, u"default"_ns,
NS_ConvertUTF8toUTF16(spec), body);
}
// This runnable is used to write a deprecation message from a worker to the
// console running on the main-thread.
class DeprecationWarningRunnable final
: public WorkerProxyToMainThreadRunnable {
const DeprecatedOperations mOperation;
public:
explicit DeprecationWarningRunnable(DeprecatedOperations aOperation)
: mOperation(aOperation) {}
private:
void RunOnMainThread(WorkerPrivate* aWorkerPrivate) override {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aWorkerPrivate);
// Walk up to our containing page
WorkerPrivate* wp = aWorkerPrivate;
while (wp->GetParent()) {
wp = wp->GetParent();
}
nsPIDOMWindowInner* window = wp->GetWindow();
if (window && window->GetExtantDoc()) {
window->GetExtantDoc()->WarnOnceAbout(mOperation);
}
}
void RunBackOnWorkerThreadForCleanup(WorkerPrivate* aWorkerPrivate) override {
}
};
void MaybeShowDeprecationWarning(const GlobalObject& aGlobal,
DeprecatedOperations aOperation) {
if (NS_IsMainThread()) {
nsCOMPtr<nsPIDOMWindowInner> window =
do_QueryInterface(aGlobal.GetAsSupports());
if (window && window->GetExtantDoc()) {
window->GetExtantDoc()->WarnOnceAbout(aOperation);
}
return;
}
WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aGlobal.Context());
if (!workerPrivate) {
return;
}
RefPtr<DeprecationWarningRunnable> runnable =
new DeprecationWarningRunnable(aOperation);
runnable->Dispatch(workerPrivate);
}
void MaybeReportDeprecation(const GlobalObject& aGlobal,
DeprecatedOperations aOperation) {
nsCOMPtr<nsIURI> uri;
if (NS_IsMainThread()) {
nsCOMPtr<nsPIDOMWindowInner> window =
do_QueryInterface(aGlobal.GetAsSupports());
if (!window || !window->GetExtantDoc()) {
return;
}
uri = window->GetExtantDoc()->GetDocumentURI();
} else {
WorkerPrivate* workerPrivate =
GetWorkerPrivateFromContext(aGlobal.Context());
if (!workerPrivate) {
return;
}
uri = workerPrivate->GetResolvedScriptURI();
}
if (NS_WARN_IF(!uri)) {
return;
}
nsAutoString fileName;
Nullable<uint32_t> lineNumber;
Nullable<uint32_t> columnNumber;
uint32_t line = 0;
uint32_t column = 0;
if (nsJSUtils::GetCallingLocation(aGlobal.Context(), fileName, &line,
&column)) {
lineNumber.SetValue(line);
columnNumber.SetValue(column);
}
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
MOZ_ASSERT(global);
ReportDeprecation(global, uri, aOperation, fileName, lineNumber,
columnNumber);
}
} // anonymous namespace
void DeprecationWarning(JSContext* aCx, JSObject* aObject,
DeprecatedOperations aOperation) {
GlobalObject global(aCx, aObject);
if (global.Failed()) {
NS_ERROR("Could not create global for DeprecationWarning");
return;
}
DeprecationWarning(global, aOperation);
}
void DeprecationWarning(const GlobalObject& aGlobal,
DeprecatedOperations aOperation) {
MaybeShowDeprecationWarning(aGlobal, aOperation);
MaybeReportDeprecation(aGlobal, aOperation);
}
namespace binding_detail {
JSObject* UnprivilegedJunkScopeOrWorkerGlobal(const fallible_t&) {
if (NS_IsMainThread()) {
return xpc::UnprivilegedJunkScope(fallible);
}
return GetCurrentThreadWorkerGlobal();
}
JSObject* UnprivilegedJunkScopeOrWorkerGlobal() {
JSObject* scope = UnprivilegedJunkScopeOrWorkerGlobal(fallible);
MOZ_RELEASE_ASSERT(scope);
return scope;
}
} // namespace binding_detail
JS::Handle<JSObject*> GetPerInterfaceObjectHandle(
JSContext* aCx, size_t aSlotId, CreateInterfaceObjectsMethod aCreator,
bool aDefineOnGlobal) {
/* Make sure our global is sane. Hopefully we can remove this sometime */
JSObject* global = JS::CurrentGlobalOrNull(aCx);
if (!(JS::GetClass(global)->flags & JSCLASS_DOM_GLOBAL)) {
return nullptr;
}
/* Check to see whether the interface objects are already installed */
ProtoAndIfaceCache& protoAndIfaceCache = *GetProtoAndIfaceCache(global);
if (!protoAndIfaceCache.HasEntryInSlot(aSlotId)) {
JS::Rooted<JSObject*> rootedGlobal(aCx, global);
aCreator(aCx, rootedGlobal, protoAndIfaceCache, aDefineOnGlobal);
}
/*
* The object might _still_ be null, but that's OK.
*
* Calling fromMarkedLocation() is safe because protoAndIfaceCache is
* traced by TraceProtoAndIfaceCache() and its contents are never
* changed after they have been set.
*
* Calling address() avoids the read barrier that does gray unmarking, but
* it's not possible for the object to be gray here.
*/
const JS::Heap<JSObject*>& entrySlot =
protoAndIfaceCache.EntrySlotMustExist(aSlotId);
JS::AssertObjectIsNotGray(entrySlot);
return JS::Handle<JSObject*>::fromMarkedLocation(entrySlot.address());
}
namespace binding_detail {
bool IsGetterEnabled(JSContext* aCx, JS::Handle<JSObject*> aObj,
JSJitGetterOp aGetter,
const Prefable<const JSPropertySpec>* aAttributes) {
MOZ_ASSERT(aAttributes);
MOZ_ASSERT(aAttributes->specs);
do {
if (aAttributes->isEnabled(aCx, aObj)) {
const JSPropertySpec* specs = aAttributes->specs;
do {
if (!specs->isAccessor() || specs->isSelfHosted()) {
// It won't have a JSJitGetterOp.
continue;
}
const JSJitInfo* info = specs->u.accessors.getter.native.info;
if (!info) {
continue;
}
MOZ_ASSERT(info->type() == JSJitInfo::OpType::Getter);
if (info->getter == aGetter) {
return true;
}
} while ((++specs)->name);
}
} while ((++aAttributes)->specs);
// Didn't find it.
return false;
}
} // namespace binding_detail
} // namespace dom
} // namespace mozilla
|