summaryrefslogtreecommitdiffstats
path: root/js/xpconnect/src/Sandbox.cpp
blob: ed77605193bed116d99cc6e45f9975ba2e3ce2f4 (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
/* -*- 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/. */

/*
 * The Components.Sandbox object.
 */

#include "AccessCheck.h"
#include "jsfriendapi.h"
#include "js/Array.h"             // JS::GetArrayLength, JS::IsArrayObject
#include "js/CallAndConstruct.h"  // JS::Call, JS::IsCallable
#include "js/CharacterEncoding.h"
#include "js/CompilationAndEvaluation.h"
#include "js/Object.h"  // JS::GetClass, JS::GetCompartment, JS::GetReservedSlot
#include "js/PropertyAndElement.h"  // JS_DefineFunction, JS_DefineFunctions, JS_DefineProperty, JS_GetElement, JS_GetProperty, JS_HasProperty, JS_SetProperty, JS_SetPropertyById
#include "js/PropertyDescriptor.h"  // JS::PropertyDescriptor, JS_GetOwnPropertyDescriptorById, JS_GetPropertyDescriptorById
#include "js/PropertySpec.h"
#include "js/Proxy.h"
#include "js/SourceText.h"
#include "js/StructuredClone.h"
#include "nsContentUtils.h"
#include "nsGlobalWindowInner.h"
#include "nsIException.h"  // for nsIStackFrame
#include "nsIScriptContext.h"
#include "nsIScriptObjectPrincipal.h"
#include "nsIURI.h"
#include "nsJSUtils.h"
#include "nsNetUtil.h"
#include "ExpandedPrincipal.h"
#include "WrapperFactory.h"
#include "xpcprivate.h"
#include "xpc_make_class.h"
#include "XPCWrapper.h"
#include "Crypto.h"
#include "mozilla/Result.h"
#include "mozilla/dom/AbortControllerBinding.h"
#include "mozilla/dom/AutoEntryScript.h"
#include "mozilla/dom/BindingCallContext.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/BlobBinding.h"
#include "mozilla/dom/cache/CacheStorage.h"
#include "mozilla/dom/CSSBinding.h"
#include "mozilla/dom/CSSRuleBinding.h"
#include "mozilla/dom/DirectoryBinding.h"
#include "mozilla/dom/DocumentBinding.h"
#include "mozilla/dom/DOMExceptionBinding.h"
#include "mozilla/dom/DOMParserBinding.h"
#include "mozilla/dom/DOMTokenListBinding.h"
#include "mozilla/dom/ElementBinding.h"
#include "mozilla/dom/ElementInternalsBinding.h"
#include "mozilla/dom/EventBinding.h"
#include "mozilla/dom/Exceptions.h"
#include "mozilla/dom/IndexedDatabaseManager.h"
#include "mozilla/dom/Fetch.h"
#include "mozilla/dom/FileBinding.h"
#include "mozilla/dom/HeadersBinding.h"
#include "mozilla/dom/IOUtilsBinding.h"
#include "mozilla/dom/InspectorUtilsBinding.h"
#include "mozilla/dom/MessageChannelBinding.h"
#include "mozilla/dom/MessagePortBinding.h"
#include "mozilla/dom/MIDIInputMapBinding.h"
#include "mozilla/dom/MIDIOutputMapBinding.h"
#include "mozilla/dom/ModuleLoader.h"
#include "mozilla/dom/NodeBinding.h"
#include "mozilla/dom/NodeFilterBinding.h"
#include "mozilla/dom/PathUtilsBinding.h"
#include "mozilla/dom/PerformanceBinding.h"
#include "mozilla/dom/PromiseBinding.h"
#include "mozilla/dom/PromiseDebuggingBinding.h"
#include "mozilla/dom/RangeBinding.h"
#include "mozilla/dom/RequestBinding.h"
#include "mozilla/dom/ReadableStreamBinding.h"
#include "mozilla/dom/ResponseBinding.h"
#ifdef MOZ_WEBRTC
#  include "mozilla/dom/RTCIdentityProviderRegistrar.h"
#endif
#include "mozilla/dom/FileReaderBinding.h"
#include "mozilla/dom/ScriptLoader.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/SelectionBinding.h"
#include "mozilla/dom/StorageManager.h"
#include "mozilla/dom/TextDecoderBinding.h"
#include "mozilla/dom/TextEncoderBinding.h"
#include "mozilla/dom/URLBinding.h"
#include "mozilla/dom/URLSearchParamsBinding.h"
#include "mozilla/dom/XMLHttpRequest.h"
#include "mozilla/dom/WebSocketBinding.h"
#include "mozilla/dom/WindowBinding.h"
#include "mozilla/dom/XMLSerializerBinding.h"
#include "mozilla/dom/FormDataBinding.h"
#include "mozilla/dom/nsCSPContext.h"
#include "mozilla/ipc/BackgroundUtils.h"
#include "mozilla/ipc/PBackgroundSharedTypes.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/DeferredFinalize.h"
#include "mozilla/ExtensionPolicyService.h"
#include "mozilla/Maybe.h"
#include "mozilla/NullPrincipal.h"
#include "mozilla/ResultExtensions.h"
#include "mozilla/StaticPrefs_extensions.h"

using namespace mozilla;
using namespace mozilla::dom;
using namespace JS;
using namespace JS::loader;
using namespace xpc;

using mozilla::dom::DestroyProtoAndIfaceCache;
using mozilla::dom::IndexedDatabaseManager;

NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_CLASS(SandboxPrivate)

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(SandboxPrivate)
  NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
  NS_IMPL_CYCLE_COLLECTION_UNLINK_WEAK_REFERENCE
  NS_IMPL_CYCLE_COLLECTION_UNLINK_WEAK_PTR
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mModuleLoader)
  tmp->UnlinkObjectsInGlobal();
NS_IMPL_CYCLE_COLLECTION_UNLINK_END

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(SandboxPrivate)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mModuleLoader)
  tmp->TraverseObjectsInGlobal(cb);
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

NS_IMPL_CYCLE_COLLECTING_ADDREF(SandboxPrivate)
NS_IMPL_CYCLE_COLLECTING_RELEASE(SandboxPrivate)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(SandboxPrivate)
  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIScriptObjectPrincipal)
  NS_INTERFACE_MAP_ENTRY(nsIScriptObjectPrincipal)
  NS_INTERFACE_MAP_ENTRY(nsIGlobalObject)
  NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_END

class nsXPCComponents_utils_Sandbox : public nsIXPCComponents_utils_Sandbox,
                                      public nsIXPCScriptable {
 public:
  // Aren't macros nice?
  NS_DECL_ISUPPORTS
  NS_DECL_NSIXPCCOMPONENTS_UTILS_SANDBOX
  NS_DECL_NSIXPCSCRIPTABLE

 public:
  nsXPCComponents_utils_Sandbox();

 private:
  virtual ~nsXPCComponents_utils_Sandbox();

  static nsresult CallOrConstruct(nsIXPConnectWrappedNative* wrapper,
                                  JSContext* cx, HandleObject obj,
                                  const CallArgs& args, bool* _retval);
};

already_AddRefed<nsIXPCComponents_utils_Sandbox> xpc::NewSandboxConstructor() {
  nsCOMPtr<nsIXPCComponents_utils_Sandbox> sbConstructor =
      new nsXPCComponents_utils_Sandbox();
  return sbConstructor.forget();
}

static bool SandboxDump(JSContext* cx, unsigned argc, Value* vp) {
  if (!nsJSUtils::DumpEnabled()) {
    return true;
  }

  CallArgs args = CallArgsFromVp(argc, vp);

  if (args.length() == 0) {
    return true;
  }

  RootedString str(cx, ToString(cx, args[0]));
  if (!str) {
    return false;
  }

  JS::UniqueChars utf8str = JS_EncodeStringToUTF8(cx, str);
  char* cstr = utf8str.get();
  if (!cstr) {
    return false;
  }

#if defined(XP_MACOSX)
  // Be nice and convert all \r to \n.
  char* c = cstr;
  char* cEnd = cstr + strlen(cstr);
  while (c < cEnd) {
    if (*c == '\r') {
      *c = '\n';
    }
    c++;
  }
#endif
  MOZ_LOG(nsContentUtils::DOMDumpLog(), mozilla::LogLevel::Debug,
          ("[Sandbox.Dump] %s", cstr));
#ifdef ANDROID
  __android_log_write(ANDROID_LOG_INFO, "GeckoDump", cstr);
#endif
  fputs(cstr, stdout);
  fflush(stdout);
  args.rval().setBoolean(true);
  return true;
}

static bool SandboxDebug(JSContext* cx, unsigned argc, Value* vp) {
#ifdef DEBUG
  return SandboxDump(cx, argc, vp);
#else
  return true;
#endif
}

static bool SandboxImport(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  if (args.length() < 1 || args[0].isPrimitive()) {
    XPCThrower::Throw(NS_ERROR_INVALID_ARG, cx);
    return false;
  }

  RootedString funname(cx);
  if (args.length() > 1) {
    // Use the second parameter as the function name.
    funname = ToString(cx, args[1]);
    if (!funname) {
      return false;
    }
  } else {
    // NB: funobj must only be used to get the JSFunction out.
    RootedObject funobj(cx, &args[0].toObject());
    if (js::IsProxy(funobj)) {
      funobj = XPCWrapper::UnsafeUnwrapSecurityWrapper(funobj);
    }

    JSAutoRealm ar(cx, funobj);

    RootedValue funval(cx, ObjectValue(*funobj));
    JS::Rooted<JSFunction*> fun(cx, JS_ValueToFunction(cx, funval));
    if (!fun) {
      XPCThrower::Throw(NS_ERROR_INVALID_ARG, cx);
      return false;
    }

    // Use the actual function name as the name.
    if (!JS_GetFunctionId(cx, fun, &funname)) {
      return false;
    }
    if (!funname) {
      XPCThrower::Throw(NS_ERROR_INVALID_ARG, cx);
      return false;
    }
  }
  JS_MarkCrossZoneIdValue(cx, StringValue(funname));

  RootedId id(cx);
  if (!JS_StringToId(cx, funname, &id)) {
    return false;
  }

  // We need to resolve the this object, because this function is used
  // unbound and should still work and act on the original sandbox.

  RootedObject thisObject(cx);
  if (!args.computeThis(cx, &thisObject)) {
    return false;
  }

  if (!JS_SetPropertyById(cx, thisObject, id, args[0])) {
    return false;
  }

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

bool xpc::SandboxCreateCrypto(JSContext* cx, JS::Handle<JSObject*> obj) {
  MOZ_ASSERT(JS_IsGlobalObject(obj));

  nsIGlobalObject* native = xpc::NativeGlobal(obj);
  MOZ_ASSERT(native);

  dom::Crypto* crypto = new dom::Crypto(native);
  JS::RootedObject wrapped(cx, crypto->WrapObject(cx, nullptr));
  return JS_DefineProperty(cx, obj, "crypto", wrapped, JSPROP_ENUMERATE);
}

#ifdef MOZ_WEBRTC
static bool SandboxCreateRTCIdentityProvider(JSContext* cx,
                                             JS::HandleObject obj) {
  MOZ_ASSERT(JS_IsGlobalObject(obj));

  nsCOMPtr<nsIGlobalObject> nativeGlobal = xpc::NativeGlobal(obj);
  MOZ_ASSERT(nativeGlobal);

  dom::RTCIdentityProviderRegistrar* registrar =
      new dom::RTCIdentityProviderRegistrar(nativeGlobal);
  JS::RootedObject wrapped(cx, registrar->WrapObject(cx, nullptr));
  return JS_DefineProperty(cx, obj, "rtcIdentityProvider", wrapped,
                           JSPROP_ENUMERATE);
}
#endif

static bool SandboxFetch(JSContext* cx, JS::HandleObject scope,
                         const CallArgs& args) {
  if (args.length() < 1) {
    JS_ReportErrorASCII(cx, "fetch requires at least 1 argument");
    return false;
  }

  BindingCallContext callCx(cx, "fetch");
  RequestOrUTF8String request;
  if (!request.Init(callCx, args[0], "Argument 1")) {
    return false;
  }
  RootedDictionary<dom::RequestInit> options(cx);
  if (!options.Init(callCx, args.hasDefined(1) ? args[1] : JS::NullHandleValue,
                    "Argument 2", false)) {
    return false;
  }
  nsCOMPtr<nsIGlobalObject> global = xpc::NativeGlobal(scope);
  if (!global) {
    return false;
  }
  dom::CallerType callerType = nsContentUtils::IsSystemCaller(cx)
                                   ? dom::CallerType::System
                                   : dom::CallerType::NonSystem;
  ErrorResult rv;
  RefPtr<dom::Promise> response = FetchRequest(
      global, Constify(request), Constify(options), callerType, rv);
  if (rv.MaybeSetPendingException(cx)) {
    return false;
  }

  args.rval().setObject(*response->PromiseObj());
  return true;
}

static bool SandboxFetchPromise(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);
  RootedObject scope(cx, JS::CurrentGlobalOrNull(cx));
  if (SandboxFetch(cx, scope, args)) {
    return true;
  }
  return ConvertExceptionToPromise(cx, args.rval());
}

bool xpc::SandboxCreateFetch(JSContext* cx, JS::Handle<JSObject*> obj) {
  MOZ_ASSERT(JS_IsGlobalObject(obj));

  return JS_DefineFunction(cx, obj, "fetch", SandboxFetchPromise, 2, 0) &&
         dom::Request_Binding::GetConstructorObject(cx) &&
         dom::Response_Binding::GetConstructorObject(cx) &&
         dom::Headers_Binding::GetConstructorObject(cx);
}

static bool SandboxCreateStorage(JSContext* cx, JS::HandleObject obj) {
  MOZ_ASSERT(JS_IsGlobalObject(obj));

  nsIGlobalObject* native = xpc::NativeGlobal(obj);
  MOZ_ASSERT(native);

  dom::StorageManager* storageManager = new dom::StorageManager(native);
  JS::RootedObject wrapped(cx, storageManager->WrapObject(cx, nullptr));
  return JS_DefineProperty(cx, obj, "storage", wrapped, JSPROP_ENUMERATE);
}

static bool SandboxStructuredClone(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  if (!args.requireAtLeast(cx, "structuredClone", 1)) {
    return false;
  }

  RootedDictionary<dom::StructuredSerializeOptions> options(cx);
  BindingCallContext callCx(cx, "structuredClone");
  if (!options.Init(cx, args.hasDefined(1) ? args[1] : JS::NullHandleValue,
                    "Argument 2", false)) {
    return false;
  }

  nsIGlobalObject* global = CurrentNativeGlobal(cx);
  if (!global) {
    JS_ReportErrorASCII(cx, "structuredClone: Missing global");
    return false;
  }

  JS::Rooted<JS::Value> result(cx);
  ErrorResult rv;
  nsContentUtils::StructuredClone(cx, global, args[0], options, &result, rv);
  if (rv.MaybeSetPendingException(cx)) {
    return false;
  }

  MOZ_ASSERT_IF(result.isGCThing(),
                !JS::GCThingIsMarkedGray(result.toGCCellPtr()));
  args.rval().set(result);
  return true;
}

bool xpc::SandboxCreateStructuredClone(JSContext* cx, HandleObject obj) {
  MOZ_ASSERT(JS_IsGlobalObject(obj));

  return JS_DefineFunction(cx, obj, "structuredClone", SandboxStructuredClone,
                           1, 0);
}

static bool SandboxIsProxy(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);
  if (args.length() < 1) {
    JS_ReportErrorASCII(cx, "Function requires at least 1 argument");
    return false;
  }
  if (!args[0].isObject()) {
    args.rval().setBoolean(false);
    return true;
  }

  RootedObject obj(cx, &args[0].toObject());
  // CheckedUnwrapStatic is OK here, since we only care about whether
  // it's a scripted proxy and the things CheckedUnwrapStatic fails on
  // are not.
  obj = js::CheckedUnwrapStatic(obj);
  if (!obj) {
    args.rval().setBoolean(false);
    return true;
  }

  args.rval().setBoolean(js::IsScriptedProxy(obj));
  return true;
}

/*
 * Expected type of the arguments and the return value:
 * function exportFunction(function funToExport,
 *                         object targetScope,
 *                         [optional] object options)
 */
static bool SandboxExportFunction(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);
  if (args.length() < 2) {
    JS_ReportErrorASCII(cx, "Function requires at least 2 arguments");
    return false;
  }

  RootedValue options(cx, args.length() > 2 ? args[2] : UndefinedValue());
  return ExportFunction(cx, args[0], args[1], options, args.rval());
}

static bool SandboxCreateObjectIn(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);
  if (args.length() < 1) {
    JS_ReportErrorASCII(cx, "Function requires at least 1 argument");
    return false;
  }

  RootedObject optionsObj(cx);
  bool calledWithOptions = args.length() > 1;
  if (calledWithOptions) {
    if (!args[1].isObject()) {
      JS_ReportErrorASCII(
          cx, "Expected the 2nd argument (options) to be an object");
      return false;
    }
    optionsObj = &args[1].toObject();
  }

  CreateObjectInOptions options(cx, optionsObj);
  if (calledWithOptions && !options.Parse()) {
    return false;
  }

  return xpc::CreateObjectIn(cx, args[0], options, args.rval());
}

static bool SandboxCloneInto(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);
  if (args.length() < 2) {
    JS_ReportErrorASCII(cx, "Function requires at least 2 arguments");
    return false;
  }

  RootedValue options(cx, args.length() > 2 ? args[2] : UndefinedValue());
  return xpc::CloneInto(cx, args[0], args[1], options, args.rval());
}

static void sandbox_finalize(JS::GCContext* gcx, JSObject* obj) {
  SandboxPrivate* priv = SandboxPrivate::GetPrivate(obj);
  if (!priv) {
    // priv can be null if CreateSandboxObject fails in the middle.
    return;
  }

  priv->ForgetGlobalObject(obj);
  DestroyProtoAndIfaceCache(obj);
  DeferredFinalize(static_cast<nsIScriptObjectPrincipal*>(priv));
}

static size_t sandbox_moved(JSObject* obj, JSObject* old) {
  // Note that this hook can be called before the private pointer is set. In
  // this case the SandboxPrivate will not exist yet, so there is nothing to
  // do.
  SandboxPrivate* priv = SandboxPrivate::GetPrivate(obj);
  if (!priv) {
    return 0;
  }

  return priv->ObjectMoved(obj, old);
}

#define XPCONNECT_SANDBOX_CLASS_METADATA_SLOT \
  (XPCONNECT_GLOBAL_EXTRA_SLOT_OFFSET)

static const JSClassOps SandboxClassOps = {
    nullptr,                         // addProperty
    nullptr,                         // delProperty
    nullptr,                         // enumerate
    JS_NewEnumerateStandardClasses,  // newEnumerate
    JS_ResolveStandardClass,         // resolve
    JS_MayResolveStandardClass,      // mayResolve
    sandbox_finalize,                // finalize
    nullptr,                         // call
    nullptr,                         // construct
    JS_GlobalObjectTraceHook,        // trace
};

static const js::ClassExtension SandboxClassExtension = {
    sandbox_moved,  // objectMovedOp
};

static const JSClass SandboxClass = {
    "Sandbox",
    XPCONNECT_GLOBAL_FLAGS_WITH_EXTRA_SLOTS(1) | JSCLASS_FOREGROUND_FINALIZE,
    &SandboxClassOps,
    JS_NULL_CLASS_SPEC,
    &SandboxClassExtension,
    JS_NULL_OBJECT_OPS};

static const JSFunctionSpec SandboxFunctions[] = {
    JS_FN("dump", SandboxDump, 1, 0), JS_FN("debug", SandboxDebug, 1, 0),
    JS_FN("importFunction", SandboxImport, 1, 0), JS_FS_END};

bool xpc::IsSandbox(JSObject* obj) {
  const JSClass* clasp = JS::GetClass(obj);
  return clasp == &SandboxClass;
}

/***************************************************************************/
nsXPCComponents_utils_Sandbox::nsXPCComponents_utils_Sandbox() = default;

nsXPCComponents_utils_Sandbox::~nsXPCComponents_utils_Sandbox() = default;

NS_IMPL_QUERY_INTERFACE(nsXPCComponents_utils_Sandbox,
                        nsIXPCComponents_utils_Sandbox, nsIXPCScriptable)

NS_IMPL_ADDREF(nsXPCComponents_utils_Sandbox)
NS_IMPL_RELEASE(nsXPCComponents_utils_Sandbox)

// We use the nsIXPScriptable macros to generate lots of stuff for us.
#define XPC_MAP_CLASSNAME nsXPCComponents_utils_Sandbox
#define XPC_MAP_QUOTED_CLASSNAME "nsXPCComponents_utils_Sandbox"
#define XPC_MAP_FLAGS (XPC_SCRIPTABLE_WANT_CALL | XPC_SCRIPTABLE_WANT_CONSTRUCT)
#include "xpc_map_end.h" /* This #undef's the above. */

class SandboxProxyHandler : public js::Wrapper {
 public:
  constexpr SandboxProxyHandler() : js::Wrapper(0) {}

  virtual bool getOwnPropertyDescriptor(
      JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
      JS::MutableHandle<Maybe<JS::PropertyDescriptor>> desc) const override;

  // We just forward the high-level methods to the BaseProxyHandler versions
  // which implement them in terms of lower-level methods.
  virtual bool has(JSContext* cx, JS::Handle<JSObject*> proxy,
                   JS::Handle<jsid> id, bool* bp) const override;
  virtual bool get(JSContext* cx, JS::Handle<JSObject*> proxy,
                   JS::HandleValue receiver, JS::Handle<jsid> id,
                   JS::MutableHandle<JS::Value> vp) const override;
  virtual bool set(JSContext* cx, JS::Handle<JSObject*> proxy,
                   JS::Handle<jsid> id, JS::Handle<JS::Value> v,
                   JS::Handle<JS::Value> receiver,
                   JS::ObjectOpResult& result) const override;

  virtual bool hasOwn(JSContext* cx, JS::Handle<JSObject*> proxy,
                      JS::Handle<jsid> id, bool* bp) const override;
  virtual bool getOwnEnumerablePropertyKeys(
      JSContext* cx, JS::Handle<JSObject*> proxy,
      JS::MutableHandleIdVector props) const override;
  virtual bool enumerate(JSContext* cx, JS::Handle<JSObject*> proxy,
                         JS::MutableHandleIdVector props) const override;

 private:
  // Implements the custom getPropertyDescriptor behavior. If the getOwn
  // argument is true we only look for "own" properties.
  bool getPropertyDescriptorImpl(
      JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
      bool getOwn, JS::MutableHandle<Maybe<JS::PropertyDescriptor>> desc) const;
};

static const SandboxProxyHandler sandboxProxyHandler;

namespace xpc {

bool IsSandboxPrototypeProxy(JSObject* obj) {
  return js::IsProxy(obj) && js::GetProxyHandler(obj) == &sandboxProxyHandler;
}

bool IsWebExtensionContentScriptSandbox(JSObject* obj) {
  return IsSandbox(obj) &&
         CompartmentPrivate::Get(obj)->isWebExtensionContentScript;
}

}  // namespace xpc

// A proxy handler that lets us wrap callables and invoke them with
// the correct this object, while forwarding all other operations down
// to them directly.
class SandboxCallableProxyHandler : public js::Wrapper {
 public:
  constexpr SandboxCallableProxyHandler() : js::Wrapper(0) {}

  virtual bool call(JSContext* cx, JS::Handle<JSObject*> proxy,
                    const JS::CallArgs& args) const override;

  static const size_t SandboxProxySlot = 0;

  static inline JSObject* getSandboxProxy(JS::Handle<JSObject*> proxy) {
    return &js::GetProxyReservedSlot(proxy, SandboxProxySlot).toObject();
  }
};

static const SandboxCallableProxyHandler sandboxCallableProxyHandler;

bool SandboxCallableProxyHandler::call(JSContext* cx,
                                       JS::Handle<JSObject*> proxy,
                                       const JS::CallArgs& args) const {
  // We forward the call to our underlying callable.

  // Get our SandboxProxyHandler proxy.
  RootedObject sandboxProxy(cx, getSandboxProxy(proxy));
  MOZ_ASSERT(js::IsProxy(sandboxProxy) &&
             js::GetProxyHandler(sandboxProxy) == &sandboxProxyHandler);

  // The global of the sandboxProxy is the sandbox global, and the
  // target object is the original proto.
  RootedObject sandboxGlobal(cx, JS::GetNonCCWObjectGlobal(sandboxProxy));
  MOZ_ASSERT(IsSandbox(sandboxGlobal));

  // If our this object is the sandbox global, we call with this set to the
  // original proto instead.
  //
  // There are two different ways we can compute |this|. If we use
  // JS_THIS_VALUE, we'll get the bonafide |this| value as passed by the
  // caller, which may be undefined if a global function was invoked without
  // an explicit invocant. If we use JS_THIS or JS_THIS_OBJECT, the |this|
  // in |vp| will be coerced to the global, which is not the correct
  // behavior in ES5 strict mode. And we have no way to compute strictness
  // here.
  //
  // The naive approach is simply to use JS_THIS_VALUE here. If |this| was
  // explicit, we can remap it appropriately. If it was implicit, then we
  // leave it as undefined, and let the callee sort it out. Since the callee
  // is generally in the same compartment as its global (eg the Window's
  // compartment, not the Sandbox's), the callee will generally compute the
  // correct |this|.
  //
  // However, this breaks down in the Xray case. If the sandboxPrototype
  // is an Xray wrapper, then we'll end up reifying the native methods in
  // the Sandbox's scope, which means that they'll compute |this| to be the
  // Sandbox, breaking old-style XPC_WN_CallMethod methods.
  //
  // Luckily, the intent of Xrays is to provide a vanilla view of a foreign
  // DOM interface, which means that we don't care about script-enacted
  // strictness in the prototype's home compartment. Indeed, since DOM
  // methods are always non-strict, we can just assume non-strict semantics
  // if the sandboxPrototype is an Xray Wrapper, which lets us appropriately
  // remap |this|.
  bool isXray = WrapperFactory::IsXrayWrapper(sandboxProxy);
  RootedValue thisVal(cx, args.thisv());
  if (isXray) {
    RootedObject thisObject(cx);
    if (!args.computeThis(cx, &thisObject)) {
      return false;
    }
    thisVal.setObject(*thisObject);
  }

  if (thisVal == ObjectValue(*sandboxGlobal)) {
    thisVal = ObjectValue(*js::GetProxyTargetObject(sandboxProxy));
  }

  RootedValue func(cx, js::GetProxyPrivate(proxy));
  return JS::Call(cx, thisVal, func, args, args.rval());
}

/*
 * Wrap a callable such that if we're called with oldThisObj as the
 * "this" we will instead call it with newThisObj as the this.
 */
static JSObject* WrapCallable(JSContext* cx, HandleObject callable,
                              HandleObject sandboxProtoProxy) {
  MOZ_ASSERT(JS::IsCallable(callable));
  // Our proxy is wrapping the callable.  So we need to use the
  // callable as the private.  We put the given sandboxProtoProxy in
  // an extra slot, and our call() hook depends on that.
  MOZ_ASSERT(js::IsProxy(sandboxProtoProxy) &&
             js::GetProxyHandler(sandboxProtoProxy) == &sandboxProxyHandler);

  RootedValue priv(cx, ObjectValue(*callable));
  // We want to claim to have the same proto as our wrapped callable, so set
  // ourselves up with a lazy proto.
  js::ProxyOptions options;
  options.setLazyProto(true);
  JSObject* obj = js::NewProxyObject(cx, &sandboxCallableProxyHandler, priv,
                                     nullptr, options);
  if (obj) {
    js::SetProxyReservedSlot(obj, SandboxCallableProxyHandler::SandboxProxySlot,
                             ObjectValue(*sandboxProtoProxy));
  }

  return obj;
}

bool WrapAccessorFunction(JSContext* cx, MutableHandleObject accessor,
                          HandleObject sandboxProtoProxy) {
  if (!accessor) {
    return true;
  }

  accessor.set(WrapCallable(cx, accessor, sandboxProtoProxy));
  return !!accessor;
}

static bool IsMaybeWrappedDOMConstructor(JSObject* obj) {
  // We really care about the underlying object here, which might be wrapped in
  // cross-compartment wrappers.  CheckedUnwrapStatic is fine, since we just
  // care whether it's a DOM constructor.
  obj = js::CheckedUnwrapStatic(obj);
  if (!obj) {
    return false;
  }

  return dom::IsDOMConstructor(obj);
}

bool SandboxProxyHandler::getPropertyDescriptorImpl(
    JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
    bool getOwn, MutableHandle<Maybe<PropertyDescriptor>> desc_) const {
  JS::RootedObject obj(cx, wrappedObject(proxy));

  MOZ_ASSERT(JS::GetCompartment(obj) == JS::GetCompartment(proxy));

  if (getOwn) {
    if (!JS_GetOwnPropertyDescriptorById(cx, obj, id, desc_)) {
      return false;
    }
  } else {
    Rooted<JSObject*> holder(cx);
    if (!JS_GetPropertyDescriptorById(cx, obj, id, desc_, &holder)) {
      return false;
    }
  }

  if (desc_.isNothing()) {
    return true;
  }

  Rooted<PropertyDescriptor> desc(cx, *desc_);

  // Now fix up the getter/setter/value as needed.
  if (desc.hasGetter() && !WrapAccessorFunction(cx, desc.getter(), proxy)) {
    return false;
  }
  if (desc.hasSetter() && !WrapAccessorFunction(cx, desc.setter(), proxy)) {
    return false;
  }
  if (desc.hasValue() && desc.value().isObject()) {
    RootedObject val(cx, &desc.value().toObject());
    if (JS::IsCallable(val) &&
        // Don't wrap DOM constructors: they don't care about the "this"
        // they're invoked with anyway, being constructors.  And if we wrap
        // them here we break invariants like Node == Node and whatnot.
        !IsMaybeWrappedDOMConstructor(val)) {
      val = WrapCallable(cx, val, proxy);
      if (!val) {
        return false;
      }
      desc.value().setObject(*val);
    }
  }

  desc_.set(Some(desc.get()));
  return true;
}

bool SandboxProxyHandler::getOwnPropertyDescriptor(
    JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
    MutableHandle<Maybe<PropertyDescriptor>> desc) const {
  return getPropertyDescriptorImpl(cx, proxy, id, /* getOwn = */ true, desc);
}

/*
 * Reuse the BaseProxyHandler versions of the derived traps that are implemented
 * in terms of the fundamental traps.
 */

bool SandboxProxyHandler::has(JSContext* cx, JS::Handle<JSObject*> proxy,
                              JS::Handle<jsid> id, bool* bp) const {
  // This uses JS_GetPropertyDescriptorById for backward compatibility.
  Rooted<Maybe<PropertyDescriptor>> desc(cx);
  if (!getPropertyDescriptorImpl(cx, proxy, id, /* getOwn = */ false, &desc)) {
    return false;
  }

  *bp = desc.isSome();
  return true;
}
bool SandboxProxyHandler::hasOwn(JSContext* cx, JS::Handle<JSObject*> proxy,
                                 JS::Handle<jsid> id, bool* bp) const {
  return BaseProxyHandler::hasOwn(cx, proxy, id, bp);
}

bool SandboxProxyHandler::get(JSContext* cx, JS::Handle<JSObject*> proxy,
                              JS::Handle<JS::Value> receiver,
                              JS::Handle<jsid> id,
                              JS::MutableHandle<Value> vp) const {
  // This uses JS_GetPropertyDescriptorById for backward compatibility.
  Rooted<Maybe<PropertyDescriptor>> desc(cx);
  if (!getPropertyDescriptorImpl(cx, proxy, id, /* getOwn = */ false, &desc)) {
    return false;
  }

  if (desc.isNothing()) {
    vp.setUndefined();
    return true;
  } else {
    desc->assertComplete();
  }

  // Everything after here follows [[Get]] for ordinary objects.
  if (desc->isDataDescriptor()) {
    vp.set(desc->value());
    return true;
  }

  MOZ_ASSERT(desc->isAccessorDescriptor());
  RootedObject getter(cx, desc->getter());

  if (!getter) {
    vp.setUndefined();
    return true;
  }

  return Call(cx, receiver, getter, HandleValueArray::empty(), vp);
}

bool SandboxProxyHandler::set(JSContext* cx, JS::Handle<JSObject*> proxy,
                              JS::Handle<jsid> id, JS::Handle<Value> v,
                              JS::Handle<Value> receiver,
                              JS::ObjectOpResult& result) const {
  return BaseProxyHandler::set(cx, proxy, id, v, receiver, result);
}

bool SandboxProxyHandler::getOwnEnumerablePropertyKeys(
    JSContext* cx, JS::Handle<JSObject*> proxy,
    MutableHandleIdVector props) const {
  return BaseProxyHandler::getOwnEnumerablePropertyKeys(cx, proxy, props);
}

bool SandboxProxyHandler::enumerate(JSContext* cx, JS::Handle<JSObject*> proxy,
                                    JS::MutableHandleIdVector props) const {
  return BaseProxyHandler::enumerate(cx, proxy, props);
}

bool xpc::GlobalProperties::Parse(JSContext* cx, JS::HandleObject obj) {
  uint32_t length;
  bool ok = JS::GetArrayLength(cx, obj, &length);
  NS_ENSURE_TRUE(ok, false);
  for (uint32_t i = 0; i < length; i++) {
    RootedValue nameValue(cx);
    ok = JS_GetElement(cx, obj, i, &nameValue);
    NS_ENSURE_TRUE(ok, false);
    if (!nameValue.isString()) {
      JS_ReportErrorASCII(cx, "Property names must be strings");
      return false;
    }
    JSLinearString* nameStr = JS_EnsureLinearString(cx, nameValue.toString());
    if (!nameStr) {
      return false;
    }

    if (JS_LinearStringEqualsLiteral(nameStr, "AbortController")) {
      AbortController = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "Blob")) {
      Blob = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "ChromeUtils")) {
      ChromeUtils = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "CSS")) {
      CSS = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "CSSRule")) {
      CSSRule = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "CustomStateSet")) {
      CustomStateSet = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "Document")) {
      Document = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "Directory")) {
      Directory = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "DOMException")) {
      DOMException = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "DOMParser")) {
      DOMParser = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "DOMTokenList")) {
      DOMTokenList = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "Element")) {
      Element = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "Event")) {
      Event = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "File")) {
      File = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "FileReader")) {
      FileReader = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "FormData")) {
      FormData = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "Headers")) {
      Headers = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "IOUtils")) {
      IOUtils = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "InspectorUtils")) {
      InspectorUtils = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "MessageChannel")) {
      MessageChannel = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "MIDIInputMap")) {
      MIDIInputMap = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "MIDIOutputMap")) {
      MIDIOutputMap = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "Node")) {
      Node = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "NodeFilter")) {
      NodeFilter = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "PathUtils")) {
      PathUtils = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "Performance")) {
      Performance = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "PromiseDebugging")) {
      PromiseDebugging = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "Range")) {
      Range = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "Selection")) {
      Selection = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "TextDecoder")) {
      TextDecoder = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "TextEncoder")) {
      TextEncoder = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "URL")) {
      URL = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "URLSearchParams")) {
      URLSearchParams = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "XMLHttpRequest")) {
      XMLHttpRequest = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "WebSocket")) {
      WebSocket = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "Window")) {
      Window = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "XMLSerializer")) {
      XMLSerializer = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "ReadableStream")) {
      ReadableStream = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "atob")) {
      atob = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "btoa")) {
      btoa = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "caches")) {
      caches = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "crypto")) {
      crypto = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "fetch")) {
      fetch = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "storage")) {
      storage = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "structuredClone")) {
      structuredClone = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "indexedDB")) {
      indexedDB = true;
    } else if (JS_LinearStringEqualsLiteral(nameStr, "isSecureContext")) {
      isSecureContext = true;
#ifdef MOZ_WEBRTC
    } else if (JS_LinearStringEqualsLiteral(nameStr, "rtcIdentityProvider")) {
      rtcIdentityProvider = true;
#endif
    } else {
      RootedString nameStr(cx, nameValue.toString());
      JS::UniqueChars name = JS_EncodeStringToUTF8(cx, nameStr);
      if (!name) {
        return false;
      }

      JS_ReportErrorUTF8(cx, "Unknown property name: %s", name.get());
      return false;
    }
  }
  return true;
}

bool xpc::GlobalProperties::Define(JSContext* cx, JS::HandleObject obj) {
  MOZ_ASSERT(js::GetContextCompartment(cx) == JS::GetCompartment(obj));
  // Properties will be exposed to System automatically but not to Sandboxes
  // if |[Exposed=System]| is specified.
  // This function holds common properties not exposed automatically but able
  // to be requested either in |Cu.importGlobalProperties| or
  // |wantGlobalProperties| of a sandbox.
  if (AbortController &&
      !dom::AbortController_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (Blob && !dom::Blob_Binding::GetConstructorObject(cx)) return false;

  if (ChromeUtils && !dom::ChromeUtils_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (CSS && !dom::CSS_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (CSSRule && !dom::CSSRule_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (CustomStateSet &&
      !dom::CustomStateSet_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (Directory && !dom::Directory_Binding::GetConstructorObject(cx))
    return false;

  if (Document && !dom::Document_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (DOMException && !dom::DOMException_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (DOMParser && !dom::DOMParser_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (DOMTokenList && !dom::DOMTokenList_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (Element && !dom::Element_Binding::GetConstructorObject(cx)) return false;

  if (Event && !dom::Event_Binding::GetConstructorObject(cx)) return false;

  if (File && !dom::File_Binding::GetConstructorObject(cx)) return false;

  if (FileReader && !dom::FileReader_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (FormData && !dom::FormData_Binding::GetConstructorObject(cx))
    return false;

  if (Headers && !dom::Headers_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (IOUtils && !dom::IOUtils_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (InspectorUtils && !dom::InspectorUtils_Binding::GetConstructorObject(cx))
    return false;

  if (MessageChannel &&
      (!dom::MessageChannel_Binding::GetConstructorObject(cx) ||
       !dom::MessagePort_Binding::GetConstructorObject(cx)))
    return false;

  if (MIDIInputMap && !dom::MIDIInputMap_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (MIDIOutputMap && !dom::MIDIOutputMap_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (Node && !dom::Node_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (NodeFilter && !dom::NodeFilter_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (PathUtils && !dom::PathUtils_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (Performance && !dom::Performance_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (PromiseDebugging &&
      !dom::PromiseDebugging_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (Range && !dom::Range_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (Selection && !dom::Selection_Binding::GetConstructorObject(cx)) {
    return false;
  }

  if (TextDecoder && !dom::TextDecoder_Binding::GetConstructorObject(cx))
    return false;

  if (TextEncoder && !dom::TextEncoder_Binding::GetConstructorObject(cx))
    return false;

  if (URL && !dom::URL_Binding::GetConstructorObject(cx)) return false;

  if (URLSearchParams &&
      !dom::URLSearchParams_Binding::GetConstructorObject(cx))
    return false;

  if (XMLHttpRequest && !dom::XMLHttpRequest_Binding::GetConstructorObject(cx))
    return false;

  if (WebSocket && !dom::WebSocket_Binding::GetConstructorObject(cx))
    return false;

  if (Window && !dom::Window_Binding::GetConstructorObject(cx)) return false;

  if (XMLSerializer && !dom::XMLSerializer_Binding::GetConstructorObject(cx))
    return false;

  if (ReadableStream && !dom::ReadableStream_Binding::GetConstructorObject(cx))
    return false;

  if (atob && !JS_DefineFunction(cx, obj, "atob", Atob, 1, 0)) return false;

  if (btoa && !JS_DefineFunction(cx, obj, "btoa", Btoa, 1, 0)) return false;

  if (caches && !dom::cache::CacheStorage::DefineCaches(cx, obj)) {
    return false;
  }

  if (crypto && !SandboxCreateCrypto(cx, obj)) {
    return false;
  }

  if (fetch && !SandboxCreateFetch(cx, obj)) {
    return false;
  }

  if (storage && !SandboxCreateStorage(cx, obj)) {
    return false;
  }

  if (structuredClone && !SandboxCreateStructuredClone(cx, obj)) {
    return false;
  }

  // Note that isSecureContext here doesn't mean the context is actually secure
  // - just that the caller wants the property defined
  if (isSecureContext) {
    bool hasSecureContext = IsSecureContextOrObjectIsFromSecureContext(cx, obj);
    JS::Rooted<JS::Value> secureJsValue(cx, JS::BooleanValue(hasSecureContext));
    return JS_DefineProperty(cx, obj, "isSecureContext", secureJsValue,
                             JSPROP_ENUMERATE);
  }

#ifdef MOZ_WEBRTC
  if (rtcIdentityProvider && !SandboxCreateRTCIdentityProvider(cx, obj)) {
    return false;
  }
#endif

  return true;
}

bool xpc::GlobalProperties::DefineInXPCComponents(JSContext* cx,
                                                  JS::HandleObject obj) {
  if (indexedDB && !IndexedDatabaseManager::DefineIndexedDB(cx, obj))
    return false;

  return Define(cx, obj);
}

bool xpc::GlobalProperties::DefineInSandbox(JSContext* cx,
                                            JS::HandleObject obj) {
  MOZ_ASSERT(IsSandbox(obj));
  MOZ_ASSERT(js::GetContextCompartment(cx) == JS::GetCompartment(obj));

  if (indexedDB && !(IndexedDatabaseManager::ResolveSandboxBinding(cx) &&
                     IndexedDatabaseManager::DefineIndexedDB(cx, obj)))
    return false;

  return Define(cx, obj);
}

/**
 * If enabled, apply the extension base CSP, then apply the
 * content script CSP which will either be a default or one
 * provided by the extension in its manifest.
 */
nsresult ApplyAddonContentScriptCSP(nsISupports* prinOrSop) {
  nsCOMPtr<nsIPrincipal> principal = do_QueryInterface(prinOrSop);
  if (!principal) {
    return NS_OK;
  }

  auto* basePrin = BasePrincipal::Cast(principal);
  // We only get an addonPolicy if the principal is an
  // expanded principal with an extension principal in it.
  auto* addonPolicy = basePrin->ContentScriptAddonPolicy();
  if (!addonPolicy) {
    return NS_OK;
  }
  // For backwards compatibility, content scripts have no CSP
  // in manifest v2.  Only apply content script CSP to V3 or later.
  if (addonPolicy->ManifestVersion() < 3) {
    return NS_OK;
  }

  nsString url;
  MOZ_TRY_VAR(url, addonPolicy->GetURL(u""_ns));

  nsCOMPtr<nsIURI> selfURI;
  MOZ_TRY(NS_NewURI(getter_AddRefs(selfURI), url));

  const nsAString& baseCSP = addonPolicy->BaseCSP();

  // If we got here, we're definitly an expanded principal.
  auto expanded = basePrin->As<ExpandedPrincipal>();
  nsCOMPtr<nsIContentSecurityPolicy> csp;

#ifdef MOZ_DEBUG
  // Bug 1548468: Move CSP off ExpandedPrincipal
  expanded->GetCsp(getter_AddRefs(csp));
  if (csp) {
    uint32_t count = 0;
    csp->GetPolicyCount(&count);
    if (count > 0) {
      // Ensure that the policy was not already added.
      nsAutoString parsedPolicyStr;
      for (uint32_t i = 0; i < count; i++) {
        csp->GetPolicyString(i, parsedPolicyStr);
        MOZ_ASSERT(!parsedPolicyStr.Equals(baseCSP));
      }
    }
  }
#endif

  // Create a clone of the expanded principal to be used for the call to
  // SetRequestContextWithPrincipal (to prevent the CSP and expanded
  // principal instances to keep each other alive indefinitely, see
  // Bug 1741600).
  //
  // This may not be necessary anymore once Bug 1548468 will move CSP
  // off ExpandedPrincipal.
  RefPtr<ExpandedPrincipal> clonedPrincipal = ExpandedPrincipal::Create(
      expanded->AllowList(), expanded->OriginAttributesRef());
  MOZ_ASSERT(clonedPrincipal);

  csp = new nsCSPContext();
  MOZ_TRY(
      csp->SetRequestContextWithPrincipal(clonedPrincipal, selfURI, ""_ns, 0));

  MOZ_TRY(csp->AppendPolicy(baseCSP, false, false));

  expanded->SetCsp(csp);
  return NS_OK;
}

nsresult xpc::CreateSandboxObject(JSContext* cx, MutableHandleValue vp,
                                  nsISupports* prinOrSop,
                                  SandboxOptions& options) {
  // Create the sandbox global object
  nsCOMPtr<nsIPrincipal> principal = do_QueryInterface(prinOrSop);
  nsCOMPtr<nsIGlobalObject> obj = do_QueryInterface(prinOrSop);
  if (obj) {
    nsGlobalWindowInner* window =
        WindowOrNull(js::UncheckedUnwrap(obj->GetGlobalJSObject(), false));
    // If we have a secure context window inherit from it's parent
    if (window && window->IsSecureContext()) {
      options.forceSecureContext = true;
    }
  }
  if (!principal) {
    nsCOMPtr<nsIScriptObjectPrincipal> sop = do_QueryInterface(prinOrSop);
    if (sop) {
      principal = sop->GetPrincipal();
    } else {
      RefPtr<NullPrincipal> nullPrin =
          NullPrincipal::CreateWithoutOriginAttributes();
      principal = nullPrin;
    }
  }
  MOZ_ASSERT(principal);

  JS::RealmOptions realmOptions;

  auto& creationOptions = realmOptions.creationOptions();

  bool isSystemPrincipal = principal->IsSystemPrincipal();

  if (isSystemPrincipal) {
    options.forceSecureContext = true;
  }

  // If we are able to see [SecureContext] API code
  if (options.forceSecureContext) {
    creationOptions.setSecureContext(true);
  }

  xpc::SetPrefableRealmOptions(realmOptions);
  if (options.sameZoneAs) {
    creationOptions.setNewCompartmentInExistingZone(
        js::UncheckedUnwrap(options.sameZoneAs));
  } else if (options.freshZone) {
    creationOptions.setNewCompartmentAndZone();
  } else if (isSystemPrincipal && !options.invisibleToDebugger &&
             !options.freshCompartment) {
    // Use a shared system compartment for system-principal sandboxes that don't
    // require invisibleToDebugger (this is a compartment property, see bug
    // 1482215).
    creationOptions.setExistingCompartment(xpc::PrivilegedJunkScope());
  } else {
    creationOptions.setNewCompartmentInSystemZone();
  }

  creationOptions.setInvisibleToDebugger(options.invisibleToDebugger)
      .setTrace(TraceXPCGlobal);

  realmOptions.behaviors().setDiscardSource(options.discardSource);

  if (isSystemPrincipal) {
    realmOptions.behaviors().setClampAndJitterTime(false);
  }

  const JSClass* clasp = &SandboxClass;

  RootedObject sandbox(
      cx, xpc::CreateGlobalObject(cx, clasp, principal, realmOptions));
  if (!sandbox) {
    return NS_ERROR_FAILURE;
  }

  // Use exclusive expandos for non-system-principal sandboxes.
  bool hasExclusiveExpandos = !isSystemPrincipal;

  // Set up the wantXrays flag, which indicates whether xrays are desired even
  // for same-origin access.
  //
  // This flag has historically been ignored for chrome sandboxes due to
  // quirks in the wrapping implementation that have now been removed. Indeed,
  // same-origin Xrays for chrome->chrome access seems a bit superfluous.
  // Arguably we should just flip the default for chrome and still honor the
  // flag, but such a change would break code in subtle ways for minimal
  // benefit. So we just switch it off here.
  bool wantXrays = AccessCheck::isChrome(sandbox) ? false : options.wantXrays;

  if (creationOptions.compartmentSpecifier() ==
      JS::CompartmentSpecifier::ExistingCompartment) {
    // Make sure the compartment we're reusing has flags that match what we
    // would set on a new compartment.
    CompartmentPrivate* priv = CompartmentPrivate::Get(sandbox);
    MOZ_RELEASE_ASSERT(priv->allowWaivers == options.allowWaivers);
    MOZ_RELEASE_ASSERT(priv->isWebExtensionContentScript ==
                       options.isWebExtensionContentScript);
    MOZ_RELEASE_ASSERT(priv->isUAWidgetCompartment == options.isUAWidgetScope);
    MOZ_RELEASE_ASSERT(priv->hasExclusiveExpandos == hasExclusiveExpandos);
    MOZ_RELEASE_ASSERT(priv->wantXrays == wantXrays);
  } else {
    CompartmentPrivate* priv = CompartmentPrivate::Get(sandbox);
    priv->allowWaivers = options.allowWaivers;
    priv->isWebExtensionContentScript = options.isWebExtensionContentScript;
    priv->isUAWidgetCompartment = options.isUAWidgetScope;
    priv->hasExclusiveExpandos = hasExclusiveExpandos;
    priv->wantXrays = wantXrays;
  }

  {
    JSAutoRealm ar(cx, sandbox);

    // This creates a SandboxPrivate and passes ownership of it to |sandbox|.
    SandboxPrivate::Create(principal, sandbox);

    // Ensure |Object.prototype| is instantiated before prototype-
    // splicing below.
    if (!JS::GetRealmObjectPrototype(cx)) {
      return NS_ERROR_XPC_UNEXPECTED;
    }

    if (options.proto) {
      bool ok = JS_WrapObject(cx, &options.proto);
      if (!ok) {
        return NS_ERROR_XPC_UNEXPECTED;
      }

      // Now check what sort of thing we've got in |proto|, and figure out
      // if we need a SandboxProxyHandler.
      //
      // Note that, in the case of a window, we can't require that the
      // Sandbox subsumes the prototype, because we have to hold our
      // reference to it via an outer window, and the window may navigate
      // at any time. So we have to handle that case separately.
      bool useSandboxProxy =
          !!WindowOrNull(js::UncheckedUnwrap(options.proto, false));
      if (!useSandboxProxy) {
        // We just wrapped options.proto into the compartment of whatever Realm
        // is on the cx, so use that same realm for the CheckedUnwrapDynamic
        // call.
        JSObject* unwrappedProto =
            js::CheckedUnwrapDynamic(options.proto, cx, false);
        if (!unwrappedProto) {
          JS_ReportErrorASCII(cx, "Sandbox must subsume sandboxPrototype");
          return NS_ERROR_INVALID_ARG;
        }
        const JSClass* unwrappedClass = JS::GetClass(unwrappedProto);
        useSandboxProxy = unwrappedClass->isWrappedNative() ||
                          mozilla::dom::IsDOMClass(unwrappedClass);
      }

      if (useSandboxProxy) {
        // Wrap it up in a proxy that will do the right thing in terms
        // of this-binding for methods.
        RootedValue priv(cx, ObjectValue(*options.proto));
        options.proto =
            js::NewProxyObject(cx, &sandboxProxyHandler, priv, nullptr);
        if (!options.proto) {
          return NS_ERROR_OUT_OF_MEMORY;
        }
      }

      ok = JS_SetPrototype(cx, sandbox, options.proto);
      if (!ok) {
        return NS_ERROR_XPC_UNEXPECTED;
      }
    }

    bool allowComponents = principal->IsSystemPrincipal();
    if (options.wantComponents && allowComponents) {
      if (!ObjectScope(sandbox)->AttachComponentsObject(cx)) {
        return NS_ERROR_XPC_UNEXPECTED;
      }

      if (!ObjectScope(sandbox)->AttachJSServices(cx)) {
        return NS_ERROR_XPC_UNEXPECTED;
      }
    }

    if (!XPCNativeWrapper::AttachNewConstructorObject(cx, sandbox)) {
      return NS_ERROR_XPC_UNEXPECTED;
    }

    if (!JS_DefineFunctions(cx, sandbox, SandboxFunctions)) {
      return NS_ERROR_XPC_UNEXPECTED;
    }

    if (options.wantExportHelpers &&
        (!JS_DefineFunction(cx, sandbox, "exportFunction",
                            SandboxExportFunction, 3, 0) ||
         !JS_DefineFunction(cx, sandbox, "createObjectIn",
                            SandboxCreateObjectIn, 2, 0) ||
         !JS_DefineFunction(cx, sandbox, "cloneInto", SandboxCloneInto, 3, 0) ||
         !JS_DefineFunction(cx, sandbox, "isProxy", SandboxIsProxy, 1, 0)))
      return NS_ERROR_XPC_UNEXPECTED;

    if (!options.globalProperties.DefineInSandbox(cx, sandbox)) {
      return NS_ERROR_XPC_UNEXPECTED;
    }
  }

  // We handle the case where the context isn't in a compartment for the
  // benefit of UnprivilegedJunkScope().
  vp.setObject(*sandbox);
  if (js::GetContextCompartment(cx) && !JS_WrapValue(cx, vp)) {
    return NS_ERROR_UNEXPECTED;
  }

  // Set the location information for the new global, so that tools like
  // about:memory may use that information
  xpc::SetLocationForGlobal(sandbox, options.sandboxName);

  xpc::SetSandboxMetadata(cx, sandbox, options.metadata);

  JSAutoRealm ar(cx, sandbox);
  JS_FireOnNewGlobalObject(cx, sandbox);

  return NS_OK;
}

NS_IMETHODIMP
nsXPCComponents_utils_Sandbox::Call(nsIXPConnectWrappedNative* wrapper,
                                    JSContext* cx, JSObject* objArg,
                                    const CallArgs& args, bool* _retval) {
  RootedObject obj(cx, objArg);
  return CallOrConstruct(wrapper, cx, obj, args, _retval);
}

NS_IMETHODIMP
nsXPCComponents_utils_Sandbox::Construct(nsIXPConnectWrappedNative* wrapper,
                                         JSContext* cx, JSObject* objArg,
                                         const CallArgs& args, bool* _retval) {
  RootedObject obj(cx, objArg);
  return CallOrConstruct(wrapper, cx, obj, args, _retval);
}

/*
 * For sandbox constructor the first argument can be a URI string in which case
 * we use the related Content Principal for the sandbox.
 */
bool ParsePrincipal(JSContext* cx, HandleString contentUrl,
                    const OriginAttributes& aAttrs, nsIPrincipal** principal) {
  MOZ_ASSERT(principal);
  MOZ_ASSERT(contentUrl);
  nsCOMPtr<nsIURI> uri;
  nsAutoJSString contentStr;
  NS_ENSURE_TRUE(contentStr.init(cx, contentUrl), false);
  nsresult rv = NS_NewURI(getter_AddRefs(uri), contentStr);
  if (NS_FAILED(rv)) {
    JS_ReportErrorASCII(cx, "Creating URI from string failed");
    return false;
  }

  // We could allow passing in the app-id and browser-element info to the
  // sandbox constructor. But creating a sandbox based on a string is a
  // deprecated API so no need to add features to it.
  nsCOMPtr<nsIPrincipal> prin =
      BasePrincipal::CreateContentPrincipal(uri, aAttrs);
  prin.forget(principal);

  if (!*principal) {
    JS_ReportErrorASCII(cx, "Creating Principal from URI failed");
    return false;
  }
  return true;
}

/*
 * For sandbox constructor the first argument can be a principal object or
 * a script object principal (Document, Window).
 */
static bool GetPrincipalOrSOP(JSContext* cx, HandleObject from,
                              nsISupports** out) {
  MOZ_ASSERT(out);
  *out = nullptr;

  // We might have a Window here, so need ReflectorToISupportsDynamic
  nsCOMPtr<nsISupports> native = ReflectorToISupportsDynamic(from, cx);

  if (nsCOMPtr<nsIScriptObjectPrincipal> sop = do_QueryInterface(native)) {
    sop.forget(out);
    return true;
  }

  nsCOMPtr<nsIPrincipal> principal = do_QueryInterface(native);
  principal.forget(out);
  NS_ENSURE_TRUE(*out, false);

  return true;
}

/*
 * The first parameter of the sandbox constructor might be an array of
 * principals, either in string format or actual objects (see GetPrincipalOrSOP)
 */
static bool GetExpandedPrincipal(JSContext* cx, HandleObject arrayObj,
                                 const SandboxOptions& options,
                                 nsIExpandedPrincipal** out) {
  MOZ_ASSERT(out);
  uint32_t length;

  if (!JS::GetArrayLength(cx, arrayObj, &length)) {
    return false;
  }
  if (!length) {
    // We need a whitelist of principals or uri strings to create an
    // expanded principal, if we got an empty array or something else
    // report error.
    JS_ReportErrorASCII(cx, "Expected an array of URI strings");
    return false;
  }

  nsTArray<nsCOMPtr<nsIPrincipal>> allowedDomains(length);
  allowedDomains.SetLength(length);

  // If an originAttributes option has been specified, we will use that as the
  // OriginAttribute of all of the string arguments passed to this function.
  // Otherwise, we will use the OriginAttributes of a principal or SOP object
  // in the array, if any.  If no such object is present, and all we have are
  // strings, then we will use a default OriginAttribute.
  // Otherwise, we will use the origin attributes of the passed object(s). If
  // more than one object is specified, we ensure that the OAs match.
  Maybe<OriginAttributes> attrs;
  if (options.originAttributes) {
    attrs.emplace();
    JS::RootedValue val(cx, JS::ObjectValue(*options.originAttributes));
    if (!attrs->Init(cx, val)) {
      // The originAttributes option, if specified, must be valid!
      JS_ReportErrorASCII(cx, "Expected a valid OriginAttributes object");
      return false;
    }
  }

  // Now we go over the array in two passes.  In the first pass, we ignore
  // strings, and only process objects.  Assuming that no originAttributes
  // option has been passed, if we encounter a principal or SOP object, we
  // grab its OA and save it if it's the first OA encountered, otherwise
  // check to make sure that it is the same as the OA found before.
  // In the second pass, we ignore objects, and use the OA found in pass 0
  // (or the previously computed OA if we have obtained it from the options)
  // to construct content principals.
  //
  // The effective OA selected above will also be set as the OA of the
  // expanded principal object.

  // First pass:
  for (uint32_t i = 0; i < length; ++i) {
    RootedValue allowed(cx);
    if (!JS_GetElement(cx, arrayObj, i, &allowed)) {
      return false;
    }

    nsCOMPtr<nsIPrincipal> principal;
    if (allowed.isObject()) {
      // In case of object let's see if it's a Principal or a
      // ScriptObjectPrincipal.
      nsCOMPtr<nsISupports> prinOrSop;
      RootedObject obj(cx, &allowed.toObject());
      if (!GetPrincipalOrSOP(cx, obj, getter_AddRefs(prinOrSop))) {
        return false;
      }

      nsCOMPtr<nsIScriptObjectPrincipal> sop(do_QueryInterface(prinOrSop));
      principal = do_QueryInterface(prinOrSop);
      if (sop) {
        principal = sop->GetPrincipal();
      }
      NS_ENSURE_TRUE(principal, false);

      if (!options.originAttributes) {
        const OriginAttributes prinAttrs = principal->OriginAttributesRef();
        if (attrs.isNothing()) {
          attrs.emplace(prinAttrs);
        } else if (prinAttrs != attrs.ref()) {
          // If attrs is from a previously encountered principal in the
          // array, we need to ensure that it matches the OA of the
          // principal we have here.
          // If attrs comes from OriginAttributes, we don't need
          // this check.
          return false;
        }
      }

      // We do not allow ExpandedPrincipals to contain any system principals.
      bool isSystem = principal->IsSystemPrincipal();
      if (isSystem) {
        JS_ReportErrorASCII(
            cx, "System principal is not allowed in an expanded principal");
        return false;
      }
      allowedDomains[i] = principal;
    } else if (allowed.isString()) {
      // Skip any string arguments - we handle them in the next pass.
    } else {
      // Don't know what this is.
      return false;
    }
  }

  if (attrs.isNothing()) {
    // If no OriginAttributes was found in the first pass, fall back to a
    // default one.
    attrs.emplace();
  }

  // Second pass:
  for (uint32_t i = 0; i < length; ++i) {
    RootedValue allowed(cx);
    if (!JS_GetElement(cx, arrayObj, i, &allowed)) {
      return false;
    }

    nsCOMPtr<nsIPrincipal> principal;
    if (allowed.isString()) {
      // In case of string let's try to fetch a content principal from it.
      RootedString str(cx, allowed.toString());

      // attrs here is either a default OriginAttributes in case the
      // originAttributes option isn't specified, and no object in the array
      // provides a principal.  Otherwise it's either the forced principal, or
      // the principal found before, so we can use it here.
      if (!ParsePrincipal(cx, str, attrs.ref(), getter_AddRefs(principal))) {
        return false;
      }
      NS_ENSURE_TRUE(principal, false);
      allowedDomains[i] = principal;
    } else {
      MOZ_ASSERT(allowed.isObject());
    }
  }

  RefPtr<ExpandedPrincipal> result =
      ExpandedPrincipal::Create(allowedDomains, attrs.ref());
  result.forget(out);
  return true;
}

/*
 * Helper that tries to get a property from the options object.
 */
bool OptionsBase::ParseValue(const char* name, MutableHandleValue prop,
                             bool* aFound) {
  bool found;
  bool ok = JS_HasProperty(mCx, mObject, name, &found);
  NS_ENSURE_TRUE(ok, false);

  if (aFound) {
    *aFound = found;
  }

  if (!found) {
    return true;
  }

  return JS_GetProperty(mCx, mObject, name, prop);
}

/*
 * Helper that tries to get a boolean property from the options object.
 */
bool OptionsBase::ParseBoolean(const char* name, bool* prop) {
  MOZ_ASSERT(prop);
  RootedValue value(mCx);
  bool found;
  bool ok = ParseValue(name, &value, &found);
  NS_ENSURE_TRUE(ok, false);

  if (!found) {
    return true;
  }

  if (!value.isBoolean()) {
    JS_ReportErrorASCII(mCx, "Expected a boolean value for property %s", name);
    return false;
  }

  *prop = value.toBoolean();
  return true;
}

/*
 * Helper that tries to get an object property from the options object.
 */
bool OptionsBase::ParseObject(const char* name, MutableHandleObject prop) {
  RootedValue value(mCx);
  bool found;
  bool ok = ParseValue(name, &value, &found);
  NS_ENSURE_TRUE(ok, false);

  if (!found) {
    return true;
  }

  if (!value.isObject()) {
    JS_ReportErrorASCII(mCx, "Expected an object value for property %s", name);
    return false;
  }
  prop.set(&value.toObject());
  return true;
}

/*
 * Helper that tries to get an object property from the options object.
 */
bool OptionsBase::ParseJSString(const char* name, MutableHandleString prop) {
  RootedValue value(mCx);
  bool found;
  bool ok = ParseValue(name, &value, &found);
  NS_ENSURE_TRUE(ok, false);

  if (!found) {
    return true;
  }

  if (!value.isString()) {
    JS_ReportErrorASCII(mCx, "Expected a string value for property %s", name);
    return false;
  }
  prop.set(value.toString());
  return true;
}

/*
 * Helper that tries to get a string property from the options object.
 */
bool OptionsBase::ParseString(const char* name, nsCString& prop) {
  RootedValue value(mCx);
  bool found;
  bool ok = ParseValue(name, &value, &found);
  NS_ENSURE_TRUE(ok, false);

  if (!found) {
    return true;
  }

  if (!value.isString()) {
    JS_ReportErrorASCII(mCx, "Expected a string value for property %s", name);
    return false;
  }

  JS::UniqueChars tmp = JS_EncodeStringToLatin1(mCx, value.toString());
  NS_ENSURE_TRUE(tmp, false);
  prop.Assign(tmp.get(), strlen(tmp.get()));
  return true;
}

/*
 * Helper that tries to get a string property from the options object.
 */
bool OptionsBase::ParseString(const char* name, nsString& prop) {
  RootedValue value(mCx);
  bool found;
  bool ok = ParseValue(name, &value, &found);
  NS_ENSURE_TRUE(ok, false);

  if (!found) {
    return true;
  }

  if (!value.isString()) {
    JS_ReportErrorASCII(mCx, "Expected a string value for property %s", name);
    return false;
  }

  nsAutoJSString strVal;
  if (!strVal.init(mCx, value.toString())) {
    return false;
  }

  prop = strVal;
  return true;
}

/*
 * Helper that tries to get jsid property from the options object.
 */
bool OptionsBase::ParseId(const char* name, MutableHandleId prop) {
  RootedValue value(mCx);
  bool found;
  bool ok = ParseValue(name, &value, &found);
  NS_ENSURE_TRUE(ok, false);

  if (!found) {
    return true;
  }

  return JS_ValueToId(mCx, value, prop);
}

/*
 * Helper that tries to get a uint32_t property from the options object.
 */
bool OptionsBase::ParseUInt32(const char* name, uint32_t* prop) {
  MOZ_ASSERT(prop);
  RootedValue value(mCx);
  bool found;
  bool ok = ParseValue(name, &value, &found);
  NS_ENSURE_TRUE(ok, false);

  if (!found) {
    return true;
  }

  if (!JS::ToUint32(mCx, value, prop)) {
    JS_ReportErrorASCII(mCx, "Expected a uint32_t value for property %s", name);
    return false;
  }

  return true;
}

/*
 * Helper that tries to get a list of DOM constructors and other helpers from
 * the options object.
 */
bool SandboxOptions::ParseGlobalProperties() {
  RootedValue value(mCx);
  bool found;
  bool ok = ParseValue("wantGlobalProperties", &value, &found);
  NS_ENSURE_TRUE(ok, false);
  if (!found) {
    return true;
  }

  if (!value.isObject()) {
    JS_ReportErrorASCII(mCx,
                        "Expected an array value for wantGlobalProperties");
    return false;
  }

  RootedObject ctors(mCx, &value.toObject());
  bool isArray;
  if (!JS::IsArrayObject(mCx, ctors, &isArray)) {
    return false;
  }
  if (!isArray) {
    JS_ReportErrorASCII(mCx,
                        "Expected an array value for wantGlobalProperties");
    return false;
  }

  return globalProperties.Parse(mCx, ctors);
}

/*
 * Helper that parsing the sandbox options object (from) and sets the fields of
 * the incoming options struct (options).
 */
bool SandboxOptions::Parse() {
  /* All option names must be ASCII-only. */
  bool ok = ParseObject("sandboxPrototype", &proto) &&
            ParseBoolean("wantXrays", &wantXrays) &&
            ParseBoolean("allowWaivers", &allowWaivers) &&
            ParseBoolean("wantComponents", &wantComponents) &&
            ParseBoolean("wantExportHelpers", &wantExportHelpers) &&
            ParseBoolean("isWebExtensionContentScript",
                         &isWebExtensionContentScript) &&
            ParseBoolean("forceSecureContext", &forceSecureContext) &&
            ParseString("sandboxName", sandboxName) &&
            ParseObject("sameZoneAs", &sameZoneAs) &&
            ParseBoolean("freshCompartment", &freshCompartment) &&
            ParseBoolean("freshZone", &freshZone) &&
            ParseBoolean("invisibleToDebugger", &invisibleToDebugger) &&
            ParseBoolean("discardSource", &discardSource) &&
            ParseGlobalProperties() && ParseValue("metadata", &metadata) &&
            ParseUInt32("userContextId", &userContextId) &&
            ParseObject("originAttributes", &originAttributes);
  if (!ok) {
    return false;
  }

  if (freshZone && sameZoneAs) {
    JS_ReportErrorASCII(mCx, "Cannot use both sameZoneAs and freshZone");
    return false;
  }

  return true;
}

static nsresult AssembleSandboxMemoryReporterName(JSContext* cx,
                                                  nsCString& sandboxName) {
  // Use a default name when the caller did not provide a sandboxName.
  if (sandboxName.IsEmpty()) {
    sandboxName = "[anonymous sandbox]"_ns;
  } else {
#ifndef DEBUG
    // Adding the caller location is fairly expensive, so in non-debug
    // builds, only add it if we don't have an explicit sandbox name.
    return NS_OK;
#endif
  }

  // Get the xpconnect native call context.
  XPCCallContext* cc = XPCJSContext::Get()->GetCallContext();
  NS_ENSURE_TRUE(cc, NS_ERROR_INVALID_ARG);

  // Get the current source info from xpc.
  nsCOMPtr<nsIStackFrame> frame = dom::GetCurrentJSStack();

  // Append the caller's location information.
  if (frame) {
    nsString location;
    frame->GetFilename(cx, location);
    int32_t lineNumber = frame->GetLineNumber(cx);

    sandboxName.AppendLiteral(" (from: ");
    sandboxName.Append(NS_ConvertUTF16toUTF8(location));
    sandboxName.Append(':');
    sandboxName.AppendInt(lineNumber);
    sandboxName.Append(')');
  }

  return NS_OK;
}

// static
nsresult nsXPCComponents_utils_Sandbox::CallOrConstruct(
    nsIXPConnectWrappedNative* wrapper, JSContext* cx, HandleObject obj,
    const CallArgs& args, bool* _retval) {
  if (args.length() < 1) {
    return ThrowAndFail(NS_ERROR_XPC_NOT_ENOUGH_ARGS, cx, _retval);
  }

  nsresult rv;
  bool ok = false;
  bool calledWithOptions = args.length() > 1;
  if (calledWithOptions && !args[1].isObject()) {
    return ThrowAndFail(NS_ERROR_INVALID_ARG, cx, _retval);
  }

  RootedObject optionsObject(cx,
                             calledWithOptions ? &args[1].toObject() : nullptr);

  SandboxOptions options(cx, optionsObject);
  if (calledWithOptions && !options.Parse()) {
    return ThrowAndFail(NS_ERROR_INVALID_ARG, cx, _retval);
  }

  // Make sure to set up principals on the sandbox before initing classes.
  nsCOMPtr<nsIPrincipal> principal;
  nsCOMPtr<nsIExpandedPrincipal> expanded;
  nsCOMPtr<nsISupports> prinOrSop;

  if (args[0].isString()) {
    RootedString str(cx, args[0].toString());
    OriginAttributes attrs;
    if (options.originAttributes) {
      JS::RootedValue val(cx, JS::ObjectValue(*options.originAttributes));
      if (!attrs.Init(cx, val)) {
        // The originAttributes option, if specified, must be valid!
        JS_ReportErrorASCII(cx, "Expected a valid OriginAttributes object");
        return ThrowAndFail(NS_ERROR_INVALID_ARG, cx, _retval);
      }
    }
    attrs.mUserContextId = options.userContextId;
    ok = ParsePrincipal(cx, str, attrs, getter_AddRefs(principal));
    prinOrSop = principal;
  } else if (args[0].isObject()) {
    RootedObject obj(cx, &args[0].toObject());
    bool isArray;
    if (!JS::IsArrayObject(cx, obj, &isArray)) {
      ok = false;
    } else if (isArray) {
      if (options.userContextId != 0) {
        // We don't support passing a userContextId with an array.
        ok = false;
      } else {
        ok = GetExpandedPrincipal(cx, obj, options, getter_AddRefs(expanded));
        prinOrSop = expanded;
        // If this is an addon content script we need to apply the csp.
        MOZ_TRY(ApplyAddonContentScriptCSP(prinOrSop));
      }
    } else {
      ok = GetPrincipalOrSOP(cx, obj, getter_AddRefs(prinOrSop));
    }
  } else if (args[0].isNull()) {
    // Null means that we just pass prinOrSop = nullptr, and get an
    // NullPrincipal.
    ok = true;
  }

  if (!ok) {
    return ThrowAndFail(NS_ERROR_INVALID_ARG, cx, _retval);
  }

  if (NS_FAILED(AssembleSandboxMemoryReporterName(cx, options.sandboxName))) {
    return ThrowAndFail(NS_ERROR_INVALID_ARG, cx, _retval);
  }

  if (options.metadata.isNullOrUndefined()) {
    // If the caller is running in a sandbox, inherit.
    RootedObject callerGlobal(cx, JS::GetScriptedCallerGlobal(cx));
    if (IsSandbox(callerGlobal)) {
      rv = GetSandboxMetadata(cx, callerGlobal, &options.metadata);
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
      }
    }
  }

  rv = CreateSandboxObject(cx, args.rval(), prinOrSop, options);

  if (NS_FAILED(rv)) {
    return ThrowAndFail(rv, cx, _retval);
  }

  *_retval = true;
  return NS_OK;
}

nsresult xpc::EvalInSandbox(JSContext* cx, HandleObject sandboxArg,
                            const nsAString& source, const nsACString& filename,
                            int32_t lineNo, bool enforceFilenameRestrictions,
                            MutableHandleValue rval) {
  JS_AbortIfWrongThread(cx);
  rval.set(UndefinedValue());

  bool waiveXray = xpc::WrapperFactory::HasWaiveXrayFlag(sandboxArg);
  // CheckedUnwrapStatic is fine here, since we're checking for "is it a
  // sandbox".
  RootedObject sandbox(cx, js::CheckedUnwrapStatic(sandboxArg));
  if (!sandbox || !IsSandbox(sandbox)) {
    return NS_ERROR_INVALID_ARG;
  }

  SandboxPrivate* priv = SandboxPrivate::GetPrivate(sandbox);
  nsIScriptObjectPrincipal* sop = priv;
  MOZ_ASSERT(sop, "Invalid sandbox passed");
  nsCOMPtr<nsIPrincipal> prin = sop->GetPrincipal();
  NS_ENSURE_TRUE(prin, NS_ERROR_FAILURE);

  nsAutoCString filenameBuf;
  if (!filename.IsVoid() && filename.Length() != 0) {
    filenameBuf.Assign(filename);
  } else {
    // Default to the spec of the principal.
    nsresult rv = nsJSPrincipals::get(prin)->GetScriptLocation(filenameBuf);
    NS_ENSURE_SUCCESS(rv, rv);
    lineNo = 1;
  }

  // We create a separate cx to do the sandbox evaluation. Scope it.
  RootedValue v(cx, UndefinedValue());
  RootedValue exn(cx, UndefinedValue());
  bool ok = true;
  {
    // We're about to evaluate script, so make an AutoEntryScript.
    // This is clearly Gecko-specific and not in any spec.
    mozilla::dom::AutoEntryScript aes(priv, "XPConnect sandbox evaluation");
    JSContext* sandcx = aes.cx();
    JSAutoRealm ar(sandcx, sandbox);

    JS::CompileOptions options(sandcx);
    options.setFileAndLine(filenameBuf.get(), lineNo);
    options.setSkipFilenameValidation(!enforceFilenameRestrictions);
    MOZ_ASSERT(JS_IsGlobalObject(sandbox));

    const nsPromiseFlatString& flat = PromiseFlatString(source);

    JS::SourceText<char16_t> buffer;
    ok = buffer.init(sandcx, flat.get(), flat.Length(),
                     JS::SourceOwnership::Borrowed) &&
         JS::Evaluate(sandcx, options, buffer, &v);

    // If the sandbox threw an exception, grab it off the context.
    if (aes.HasException()) {
      if (!aes.StealException(&exn)) {
        return NS_ERROR_OUT_OF_MEMORY;
      }
    }
  }

  //
  // Alright, we're back on the caller's cx. If an error occured, try to
  // wrap and set the exception. Otherwise, wrap the return value.
  //

  if (!ok) {
    // If we end up without an exception, it was probably due to OOM along
    // the way, in which case we thow. Otherwise, wrap it.
    if (exn.isUndefined() || !JS_WrapValue(cx, &exn)) {
      return NS_ERROR_OUT_OF_MEMORY;
    }

    // Set the exception on our caller's cx.
    JS_SetPendingException(cx, exn);
    return NS_ERROR_FAILURE;
  }

  // Transitively apply Xray waivers if |sb| was waived.
  if (waiveXray) {
    ok = xpc::WrapperFactory::WaiveXrayAndWrap(cx, &v);
  } else {
    ok = JS_WrapValue(cx, &v);
  }
  NS_ENSURE_TRUE(ok, NS_ERROR_FAILURE);

  // Whew!
  rval.set(v);
  return NS_OK;
}

nsresult xpc::GetSandboxMetadata(JSContext* cx, HandleObject sandbox,
                                 MutableHandleValue rval) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(IsSandbox(sandbox));

  RootedValue metadata(cx);
  {
    JSAutoRealm ar(cx, sandbox);
    metadata =
        JS::GetReservedSlot(sandbox, XPCONNECT_SANDBOX_CLASS_METADATA_SLOT);
  }

  if (!JS_WrapValue(cx, &metadata)) {
    return NS_ERROR_UNEXPECTED;
  }

  rval.set(metadata);
  return NS_OK;
}

nsresult xpc::SetSandboxMetadata(JSContext* cx, HandleObject sandbox,
                                 HandleValue metadataArg) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(IsSandbox(sandbox));

  RootedValue metadata(cx);

  JSAutoRealm ar(cx, sandbox);
  if (!JS_StructuredClone(cx, metadataArg, &metadata, nullptr, nullptr)) {
    return NS_ERROR_UNEXPECTED;
  }

  JS_SetReservedSlot(sandbox, XPCONNECT_SANDBOX_CLASS_METADATA_SLOT, metadata);

  return NS_OK;
}

ModuleLoaderBase* SandboxPrivate::GetModuleLoader(JSContext* aCx) {
  if (mModuleLoader) {
    return mModuleLoader;
  }

  JSObject* object = GetGlobalJSObject();
  nsGlobalWindowInner* sandboxWindow = xpc::SandboxWindowOrNull(object, aCx);
  if (!sandboxWindow) {
    return nullptr;
  }

  ModuleLoader* mainModuleLoader =
      static_cast<ModuleLoader*>(sandboxWindow->GetModuleLoader(aCx));

  ScriptLoader* scriptLoader = mainModuleLoader->GetScriptLoader();

  ModuleLoader* moduleLoader =
      new ModuleLoader(scriptLoader, this, ModuleLoader::WebExtension);
  scriptLoader->RegisterContentScriptModuleLoader(moduleLoader);
  mModuleLoader = moduleLoader;

  return moduleLoader;
}

mozilla::Result<mozilla::ipc::PrincipalInfo, nsresult>
SandboxPrivate::GetStorageKey() {
  MOZ_ASSERT(NS_IsMainThread());

  mozilla::ipc::PrincipalInfo principalInfo;
  nsresult rv = PrincipalToPrincipalInfo(mPrincipal, &principalInfo);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return mozilla::Err(rv);
  }

  // Block expanded and null principals, let content and system through.
  if (principalInfo.type() !=
          mozilla::ipc::PrincipalInfo::TContentPrincipalInfo &&
      principalInfo.type() !=
          mozilla::ipc::PrincipalInfo::TSystemPrincipalInfo) {
    return Err(NS_ERROR_DOM_SECURITY_ERR);
  }

  return std::move(principalInfo);
}