summaryrefslogtreecommitdiffstats
path: root/dom/promise/Promise.cpp
blob: f636a91010802aafdbd7c9fdc8ab970bc852dd7a (plain)
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
/* -*- 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 "mozilla/dom/Promise.h"

#include "js/Debug.h"

#include "mozilla/Atomics.h"
#include "mozilla/CycleCollectedJSContext.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/Preferences.h"

#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/DOMError.h"
#include "mozilla/dom/DOMException.h"
#include "mozilla/dom/DOMExceptionBinding.h"
#include "mozilla/dom/MediaStreamError.h"
#include "mozilla/dom/PromiseBinding.h"
#include "mozilla/dom/ScriptSettings.h"

#include "jsfriendapi.h"
#include "js/StructuredClone.h"
#include "nsContentUtils.h"
#include "nsGlobalWindow.h"
#include "nsIScriptObjectPrincipal.h"
#include "nsJSEnvironment.h"
#include "nsJSPrincipals.h"
#include "nsJSUtils.h"
#include "nsPIDOMWindow.h"
#include "PromiseCallback.h"
#include "PromiseDebugging.h"
#include "PromiseNativeHandler.h"
#include "PromiseWorkerProxy.h"
#include "WorkerPrivate.h"
#include "WorkerRunnable.h"
#include "WrapperFactory.h"
#include "xpcpublic.h"

namespace mozilla {
namespace dom {

namespace {
// Generator used by Promise::GetID.
Atomic<uintptr_t> gIDGenerator(0);
} // namespace

using namespace workers;

#ifndef SPIDERMONKEY_PROMISE
// This class processes the promise's callbacks with promise's result.
class PromiseReactionJob final : public Runnable
{
public:
  PromiseReactionJob(Promise* aPromise,
                     PromiseCallback* aCallback,
                     const JS::Value& aValue)
    : mPromise(aPromise)
    , mCallback(aCallback)
    , mValue(CycleCollectedJSContext::Get()->Context(), aValue)
  {
    MOZ_ASSERT(aPromise);
    MOZ_ASSERT(aCallback);
    MOZ_COUNT_CTOR(PromiseReactionJob);
  }

  virtual
  ~PromiseReactionJob()
  {
    NS_ASSERT_OWNINGTHREAD(PromiseReactionJob);
    MOZ_COUNT_DTOR(PromiseReactionJob);
  }

protected:
  NS_IMETHOD
  Run() override
  {
    NS_ASSERT_OWNINGTHREAD(PromiseReactionJob);

    MOZ_ASSERT(mPromise->GetWrapper()); // It was preserved!

    AutoJSAPI jsapi;
    if (!jsapi.Init(mPromise->GetWrapper())) {
      return NS_ERROR_FAILURE;
    }
    JSContext* cx = jsapi.cx();

    JS::Rooted<JS::Value> value(cx, mValue);
    if (!MaybeWrapValue(cx, &value)) {
      NS_WARNING("Failed to wrap value into the right compartment.");
      JS_ClearPendingException(cx);
      return NS_OK;
    }

    JS::Rooted<JSObject*> asyncStack(cx, mPromise->mAllocationStack);

    {
      Maybe<JS::AutoSetAsyncStackForNewCalls> sas;
      if (asyncStack) {
        sas.emplace(cx, asyncStack, "Promise");
      }
      mCallback->Call(cx, value);
    }

    return NS_OK;
  }

private:
  RefPtr<Promise> mPromise;
  RefPtr<PromiseCallback> mCallback;
  JS::PersistentRooted<JS::Value> mValue;
  NS_DECL_OWNINGTHREAD;
};

/*
 * Utilities for thenable callbacks.
 *
 * A thenable is a { then: function(resolve, reject) { } }.
 * `then` is called with a resolve and reject callback pair.
 * Since only one of these should be called at most once (first call wins), the
 * two keep a reference to each other in SLOT_DATA. When either of them is
 * called, the references are cleared. Further calls are ignored.
 */
namespace {
void
LinkThenableCallables(JSContext* aCx, JS::Handle<JSObject*> aResolveFunc,
                      JS::Handle<JSObject*> aRejectFunc)
{
  js::SetFunctionNativeReserved(aResolveFunc, Promise::SLOT_DATA,
                                JS::ObjectValue(*aRejectFunc));
  js::SetFunctionNativeReserved(aRejectFunc, Promise::SLOT_DATA,
                                JS::ObjectValue(*aResolveFunc));
}

/*
 * Returns false if callback was already called before, otherwise breaks the
 * links and returns true.
 */
bool
MarkAsCalledIfNotCalledBefore(JSContext* aCx, JS::Handle<JSObject*> aFunc)
{
  JS::Value otherFuncVal =
    js::GetFunctionNativeReserved(aFunc, Promise::SLOT_DATA);

  if (!otherFuncVal.isObject()) {
    return false;
  }

  JSObject* otherFuncObj = &otherFuncVal.toObject();
  MOZ_ASSERT(js::GetFunctionNativeReserved(otherFuncObj,
                                           Promise::SLOT_DATA).isObject());

  // Break both references.
  js::SetFunctionNativeReserved(aFunc, Promise::SLOT_DATA,
                                JS::UndefinedValue());
  js::SetFunctionNativeReserved(otherFuncObj, Promise::SLOT_DATA,
                                JS::UndefinedValue());

  return true;
}

Promise*
GetPromise(JSContext* aCx, JS::Handle<JSObject*> aFunc)
{
  JS::Value promiseVal = js::GetFunctionNativeReserved(aFunc,
                                                       Promise::SLOT_PROMISE);

  MOZ_ASSERT(promiseVal.isObject());

  Promise* promise;
  UNWRAP_OBJECT(Promise, &promiseVal.toObject(), promise);
  return promise;
}
} // namespace

// Runnable to resolve thenables.
// Equivalent to the specification's ResolvePromiseViaThenableTask.
class PromiseResolveThenableJob final : public Runnable
{
public:
  PromiseResolveThenableJob(Promise* aPromise,
                            JS::Handle<JSObject*> aThenable,
                            PromiseInit* aThen)
    : mPromise(aPromise)
    , mThenable(CycleCollectedJSContext::Get()->Context(), aThenable)
    , mThen(aThen)
  {
    MOZ_ASSERT(aPromise);
    MOZ_COUNT_CTOR(PromiseResolveThenableJob);
  }

  virtual
  ~PromiseResolveThenableJob()
  {
    NS_ASSERT_OWNINGTHREAD(PromiseResolveThenableJob);
    MOZ_COUNT_DTOR(PromiseResolveThenableJob);
  }

protected:
  NS_IMETHOD
  Run() override
  {
    NS_ASSERT_OWNINGTHREAD(PromiseResolveThenableJob);

    MOZ_ASSERT(mPromise->GetWrapper()); // It was preserved!

    AutoJSAPI jsapi;
    // If we ever change which compartment we're working in here, make sure to
    // fix the fast-path for resolved-with-a-Promise in ResolveInternal.
    if (!jsapi.Init(mPromise->GetWrapper())) {
      return NS_ERROR_FAILURE;
    }
    JSContext* cx = jsapi.cx();

    JS::Rooted<JSObject*> resolveFunc(cx,
      mPromise->CreateThenableFunction(cx, mPromise, PromiseCallback::Resolve));

    if (!resolveFunc) {
      mPromise->HandleException(cx);
      return NS_OK;
    }

    JS::Rooted<JSObject*> rejectFunc(cx,
      mPromise->CreateThenableFunction(cx, mPromise, PromiseCallback::Reject));
    if (!rejectFunc) {
      mPromise->HandleException(cx);
      return NS_OK;
    }

    LinkThenableCallables(cx, resolveFunc, rejectFunc);

    ErrorResult rv;

    JS::Rooted<JSObject*> rootedThenable(cx, mThenable);

    mThen->Call(rootedThenable, resolveFunc, rejectFunc, rv,
                "promise thenable", CallbackObject::eRethrowExceptions,
                mPromise->Compartment());

    rv.WouldReportJSException();
    if (rv.Failed()) {
      JS::Rooted<JS::Value> exn(cx);
      { // Scope for JSAutoCompartment

        // Convert the ErrorResult to a JS exception object that we can reject
        // ourselves with.  This will be exactly the exception that would get
        // thrown from a binding method whose ErrorResult ended up with
        // whatever is on "rv" right now.
        JSAutoCompartment ac(cx, mPromise->GlobalJSObject());
        DebugOnly<bool> conversionResult = ToJSValue(cx, rv, &exn);
        MOZ_ASSERT(conversionResult);
      }

      bool couldMarkAsCalled = MarkAsCalledIfNotCalledBefore(cx, resolveFunc);

      // If we could mark as called, neither of the callbacks had been called
      // when the exception was thrown. So we can reject the Promise.
      if (couldMarkAsCalled) {
        bool ok = JS_WrapValue(cx, &exn);
        MOZ_ASSERT(ok);
        if (!ok) {
          NS_WARNING("Failed to wrap value into the right compartment.");
        }

        mPromise->RejectInternal(cx, exn);
      }
      // At least one of resolveFunc or rejectFunc have been called, so ignore
      // the exception. FIXME(nsm): This should be reported to the error
      // console though, for debugging.
    }

    return rv.StealNSResult();
  }

private:
  RefPtr<Promise> mPromise;
  JS::PersistentRooted<JSObject*> mThenable;
  RefPtr<PromiseInit> mThen;
  NS_DECL_OWNINGTHREAD;
};

// A struct implementing
// <http://www.ecma-international.org/ecma-262/6.0/#sec-promisecapability-records>.
// While the spec holds on to these in some places, in practice those places
// don't actually need everything from this struct, so we explicitly grab
// members from it as needed in those situations.  That allows us to make this a
// stack-only struct and keep the rooting simple.
//
// We also add an optimization for the (common) case when we discover that the
// Promise constructor we're supposed to use is in fact the canonical Promise
// constructor.  In that case we will just set mNativePromise in our
// PromiseCapability and not set mPromise/mResolve/mReject; the correct
// callbacks will be the standard Promise ones, and we don't really want to
// synthesize JSFunctions for them in that situation.
struct MOZ_STACK_CLASS Promise::PromiseCapability
{
  explicit PromiseCapability(JSContext* aCx)
    : mPromise(aCx)
    , mResolve(aCx)
    , mReject(aCx)
  {}

  // Take an exception on aCx and try to convert it into a promise rejection.
  // Note that this can result in a new exception being thrown on aCx, or an
  // exception getting thrown on aRv.  On entry to this method, aRv is assumed
  // to not be a failure.  This should only be called if NewPromiseCapability
  // succeeded on this PromiseCapability.
  void RejectWithException(JSContext* aCx, ErrorResult& aRv);

  // Return a JS::Value representing the promise.  This should only be called if
  // NewPromiseCapability succeeded on this PromiseCapability.  It makes no
  // guarantees about compartments (e.g. in the mNativePromise case it's in the
  // compartment of the reflector, but in the mPromise case it might be in the
  // compartment of some cross-compartment wrapper for a reflector).
  JS::Value PromiseValue() const;

  // All the JS::Value fields of this struct are actually objects, but for our
  // purposes it's simpler to store them as JS::Value.

  // [[Promise]].
  JS::Rooted<JSObject*> mPromise;
  // [[Resolve]].  Value in the context compartment.
  JS::Rooted<JS::Value> mResolve;
  // [[Reject]].  Value in the context compartment.
  JS::Rooted<JS::Value> mReject;
  // If mNativePromise is non-null, we should use it, not mPromise.
  RefPtr<Promise> mNativePromise;

private:
  // We don't want to allow creation of temporaries of this type, ever.
  PromiseCapability(const PromiseCapability&) = delete;
  PromiseCapability(PromiseCapability&&) = delete;
};

void
Promise::PromiseCapability::RejectWithException(JSContext* aCx,
                                                ErrorResult& aRv)
{
  // This method basically implements
  // http://www.ecma-international.org/ecma-262/6.0/#sec-ifabruptrejectpromise
  // or at least the parts of it that happen if we have an abrupt completion.

  MOZ_ASSERT(!aRv.Failed());
  MOZ_ASSERT(mNativePromise || mPromise,
             "NewPromiseCapability didn't succeed");

  JS::Rooted<JS::Value> exn(aCx);
  if (!JS_GetPendingException(aCx, &exn)) {
    // This is an uncatchable exception, so can't be converted into a rejection.
    // Just rethrow that on aRv.
    aRv.ThrowUncatchableException();
    return;
  }

  JS_ClearPendingException(aCx);

  // If we have a native promise, just reject it without trying to call out into
  // JS.
  if (mNativePromise) {
    mNativePromise->MaybeRejectInternal(aCx, exn);
    return;
  }

  JS::Rooted<JS::Value> ignored(aCx);
  if (!JS::Call(aCx, JS::UndefinedHandleValue, mReject, JS::HandleValueArray(exn),
                &ignored)) {
    aRv.NoteJSContextException(aCx);
  }
}

JS::Value
Promise::PromiseCapability::PromiseValue() const
{
  MOZ_ASSERT(mNativePromise || mPromise,
             "NewPromiseCapability didn't succeed");

  if (mNativePromise) {
    return JS::ObjectValue(*mNativePromise->GetWrapper());
  }

  return JS::ObjectValue(*mPromise);
}

#endif // SPIDERMONKEY_PROMISE

// Promise

NS_IMPL_CYCLE_COLLECTION_CLASS(Promise)

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(Promise)
#ifndef SPIDERMONKEY_PROMISE
#if defined(DOM_PROMISE_DEPRECATED_REPORTING)
  tmp->MaybeReportRejectedOnce();
#else
  tmp->mResult = JS::UndefinedValue();
#endif // defined(DOM_PROMISE_DEPRECATED_REPORTING)
#endif // SPIDERMONKEY_PROMISE
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mGlobal)
#ifndef SPIDERMONKEY_PROMISE
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mResolveCallbacks)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mRejectCallbacks)
  NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
#else // SPIDERMONKEY_PROMISE
  tmp->mPromiseObj = nullptr;
#endif // SPIDERMONKEY_PROMISE
NS_IMPL_CYCLE_COLLECTION_UNLINK_END

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(Promise)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mGlobal)
#ifndef SPIDERMONKEY_PROMISE
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mResolveCallbacks)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRejectCallbacks)
#endif // SPIDERMONKEY_PROMISE
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(Promise)
#ifndef SPIDERMONKEY_PROMISE
  NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mResult)
  NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mAllocationStack)
  NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mRejectionStack)
  NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mFullfillmentStack)
  NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER
#else // SPIDERMONKEY_PROMISE
  NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mPromiseObj);
#endif // SPIDERMONKEY_PROMISE
NS_IMPL_CYCLE_COLLECTION_TRACE_END

#ifndef SPIDERMONKEY_PROMISE
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_BEGIN(Promise)
  if (tmp->IsBlack()) {
    tmp->mResult.exposeToActiveJS();
    tmp->mAllocationStack.exposeToActiveJS();
    tmp->mRejectionStack.exposeToActiveJS();
    tmp->mFullfillmentStack.exposeToActiveJS();
    return true;
  }
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_END

NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_BEGIN(Promise)
  return tmp->IsBlackAndDoesNotNeedTracing(tmp);
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_END

NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_BEGIN(Promise)
  return tmp->IsBlack();
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_END
#endif // SPIDERMONKEY_PROMISE

NS_IMPL_CYCLE_COLLECTING_ADDREF(Promise)
NS_IMPL_CYCLE_COLLECTING_RELEASE(Promise)

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Promise)
#ifndef SPIDERMONKEY_PROMISE
  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
#endif // SPIDERMONKEY_PROMISE
  NS_INTERFACE_MAP_ENTRY(nsISupports)
  NS_INTERFACE_MAP_ENTRY(Promise)
NS_INTERFACE_MAP_END

Promise::Promise(nsIGlobalObject* aGlobal)
  : mGlobal(aGlobal)
#ifndef SPIDERMONKEY_PROMISE
  , mResult(JS::UndefinedValue())
  , mAllocationStack(nullptr)
  , mRejectionStack(nullptr)
  , mFullfillmentStack(nullptr)
  , mState(Pending)
#if defined(DOM_PROMISE_DEPRECATED_REPORTING)
  , mHadRejectCallback(false)
#endif // defined(DOM_PROMISE_DEPRECATED_REPORTING)
  , mTaskPending(false)
  , mResolvePending(false)
  , mIsLastInChain(true)
  , mWasNotifiedAsUncaught(false)
  , mID(0)
#else // SPIDERMONKEY_PROMISE
  , mPromiseObj(nullptr)
#endif // SPIDERMONKEY_PROMISE
{
  MOZ_ASSERT(mGlobal);

  mozilla::HoldJSObjects(this);

#ifndef SPIDERMONKEY_PROMISE
  mCreationTimestamp = TimeStamp::Now();
#endif // SPIDERMONKEY_PROMISE
}

Promise::~Promise()
{
#ifndef SPIDERMONKEY_PROMISE
#if defined(DOM_PROMISE_DEPRECATED_REPORTING)
  MaybeReportRejectedOnce();
#endif // defined(DOM_PROMISE_DEPRECATED_REPORTING)
#endif // SPIDERMONKEY_PROMISE
  mozilla::DropJSObjects(this);
}

#ifdef SPIDERMONKEY_PROMISE

bool
Promise::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto,
                    JS::MutableHandle<JSObject*> aWrapper)
{
#ifdef DEBUG
  binding_detail::AssertReflectorHasGivenProto(aCx, mPromiseObj, aGivenProto);
#endif // DEBUG
  aWrapper.set(mPromiseObj);
  return true;
}

// static
already_AddRefed<Promise>
Promise::Create(nsIGlobalObject* aGlobal, ErrorResult& aRv)
{
  if (!aGlobal) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }
  RefPtr<Promise> p = new Promise(aGlobal);
  p->CreateWrapper(nullptr, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }
  return p.forget();
}

// static
already_AddRefed<Promise>
Promise::Resolve(nsIGlobalObject* aGlobal, JSContext* aCx,
                 JS::Handle<JS::Value> aValue, ErrorResult& aRv)
{
  JSAutoCompartment ac(aCx, aGlobal->GetGlobalJSObject());
  JS::Rooted<JSObject*> p(aCx,
                          JS::CallOriginalPromiseResolve(aCx, aValue));
  if (!p) {
    aRv.NoteJSContextException(aCx);
    return nullptr;
  }

  return CreateFromExisting(aGlobal, p);
}

// static
already_AddRefed<Promise>
Promise::Reject(nsIGlobalObject* aGlobal, JSContext* aCx,
                JS::Handle<JS::Value> aValue, ErrorResult& aRv)
{
  JSAutoCompartment ac(aCx, aGlobal->GetGlobalJSObject());
  JS::Rooted<JSObject*> p(aCx,
                          JS::CallOriginalPromiseReject(aCx, aValue));
  if (!p) {
    aRv.NoteJSContextException(aCx);
    return nullptr;
  }

  return CreateFromExisting(aGlobal, p);
}

// static
already_AddRefed<Promise>
Promise::All(JSContext* aCx,
             const nsTArray<RefPtr<Promise>>& aPromiseList, ErrorResult& aRv)
{
  JS::Rooted<JSObject*> globalObj(aCx, JS::CurrentGlobalOrNull(aCx));
  if (!globalObj) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }

  nsCOMPtr<nsIGlobalObject> global = xpc::NativeGlobal(globalObj);
  if (!global) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }

  JS::AutoObjectVector promises(aCx);
  if (!promises.reserve(aPromiseList.Length())) {
    aRv.NoteJSContextException(aCx);
    return nullptr;
  }

  for (auto& promise : aPromiseList) {
    JS::Rooted<JSObject*> promiseObj(aCx, promise->PromiseObj());
    // Just in case, make sure these are all in the context compartment.
    if (!JS_WrapObject(aCx, &promiseObj)) {
      aRv.NoteJSContextException(aCx);
      return nullptr;
    }
    promises.infallibleAppend(promiseObj);
  }

  JS::Rooted<JSObject*> result(aCx, JS::GetWaitForAllPromise(aCx, promises));
  if (!result) {
    aRv.NoteJSContextException(aCx);
    return nullptr;
  }

  return CreateFromExisting(global, result);
}

void
Promise::Then(JSContext* aCx,
              // aCalleeGlobal may not be in the compartment of aCx, when called over
              // Xrays.
              JS::Handle<JSObject*> aCalleeGlobal,
              AnyCallback* aResolveCallback, AnyCallback* aRejectCallback,
              JS::MutableHandle<JS::Value> aRetval,
              ErrorResult& aRv)
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  // Let's hope this does the right thing with Xrays...  Ensure everything is
  // just in the caller compartment; that ought to do the trick.  In theory we
  // should consider aCalleeGlobal, but in practice our only caller is
  // DOMRequest::Then, which is not working with a Promise subclass, so things
  // should be OK.
  JS::Rooted<JSObject*> promise(aCx, PromiseObj());
  if (!JS_WrapObject(aCx, &promise)) {
    aRv.NoteJSContextException(aCx);
    return;
  }

  JS::Rooted<JSObject*> resolveCallback(aCx);
  if (aResolveCallback) {
    resolveCallback = aResolveCallback->Callback();
    if (!JS_WrapObject(aCx, &resolveCallback)) {
      aRv.NoteJSContextException(aCx);
      return;
    }
  }

  JS::Rooted<JSObject*> rejectCallback(aCx);
  if (aRejectCallback) {
    rejectCallback = aRejectCallback->Callback();
    if (!JS_WrapObject(aCx, &rejectCallback)) {
      aRv.NoteJSContextException(aCx);
      return;
    }
  }

  JS::Rooted<JSObject*> retval(aCx);
  retval = JS::CallOriginalPromiseThen(aCx, promise, resolveCallback,
                                       rejectCallback);
  if (!retval) {
    aRv.NoteJSContextException(aCx);
    return;
  }

  aRetval.setObject(*retval);
}

// We need a dummy function to pass to JS::NewPromiseObject.
static bool
DoNothingPromiseExecutor(JSContext*, unsigned aArgc, JS::Value* aVp)
{
  JS::CallArgs args = CallArgsFromVp(aArgc, aVp);
  args.rval().setUndefined();
  return true;
}

void
Promise::CreateWrapper(JS::Handle<JSObject*> aDesiredProto, ErrorResult& aRv)
{
  AutoJSAPI jsapi;
  if (!jsapi.Init(mGlobal)) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return;
  }
  JSContext* cx = jsapi.cx();

  JSFunction* doNothingFunc =
    JS_NewFunction(cx, DoNothingPromiseExecutor, /* nargs = */ 2,
                   /* flags = */ 0, nullptr);
  if (!doNothingFunc) {
    JS_ClearPendingException(cx);
    aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
    return;
  }

  JS::Rooted<JSObject*> doNothingObj(cx, JS_GetFunctionObject(doNothingFunc));
  mPromiseObj = JS::NewPromiseObject(cx, doNothingObj, aDesiredProto);
  if (!mPromiseObj) {
    JS_ClearPendingException(cx);
    aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
    return;
  }
}

void
Promise::MaybeResolve(JSContext* aCx,
                      JS::Handle<JS::Value> aValue)
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  JS::Rooted<JSObject*> p(aCx, PromiseObj());
  if (!JS::ResolvePromise(aCx, p, aValue)) {
    // Now what?  There's nothing sane to do here.
    JS_ClearPendingException(aCx);
  }
}

void
Promise::MaybeReject(JSContext* aCx,
                     JS::Handle<JS::Value> aValue)
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  JS::Rooted<JSObject*> p(aCx, PromiseObj());
  if (!JS::RejectPromise(aCx, p, aValue)) {
    // Now what?  There's nothing sane to do here.
    JS_ClearPendingException(aCx);
  }
}

#define SLOT_NATIVEHANDLER 0
#define SLOT_NATIVEHANDLER_TASK 1

enum class NativeHandlerTask : int32_t {
  Resolve,
  Reject
};

static bool
NativeHandlerCallback(JSContext* aCx, unsigned aArgc, JS::Value* aVp)
{
  JS::CallArgs args = CallArgsFromVp(aArgc, aVp);

  JS::Value v = js::GetFunctionNativeReserved(&args.callee(),
                                              SLOT_NATIVEHANDLER);
  MOZ_ASSERT(v.isObject());

  JS::Rooted<JSObject*> obj(aCx, &v.toObject());
  PromiseNativeHandler* handler = nullptr;
  if (NS_FAILED(UNWRAP_OBJECT(PromiseNativeHandler, &obj, handler))) {
    return Throw(aCx, NS_ERROR_UNEXPECTED);
  }

  v = js::GetFunctionNativeReserved(&args.callee(), SLOT_NATIVEHANDLER_TASK);
  NativeHandlerTask task = static_cast<NativeHandlerTask>(v.toInt32());

  if (task == NativeHandlerTask::Resolve) {
    handler->ResolvedCallback(aCx, args.get(0));
  } else {
    MOZ_ASSERT(task == NativeHandlerTask::Reject);
    handler->RejectedCallback(aCx, args.get(0));
  }

  return true;
}

static JSObject*
CreateNativeHandlerFunction(JSContext* aCx, JS::Handle<JSObject*> aHolder,
                            NativeHandlerTask aTask)
{
  JSFunction* func = js::NewFunctionWithReserved(aCx, NativeHandlerCallback,
                                                 /* nargs = */ 1,
                                                 /* flags = */ 0, nullptr);
  if (!func) {
    return nullptr;
  }

  JS::Rooted<JSObject*> obj(aCx, JS_GetFunctionObject(func));

  JS::ExposeObjectToActiveJS(aHolder);
  js::SetFunctionNativeReserved(obj, SLOT_NATIVEHANDLER,
                                JS::ObjectValue(*aHolder));
  js::SetFunctionNativeReserved(obj, SLOT_NATIVEHANDLER_TASK,
                                JS::Int32Value(static_cast<int32_t>(aTask)));

  return obj;
}

namespace {

class PromiseNativeHandlerShim final : public PromiseNativeHandler
{
  RefPtr<PromiseNativeHandler> mInner;

  ~PromiseNativeHandlerShim()
  {
  }

public:
  explicit PromiseNativeHandlerShim(PromiseNativeHandler* aInner)
    : mInner(aInner)
  {
    MOZ_ASSERT(mInner);
  }

  void
  ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override
  {
    mInner->ResolvedCallback(aCx, aValue);
    mInner = nullptr;
  }

  void
  RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override
  {
    mInner->RejectedCallback(aCx, aValue);
    mInner = nullptr;
  }

  bool
  WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto,
             JS::MutableHandle<JSObject*> aWrapper)
  {
    return PromiseNativeHandlerBinding::Wrap(aCx, this, aGivenProto, aWrapper);
  }

  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
  NS_DECL_CYCLE_COLLECTION_CLASS(PromiseNativeHandlerShim)
};

NS_IMPL_CYCLE_COLLECTION(PromiseNativeHandlerShim, mInner)

NS_IMPL_CYCLE_COLLECTING_ADDREF(PromiseNativeHandlerShim)
NS_IMPL_CYCLE_COLLECTING_RELEASE(PromiseNativeHandlerShim)

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(PromiseNativeHandlerShim)
  NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END

} // anonymous namespace

void
Promise::AppendNativeHandler(PromiseNativeHandler* aRunnable)
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  AutoJSAPI jsapi;
  if (NS_WARN_IF(!jsapi.Init(mGlobal))) {
    // Our API doesn't allow us to return a useful error.  Not like this should
    // happen anyway.
    return;
  }

  // The self-hosted promise js may keep the object we pass to it alive
  // for quite a while depending on when GC runs.  Therefore, pass a shim
  // object instead.  The shim will free its inner PromiseNativeHandler
  // after the promise has settled just like our previous c++ promises did.
  RefPtr<PromiseNativeHandlerShim> shim =
    new PromiseNativeHandlerShim(aRunnable);

  JSContext* cx = jsapi.cx();
  JS::Rooted<JSObject*> handlerWrapper(cx);
  // Note: PromiseNativeHandler is NOT wrappercached.  So we can't use
  // ToJSValue here, because it will try to do XPConnect wrapping on it, sadly.
  if (NS_WARN_IF(!shim->WrapObject(cx, nullptr, &handlerWrapper))) {
    // Again, no way to report errors.
    jsapi.ClearException();
    return;
  }

  JS::Rooted<JSObject*> resolveFunc(cx);
  resolveFunc =
    CreateNativeHandlerFunction(cx, handlerWrapper, NativeHandlerTask::Resolve);
  if (NS_WARN_IF(!resolveFunc)) {
    jsapi.ClearException();
    return;
  }

  JS::Rooted<JSObject*> rejectFunc(cx);
  rejectFunc =
    CreateNativeHandlerFunction(cx, handlerWrapper, NativeHandlerTask::Reject);
  if (NS_WARN_IF(!rejectFunc)) {
    jsapi.ClearException();
    return;
  }

  JS::Rooted<JSObject*> promiseObj(cx, PromiseObj());
  if (NS_WARN_IF(!JS::AddPromiseReactions(cx, promiseObj, resolveFunc,
                                          rejectFunc))) {
    jsapi.ClearException();
    return;
  }
}

void
Promise::HandleException(JSContext* aCx)
{
  JS::Rooted<JS::Value> exn(aCx);
  if (JS_GetPendingException(aCx, &exn)) {
    JS_ClearPendingException(aCx);
    // This is only called from MaybeSomething, so it's OK to MaybeReject here,
    // unlike in the version that's used when !SPIDERMONKEY_PROMISE.
    MaybeReject(aCx, exn);
  }
}

// static
already_AddRefed<Promise>
Promise::CreateFromExisting(nsIGlobalObject* aGlobal,
                            JS::Handle<JSObject*> aPromiseObj)
{
  MOZ_ASSERT(js::GetObjectCompartment(aGlobal->GetGlobalJSObject()) ==
             js::GetObjectCompartment(aPromiseObj));
  RefPtr<Promise> p = new Promise(aGlobal);
  p->mPromiseObj = aPromiseObj;
  return p.forget();
}

#else // SPIDERMONKEY_PROMISE

JSObject*
Promise::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
{
  return PromiseBinding::Wrap(aCx, this, aGivenProto);
}

already_AddRefed<Promise>
Promise::Create(nsIGlobalObject* aGlobal, ErrorResult& aRv,
                JS::Handle<JSObject*> aDesiredProto)
{
  if (!aGlobal) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }
  RefPtr<Promise> p = new Promise(aGlobal);
  p->CreateWrapper(aDesiredProto, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }
  return p.forget();
}

void
Promise::CreateWrapper(JS::Handle<JSObject*> aDesiredProto, ErrorResult& aRv)
{
  AutoJSAPI jsapi;
  if (!jsapi.Init(mGlobal)) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return;
  }
  JSContext* cx = jsapi.cx();

  JS::Rooted<JS::Value> wrapper(cx);
  if (!GetOrCreateDOMReflector(cx, this, &wrapper, aDesiredProto)) {
    JS_ClearPendingException(cx);
    aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
    return;
  }

  dom::PreserveWrapper(this);

  // Now grab our allocation stack
  if (!CaptureStack(cx, mAllocationStack)) {
    JS_ClearPendingException(cx);
    aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
    return;
  }

  JS::RootedObject obj(cx, &wrapper.toObject());
  JS::dbg::onNewPromise(cx, obj);
}

void
Promise::MaybeResolve(JSContext* aCx,
                      JS::Handle<JS::Value> aValue)
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  MaybeResolveInternal(aCx, aValue);
}

void
Promise::MaybeReject(JSContext* aCx,
                     JS::Handle<JS::Value> aValue)
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  MaybeRejectInternal(aCx, aValue);
}

#endif // SPIDERMONKEY_PROMISE

void
Promise::MaybeResolveWithUndefined()
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  MaybeResolve(JS::UndefinedHandleValue);
}

void
Promise::MaybeReject(const RefPtr<MediaStreamError>& aArg) {
  NS_ASSERT_OWNINGTHREAD(Promise);

  MaybeSomething(aArg, &Promise::MaybeReject);
}

void
Promise::MaybeRejectWithUndefined()
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  MaybeSomething(JS::UndefinedHandleValue, &Promise::MaybeReject);
}

#ifdef SPIDERMONKEY_PROMISE
void
Promise::ReportRejectedPromise(JSContext* aCx, JS::HandleObject aPromise)
{
  MOZ_ASSERT(!js::IsWrapper(aPromise));

  MOZ_ASSERT(JS::GetPromiseState(aPromise) == JS::PromiseState::Rejected);

  JS::Rooted<JS::Value> result(aCx, JS::GetPromiseResult(aPromise));

  js::ErrorReport report(aCx);
  if (!report.init(aCx, result, js::ErrorReport::NoSideEffects)) {
    JS_ClearPendingException(aCx);
    return;
  }

  RefPtr<xpc::ErrorReport> xpcReport = new xpc::ErrorReport();
  bool isMainThread = MOZ_LIKELY(NS_IsMainThread());
  bool isChrome = isMainThread ? nsContentUtils::IsSystemPrincipal(nsContentUtils::ObjectPrincipal(aPromise))
                               : GetCurrentThreadWorkerPrivate()->IsChromeWorker();
  nsGlobalWindow* win = isMainThread ? xpc::WindowGlobalOrNull(aPromise) : nullptr;
  xpcReport->Init(report.report(), report.toStringResult().c_str(), isChrome,
                  win ? win->AsInner()->WindowID() : 0);

  // Now post an event to do the real reporting async
  NS_DispatchToMainThread(new AsyncErrorReporter(xpcReport));
}
#endif // defined(SPIDERMONKEY_PROMISE)

bool
Promise::PerformMicroTaskCheckpoint()
{
  MOZ_ASSERT(NS_IsMainThread(), "Wrong thread!");

  CycleCollectedJSContext* context = CycleCollectedJSContext::Get();

  // On the main thread, we always use the main promise micro task queue.
  std::queue<nsCOMPtr<nsIRunnable>>& microtaskQueue =
    context->GetPromiseMicroTaskQueue();

  if (microtaskQueue.empty()) {
    return false;
  }

  AutoSlowOperation aso;

  do {
    nsCOMPtr<nsIRunnable> runnable = microtaskQueue.front().forget();
    MOZ_ASSERT(runnable);

    // This function can re-enter, so we remove the element before calling.
    microtaskQueue.pop();
    nsresult rv = runnable->Run();
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return false;
    }
    aso.CheckForInterrupt();
    context->AfterProcessMicrotask();
  } while (!microtaskQueue.empty());

  return true;
}

void
Promise::PerformWorkerMicroTaskCheckpoint()
{
  MOZ_ASSERT(!NS_IsMainThread(), "Wrong thread!");

  CycleCollectedJSContext* context = CycleCollectedJSContext::Get();
  if (!context) {
    return;
  }

  for (;;) {
    // For a normal microtask checkpoint, we try to use the debugger microtask
    // queue first. If the debugger queue is empty, we use the normal microtask
    // queue instead.
    std::queue<nsCOMPtr<nsIRunnable>>* microtaskQueue =
      &context->GetDebuggerPromiseMicroTaskQueue();

    if (microtaskQueue->empty()) {
      microtaskQueue = &context->GetPromiseMicroTaskQueue();
      if (microtaskQueue->empty()) {
        break;
      }
    }

    nsCOMPtr<nsIRunnable> runnable = microtaskQueue->front().forget();
    MOZ_ASSERT(runnable);

    // This function can re-enter, so we remove the element before calling.
    microtaskQueue->pop();
    nsresult rv = runnable->Run();
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return;
    }
    context->AfterProcessMicrotask();
  }
}

void
Promise::PerformWorkerDebuggerMicroTaskCheckpoint()
{
  MOZ_ASSERT(!NS_IsMainThread(), "Wrong thread!");

  CycleCollectedJSContext* context = CycleCollectedJSContext::Get();
  if (!context) {
    return;
  }

  for (;;) {
    // For a debugger microtask checkpoint, we always use the debugger microtask
    // queue.
    std::queue<nsCOMPtr<nsIRunnable>>* microtaskQueue =
      &context->GetDebuggerPromiseMicroTaskQueue();

    if (microtaskQueue->empty()) {
      break;
    }

    nsCOMPtr<nsIRunnable> runnable = microtaskQueue->front().forget();
    MOZ_ASSERT(runnable);

    // This function can re-enter, so we remove the element before calling.
    microtaskQueue->pop();
    nsresult rv = runnable->Run();
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return;
    }
    context->AfterProcessMicrotask();
  }
}

#ifndef SPIDERMONKEY_PROMISE

/* static */ bool
Promise::JSCallback(JSContext* aCx, unsigned aArgc, JS::Value* aVp)
{
  JS::CallArgs args = CallArgsFromVp(aArgc, aVp);

  JS::Rooted<JS::Value> v(aCx,
                          js::GetFunctionNativeReserved(&args.callee(),
                                                        SLOT_PROMISE));
  MOZ_ASSERT(v.isObject());

  Promise* promise;
  if (NS_FAILED(UNWRAP_OBJECT(Promise, &v.toObject(), promise))) {
    return Throw(aCx, NS_ERROR_UNEXPECTED);
  }

  v = js::GetFunctionNativeReserved(&args.callee(), SLOT_DATA);
  PromiseCallback::Task task = static_cast<PromiseCallback::Task>(v.toInt32());

  if (task == PromiseCallback::Resolve) {
    if (!promise->CaptureStack(aCx, promise->mFullfillmentStack)) {
      return false;
    }
    promise->MaybeResolveInternal(aCx, args.get(0));
  } else {
    promise->MaybeRejectInternal(aCx, args.get(0));
    if (!promise->CaptureStack(aCx, promise->mRejectionStack)) {
      return false;
    }
  }

  args.rval().setUndefined();
  return true;
}

/*
 * Common bits of (JSCallbackThenableResolver/JSCallbackThenableRejecter).
 * Resolves/rejects the Promise if it is ok to do so, based on whether either of
 * the callbacks have been called before or not.
 */
/* static */ bool
Promise::ThenableResolverCommon(JSContext* aCx, uint32_t aTask,
                                unsigned aArgc, JS::Value* aVp)
{
  JS::CallArgs args = CallArgsFromVp(aArgc, aVp);
  JS::Rooted<JSObject*> thisFunc(aCx, &args.callee());
  if (!MarkAsCalledIfNotCalledBefore(aCx, thisFunc)) {
    // A function from this pair has been called before.
    args.rval().setUndefined();
    return true;
  }

  Promise* promise = GetPromise(aCx, thisFunc);
  MOZ_ASSERT(promise);

  if (aTask == PromiseCallback::Resolve) {
    promise->ResolveInternal(aCx, args.get(0));
  } else {
    promise->RejectInternal(aCx, args.get(0));
  }

  args.rval().setUndefined();
  return true;
}

/* static */ bool
Promise::JSCallbackThenableResolver(JSContext* aCx,
                                    unsigned aArgc, JS::Value* aVp)
{
  return ThenableResolverCommon(aCx, PromiseCallback::Resolve, aArgc, aVp);
}

/* static */ bool
Promise::JSCallbackThenableRejecter(JSContext* aCx,
                                    unsigned aArgc, JS::Value* aVp)
{
  return ThenableResolverCommon(aCx, PromiseCallback::Reject, aArgc, aVp);
}

/* static */ JSObject*
Promise::CreateFunction(JSContext* aCx, Promise* aPromise, int32_t aTask)
{
  // If this function ever changes, make sure to update
  // WrapperPromiseCallback::GetDependentPromise.
  JSFunction* func = js::NewFunctionWithReserved(aCx, JSCallback,
                                                 1 /* nargs */, 0 /* flags */,
                                                 nullptr);
  if (!func) {
    return nullptr;
  }

  JS::Rooted<JSObject*> obj(aCx, JS_GetFunctionObject(func));

  JS::Rooted<JS::Value> promiseObj(aCx);
  if (!dom::GetOrCreateDOMReflector(aCx, aPromise, &promiseObj)) {
    return nullptr;
  }

  JS::ExposeValueToActiveJS(promiseObj);
  js::SetFunctionNativeReserved(obj, SLOT_PROMISE, promiseObj);
  js::SetFunctionNativeReserved(obj, SLOT_DATA, JS::Int32Value(aTask));

  return obj;
}

/* static */ JSObject*
Promise::CreateThenableFunction(JSContext* aCx, Promise* aPromise, uint32_t aTask)
{
  JSNative whichFunc =
    aTask == PromiseCallback::Resolve ? JSCallbackThenableResolver :
                                        JSCallbackThenableRejecter ;

  JSFunction* func = js::NewFunctionWithReserved(aCx, whichFunc,
                                                 1 /* nargs */, 0 /* flags */,
                                                 nullptr);
  if (!func) {
    return nullptr;
  }

  JS::Rooted<JSObject*> obj(aCx, JS_GetFunctionObject(func));

  JS::Rooted<JS::Value> promiseObj(aCx);
  if (!dom::GetOrCreateDOMReflector(aCx, aPromise, &promiseObj)) {
    return nullptr;
  }

  JS::ExposeValueToActiveJS(promiseObj);
  js::SetFunctionNativeReserved(obj, SLOT_PROMISE, promiseObj);

  return obj;
}

/* static */ already_AddRefed<Promise>
Promise::Constructor(const GlobalObject& aGlobal, PromiseInit& aInit,
                     ErrorResult& aRv, JS::Handle<JSObject*> aDesiredProto)
{
  nsCOMPtr<nsIGlobalObject> global;
  global = do_QueryInterface(aGlobal.GetAsSupports());
  if (!global) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }

  RefPtr<Promise> promise = Create(global, aRv, aDesiredProto);
  if (aRv.Failed()) {
    return nullptr;
  }

  promise->CallInitFunction(aGlobal, aInit, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }

  return promise.forget();
}

void
Promise::CallInitFunction(const GlobalObject& aGlobal,
                          PromiseInit& aInit, ErrorResult& aRv)
{
  JSContext* cx = aGlobal.Context();

  JS::Rooted<JSObject*> resolveFunc(cx,
                                    CreateFunction(cx, this,
                                                   PromiseCallback::Resolve));
  if (!resolveFunc) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return;
  }

  JS::Rooted<JSObject*> rejectFunc(cx,
                                   CreateFunction(cx, this,
                                                  PromiseCallback::Reject));
  if (!rejectFunc) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return;
  }

  aInit.Call(resolveFunc, rejectFunc, aRv, "promise initializer",
             CallbackObject::eRethrowExceptions, Compartment());
  aRv.WouldReportJSException();

  if (aRv.Failed()) {
    if (aRv.IsUncatchableException()) {
      // Just propagate this to the caller.
      return;
    }

    // There are two possibilities here.  Either we've got a rethrown exception,
    // or we reported that already and synthesized a generic NS_ERROR_FAILURE on
    // the ErrorResult.  In the former case, it doesn't much matter how we get
    // the exception JS::Value from the ErrorResult to us, since we'll just end
    // up wrapping it into the right compartment as needed if we hand it to
    // someone.  But in the latter case we have to ensure that the new exception
    // object we create is created in our reflector compartment, not in our
    // current compartment, because in the case when we're a Promise constructor
    // called over Xrays creating it in the current compartment would mean
    // rejecting with a value that can't be accessed by code that can call
    // then() on this Promise.
    //
    // Luckily, MaybeReject(aRv) does exactly what we want here: it enters our
    // reflector compartment before trying to produce a JS::Value from the
    // ErrorResult.
    MaybeReject(aRv);
  }
}

#define GET_CAPABILITIES_EXECUTOR_RESOLVE_SLOT 0
#define GET_CAPABILITIES_EXECUTOR_REJECT_SLOT 1

namespace {
bool
GetCapabilitiesExecutor(JSContext* aCx, unsigned aArgc, JS::Value* aVp)
{
  // Implements
  // http://www.ecma-international.org/ecma-262/6.0/#sec-getcapabilitiesexecutor-functions
  // except we store the [[Resolve]] and [[Reject]] in our own internal slots,
  // not in a PromiseCapability.  The PromiseCapability will then read them from
  // us.
  JS::CallArgs args = CallArgsFromVp(aArgc, aVp);

  // Step 1 is an assert.

  // Step 2 doesn't need to be done, because it's just giving a name to the
  // PromiseCapability record which is supposed to be stored in an internal
  // slot.  But we don't store that at all, per the comment above; we just
  // directly store its [[Resolve]] and [[Reject]] members.

  // Steps 3 and 4.
  if (!js::GetFunctionNativeReserved(&args.callee(),
                                     GET_CAPABILITIES_EXECUTOR_RESOLVE_SLOT).isUndefined() ||
      !js::GetFunctionNativeReserved(&args.callee(),
                                     GET_CAPABILITIES_EXECUTOR_REJECT_SLOT).isUndefined()) {
    ErrorResult rv;
    rv.ThrowTypeError<MSG_PROMISE_CAPABILITY_HAS_SOMETHING_ALREADY>();
    return !rv.MaybeSetPendingException(aCx);
  }

  // Step 5.
  js::SetFunctionNativeReserved(&args.callee(),
                                GET_CAPABILITIES_EXECUTOR_RESOLVE_SLOT,
                                args.get(0));

  // Step 6.
  js::SetFunctionNativeReserved(&args.callee(),
                                GET_CAPABILITIES_EXECUTOR_REJECT_SLOT,
                                args.get(1));

  // Step 7.
  args.rval().setUndefined();
  return true;
}
} // anonymous namespace

/* static */ void
Promise::NewPromiseCapability(JSContext* aCx, nsIGlobalObject* aGlobal,
                              JS::Handle<JS::Value> aConstructor,
                              bool aForceCallbackCreation,
                              PromiseCapability& aCapability,
                              ErrorResult& aRv)
{
  // Implements
  // http://www.ecma-international.org/ecma-262/6.0/#sec-newpromisecapability

  if (!aConstructor.isObject() ||
      !JS::IsConstructor(&aConstructor.toObject())) {
    aRv.ThrowTypeError<MSG_ILLEGAL_PROMISE_CONSTRUCTOR>();
    return;
  }

  // Step 2 is a note.
  // Step 3 is already done because we got the PromiseCapability passed in.

  // Optimization: Check whether constructor is in fact the canonical
  // Promise constructor for aGlobal.
  JS::Rooted<JSObject*> global(aCx, aGlobal->GetGlobalJSObject());
  {
    // Scope for the JSAutoCompartment, since we need to enter the compartment
    // of global to get constructors from it.  Save the compartment we used to
    // be in, though; we'll need it later.
    JS::Rooted<JSObject*> callerGlobal(aCx, JS::CurrentGlobalOrNull(aCx));
    JSAutoCompartment ac(aCx, global);

    // Now wrap aConstructor into the compartment of aGlobal, so comparing it to
    // the canonical Promise for that compartment actually makes sense.
    JS::Rooted<JS::Value> constructorValue(aCx, aConstructor);
    if (!MaybeWrapObjectValue(aCx, &constructorValue)) {
      aRv.NoteJSContextException(aCx);
      return;
    }

    JSObject* defaultCtor = PromiseBinding::GetConstructorObject(aCx);
    if (!defaultCtor) {
      aRv.NoteJSContextException(aCx);
      return;
    }
    if (defaultCtor == &constructorValue.toObject()) {
      // This is the canonical Promise constructor.
      aCapability.mNativePromise = Promise::Create(aGlobal, aRv);
      if (aForceCallbackCreation) {
        // We have to be a bit careful here.  We want to create these functions
        // in the compartment in which they would be created if we actually
        // invoked the constructor via JS::Construct below.  That means our
        // callerGlobal compartment if aConstructor is an Xray and the reflector
        // compartment of the promise we're creating otherwise.  But note that
        // our callerGlobal compartment is precisely the reflector compartment
        // unless the call was done over Xrays, because the reflector
        // compartment comes from xpc::XrayAwareCalleeGlobal.  So we really just
        // want to create these functions in the callerGlobal compartment.
        MOZ_ASSERT(xpc::WrapperFactory::IsXrayWrapper(&aConstructor.toObject()) ||
                   callerGlobal == global);
        JSAutoCompartment ac2(aCx, callerGlobal);

        JSObject* resolveFuncObj =
          CreateFunction(aCx, aCapability.mNativePromise,
                         PromiseCallback::Resolve);
        if (!resolveFuncObj) {
          aRv.NoteJSContextException(aCx);
          return;
        }
        aCapability.mResolve.setObject(*resolveFuncObj);

        JSObject* rejectFuncObj =
          CreateFunction(aCx, aCapability.mNativePromise,
                         PromiseCallback::Reject);
        if (!rejectFuncObj) {
          aRv.NoteJSContextException(aCx);
          return;
        }
        aCapability.mReject.setObject(*rejectFuncObj);
      }
      return;
    }
  }

  // Step 4.
  // We can create our get-capabilities function in the calling compartment.  It
  // will work just as if we did |new promiseConstructor(function(a,b){}).
  // Notably, if we're called over Xrays that's all fine, because we will end up
  // creating the callbacks in the caller compartment in that case.
  JSFunction* getCapabilitiesFunc =
    js::NewFunctionWithReserved(aCx, GetCapabilitiesExecutor,
                                2 /* nargs */,
                                0 /* flags */,
                                nullptr);
  if (!getCapabilitiesFunc) {
    aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
    return;
  }

  JS::Rooted<JSObject*> getCapabilitiesObj(aCx);
  getCapabilitiesObj = JS_GetFunctionObject(getCapabilitiesFunc);

  // Step 5 doesn't need to be done, since we're not actually storing a
  // PromiseCapability in the executor; see the comments in
  // GetCapabilitiesExecutor above.

  // Step 6 and step 7.
  JS::Rooted<JS::Value> getCapabilities(aCx,
                                        JS::ObjectValue(*getCapabilitiesObj));
  JS::Rooted<JSObject*> promiseObj(aCx);
  if (!JS::Construct(aCx, aConstructor,
                     JS::HandleValueArray(getCapabilities),
                     &promiseObj)) {
    aRv.NoteJSContextException(aCx);
    return;
  }

  // Step 8 plus copying over the value to the PromiseCapability.
  JS::Rooted<JS::Value> v(aCx);
  v = js::GetFunctionNativeReserved(getCapabilitiesObj,
                                    GET_CAPABILITIES_EXECUTOR_RESOLVE_SLOT);
  if (!v.isObject() || !JS::IsCallable(&v.toObject())) {
    aRv.ThrowTypeError<MSG_PROMISE_RESOLVE_FUNCTION_NOT_CALLABLE>();
    return;
  }
  aCapability.mResolve = v;

  // Step 9 plus copying over the value to the PromiseCapability.
  v = js::GetFunctionNativeReserved(getCapabilitiesObj,
                                    GET_CAPABILITIES_EXECUTOR_REJECT_SLOT);
  if (!v.isObject() || !JS::IsCallable(&v.toObject())) {
    aRv.ThrowTypeError<MSG_PROMISE_REJECT_FUNCTION_NOT_CALLABLE>();
    return;
  }
  aCapability.mReject = v;

  // Step 10.
  aCapability.mPromise = promiseObj;

  // Step 11 doesn't need anything, since the PromiseCapability was passed in.
}

/* static */ void
Promise::Resolve(const GlobalObject& aGlobal, JS::Handle<JS::Value> aThisv,
                 JS::Handle<JS::Value> aValue,
                 JS::MutableHandle<JS::Value> aRetval, ErrorResult& aRv)
{
  // Implementation of
  // http://www.ecma-international.org/ecma-262/6.0/#sec-promise.resolve

  JSContext* cx = aGlobal.Context();

  nsCOMPtr<nsIGlobalObject> global =
    do_QueryInterface(aGlobal.GetAsSupports());
  if (!global) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return;
  }

  // Steps 1 and 2.
  if (!aThisv.isObject()) {
    aRv.ThrowTypeError<MSG_ILLEGAL_PROMISE_CONSTRUCTOR>();
    return;
  }

  // Step 3.  If a Promise was passed and matches our constructor, just return it.
  if (aValue.isObject()) {
    JS::Rooted<JSObject*> valueObj(cx, &aValue.toObject());
    Promise* nextPromise;
    nsresult rv = UNWRAP_OBJECT(Promise, valueObj, nextPromise);

    if (NS_SUCCEEDED(rv)) {
      JS::Rooted<JS::Value> constructor(cx);
      if (!JS_GetProperty(cx, valueObj, "constructor", &constructor)) {
        aRv.NoteJSContextException(cx);
        return;
      }

      // Cheat instead of calling JS_SameValue, since we know one's an object.
      if (aThisv == constructor) {
        aRetval.setObject(*valueObj);
        return;
      }
    }
  }

  // Step 4.
  PromiseCapability capability(cx);
  NewPromiseCapability(cx, global, aThisv, false, capability, aRv);
  // Step 5.
  if (aRv.Failed()) {
    return;
  }

  // Step 6.
  Promise* p = capability.mNativePromise;
  if (p) {
    p->MaybeResolveInternal(cx, aValue);
    p->mFullfillmentStack = p->mAllocationStack;
  } else {
    JS::Rooted<JS::Value> value(cx, aValue);
    JS::Rooted<JS::Value> ignored(cx);
    if (!JS::Call(cx, JS::UndefinedHandleValue /* thisVal */,
                  capability.mResolve, JS::HandleValueArray(value),
                  &ignored)) {
      // Step 7.
      aRv.NoteJSContextException(cx);
      return;
    }
  }

  // Step 8.
  aRetval.set(capability.PromiseValue());
}

/* static */ already_AddRefed<Promise>
Promise::Resolve(nsIGlobalObject* aGlobal, JSContext* aCx,
                 JS::Handle<JS::Value> aValue, ErrorResult& aRv)
{
  RefPtr<Promise> promise = Create(aGlobal, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }

  promise->MaybeResolveInternal(aCx, aValue);
  return promise.forget();
}

/* static */ void
Promise::Reject(const GlobalObject& aGlobal, JS::Handle<JS::Value> aThisv,
                JS::Handle<JS::Value> aValue,
                JS::MutableHandle<JS::Value> aRetval, ErrorResult& aRv)
{
  // Implementation of
  // http://www.ecma-international.org/ecma-262/6.0/#sec-promise.reject

  JSContext* cx = aGlobal.Context();

  nsCOMPtr<nsIGlobalObject> global =
    do_QueryInterface(aGlobal.GetAsSupports());
  if (!global) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return;
  }

  // Steps 1 and 2.
  if (!aThisv.isObject()) {
    aRv.ThrowTypeError<MSG_ILLEGAL_PROMISE_CONSTRUCTOR>();
    return;
  }

  // Step 3.
  PromiseCapability capability(cx);
  NewPromiseCapability(cx, global, aThisv, false, capability, aRv);
  // Step 4.
  if (aRv.Failed()) {
    return;
  }

  // Step 5.
  Promise* p = capability.mNativePromise;
  if (p) {
    p->MaybeRejectInternal(cx, aValue);
    p->mRejectionStack = p->mAllocationStack;
  } else {
    JS::Rooted<JS::Value> value(cx, aValue);
    JS::Rooted<JS::Value> ignored(cx);
    if (!JS::Call(cx, JS::UndefinedHandleValue /* thisVal */,
                  capability.mReject, JS::HandleValueArray(value),
                  &ignored)) {
      // Step 6.
      aRv.NoteJSContextException(cx);
      return;
    }
  }

  // Step 7.
  aRetval.set(capability.PromiseValue());
}

/* static */ already_AddRefed<Promise>
Promise::Reject(nsIGlobalObject* aGlobal, JSContext* aCx,
                JS::Handle<JS::Value> aValue, ErrorResult& aRv)
{
  RefPtr<Promise> promise = Create(aGlobal, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }

  promise->MaybeRejectInternal(aCx, aValue);
  return promise.forget();
}

namespace {
void
SpeciesConstructor(JSContext* aCx,
                   JS::Handle<JSObject*> promise,
                   JS::Handle<JS::Value> defaultCtor,
                   JS::MutableHandle<JS::Value> ctor,
                   ErrorResult& aRv)
{
  // Implements
  // http://www.ecma-international.org/ecma-262/6.0/#sec-speciesconstructor

  // Step 1.
  MOZ_ASSERT(promise);

  // Step 2.
  JS::Rooted<JS::Value> constructorVal(aCx);
  if (!JS_GetProperty(aCx, promise, "constructor", &constructorVal)) {
    // Step 3.
    aRv.NoteJSContextException(aCx);
    return;
  }

  // Step 4.
  if (constructorVal.isUndefined()) {
    ctor.set(defaultCtor);
    return;
  }

  // Step 5.
  if (!constructorVal.isObject()) {
    aRv.ThrowTypeError<MSG_ILLEGAL_PROMISE_CONSTRUCTOR>();
    return;
  }

  // Step 6.
  JS::Rooted<jsid> species(aCx,
    SYMBOL_TO_JSID(JS::GetWellKnownSymbol(aCx, JS::SymbolCode::species)));
  JS::Rooted<JS::Value> speciesVal(aCx);
  JS::Rooted<JSObject*> constructorObj(aCx, &constructorVal.toObject());
  if (!JS_GetPropertyById(aCx, constructorObj, species, &speciesVal)) {
    // Step 7.
    aRv.NoteJSContextException(aCx);
    return;
  }

  // Step 8.
  if (speciesVal.isNullOrUndefined()) {
    ctor.set(defaultCtor);
    return;
  }

  // Step 9.
  if (speciesVal.isObject() && JS::IsConstructor(&speciesVal.toObject())) {
    ctor.set(speciesVal);
    return;
  }

  // Step 10.
  aRv.ThrowTypeError<MSG_ILLEGAL_PROMISE_CONSTRUCTOR>();
}
} // anonymous namespace

void
Promise::Then(JSContext* aCx, JS::Handle<JSObject*> aCalleeGlobal,
              AnyCallback* aResolveCallback, AnyCallback* aRejectCallback,
              JS::MutableHandle<JS::Value> aRetval, ErrorResult& aRv)
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  // Implements
  // http://www.ecma-international.org/ecma-262/6.0/#sec-promise.prototype.then

  // Step 1.
  JS::Rooted<JS::Value> promiseVal(aCx, JS::ObjectValue(*GetWrapper()));
  if (!MaybeWrapObjectValue(aCx, &promiseVal)) {
    aRv.NoteJSContextException(aCx);
    return;
  }
  JS::Rooted<JSObject*> promiseObj(aCx, &promiseVal.toObject());
  MOZ_ASSERT(promiseObj);

  // Step 2 was done by the bindings.

  // Step 3.  We want to use aCalleeGlobal here because it will do the
  // right thing for us via Xrays (where we won't find @@species on
  // our promise constructor for now).
  JS::Rooted<JS::Value> defaultCtorVal(aCx);
  { // Scope for JSAutoCompartment
    JSAutoCompartment ac(aCx, aCalleeGlobal);
    JSObject* defaultCtor = PromiseBinding::GetConstructorObject(aCx);
    if (!defaultCtor) {
      aRv.NoteJSContextException(aCx);
      return;
    }
    defaultCtorVal.setObject(*defaultCtor);
  }
  if (!MaybeWrapObjectValue(aCx, &defaultCtorVal)) {
    aRv.NoteJSContextException(aCx);
    return;
  }

  JS::Rooted<JS::Value> constructor(aCx);
  SpeciesConstructor(aCx, promiseObj, defaultCtorVal, &constructor, aRv);
  if (aRv.Failed()) {
    // Step 4.
    return;
  }

  // Step 5.
  GlobalObject globalObj(aCx, GetWrapper());
  if (globalObj.Failed()) {
    aRv.NoteJSContextException(aCx);
    return;
  }
  nsCOMPtr<nsIGlobalObject> globalObject =
    do_QueryInterface(globalObj.GetAsSupports());
  if (!globalObject) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return;
  }
  PromiseCapability capability(aCx);
  NewPromiseCapability(aCx, globalObject, constructor, false, capability, aRv);
  if (aRv.Failed()) {
    // Step 6.
    return;
  }

  // Now step 7: start
  // http://www.ecma-international.org/ecma-262/6.0/#sec-performpromisethen

  // Step 1 and step 2 are just assertions.

  // Step 3 and step 4 are kinda handled for us already; we use null
  // to represent "Identity" and "Thrower".

  // Steps 5 and 6.  These branch based on whether we know we have a
  // vanilla Promise or not.
  JS::Rooted<JSObject*> global(aCx, JS::CurrentGlobalOrNull(aCx));
  if (capability.mNativePromise) {
    Promise* promise = capability.mNativePromise;

    RefPtr<PromiseCallback> resolveCb =
      PromiseCallback::Factory(promise, global, aResolveCallback,
                               PromiseCallback::Resolve);

    RefPtr<PromiseCallback> rejectCb =
      PromiseCallback::Factory(promise, global, aRejectCallback,
                               PromiseCallback::Reject);

    AppendCallbacks(resolveCb, rejectCb);
  } else {
    JS::Rooted<JSObject*> resolveObj(aCx, &capability.mResolve.toObject());
    RefPtr<AnyCallback> resolveFunc =
      new AnyCallback(aCx, resolveObj, GetIncumbentGlobal());

    JS::Rooted<JSObject*> rejectObj(aCx, &capability.mReject.toObject());
    RefPtr<AnyCallback> rejectFunc =
      new AnyCallback(aCx, rejectObj, GetIncumbentGlobal());

    if (!capability.mPromise) {
      aRv.ThrowTypeError<MSG_ILLEGAL_PROMISE_CONSTRUCTOR>();
      return;
    }
    JS::Rooted<JSObject*> newPromiseObj(aCx, capability.mPromise);
    // We want to store the reflector itself.
    newPromiseObj = js::CheckedUnwrap(newPromiseObj);
    if (!newPromiseObj) {
      // Just throw something.
      aRv.ThrowTypeError<MSG_ILLEGAL_PROMISE_CONSTRUCTOR>();
      return;
    }

    RefPtr<PromiseCallback> resolveCb;
    if (aResolveCallback) {
      resolveCb = new WrapperPromiseCallback(global, aResolveCallback,
                                             newPromiseObj,
                                             resolveFunc, rejectFunc);
    } else {
      resolveCb = new InvokePromiseFuncCallback(global, newPromiseObj,
                                                resolveFunc);
    }

    RefPtr<PromiseCallback> rejectCb;
    if (aRejectCallback) {
      rejectCb = new WrapperPromiseCallback(global, aRejectCallback,
                                            newPromiseObj,
                                            resolveFunc, rejectFunc);
    } else {
      rejectCb = new InvokePromiseFuncCallback(global, newPromiseObj,
                                               rejectFunc);
    }

    AppendCallbacks(resolveCb, rejectCb);
  }

  aRetval.set(capability.PromiseValue());
}

void
Promise::Catch(JSContext* aCx, AnyCallback* aRejectCallback,
               JS::MutableHandle<JS::Value> aRetval,
               ErrorResult& aRv)
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  // Implements
  // http://www.ecma-international.org/ecma-262/6.0/#sec-promise.prototype.catch

  // We can't call Promise::Then directly, because someone might have
  // overridden Promise.prototype.then.
  JS::Rooted<JS::Value> promiseVal(aCx, JS::ObjectValue(*GetWrapper()));
  if (!MaybeWrapObjectValue(aCx, &promiseVal)) {
    aRv.NoteJSContextException(aCx);
    return;
  }
  JS::Rooted<JSObject*> promiseObj(aCx, &promiseVal.toObject());
  MOZ_ASSERT(promiseObj);
  JS::AutoValueArray<2> callbacks(aCx);
  callbacks[0].setUndefined();
  if (aRejectCallback) {
    callbacks[1].setObject(*aRejectCallback->Callable());
    // It could be in any compartment, so put it in ours.
    if (!MaybeWrapObjectValue(aCx, callbacks[1])) {
      aRv.NoteJSContextException(aCx);
      return;
    }
  } else {
    callbacks[1].setNull();
  }
  if (!JS_CallFunctionName(aCx, promiseObj, "then", callbacks, aRetval)) {
    aRv.NoteJSContextException(aCx);
  }
}

/**
 * The CountdownHolder class encapsulates Promise.all countdown functions and
 * the countdown holder parts of the Promises spec. It maintains the result
 * array and AllResolveElementFunctions use SetValue() to set the array indices.
 */
class CountdownHolder final : public nsISupports
{
public:
  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(CountdownHolder)

  CountdownHolder(const GlobalObject& aGlobal, Promise* aPromise,
                  uint32_t aCountdown)
    : mPromise(aPromise), mCountdown(aCountdown)
  {
    MOZ_ASSERT(aCountdown != 0);
    JSContext* cx = aGlobal.Context();

    // The only time aGlobal.Context() and aGlobal.Get() are not
    // same-compartment is when we're called via Xrays, and in that situation we
    // in fact want to create the array in the callee compartment

    JSAutoCompartment ac(cx, aGlobal.Get());
    mValues = JS_NewArrayObject(cx, aCountdown);
    mozilla::HoldJSObjects(this);
  }

private:
  ~CountdownHolder()
  {
    mozilla::DropJSObjects(this);
  }

public:
  void SetValue(uint32_t index, const JS::Handle<JS::Value> aValue)
  {
    MOZ_ASSERT(mCountdown > 0);

    AutoJSAPI jsapi;
    if (!jsapi.Init(mValues)) {
      return;
    }
    JSContext* cx = jsapi.cx();

    JS::Rooted<JS::Value> value(cx, aValue);
    JS::Rooted<JSObject*> values(cx, mValues);
    if (!JS_WrapValue(cx, &value) ||
        !JS_DefineElement(cx, values, index, value, JSPROP_ENUMERATE)) {
      MOZ_ASSERT(JS_IsExceptionPending(cx));
      JS::Rooted<JS::Value> exn(cx);
      if (!jsapi.StealException(&exn)) {
        mPromise->MaybeReject(NS_ERROR_OUT_OF_MEMORY);
      } else {
        mPromise->MaybeReject(cx, exn);
      }
    }

    --mCountdown;
    if (mCountdown == 0) {
      JS::Rooted<JS::Value> result(cx, JS::ObjectValue(*mValues));
      mPromise->MaybeResolve(cx, result);
    }
  }

private:
  RefPtr<Promise> mPromise;
  uint32_t mCountdown;
  JS::Heap<JSObject*> mValues;
};

NS_IMPL_CYCLE_COLLECTING_ADDREF(CountdownHolder)
NS_IMPL_CYCLE_COLLECTING_RELEASE(CountdownHolder)
NS_IMPL_CYCLE_COLLECTION_CLASS(CountdownHolder)

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(CountdownHolder)
  NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END

NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(CountdownHolder)
  NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mValues)
NS_IMPL_CYCLE_COLLECTION_TRACE_END

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(CountdownHolder)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPromise)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(CountdownHolder)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mPromise)
  tmp->mValues = nullptr;
NS_IMPL_CYCLE_COLLECTION_UNLINK_END

/**
 * An AllResolveElementFunction is the per-promise
 * part of the Promise.all() algorithm.
 * Every Promise in the handler is handed an instance of this as a resolution
 * handler and it sets the relevant index in the CountdownHolder.
 */
class AllResolveElementFunction final : public PromiseNativeHandler
{
public:
  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
  NS_DECL_CYCLE_COLLECTION_CLASS(AllResolveElementFunction)

  AllResolveElementFunction(CountdownHolder* aHolder, uint32_t aIndex)
    : mCountdownHolder(aHolder), mIndex(aIndex)
  {
    MOZ_ASSERT(aHolder);
  }

  void
  ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override
  {
    mCountdownHolder->SetValue(mIndex, aValue);
  }

  void
  RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override
  {
    // Should never be attached to Promise as a reject handler.
    MOZ_CRASH("AllResolveElementFunction should never be attached to a Promise's reject handler!");
  }

private:
  ~AllResolveElementFunction()
  {
  }

  RefPtr<CountdownHolder> mCountdownHolder;
  uint32_t mIndex;
};

NS_IMPL_CYCLE_COLLECTING_ADDREF(AllResolveElementFunction)
NS_IMPL_CYCLE_COLLECTING_RELEASE(AllResolveElementFunction)

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(AllResolveElementFunction)
  NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END

NS_IMPL_CYCLE_COLLECTION(AllResolveElementFunction, mCountdownHolder)

static const JSClass PromiseAllDataHolderClass = {
  "PromiseAllDataHolder", JSCLASS_HAS_RESERVED_SLOTS(3)
};

// Slot indices for objects of class PromiseAllDataHolderClass.
#define DATA_HOLDER_REMAINING_ELEMENTS_SLOT 0
#define DATA_HOLDER_VALUES_ARRAY_SLOT 1
#define DATA_HOLDER_RESOLVE_FUNCTION_SLOT 2

// Slot indices for PromiseAllResolveElement.
// The RESOLVE_ELEMENT_INDEX_SLOT stores our index unless we've already been
// called.  Then it stores INT32_MIN (which is never a valid index value).
#define RESOLVE_ELEMENT_INDEX_SLOT 0
// The RESOLVE_ELEMENT_DATA_HOLDER_SLOT slot stores an object of class
// PromiseAllDataHolderClass.
#define RESOLVE_ELEMENT_DATA_HOLDER_SLOT 1

static bool
PromiseAllResolveElement(JSContext* aCx, unsigned aArgc, JS::Value* aVp)
{
  // Implements
  // http://www.ecma-international.org/ecma-262/6.0/#sec-promise.all-resolve-element-functions
  //
  // See the big comment about compartments in Promise::All "Substep 4" that
  // explains what compartments the various stuff here lives in.
  JS::CallArgs args = CallArgsFromVp(aArgc, aVp);

  // Step 1.
  int32_t index =
    js::GetFunctionNativeReserved(&args.callee(),
                                  RESOLVE_ELEMENT_INDEX_SLOT).toInt32();
  // Step 2.
  if (index == INT32_MIN) {
    args.rval().setUndefined();
    return true;
  }

  // Step 3.
  js::SetFunctionNativeReserved(&args.callee(),
                                RESOLVE_ELEMENT_INDEX_SLOT,
                                JS::Int32Value(INT32_MIN));

  // Step 4 already done.

  // Step 5.
  JS::Rooted<JSObject*> dataHolder(aCx,
    &js::GetFunctionNativeReserved(&args.callee(),
                                   RESOLVE_ELEMENT_DATA_HOLDER_SLOT).toObject());

  JS::Rooted<JS::Value> values(aCx,
    js::GetReservedSlot(dataHolder, DATA_HOLDER_VALUES_ARRAY_SLOT));

  // Step 6, effectively.
  JS::Rooted<JS::Value> resolveFunc(aCx,
    js::GetReservedSlot(dataHolder, DATA_HOLDER_RESOLVE_FUNCTION_SLOT));

  // Step 7.
  int32_t remainingElements =
    js::GetReservedSlot(dataHolder, DATA_HOLDER_REMAINING_ELEMENTS_SLOT).toInt32();

  // Step 8.
  JS::Rooted<JSObject*> valuesObj(aCx, &values.toObject());
  if (!JS_DefineElement(aCx, valuesObj, index, args.get(0), JSPROP_ENUMERATE)) {
    return false;
  }

  // Step 9.
  remainingElements -= 1;
  js::SetReservedSlot(dataHolder, DATA_HOLDER_REMAINING_ELEMENTS_SLOT,
                      JS::Int32Value(remainingElements));

  // Step 10.
  if (remainingElements == 0) {
    return JS::Call(aCx, JS::UndefinedHandleValue, resolveFunc,
                    JS::HandleValueArray(values), args.rval());
  }

  // Step 11.
  args.rval().setUndefined();
  return true;
}


/* static */ void
Promise::All(const GlobalObject& aGlobal, JS::Handle<JS::Value> aThisv,
             JS::Handle<JS::Value> aIterable,
             JS::MutableHandle<JS::Value> aRetval, ErrorResult& aRv)
{
  // Implements http://www.ecma-international.org/ecma-262/6.0/#sec-promise.all
  nsCOMPtr<nsIGlobalObject> global =
    do_QueryInterface(aGlobal.GetAsSupports());
  if (!global) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return;
  }

  JSContext* cx = aGlobal.Context();

  // Steps 1-5: nothing to do.  Note that the @@species bits got removed in
  // https://github.com/tc39/ecma262/pull/211

  // Step 6.
  PromiseCapability capability(cx);
  NewPromiseCapability(cx, global, aThisv, true, capability, aRv);
  // Step 7.
  if (aRv.Failed()) {
    return;
  }

  MOZ_ASSERT(aThisv.isObject(), "How did NewPromiseCapability succeed?");
  JS::Rooted<JSObject*> constructorObj(cx, &aThisv.toObject());

  // After this point we have a useful promise value in "capability", so just go
  // ahead and put it in our retval now.  Every single return path below would
  // want to do that anyway.
  aRetval.set(capability.PromiseValue());
  if (!MaybeWrapValue(cx, aRetval)) {
    aRv.NoteJSContextException(cx);
    return;
  }

  // The arguments we're going to be passing to "then" on each loop iteration.
  // The second one we know already; the first one will be created on each
  // iteration of the loop.
  JS::AutoValueArray<2> callbackFunctions(cx);
  callbackFunctions[1].set(capability.mReject);

  // Steps 8 and 9.
  JS::ForOfIterator iter(cx);
  if (!iter.init(aIterable, JS::ForOfIterator::AllowNonIterable)) {
    capability.RejectWithException(cx, aRv);
    return;
  }

  if (!iter.valueIsIterable()) {
    ThrowErrorMessage(cx, MSG_PROMISE_ARG_NOT_ITERABLE,
                      "Argument of Promise.all");
    capability.RejectWithException(cx, aRv);
    return;
  }

  // Step 10 doesn't need to be done, because ForOfIterator handles it
  // for us.

  // Now we jump over to
  // http://www.ecma-international.org/ecma-262/6.0/#sec-performpromiseall
  // and do its steps.

  // Substep 4. Create our data holder that holds all the things shared across
  // every step of the iterator.  In particular, this holds the
  // remainingElementsCount (as an integer reserved slot), the array of values,
  // and the resolve function from our PromiseCapability.
  //
  // We have to be very careful about which compartments we create things in
  // here.  In particular, we have to maintain the invariant that anything
  // stored in a reserved slot is same-compartment with the object whose
  // reserved slot it's in.  But we want to create the values array in the
  // Promise reflector compartment, because that array can get exposed to code
  // that has access to the Promise reflector (in particular code from that
  // compartment), and that should work, even if the Promise reflector
  // compartment is less-privileged than our caller compartment.
  //
  // So the plan is as follows: Create the values array in the promise reflector
  // compartment.  Create the PromiseAllResolveElement function and the data
  // holder in our current compartment.  Store a cross-compartment wrapper to
  // the values array in the holder.  This should be OK because the only things
  // we hand the PromiseAllResolveElement function to are the "then" calls we do
  // and in the case when the reflector compartment is not the current
  // compartment those are happening over Xrays anyway, which means they get the
  // canonical "then" function and content can't see our
  // PromiseAllResolveElement.
  JS::Rooted<JSObject*> dataHolder(cx);
  dataHolder = JS_NewObjectWithGivenProto(cx, &PromiseAllDataHolderClass,
                                          nullptr);
  if (!dataHolder) {
    capability.RejectWithException(cx, aRv);
    return;
  }

  JS::Rooted<JSObject*> reflectorGlobal(cx, global->GetGlobalJSObject());
  JS::Rooted<JSObject*> valuesArray(cx);
  { // Scope for JSAutoCompartment.
    JSAutoCompartment ac(cx, reflectorGlobal);
    valuesArray = JS_NewArrayObject(cx, 0);
  }
  if (!valuesArray) {
    // It's important that we've exited the JSAutoCompartment by now, before
    // calling RejectWithException and possibly invoking capability.mReject.
    capability.RejectWithException(cx, aRv);
    return;
  }

  // The values array as a value we can pass to a function in our current
  // compartment, or store in the holder's reserved slot.
  JS::Rooted<JS::Value> valuesArrayVal(cx, JS::ObjectValue(*valuesArray));
  if (!MaybeWrapObjectValue(cx, &valuesArrayVal)) {
    capability.RejectWithException(cx, aRv);
    return;
  }

  js::SetReservedSlot(dataHolder, DATA_HOLDER_REMAINING_ELEMENTS_SLOT,
                      JS::Int32Value(1));
  js::SetReservedSlot(dataHolder, DATA_HOLDER_VALUES_ARRAY_SLOT,
                      valuesArrayVal);
  js::SetReservedSlot(dataHolder, DATA_HOLDER_RESOLVE_FUNCTION_SLOT,
                      capability.mResolve);

  // Substep 5.
  CheckedInt32 index = 0;

  // Substep 6.
  JS::Rooted<JS::Value> nextValue(cx);
  while (true) {
    bool done;
    // Steps a, b, c, e, f, g.
    if (!iter.next(&nextValue, &done)) {
      capability.RejectWithException(cx, aRv);
      return;
    }

    // Step d.
    if (done) {
      int32_t remainingCount =
        js::GetReservedSlot(dataHolder,
                            DATA_HOLDER_REMAINING_ELEMENTS_SLOT).toInt32();
      remainingCount -= 1;
      if (remainingCount == 0) {
        JS::Rooted<JS::Value> ignored(cx);
        if (!JS::Call(cx, JS::UndefinedHandleValue, capability.mResolve,
                      JS::HandleValueArray(valuesArrayVal), &ignored)) {
          capability.RejectWithException(cx, aRv);
        }
        return;
      }
      js::SetReservedSlot(dataHolder, DATA_HOLDER_REMAINING_ELEMENTS_SLOT,
                          JS::Int32Value(remainingCount));
      // We're all set for now!
      return;
    }

    // Step h.
    { // Scope for the JSAutoCompartment we need to work with valuesArray.  We
      // mostly do this for performance; we could go ahead and do the define via
      // a cross-compartment proxy instead...
      JSAutoCompartment ac(cx, valuesArray);
      if (!JS_DefineElement(cx, valuesArray, index.value(),
                            JS::UndefinedHandleValue, JSPROP_ENUMERATE)) {
        // Have to go back into the caller compartment before we try to touch
        // capability.mReject.  Luckily, capability.mReject is guaranteed to be
        // an object in the right compartment here.
        JSAutoCompartment ac2(cx, &capability.mReject.toObject());
        capability.RejectWithException(cx, aRv);
        return;
      }
    }

    // Step i.  Sadly, we can't take a shortcut here even if
    // capability.mNativePromise exists, because someone could have overridden
    // "resolve" on the canonical Promise constructor.
    JS::Rooted<JS::Value> nextPromise(cx);
    if (!JS_CallFunctionName(cx, constructorObj, "resolve",
                             JS::HandleValueArray(nextValue),
                             &nextPromise)) {
      // Step j.
      capability.RejectWithException(cx, aRv);
      return;
    }

    // Step k.
    JS::Rooted<JSObject*> resolveElement(cx);
    JSFunction* resolveFunc =
      js::NewFunctionWithReserved(cx, PromiseAllResolveElement,
                                  1 /* nargs */, 0 /* flags */, nullptr);
    if (!resolveFunc) {
      capability.RejectWithException(cx, aRv);
      return;
    }

    resolveElement = JS_GetFunctionObject(resolveFunc);
    // Steps l-p.
    js::SetFunctionNativeReserved(resolveElement,
                                  RESOLVE_ELEMENT_INDEX_SLOT,
                                  JS::Int32Value(index.value()));
    js::SetFunctionNativeReserved(resolveElement,
                                  RESOLVE_ELEMENT_DATA_HOLDER_SLOT,
                                  JS::ObjectValue(*dataHolder));

    // Step q.
    int32_t remainingElements =
      js::GetReservedSlot(dataHolder, DATA_HOLDER_REMAINING_ELEMENTS_SLOT).toInt32();
    js::SetReservedSlot(dataHolder, DATA_HOLDER_REMAINING_ELEMENTS_SLOT,
                        JS::Int32Value(remainingElements + 1));

    // Step r.  And now we don't know whether nextPromise has an overridden
    // "then" method, so no shortcuts here either.
    callbackFunctions[0].setObject(*resolveElement);
    JS::Rooted<JSObject*> nextPromiseObj(cx);
    JS::Rooted<JS::Value> ignored(cx);
    if (!JS_ValueToObject(cx, nextPromise, &nextPromiseObj) ||
        !JS_CallFunctionName(cx, nextPromiseObj, "then", callbackFunctions,
                             &ignored)) {
      // Step s.
      capability.RejectWithException(cx, aRv);
    }

    // Step t.
    index += 1;
    if (!index.isValid()) {
      // Let's just claim OOM.
      aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
      capability.RejectWithException(cx, aRv);
    }
  }
}

/* static */ already_AddRefed<Promise>
Promise::All(const GlobalObject& aGlobal,
             const nsTArray<RefPtr<Promise>>& aPromiseList, ErrorResult& aRv)
{
  nsCOMPtr<nsIGlobalObject> global =
    do_QueryInterface(aGlobal.GetAsSupports());
  if (!global) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }

  JSContext* cx = aGlobal.Context();

  if (aPromiseList.IsEmpty()) {
    JS::Rooted<JSObject*> empty(cx, JS_NewArrayObject(cx, 0));
    if (!empty) {
      aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
      return nullptr;
    }
    JS::Rooted<JS::Value> value(cx, JS::ObjectValue(*empty));
    // We know "value" is not a promise, so call the Resolve function
    // that doesn't have to check for that.
    return Promise::Resolve(global, cx, value, aRv);
  }

  RefPtr<Promise> promise = Create(global, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }
  RefPtr<CountdownHolder> holder =
    new CountdownHolder(aGlobal, promise, aPromiseList.Length());

  JS::Rooted<JSObject*> obj(cx, JS::CurrentGlobalOrNull(cx));
  if (!obj) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }

  RefPtr<PromiseCallback> rejectCb = new RejectPromiseCallback(promise, obj);

  for (uint32_t i = 0; i < aPromiseList.Length(); ++i) {
    RefPtr<PromiseNativeHandler> resolveHandler =
      new AllResolveElementFunction(holder, i);

    RefPtr<PromiseCallback> resolveCb =
      new NativePromiseCallback(resolveHandler, Resolved);

    // Every promise gets its own resolve callback, which will set the right
    // index in the array to the resolution value.
    aPromiseList[i]->AppendCallbacks(resolveCb, rejectCb);
  }

  return promise.forget();
}

/* static */ void
Promise::Race(const GlobalObject& aGlobal, JS::Handle<JS::Value> aThisv,
              JS::Handle<JS::Value> aIterable, JS::MutableHandle<JS::Value> aRetval,
              ErrorResult& aRv)
{
  // Implements http://www.ecma-international.org/ecma-262/6.0/#sec-promise.race
  nsCOMPtr<nsIGlobalObject> global =
    do_QueryInterface(aGlobal.GetAsSupports());
  if (!global) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return;
  }

  JSContext* cx = aGlobal.Context();

  // Steps 1-5: nothing to do.  Note that the @@species bits got removed in
  // https://github.com/tc39/ecma262/pull/211
  PromiseCapability capability(cx);

  // Step 6.
  NewPromiseCapability(cx, global, aThisv, true, capability, aRv);
  // Step 7.
  if (aRv.Failed()) {
    return;
  }

  MOZ_ASSERT(aThisv.isObject(), "How did NewPromiseCapability succeed?");
  JS::Rooted<JSObject*> constructorObj(cx, &aThisv.toObject());

  // After this point we have a useful promise value in "capability", so just go
  // ahead and put it in our retval now.  Every single return path below would
  // want to do that anyway.
  aRetval.set(capability.PromiseValue());
  if (!MaybeWrapValue(cx, aRetval)) {
    aRv.NoteJSContextException(cx);
    return;
  }

  // The arguments we're going to be passing to "then" on each loop iteration.
  JS::AutoValueArray<2> callbackFunctions(cx);
  callbackFunctions[0].set(capability.mResolve);
  callbackFunctions[1].set(capability.mReject);

  // Steps 8 and 9.
  JS::ForOfIterator iter(cx);
  if (!iter.init(aIterable, JS::ForOfIterator::AllowNonIterable)) {
    capability.RejectWithException(cx, aRv);
    return;
  }

  if (!iter.valueIsIterable()) {
    ThrowErrorMessage(cx, MSG_PROMISE_ARG_NOT_ITERABLE,
                      "Argument of Promise.race");
    capability.RejectWithException(cx, aRv);
    return;
  }

  // Step 10 doesn't need to be done, because ForOfIterator handles it
  // for us.

  // Now we jump over to
  // http://www.ecma-international.org/ecma-262/6.0/#sec-performpromiserace
  // and do its steps.
  JS::Rooted<JS::Value> nextValue(cx);
  while (true) {
    bool done;
    // Steps a, b, c, e, f, g.
    if (!iter.next(&nextValue, &done)) {
      capability.RejectWithException(cx, aRv);
      return;
    }

    // Step d.
    if (done) {
      // We're all set!
      return;
    }

    // Step h.  Sadly, we can't take a shortcut here even if
    // capability.mNativePromise exists, because someone could have overridden
    // "resolve" on the canonical Promise constructor.
    JS::Rooted<JS::Value> nextPromise(cx);
    if (!JS_CallFunctionName(cx, constructorObj, "resolve",
                             JS::HandleValueArray(nextValue), &nextPromise)) {
      // Step i.
      capability.RejectWithException(cx, aRv);
      return;
    }

    // Step j.  And now we don't know whether nextPromise has an overridden
    // "then" method, so no shortcuts here either.
    JS::Rooted<JSObject*> nextPromiseObj(cx);
    JS::Rooted<JS::Value> ignored(cx);
    if (!JS_ValueToObject(cx, nextPromise, &nextPromiseObj) ||
        !JS_CallFunctionName(cx, nextPromiseObj, "then", callbackFunctions,
                             &ignored)) {
      // Step k.
      capability.RejectWithException(cx, aRv);
    }
  }
}

/* static */
bool
Promise::PromiseSpecies(JSContext* aCx, unsigned aArgc, JS::Value* aVp)
{
  JS::CallArgs args = CallArgsFromVp(aArgc, aVp);
  args.rval().set(args.thisv());
  return true;
}

void
Promise::AppendNativeHandler(PromiseNativeHandler* aRunnable)
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  RefPtr<PromiseCallback> resolveCb =
    new NativePromiseCallback(aRunnable, Resolved);

  RefPtr<PromiseCallback> rejectCb =
    new NativePromiseCallback(aRunnable, Rejected);

  AppendCallbacks(resolveCb, rejectCb);
}

#endif // SPIDERMONKEY_PROMISE

JSObject*
Promise::GlobalJSObject() const
{
  return mGlobal->GetGlobalJSObject();
}

JSCompartment*
Promise::Compartment() const
{
  return js::GetObjectCompartment(GlobalJSObject());
}

#ifndef SPIDERMONKEY_PROMISE
void
Promise::AppendCallbacks(PromiseCallback* aResolveCallback,
                         PromiseCallback* aRejectCallback)
{
  if (!mGlobal || mGlobal->IsDying()) {
    return;
  }

  MOZ_ASSERT(aResolveCallback);
  MOZ_ASSERT(aRejectCallback);

  if (mIsLastInChain && mState == PromiseState::Rejected) {
    // This rejection is now consumed.
    PromiseDebugging::AddConsumedRejection(*this);
    // Note that we may not have had the opportunity to call
    // RunResolveTask() yet, so we may never have called
    // `PromiseDebugging:AddUncaughtRejection`.
  }
  mIsLastInChain = false;

#if defined(DOM_PROMISE_DEPRECATED_REPORTING)
  // Now that there is a callback, we don't need to report anymore.
  mHadRejectCallback = true;
  RemoveWorkerHolder();
#endif // defined(DOM_PROMISE_DEPRECATED_REPORTING)

  mResolveCallbacks.AppendElement(aResolveCallback);
  mRejectCallbacks.AppendElement(aRejectCallback);

  // If promise's state is fulfilled, queue a task to process our fulfill
  // callbacks with promise's result. If promise's state is rejected, queue a
  // task to process our reject callbacks with promise's result.
  if (mState != Pending) {
    TriggerPromiseReactions();
  }
}
#endif // SPIDERMONKEY_PROMISE

#ifndef SPIDERMONKEY_PROMISE
#if defined(DOM_PROMISE_DEPRECATED_REPORTING)
void
Promise::MaybeReportRejected()
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  if (mState != Rejected || mHadRejectCallback || mResult.isUndefined()) {
    return;
  }

  AutoJSAPI jsapi;
  // We may not have a usable global by now (if it got unlinked
  // already), so don't init with it.
  jsapi.Init();
  JSContext* cx = jsapi.cx();
  JS::Rooted<JSObject*> obj(cx, GetWrapper());
  MOZ_ASSERT(obj); // We preserve our wrapper, so should always have one here.
  JS::Rooted<JS::Value> val(cx, mResult);

  JSAutoCompartment ac(cx, obj);
  if (!JS_WrapValue(cx, &val)) {
    JS_ClearPendingException(cx);
    return;
  }

  js::ErrorReport report(cx);
  RefPtr<Exception> exp;
  bool isObject = val.isObject();
  if (!isObject || NS_FAILED(UNWRAP_OBJECT(Exception, &val.toObject(), exp))) {
    if (!isObject ||
        NS_FAILED(UNWRAP_OBJECT(DOMException, &val.toObject(), exp))) {
      if (!report.init(cx, val, js::ErrorReport::NoSideEffects)) {
        NS_WARNING("Couldn't convert the unhandled rejected value to an exception.");
        JS_ClearPendingException(cx);
        return;
      }
    }
  }

  RefPtr<xpc::ErrorReport> xpcReport = new xpc::ErrorReport();
  bool isMainThread = MOZ_LIKELY(NS_IsMainThread());
  bool isChrome = isMainThread ? nsContentUtils::IsSystemPrincipal(nsContentUtils::ObjectPrincipal(obj))
                               : GetCurrentThreadWorkerPrivate()->IsChromeWorker();
  nsGlobalWindow* win = isMainThread ? xpc::WindowGlobalOrNull(obj) : nullptr;
  uint64_t windowID = win ? win->AsInner()->WindowID() : 0;
  if (exp) {
    xpcReport->Init(cx, exp, isChrome, windowID);
  } else {
    xpcReport->Init(report.report(), report.toStringResult(),
                    isChrome, windowID);
  }

  // Now post an event to do the real reporting async
  // Since Promises preserve their wrapper, it is essential to RefPtr<> the
  // AsyncErrorReporter, otherwise if the call to DispatchToMainThread fails, it
  // will leak. See Bug 958684.  So... don't use DispatchToMainThread()
  nsCOMPtr<nsIThread> mainThread = do_GetMainThread();
  if (NS_WARN_IF(!mainThread)) {
    // Would prefer NS_ASSERTION, but that causes failure in xpcshell tests
    NS_WARNING("!!! Trying to report rejected Promise after MainThread shutdown");
  }
  if (mainThread) {
    RefPtr<AsyncErrorReporter> r = new AsyncErrorReporter(xpcReport);
    mainThread->Dispatch(r.forget(), NS_DISPATCH_NORMAL);
  }
}
#endif // defined(DOM_PROMISE_DEPRECATED_REPORTING)

void
Promise::MaybeResolveInternal(JSContext* aCx,
                              JS::Handle<JS::Value> aValue)
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  if (mResolvePending) {
    return;
  }

  ResolveInternal(aCx, aValue);
}

void
Promise::MaybeRejectInternal(JSContext* aCx,
                             JS::Handle<JS::Value> aValue)
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  if (mResolvePending) {
    return;
  }

  RejectInternal(aCx, aValue);
}

void
Promise::HandleException(JSContext* aCx)
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  JS::Rooted<JS::Value> exn(aCx);
  if (JS_GetPendingException(aCx, &exn)) {
    JS_ClearPendingException(aCx);
    RejectInternal(aCx, exn);
  }
}

void
Promise::ResolveInternal(JSContext* aCx,
                         JS::Handle<JS::Value> aValue)
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  CycleCollectedJSContext* context = CycleCollectedJSContext::Get();

  mResolvePending = true;

  if (aValue.isObject()) {
    JS::Rooted<JSObject*> valueObj(aCx, &aValue.toObject());

    // Thenables.
    JS::Rooted<JS::Value> then(aCx);
    if (!JS_GetProperty(aCx, valueObj, "then", &then)) {
      HandleException(aCx);
      return;
    }

    if (then.isObject() && JS::IsCallable(&then.toObject())) {
      // This is the then() function of the thenable aValueObj.
      JS::Rooted<JSObject*> thenObj(aCx, &then.toObject());

      // We used to have a fast path here for the case when the following
      // requirements held:
      //
      // 1) valueObj is a Promise.
      // 2) thenObj is a JSFunction backed by our actual Promise::Then
      //    implementation.
      //
      // But now that we're doing subclassing in Promise.prototype.then we would
      // also need the following requirements:
      //
      // 3) Getting valueObj.constructor has no side-effects.
      // 4) Getting valueObj.constructor[@@species] has no side-effects.
      // 5) valueObj.constructor[@@species] is a function and calling it has no
      //    side-effects (e.g. it's the canonical Promise constructor) and it
      //    provides some callback functions to call as arguments to its
      //    argument.
      //
      // Ensuring that stuff while not inside SpiderMonkey is painful, so let's
      // drop the fast path for now.

      RefPtr<PromiseInit> thenCallback =
        new PromiseInit(nullptr, thenObj, mozilla::dom::GetIncumbentGlobal());
      RefPtr<PromiseResolveThenableJob> task =
        new PromiseResolveThenableJob(this, valueObj, thenCallback);
      context->DispatchToMicroTask(task.forget());
      return;
    }
  }

  MaybeSettle(aValue, Resolved);
}

void
Promise::RejectInternal(JSContext* aCx,
                        JS::Handle<JS::Value> aValue)
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  mResolvePending = true;

  MaybeSettle(aValue, Rejected);
}

void
Promise::Settle(JS::Handle<JS::Value> aValue, PromiseState aState)
{
  MOZ_ASSERT(mGlobal,
             "We really should have a global here.  Except we sometimes don't "
             "in the wild for some odd reason");
  NS_ASSERT_OWNINGTHREAD(Promise);

  if (!mGlobal || mGlobal->IsDying()) {
    return;
  }

  mSettlementTimestamp = TimeStamp::Now();

  AutoJSAPI jsapi;
  jsapi.Init();
  JSContext* cx = jsapi.cx();
  JS::RootedObject wrapper(cx, GetWrapper());
  MOZ_ASSERT(wrapper); // We preserved it
  JSAutoCompartment ac(cx, wrapper);

  JS::Rooted<JS::Value> value(cx, aValue);

  if (!JS_WrapValue(cx, &value)) {
    JS_ClearPendingException(cx);
    value = JS::UndefinedValue();
  }
  SetResult(value);
  SetState(aState);

  JS::dbg::onPromiseSettled(cx, wrapper);

  if (aState == PromiseState::Rejected &&
      mIsLastInChain) {
    // The Promise has just been rejected, and it is last in chain.
    // We need to inform PromiseDebugging.
    // If the Promise is eventually not the last in chain anymore,
    // we will need to inform PromiseDebugging again.
    PromiseDebugging::AddUncaughtRejection(*this);
  }

#if defined(DOM_PROMISE_DEPRECATED_REPORTING)
  // If the Promise was rejected, and there is no reject handler already setup,
  // watch for thread shutdown.
  if (aState == PromiseState::Rejected &&
      !mHadRejectCallback &&
      !NS_IsMainThread()) {
    WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
    MOZ_ASSERT(worker);
    worker->AssertIsOnWorkerThread();

    mWorkerHolder = new PromiseReportRejectWorkerHolder(this);
    if (NS_WARN_IF(!mWorkerHolder->HoldWorker(worker, Closing))) {
      mWorkerHolder = nullptr;
      // Worker is shutting down, report rejection immediately since it is
      // unlikely that reject callbacks will be added after this point.
      MaybeReportRejectedOnce();
    }
  }
#endif // defined(DOM_PROMISE_DEPRECATED_REPORTING)

  TriggerPromiseReactions();
}

void
Promise::MaybeSettle(JS::Handle<JS::Value> aValue,
                     PromiseState aState)
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  // Promise.all() or Promise.race() implementations will repeatedly call
  // Resolve/RejectInternal rather than using the Maybe... forms. Stop SetState
  // from asserting.
  if (mState != Pending) {
    return;
  }

  Settle(aValue, aState);
}

void
Promise::TriggerPromiseReactions()
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  CycleCollectedJSContext* runtime = CycleCollectedJSContext::Get();

  nsTArray<RefPtr<PromiseCallback>> callbacks;
  callbacks.SwapElements(mState == Resolved ? mResolveCallbacks
                                            : mRejectCallbacks);
  mResolveCallbacks.Clear();
  mRejectCallbacks.Clear();

  for (uint32_t i = 0; i < callbacks.Length(); ++i) {
    RefPtr<PromiseReactionJob> task =
      new PromiseReactionJob(this, callbacks[i], mResult);
    runtime->DispatchToMicroTask(task.forget());
  }
}

#if defined(DOM_PROMISE_DEPRECATED_REPORTING)
void
Promise::RemoveWorkerHolder()
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  // The DTOR of this WorkerHolder will release the worker for us.
  mWorkerHolder = nullptr;
}

bool
PromiseReportRejectWorkerHolder::Notify(Status aStatus)
{
  MOZ_ASSERT(aStatus > Running);
  mPromise->MaybeReportRejectedOnce();
  // After this point, `this` has been deleted by RemoveWorkerHolder!
  return true;
}
#endif // defined(DOM_PROMISE_DEPRECATED_REPORTING)

bool
Promise::CaptureStack(JSContext* aCx, JS::Heap<JSObject*>& aTarget)
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  JS::Rooted<JSObject*> stack(aCx);
  if (!JS::CaptureCurrentStack(aCx, &stack)) {
    return false;
  }
  aTarget = stack;
  return true;
}

void
Promise::GetDependentPromises(nsTArray<RefPtr<Promise>>& aPromises)
{
  NS_ASSERT_OWNINGTHREAD(Promise);

  // We want to return promises that correspond to then() calls, Promise.all()
  // calls, and Promise.race() calls.
  //
  // For the then() case, we have both resolve and reject callbacks that know
  // what the next promise is.
  //
  // For the race() case, likewise.
  //
  // For the all() case, our reject callback knows what the next promise is, but
  // our resolve callback just knows it needs to notify some
  // PromiseNativeHandler, which itself only has an indirect relationship to the
  // next promise.
  //
  // So we walk over our _reject_ callbacks and ask each of them what promise
  // its dependent promise is.
  for (size_t i = 0; i < mRejectCallbacks.Length(); ++i) {
    Promise* p = mRejectCallbacks[i]->GetDependentPromise();
    if (p) {
      aPromises.AppendElement(p);
    }
  }
}

#endif // SPIDERMONKEY_PROMISE

// A WorkerRunnable to resolve/reject the Promise on the worker thread.
// Calling thread MUST hold PromiseWorkerProxy's mutex before creating this.
class PromiseWorkerProxyRunnable : public WorkerRunnable
{
public:
  PromiseWorkerProxyRunnable(PromiseWorkerProxy* aPromiseWorkerProxy,
                             PromiseWorkerProxy::RunCallbackFunc aFunc)
    : WorkerRunnable(aPromiseWorkerProxy->GetWorkerPrivate(),
                     WorkerThreadUnchangedBusyCount)
    , mPromiseWorkerProxy(aPromiseWorkerProxy)
    , mFunc(aFunc)
  {
    MOZ_ASSERT(NS_IsMainThread());
    MOZ_ASSERT(mPromiseWorkerProxy);
  }

  virtual bool
  WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate)
  {
    MOZ_ASSERT(aWorkerPrivate);
    aWorkerPrivate->AssertIsOnWorkerThread();
    MOZ_ASSERT(aWorkerPrivate == mWorkerPrivate);

    MOZ_ASSERT(mPromiseWorkerProxy);
    RefPtr<Promise> workerPromise = mPromiseWorkerProxy->WorkerPromise();

    // Here we convert the buffer to a JS::Value.
    JS::Rooted<JS::Value> value(aCx);
    if (!mPromiseWorkerProxy->Read(aCx, &value)) {
      JS_ClearPendingException(aCx);
      return false;
    }

    (workerPromise->*mFunc)(aCx, value);

    // Release the Promise because it has been resolved/rejected for sure.
    mPromiseWorkerProxy->CleanUp();
    return true;
  }

protected:
  ~PromiseWorkerProxyRunnable() {}

private:
  RefPtr<PromiseWorkerProxy> mPromiseWorkerProxy;

  // Function pointer for calling Promise::{ResolveInternal,RejectInternal}.
  PromiseWorkerProxy::RunCallbackFunc mFunc;
};

class PromiseWorkerHolder final : public WorkerHolder
{
  // RawPointer because this proxy keeps alive the holder.
  PromiseWorkerProxy* mProxy;

public:
  explicit PromiseWorkerHolder(PromiseWorkerProxy* aProxy)
    : mProxy(aProxy)
  {
    MOZ_ASSERT(aProxy);
  }

  bool
  Notify(Status aStatus) override
  {
    if (aStatus >= Canceling) {
      mProxy->CleanUp();
    }

    return true;
  }
};

/* static */
already_AddRefed<PromiseWorkerProxy>
PromiseWorkerProxy::Create(WorkerPrivate* aWorkerPrivate,
                           Promise* aWorkerPromise,
                           const PromiseWorkerProxyStructuredCloneCallbacks* aCb)
{
  MOZ_ASSERT(aWorkerPrivate);
  aWorkerPrivate->AssertIsOnWorkerThread();
  MOZ_ASSERT(aWorkerPromise);
  MOZ_ASSERT_IF(aCb, !!aCb->Write && !!aCb->Read);

  RefPtr<PromiseWorkerProxy> proxy =
    new PromiseWorkerProxy(aWorkerPrivate, aWorkerPromise, aCb);

  // We do this to make sure the worker thread won't shut down before the
  // promise is resolved/rejected on the worker thread.
  if (!proxy->AddRefObject()) {
    // Probably the worker is terminating. We cannot complete the operation
    // and we have to release all the resources.
    proxy->CleanProperties();
    return nullptr;
  }

  return proxy.forget();
}

NS_IMPL_ISUPPORTS0(PromiseWorkerProxy)

PromiseWorkerProxy::PromiseWorkerProxy(WorkerPrivate* aWorkerPrivate,
                                       Promise* aWorkerPromise,
                                       const PromiseWorkerProxyStructuredCloneCallbacks* aCallbacks)
  : mWorkerPrivate(aWorkerPrivate)
  , mWorkerPromise(aWorkerPromise)
  , mCleanedUp(false)
  , mCallbacks(aCallbacks)
  , mCleanUpLock("cleanUpLock")
{
}

PromiseWorkerProxy::~PromiseWorkerProxy()
{
  MOZ_ASSERT(mCleanedUp);
  MOZ_ASSERT(!mWorkerHolder);
  MOZ_ASSERT(!mWorkerPromise);
  MOZ_ASSERT(!mWorkerPrivate);
}

void
PromiseWorkerProxy::CleanProperties()
{
#ifdef DEBUG
  WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
  MOZ_ASSERT(worker);
  worker->AssertIsOnWorkerThread();
#endif
  // Ok to do this unprotected from Create().
  // CleanUp() holds the lock before calling this.
  mCleanedUp = true;
  mWorkerPromise = nullptr;
  mWorkerPrivate = nullptr;

  // Clear the StructuredCloneHolderBase class.
  Clear();
}

bool
PromiseWorkerProxy::AddRefObject()
{
  MOZ_ASSERT(mWorkerPrivate);
  mWorkerPrivate->AssertIsOnWorkerThread();

  MOZ_ASSERT(!mWorkerHolder);
  mWorkerHolder.reset(new PromiseWorkerHolder(this));
  if (NS_WARN_IF(!mWorkerHolder->HoldWorker(mWorkerPrivate, Canceling))) {
    mWorkerHolder = nullptr;
    return false;
  }

  // Maintain a reference so that we have a valid object to clean up when
  // removing the feature.
  AddRef();
  return true;
}

WorkerPrivate*
PromiseWorkerProxy::GetWorkerPrivate() const
{
#ifdef DEBUG
  if (NS_IsMainThread()) {
    mCleanUpLock.AssertCurrentThreadOwns();
  }
#endif
  // Safe to check this without a lock since we assert lock ownership on the
  // main thread above.
  MOZ_ASSERT(!mCleanedUp);
  MOZ_ASSERT(mWorkerHolder);

  return mWorkerPrivate;
}

Promise*
PromiseWorkerProxy::WorkerPromise() const
{
#ifdef DEBUG
  WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
  MOZ_ASSERT(worker);
  worker->AssertIsOnWorkerThread();
#endif
  MOZ_ASSERT(mWorkerPromise);
  return mWorkerPromise;
}

void
PromiseWorkerProxy::RunCallback(JSContext* aCx,
                                JS::Handle<JS::Value> aValue,
                                RunCallbackFunc aFunc)
{
  MOZ_ASSERT(NS_IsMainThread());

  MutexAutoLock lock(Lock());
  // If the worker thread's been cancelled we don't need to resolve the Promise.
  if (CleanedUp()) {
    return;
  }

  // The |aValue| is written into the StructuredCloneHolderBase.
  if (!Write(aCx, aValue)) {
    JS_ClearPendingException(aCx);
    MOZ_ASSERT(false, "cannot serialize the value with the StructuredCloneAlgorithm!");
  }

  RefPtr<PromiseWorkerProxyRunnable> runnable =
    new PromiseWorkerProxyRunnable(this, aFunc);

  runnable->Dispatch();
}

void
PromiseWorkerProxy::ResolvedCallback(JSContext* aCx,
                                     JS::Handle<JS::Value> aValue)
{
  RunCallback(aCx, aValue, &Promise::MaybeResolve);
}

void
PromiseWorkerProxy::RejectedCallback(JSContext* aCx,
                                     JS::Handle<JS::Value> aValue)
{
  RunCallback(aCx, aValue, &Promise::MaybeReject);
}

void
PromiseWorkerProxy::CleanUp()
{
  // Can't release Mutex while it is still locked, so scope the lock.
  {
    MutexAutoLock lock(Lock());

    // |mWorkerPrivate| is not safe to use anymore if we have already
    // cleaned up and RemoveWorkerHolder(), so we need to check |mCleanedUp|
    // first.
    if (CleanedUp()) {
      return;
    }

    MOZ_ASSERT(mWorkerPrivate);
    mWorkerPrivate->AssertIsOnWorkerThread();

    // Release the Promise and remove the PromiseWorkerProxy from the holders of
    // the worker thread since the Promise has been resolved/rejected or the
    // worker thread has been cancelled.
    MOZ_ASSERT(mWorkerHolder);
    mWorkerHolder = nullptr;

    CleanProperties();
  }
  Release();
}

JSObject*
PromiseWorkerProxy::CustomReadHandler(JSContext* aCx,
                                      JSStructuredCloneReader* aReader,
                                      uint32_t aTag,
                                      uint32_t aIndex)
{
  if (NS_WARN_IF(!mCallbacks)) {
    return nullptr;
  }

  return mCallbacks->Read(aCx, aReader, this, aTag, aIndex);
}

bool
PromiseWorkerProxy::CustomWriteHandler(JSContext* aCx,
                                       JSStructuredCloneWriter* aWriter,
                                       JS::Handle<JSObject*> aObj)
{
  if (NS_WARN_IF(!mCallbacks)) {
    return false;
  }

  return mCallbacks->Write(aCx, aWriter, this, aObj);
}

// Specializations of MaybeRejectBrokenly we actually support.
template<>
void Promise::MaybeRejectBrokenly(const RefPtr<DOMError>& aArg) {
  MaybeSomething(aArg, &Promise::MaybeReject);
}
template<>
void Promise::MaybeRejectBrokenly(const nsAString& aArg) {
  MaybeSomething(aArg, &Promise::MaybeReject);
}

#ifndef SPIDERMONKEY_PROMISE
uint64_t
Promise::GetID() {
  if (mID != 0) {
    return mID;
  }
  return mID = ++gIDGenerator;
}
#endif // SPIDERMONKEY_PROMISE

#ifndef SPIDERMONKEY_PROMISE
Promise::PromiseState
Promise::State() const
{
  return mState;
}
#else // SPIDERMONKEY_PROMISE
Promise::PromiseState
Promise::State() const
{
  JS::Rooted<JSObject*> p(RootingCx(), PromiseObj());
  const JS::PromiseState state = JS::GetPromiseState(p);

  if (state == JS::PromiseState::Fulfilled) {
      return PromiseState::Resolved;
  }

  if (state == JS::PromiseState::Rejected) {
      return PromiseState::Rejected;
  }

  return PromiseState::Pending;
}
#endif // SPIDERMONKEY_PROMISE

} // namespace dom
} // namespace mozilla