summaryrefslogtreecommitdiffstats
path: root/layout/style/Loader.cpp
blob: 1ea37b094fee2fde364e397a0aaa333c685d8cfb (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
/* -*- 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/. */

/* loading of CSS style sheets using the network APIs */

#include "mozilla/css/Loader.h"

#include "MainThreadUtils.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/css/ErrorReporter.h"
#include "mozilla/dom/DocGroup.h"
#include "mozilla/dom/FetchPriority.h"
#include "mozilla/dom/SRILogHelper.h"
#include "mozilla/IntegerPrintfMacros.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/LoadInfo.h"
#include "mozilla/Logging.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/PreloadHashKey.h"
#include "mozilla/ResultExtensions.h"
#include "mozilla/SchedulerGroup.h"
#include "mozilla/URLPreloader.h"
#include "nsIChildChannel.h"
#include "nsIPrincipal.h"
#include "nsISupportsPriority.h"
#include "nsITimedChannel.h"
#include "nsICachingChannel.h"
#include "nsSyncLoadService.h"
#include "nsContentSecurityManager.h"
#include "nsCOMPtr.h"
#include "nsString.h"
#include "nsIContent.h"
#include "nsIContentInlines.h"
#include "nsICookieJarSettings.h"
#include "mozilla/dom/Document.h"
#include "nsIURI.h"
#include "nsContentUtils.h"
#include "nsIScriptSecurityManager.h"
#include "nsContentPolicyUtils.h"
#include "nsIHttpChannel.h"
#include "nsIHttpChannelInternal.h"
#include "nsIClassOfService.h"
#include "nsIScriptError.h"
#include "nsMimeTypes.h"
#include "nsICSSLoaderObserver.h"
#include "nsThreadUtils.h"
#include "nsGkAtoms.h"
#include "nsIThreadInternal.h"
#include "nsINetworkPredictor.h"
#include "nsQueryActor.h"
#include "nsStringStream.h"
#include "mozilla/dom/MediaList.h"
#include "mozilla/dom/ShadowRoot.h"
#include "mozilla/dom/URL.h"
#include "mozilla/net/UrlClassifierFeatureFactory.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/ServoBindings.h"
#include "mozilla/StyleSheet.h"
#include "mozilla/StyleSheetInlines.h"
#include "mozilla/ConsoleReportCollector.h"
#include "mozilla/ServoUtils.h"
#include "mozilla/css/StreamLoader.h"
#include "mozilla/SharedStyleSheetCache.h"
#include "mozilla/StaticPrefs_layout.h"
#include "mozilla/StaticPrefs_network.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_network.h"
#include "mozilla/Try.h"
#include "ReferrerInfo.h"

#include "nsXULPrototypeCache.h"

#include "nsError.h"

#include "mozilla/dom/SRICheck.h"

#include "mozilla/Encoding.h"

using namespace mozilla::dom;

// 1024 bytes is specified in https://drafts.csswg.org/css-syntax/
#define SNIFFING_BUFFER_SIZE 1024

/**
 * OVERALL ARCHITECTURE
 *
 * The CSS Loader gets requests to load various sorts of style sheets:
 * inline style from <style> elements, linked style, @import-ed child
 * sheets, non-document sheets.  The loader handles the following tasks:
 * 1) Creation of the actual style sheet objects: CreateSheet()
 * 2) setting of the right media, title, enabled state, etc on the
 *    sheet: PrepareSheet()
 * 3) Insertion of the sheet in the proper cascade order:
 *    InsertSheetInTree() and InsertChildSheet()
 * 4) Load of the sheet: LoadSheet() including security checks
 * 5) Parsing of the sheet: ParseSheet()
 * 6) Cleanup: SheetComplete()
 *
 * The detailed documentation for these functions is found with the
 * function implementations.
 *
 * The following helper object is used:
 *    SheetLoadData -- a small class that is used to store all the
 *                     information needed for the loading of a sheet;
 *                     this class handles listening for the stream
 *                     loader completion and also handles charset
 *                     determination.
 */

extern mozilla::LazyLogModule sCssLoaderLog;
mozilla::LazyLogModule sCssLoaderLog("nsCSSLoader");

static mozilla::LazyLogModule gSriPRLog("SRI");

static bool IsPrivilegedURI(nsIURI* aURI) {
  return aURI->SchemeIs("chrome") || aURI->SchemeIs("resource");
}

#define LOG_ERROR(args) MOZ_LOG(sCssLoaderLog, mozilla::LogLevel::Error, args)
#define LOG_WARN(args) MOZ_LOG(sCssLoaderLog, mozilla::LogLevel::Warning, args)
#define LOG_DEBUG(args) MOZ_LOG(sCssLoaderLog, mozilla::LogLevel::Debug, args)
#define LOG(args) LOG_DEBUG(args)

#define LOG_ERROR_ENABLED() \
  MOZ_LOG_TEST(sCssLoaderLog, mozilla::LogLevel::Error)
#define LOG_WARN_ENABLED() \
  MOZ_LOG_TEST(sCssLoaderLog, mozilla::LogLevel::Warning)
#define LOG_DEBUG_ENABLED() \
  MOZ_LOG_TEST(sCssLoaderLog, mozilla::LogLevel::Debug)
#define LOG_ENABLED() LOG_DEBUG_ENABLED()

#define LOG_URI(format, uri)                      \
  PR_BEGIN_MACRO                                  \
  NS_ASSERTION(uri, "Logging null uri");          \
  if (LOG_ENABLED()) {                            \
    LOG((format, uri->GetSpecOrDefault().get())); \
  }                                               \
  PR_END_MACRO

// And some convenience strings...
static const char* const gStateStrings[] = {"NeedsParser", "Pending", "Loading",
                                            "Complete"};

namespace mozilla {

SheetLoadDataHashKey::SheetLoadDataHashKey(const css::SheetLoadData& aLoadData)
    : mURI(aLoadData.mURI),
      mPrincipal(aLoadData.mTriggeringPrincipal),
      mLoaderPrincipal(aLoadData.mLoader->LoaderPrincipal()),
      mPartitionPrincipal(aLoadData.mLoader->PartitionedPrincipal()),
      mEncodingGuess(aLoadData.mGuessedEncoding),
      mCORSMode(aLoadData.mSheet->GetCORSMode()),
      mParsingMode(aLoadData.mSheet->ParsingMode()),
      mCompatMode(aLoadData.mCompatMode),
      mIsLinkRelPreload(aLoadData.IsLinkRelPreload()) {
  MOZ_COUNT_CTOR(SheetLoadDataHashKey);
  MOZ_ASSERT(mURI);
  MOZ_ASSERT(mPrincipal);
  MOZ_ASSERT(mLoaderPrincipal);
  MOZ_ASSERT(mPartitionPrincipal);
  aLoadData.mSheet->GetIntegrity(mSRIMetadata);
}

bool SheetLoadDataHashKey::KeyEquals(const SheetLoadDataHashKey& aKey) const {
  {
    bool eq;
    if (NS_FAILED(mURI->Equals(aKey.mURI, &eq)) || !eq) {
      return false;
    }
  }

  LOG_URI("KeyEquals(%s)\n", mURI);

  if (mParsingMode != aKey.mParsingMode) {
    LOG((" > Parsing mode mismatch\n"));
    return false;
  }

  // Chrome URIs ignore everything else.
  if (IsPrivilegedURI(mURI)) {
    return true;
  }

  if (!mPrincipal->Equals(aKey.mPrincipal)) {
    LOG((" > Principal mismatch\n"));
    return false;
  }

  // We only check for partition principal equality if any of the loads are
  // triggered by a document rather than e.g. an extension (which have different
  // origins than the loader principal).
  if (mPrincipal->Equals(mLoaderPrincipal) ||
      aKey.mPrincipal->Equals(aKey.mLoaderPrincipal)) {
    if (!mPartitionPrincipal->Equals(aKey.mPartitionPrincipal)) {
      LOG((" > Partition principal mismatch\n"));
      return false;
    }
  }

  if (mCORSMode != aKey.mCORSMode) {
    LOG((" > CORS mismatch\n"));
    return false;
  }

  if (mCompatMode != aKey.mCompatMode) {
    LOG((" > Quirks mismatch\n"));
    return false;
  }

  // If encoding differs, then don't reuse the cache.
  //
  // TODO(emilio): When the encoding is determined from the request (either
  // BOM or Content-Length or @charset), we could do a bit better,
  // theoretically.
  if (mEncodingGuess != aKey.mEncodingGuess) {
    LOG((" > Encoding guess mismatch\n"));
    return false;
  }

  // Consuming stylesheet tags must never coalesce to <link preload> initiated
  // speculative loads with a weaker SRI hash or its different value.  This
  // check makes sure that regular loads will never find such a weaker preload
  // and rather start a new, independent load with new, stronger SRI checker
  // set up, so that integrity is ensured.
  if (mIsLinkRelPreload != aKey.mIsLinkRelPreload) {
    const auto& linkPreloadMetadata =
        mIsLinkRelPreload ? mSRIMetadata : aKey.mSRIMetadata;
    const auto& consumerPreloadMetadata =
        mIsLinkRelPreload ? aKey.mSRIMetadata : mSRIMetadata;

    if (!consumerPreloadMetadata.CanTrustBeDelegatedTo(linkPreloadMetadata)) {
      LOG((" > Preload SRI metadata mismatch\n"));
      return false;
    }
  }

  return true;
}

namespace css {

static NotNull<const Encoding*> GetFallbackEncoding(
    Loader& aLoader, nsINode* aOwningNode,
    const Encoding* aPreloadOrParentDataEncoding) {
  const Encoding* encoding;
  // Now try the charset on the <link> or processing instruction
  // that loaded us
  if (aOwningNode) {
    nsAutoString label16;
    LinkStyle::FromNode(*aOwningNode)->GetCharset(label16);
    encoding = Encoding::ForLabel(label16);
    if (encoding) {
      return WrapNotNull(encoding);
    }
  }

  // Try preload or parent sheet encoding.
  if (aPreloadOrParentDataEncoding) {
    return WrapNotNull(aPreloadOrParentDataEncoding);
  }

  if (auto* doc = aLoader.GetDocument()) {
    // Use the document charset.
    return doc->GetDocumentCharacterSet();
  }

  return UTF_8_ENCODING;
}

/********************************
 * SheetLoadData implementation *
 ********************************/
NS_IMPL_ISUPPORTS(SheetLoadData, nsISupports)

SheetLoadData::SheetLoadData(
    css::Loader* aLoader, const nsAString& aTitle, nsIURI* aURI,
    StyleSheet* aSheet, SyncLoad aSyncLoad, nsINode* aOwningNode,
    IsAlternate aIsAlternate, MediaMatched aMediaMatches,
    StylePreloadKind aPreloadKind, nsICSSLoaderObserver* aObserver,
    nsIPrincipal* aTriggeringPrincipal, nsIReferrerInfo* aReferrerInfo,
    const nsAString& aNonce, FetchPriority aFetchPriority)
    : mLoader(aLoader),
      mTitle(aTitle),
      mEncoding(nullptr),
      mURI(aURI),
      mSheet(aSheet),
      mPendingChildren(0),
      mSyncLoad(aSyncLoad == SyncLoad::Yes),
      mIsNonDocumentSheet(false),
      mIsChildSheet(aSheet->GetParentSheet()),
      mIsBeingParsed(false),
      mIsLoading(false),
      mIsCancelled(false),
      mMustNotify(false),
      mHadOwnerNode(!!aOwningNode),
      mWasAlternate(aIsAlternate == IsAlternate::Yes),
      mMediaMatched(aMediaMatches == MediaMatched::Yes),
      mUseSystemPrincipal(false),
      mSheetAlreadyComplete(false),
      mIsCrossOriginNoCORS(false),
      mBlockResourceTiming(false),
      mLoadFailed(false),
      mPreloadKind(aPreloadKind),
      mObserver(aObserver),
      mTriggeringPrincipal(aTriggeringPrincipal),
      mReferrerInfo(aReferrerInfo),
      mNonce(aNonce),
      mFetchPriority{aFetchPriority},
      mGuessedEncoding(GetFallbackEncoding(*aLoader, aOwningNode, nullptr)),
      mCompatMode(aLoader->CompatMode(aPreloadKind)),
      mRecordErrors(
          aLoader && aLoader->GetDocument() &&
          css::ErrorReporter::ShouldReportErrors(*aLoader->GetDocument())) {
  MOZ_ASSERT(!aOwningNode || dom::LinkStyle::FromNode(*aOwningNode),
             "Must implement LinkStyle");
  MOZ_ASSERT(mTriggeringPrincipal);
  MOZ_ASSERT(mLoader, "Must have a loader!");
}

SheetLoadData::SheetLoadData(css::Loader* aLoader, nsIURI* aURI,
                             StyleSheet* aSheet, SheetLoadData* aParentData,
                             nsICSSLoaderObserver* aObserver,
                             nsIPrincipal* aTriggeringPrincipal,
                             nsIReferrerInfo* aReferrerInfo)
    : mLoader(aLoader),
      mEncoding(nullptr),
      mURI(aURI),
      mSheet(aSheet),
      mParentData(aParentData),
      mPendingChildren(0),
      mSyncLoad(aParentData && aParentData->mSyncLoad),
      mIsNonDocumentSheet(aParentData && aParentData->mIsNonDocumentSheet),
      mIsChildSheet(aSheet->GetParentSheet()),
      mIsBeingParsed(false),
      mIsLoading(false),
      mIsCancelled(false),
      mMustNotify(false),
      mHadOwnerNode(false),
      mWasAlternate(false),
      mMediaMatched(true),
      mUseSystemPrincipal(aParentData && aParentData->mUseSystemPrincipal),
      mSheetAlreadyComplete(false),
      mIsCrossOriginNoCORS(false),
      mBlockResourceTiming(false),
      mLoadFailed(false),
      mPreloadKind(StylePreloadKind::None),
      mObserver(aObserver),
      mTriggeringPrincipal(aTriggeringPrincipal),
      mReferrerInfo(aReferrerInfo),
      mNonce(u""_ns),
      mFetchPriority(FetchPriority::Auto),
      mGuessedEncoding(GetFallbackEncoding(
          *aLoader, nullptr, aParentData ? aParentData->mEncoding : nullptr)),
      mCompatMode(aLoader->CompatMode(mPreloadKind)),
      mRecordErrors(
          aLoader && aLoader->GetDocument() &&
          css::ErrorReporter::ShouldReportErrors(*aLoader->GetDocument())) {
  MOZ_ASSERT(mLoader, "Must have a loader!");
  MOZ_ASSERT(mTriggeringPrincipal);
  MOZ_ASSERT(!mUseSystemPrincipal || mSyncLoad,
             "Shouldn't use system principal for async loads");
  MOZ_ASSERT_IF(aParentData, mIsChildSheet);
}

SheetLoadData::SheetLoadData(
    css::Loader* aLoader, nsIURI* aURI, StyleSheet* aSheet, SyncLoad aSyncLoad,
    UseSystemPrincipal aUseSystemPrincipal, StylePreloadKind aPreloadKind,
    const Encoding* aPreloadEncoding, nsICSSLoaderObserver* aObserver,
    nsIPrincipal* aTriggeringPrincipal, nsIReferrerInfo* aReferrerInfo,
    const nsAString& aNonce, FetchPriority aFetchPriority)
    : mLoader(aLoader),
      mEncoding(nullptr),
      mURI(aURI),
      mSheet(aSheet),
      mPendingChildren(0),
      mSyncLoad(aSyncLoad == SyncLoad::Yes),
      mIsNonDocumentSheet(true),
      mIsChildSheet(false),
      mIsBeingParsed(false),
      mIsLoading(false),
      mIsCancelled(false),
      mMustNotify(false),
      mHadOwnerNode(false),
      mWasAlternate(false),
      mMediaMatched(true),
      mUseSystemPrincipal(aUseSystemPrincipal == UseSystemPrincipal::Yes),
      mSheetAlreadyComplete(false),
      mIsCrossOriginNoCORS(false),
      mBlockResourceTiming(false),
      mLoadFailed(false),
      mPreloadKind(aPreloadKind),
      mObserver(aObserver),
      mTriggeringPrincipal(aTriggeringPrincipal),
      mReferrerInfo(aReferrerInfo),
      mNonce(aNonce),
      mFetchPriority(aFetchPriority),
      mGuessedEncoding(
          GetFallbackEncoding(*aLoader, nullptr, aPreloadEncoding)),
      mCompatMode(aLoader->CompatMode(aPreloadKind)),
      mRecordErrors(
          aLoader && aLoader->GetDocument() &&
          css::ErrorReporter::ShouldReportErrors(*aLoader->GetDocument())) {
  MOZ_ASSERT(mTriggeringPrincipal);
  MOZ_ASSERT(mLoader, "Must have a loader!");
  MOZ_ASSERT(!mUseSystemPrincipal || mSyncLoad,
             "Shouldn't use system principal for async loads");
  MOZ_ASSERT(!aSheet->GetParentSheet(), "Shouldn't be used for child loads");
}

SheetLoadData::~SheetLoadData() {
  MOZ_RELEASE_ASSERT(mSheetCompleteCalled || mIntentionallyDropped,
                     "Should always call SheetComplete, except when "
                     "dropping the load");
}

RefPtr<StyleSheet> SheetLoadData::ValueForCache() const {
  // We need to clone the sheet on insertion to the cache because otherwise the
  // stylesheets can keep full windows alive via either their JS wrapper, or via
  // StyleSheet::mRelevantGlobal.
  //
  // If this ever changes, then you also need to fix up the memory reporting in
  // both SizeOfIncludingThis and nsXULPrototypeCache::CollectMemoryReports.
  return mSheet->Clone(nullptr, nullptr);
}

void SheetLoadData::PrioritizeAsPreload(nsIChannel* aChannel) {
  if (nsCOMPtr<nsISupportsPriority> sp = do_QueryInterface(aChannel)) {
    sp->AdjustPriority(nsISupportsPriority::PRIORITY_HIGHEST);
  }
}

void SheetLoadData::StartPendingLoad() {
  mLoader->LoadSheet(*this, Loader::SheetState::NeedsParser, 0,
                     Loader::PendingLoad::Yes);
}

already_AddRefed<AsyncEventDispatcher>
SheetLoadData::PrepareLoadEventIfNeeded() {
  nsCOMPtr<nsINode> node = mSheet->GetOwnerNode();
  if (!node) {
    return nullptr;
  }
  MOZ_ASSERT(!RootLoadData().IsLinkRelPreload(),
             "rel=preload handled elsewhere");
  RefPtr<AsyncEventDispatcher> dispatcher;
  if (BlocksLoadEvent()) {
    dispatcher = new LoadBlockingAsyncEventDispatcher(
        node, mLoadFailed ? u"error"_ns : u"load"_ns, CanBubble::eNo,
        ChromeOnlyDispatch::eNo);
  } else {
    // Fire the load event on the link, but don't block the document load.
    dispatcher =
        new AsyncEventDispatcher(node, mLoadFailed ? u"error"_ns : u"load"_ns,
                                 CanBubble::eNo, ChromeOnlyDispatch::eNo);
  }
  return dispatcher.forget();
}

nsINode* SheetLoadData::GetRequestingNode() const {
  if (nsINode* node = mSheet->GetOwnerNodeOfOutermostSheet()) {
    return node;
  }
  return mLoader->GetDocument();
}

/*********************
 * Style sheet reuse *
 *********************/

bool LoaderReusableStyleSheets::FindReusableStyleSheet(
    nsIURI* aURL, RefPtr<StyleSheet>& aResult) {
  MOZ_ASSERT(aURL);
  for (size_t i = mReusableSheets.Length(); i > 0; --i) {
    size_t index = i - 1;
    bool sameURI;
    MOZ_ASSERT(mReusableSheets[index]->GetOriginalURI());
    nsresult rv =
        aURL->Equals(mReusableSheets[index]->GetOriginalURI(), &sameURI);
    if (!NS_FAILED(rv) && sameURI) {
      aResult = mReusableSheets[index];
      mReusableSheets.RemoveElementAt(index);
      return true;
    }
  }
  return false;
}
/*************************
 * Loader Implementation *
 *************************/

Loader::Loader()
    : mDocument(nullptr),
      mDocumentCompatMode(eCompatibility_FullStandards),
      mReporter(new ConsoleReportCollector()) {}

Loader::Loader(DocGroup* aDocGroup) : Loader() { mDocGroup = aDocGroup; }

Loader::Loader(Document* aDocument) : Loader() {
  MOZ_ASSERT(aDocument, "We should get a valid document from the caller!");
  mDocument = aDocument;
  mIsDocumentAssociated = true;
  mDocumentCompatMode = aDocument->GetCompatibilityMode();
  mSheets = SharedStyleSheetCache::Get();
  RegisterInSheetCache();
}

// Note: no real need to revoke our stylesheet loaded events -- they hold strong
// references to us, so if we're going away that means they're all done.
Loader::~Loader() = default;

void Loader::RegisterInSheetCache() {
  MOZ_ASSERT(mDocument);
  MOZ_ASSERT(mSheets);

  mSheets->RegisterLoader(*this);
}

void Loader::DeregisterFromSheetCache() {
  MOZ_ASSERT(mDocument);
  MOZ_ASSERT(mSheets);

  mSheets->CancelLoadsForLoader(*this);
  mSheets->UnregisterLoader(*this);
}

void Loader::DropDocumentReference() {
  // Flush out pending datas just so we don't leak by accident.
  if (mSheets) {
    DeregisterFromSheetCache();
  }
  mDocument = nullptr;
}

void Loader::DocumentStyleSheetSetChanged() {
  MOZ_ASSERT(mDocument);

  // start any pending alternates that aren't alternates anymore
  mSheets->StartPendingLoadsForLoader(*this, [&](const SheetLoadData& aData) {
    return IsAlternateSheet(aData.mTitle, true) != IsAlternate::Yes;
  });
}

static const char kCharsetSym[] = "@charset \"";

static bool GetCharsetFromData(const char* aStyleSheetData,
                               uint32_t aDataLength, nsACString& aCharset) {
  aCharset.Truncate();
  if (aDataLength <= sizeof(kCharsetSym) - 1) return false;

  if (strncmp(aStyleSheetData, kCharsetSym, sizeof(kCharsetSym) - 1)) {
    return false;
  }

  for (uint32_t i = sizeof(kCharsetSym) - 1; i < aDataLength; ++i) {
    char c = aStyleSheetData[i];
    if (c == '"') {
      ++i;
      if (i < aDataLength && aStyleSheetData[i] == ';') {
        return true;
      }
      // fail
      break;
    }
    aCharset.Append(c);
  }

  // Did not see end quote or semicolon
  aCharset.Truncate();
  return false;
}

NotNull<const Encoding*> SheetLoadData::DetermineNonBOMEncoding(
    const nsACString& aSegment, nsIChannel* aChannel) const {
  const Encoding* encoding;
  nsAutoCString label;

  // Check HTTP
  if (aChannel && NS_SUCCEEDED(aChannel->GetContentCharset(label))) {
    encoding = Encoding::ForLabel(label);
    if (encoding) {
      return WrapNotNull(encoding);
    }
  }

  // Check @charset
  auto sniffingLength = aSegment.Length();
  if (sniffingLength > SNIFFING_BUFFER_SIZE) {
    sniffingLength = SNIFFING_BUFFER_SIZE;
  }
  if (GetCharsetFromData(aSegment.BeginReading(), sniffingLength, label)) {
    encoding = Encoding::ForLabel(label);
    if (encoding == UTF_16BE_ENCODING || encoding == UTF_16LE_ENCODING) {
      return UTF_8_ENCODING;
    }
    if (encoding) {
      return WrapNotNull(encoding);
    }
  }
  return mGuessedEncoding;
}

static nsresult VerifySheetIntegrity(const SRIMetadata& aMetadata,
                                     nsIChannel* aChannel,
                                     const nsACString& aFirst,
                                     const nsACString& aSecond,
                                     const nsACString& aSourceFileURI,
                                     nsIConsoleReportCollector* aReporter) {
  NS_ENSURE_ARG_POINTER(aReporter);

  if (MOZ_LOG_TEST(SRILogHelper::GetSriLog(), LogLevel::Debug)) {
    nsAutoCString requestURL;
    nsCOMPtr<nsIURI> originalURI;
    if (aChannel &&
        NS_SUCCEEDED(aChannel->GetOriginalURI(getter_AddRefs(originalURI))) &&
        originalURI) {
      originalURI->GetAsciiSpec(requestURL);
    }
    MOZ_LOG(SRILogHelper::GetSriLog(), LogLevel::Debug,
            ("VerifySheetIntegrity (unichar stream)"));
  }

  SRICheckDataVerifier verifier(aMetadata, aSourceFileURI, aReporter);
  nsresult rv =
      verifier.Update(aFirst.Length(), (const uint8_t*)aFirst.BeginReading());
  NS_ENSURE_SUCCESS(rv, rv);
  rv =
      verifier.Update(aSecond.Length(), (const uint8_t*)aSecond.BeginReading());
  NS_ENSURE_SUCCESS(rv, rv);

  return verifier.Verify(aMetadata, aChannel, aSourceFileURI, aReporter);
}

static bool AllLoadsCanceled(const SheetLoadData& aData) {
  const SheetLoadData* data = &aData;
  do {
    if (!data->IsCancelled()) {
      return false;
    }
  } while ((data = data->mNext));
  return true;
}

/*
 * Stream completion code shared by Stylo and the old style system.
 *
 * Here we need to check that the load did not give us an http error
 * page and check the mimetype on the channel to make sure we're not
 * loading non-text/css data in standards mode.
 */
nsresult SheetLoadData::VerifySheetReadyToParse(
    nsresult aStatus, const nsACString& aBytes1, const nsACString& aBytes2,
    nsIChannel* aChannel, nsIURI* aFinalChannelURI,
    nsIPrincipal* aChannelResultPrincipal) {
  LOG(("SheetLoadData::VerifySheetReadyToParse"));
  NS_ASSERTION((!NS_IsMainThread() || !mLoader->mSyncCallback),
               "Synchronous callback from necko");

  if (AllLoadsCanceled(*this)) {
    if (NS_IsMainThread()) {
      LOG_WARN(("  All loads are canceled, dropping"));
      mLoader->SheetComplete(*this, NS_BINDING_ABORTED);
    }
    return NS_OK;
  }

  if (!NS_IsMainThread() && mRecordErrors) {
    // we cannot parse sheet OMT if we need to record errors
    return NS_OK;
  }

  if (NS_FAILED(aStatus)) {
    if (NS_IsMainThread()) {
      LOG_WARN(
          ("  Load failed: status 0x%" PRIx32, static_cast<uint32_t>(aStatus)));
      // Handle sheet not loading error because source was a tracking URL (or
      // fingerprinting, cryptomining, etc).
      // We make a note of this sheet node by including it in a dedicated
      // array of blocked tracking nodes under its parent document.
      //
      // Multiple sheet load instances might be tied to this request,
      // we annotate each one linked to a valid owning element (node).
      if (net::UrlClassifierFeatureFactory::IsClassifierBlockingErrorCode(
              aStatus)) {
        if (Document* doc = mLoader->GetDocument()) {
          for (SheetLoadData* data = this; data; data = data->mNext) {
            // owner node may be null but AddBlockTrackingNode can cope
            doc->AddBlockedNodeByClassifier(data->mSheet->GetOwnerNode());
          }
        }
      }
      mLoader->SheetComplete(*this, aStatus);
    }
    return NS_OK;
  }

  if (!aChannel) {
    MOZ_ASSERT(NS_IsMainThread());
    mLoader->SheetComplete(*this, NS_OK);
    return NS_OK;
  }

  nsCOMPtr<nsIURI> originalURI;
  aChannel->GetOriginalURI(getter_AddRefs(originalURI));

  // If the channel's original URI is "chrome:", we want that, since
  // the observer code in nsXULPrototypeCache depends on chrome stylesheets
  // having a chrome URI.  (Whether or not chrome stylesheets come through
  // this codepath seems nondeterministic.)
  // Otherwise we want the potentially-HTTP-redirected URI.
  if (!aFinalChannelURI || !originalURI) {
    MOZ_ASSERT(NS_IsMainThread());
    NS_ERROR("Someone just violated the nsIRequest contract");
    LOG_WARN(("  Channel without a URI.  Bad!"));
    mLoader->SheetComplete(*this, NS_ERROR_UNEXPECTED);
    return NS_OK;
  }

  nsCOMPtr<nsIPrincipal> principal;
  nsIScriptSecurityManager* secMan = nsContentUtils::GetSecurityManager();
  nsresult result = NS_ERROR_NOT_AVAILABLE;
  if (secMan) {  // Could be null if we already shut down
    if (mUseSystemPrincipal) {
      result = secMan->GetSystemPrincipal(getter_AddRefs(principal));
    } else {
      if (aChannelResultPrincipal) {
        principal = aChannelResultPrincipal;
        result = NS_OK;
      }
    }
  }

  if (NS_FAILED(result)) {
    if (NS_IsMainThread()) {
      LOG_WARN(("  Couldn't get principal"));
      mLoader->SheetComplete(*this, result);
    }
    return NS_OK;
  }

  mSheet->SetPrincipal(principal);

  // If it's an HTTP channel, we want to make sure this is not an
  // error document we got.
  if (nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aChannel)) {
    bool requestSucceeded;
    result = httpChannel->GetRequestSucceeded(&requestSucceeded);
    if (NS_SUCCEEDED(result) && !requestSucceeded) {
      if (NS_IsMainThread()) {
        LOG(("  Load returned an error page"));
        mLoader->SheetComplete(*this, NS_ERROR_NOT_AVAILABLE);
      }
      return NS_OK;
    }

    nsCString sourceMapURL;
    if (nsContentUtils::GetSourceMapURL(httpChannel, sourceMapURL)) {
      mSheet->SetSourceMapURL(std::move(sourceMapURL));
    }
  }

  nsAutoCString contentType;
  aChannel->GetContentType(contentType);

  // In standards mode, a style sheet must have one of these MIME
  // types to be processed at all.  In quirks mode, we accept any
  // MIME type, but only if the style sheet is same-origin with the
  // requesting document or parent sheet.  See bug 524223.

  bool validType = contentType.EqualsLiteral("text/css") ||
                   contentType.EqualsLiteral(UNKNOWN_CONTENT_TYPE) ||
                   contentType.IsEmpty();

  if (!validType) {
    if (!NS_IsMainThread()) {
      return NS_OK;
    }
    const char* errorMessage;
    uint32_t errorFlag;
    bool sameOrigin = true;

    bool subsumed;
    result = mTriggeringPrincipal->Subsumes(principal, &subsumed);
    if (NS_FAILED(result) || !subsumed) {
      sameOrigin = false;
    }

    if (sameOrigin && mCompatMode == eCompatibility_NavQuirks) {
      errorMessage = "MimeNotCssWarn";
      errorFlag = nsIScriptError::warningFlag;
    } else {
      errorMessage = "MimeNotCss";
      errorFlag = nsIScriptError::errorFlag;
    }

    AutoTArray<nsString, 2> strings;
    CopyUTF8toUTF16(aFinalChannelURI->GetSpecOrDefault(),
                    *strings.AppendElement());
    CopyASCIItoUTF16(contentType, *strings.AppendElement());

    nsCOMPtr<nsIURI> referrer = ReferrerInfo()->GetOriginalReferrer();
    nsContentUtils::ReportToConsole(
        errorFlag, "CSS Loader"_ns, mLoader->mDocument,
        nsContentUtils::eCSS_PROPERTIES, errorMessage, strings, referrer);

    if (errorFlag == nsIScriptError::errorFlag) {
      LOG_WARN(
          ("  Ignoring sheet with improper MIME type %s", contentType.get()));
      mLoader->SheetComplete(*this, NS_ERROR_NOT_AVAILABLE);
      return NS_OK;
    }
  }

  SRIMetadata sriMetadata;
  mSheet->GetIntegrity(sriMetadata);
  if (!sriMetadata.IsEmpty()) {
    if (!NS_IsMainThread()) {
      // We dont process any further in OMT.
      // This is because we have some main-thread only accesses below.
      // We need to find a way to optimize this handling.
      // See Bug 1882046.
      return NS_OK;
    }
    nsAutoCString sourceUri;
    if (mLoader->mDocument && mLoader->mDocument->GetDocumentURI()) {
      mLoader->mDocument->GetDocumentURI()->GetAsciiSpec(sourceUri);
    }
    nsresult rv = VerifySheetIntegrity(sriMetadata, aChannel, aBytes1, aBytes2,
                                       sourceUri, mLoader->mReporter);

    nsCOMPtr<nsILoadGroup> loadGroup;
    aChannel->GetLoadGroup(getter_AddRefs(loadGroup));
    if (loadGroup) {
      mLoader->mReporter->FlushConsoleReports(loadGroup);
    } else {
      mLoader->mReporter->FlushConsoleReports(mLoader->mDocument);
    }

    if (NS_FAILED(rv)) {
      LOG(("  Load was blocked by SRI"));
      MOZ_LOG(gSriPRLog, LogLevel::Debug,
              ("css::Loader::OnStreamComplete, bad metadata"));
      mLoader->SheetComplete(*this, NS_ERROR_SRI_CORRUPT);
      return NS_OK;
    }
  }

  if (mSheet->GetCORSMode() == CORS_NONE &&
      !mTriggeringPrincipal->Subsumes(principal)) {
    mIsCrossOriginNoCORS = true;
  }
  // Enough to set the URIs on mSheet, since any sibling datas we have share
  // the same mInner as mSheet and will thus get the same URI.
  mSheet->SetURIs(aFinalChannelURI, originalURI, aFinalChannelURI);

  ReferrerPolicy policy =
      nsContentUtils::GetReferrerPolicyFromChannel(aChannel);
  nsCOMPtr<nsIReferrerInfo> referrerInfo =
      ReferrerInfo::CreateForExternalCSSResources(mSheet, policy);

  mSheet->SetReferrerInfo(referrerInfo);
  return NS_OK_PARSE_SHEET;
}

Loader::IsAlternate Loader::IsAlternateSheet(const nsAString& aTitle,
                                             bool aHasAlternateRel) {
  // A sheet is alternate if it has a nonempty title that doesn't match the
  // currently selected style set.  But if there _is_ no currently selected
  // style set, the sheet wasn't marked as an alternate explicitly, and aTitle
  // is nonempty, we should select the style set corresponding to aTitle, since
  // that's a preferred sheet.
  if (aTitle.IsEmpty()) {
    return IsAlternate::No;
  }

  if (mDocument) {
    const nsString& currentSheetSet = mDocument->GetCurrentStyleSheetSet();
    if (!aHasAlternateRel && currentSheetSet.IsEmpty()) {
      // There's no preferred set yet, and we now have a sheet with a title.
      // Make that be the preferred set.
      // FIXME(emilio): This is kinda wild, can we do it somewhere else?
      mDocument->SetPreferredStyleSheetSet(aTitle);
      // We're definitely not an alternate. Also, beware that at this point
      // currentSheetSet may dangle.
      return IsAlternate::No;
    }

    if (aTitle.Equals(currentSheetSet)) {
      return IsAlternate::No;
    }
  }

  return IsAlternate::Yes;
}

nsresult Loader::CheckContentPolicy(nsIPrincipal* aLoadingPrincipal,
                                    nsIPrincipal* aTriggeringPrincipal,
                                    nsIURI* aTargetURI,
                                    nsINode* aRequestingNode,
                                    const nsAString& aNonce,
                                    StylePreloadKind aPreloadKind) {
  // When performing a system load don't consult content policies.
  if (!mDocument) {
    return NS_OK;
  }

  nsContentPolicyType contentPolicyType =
      aPreloadKind == StylePreloadKind::None
          ? nsIContentPolicy::TYPE_INTERNAL_STYLESHEET
          : nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD;

  nsCOMPtr<nsILoadInfo> secCheckLoadInfo = new net::LoadInfo(
      aLoadingPrincipal, aTriggeringPrincipal, aRequestingNode,
      nsILoadInfo::SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK, contentPolicyType);
  secCheckLoadInfo->SetCspNonce(aNonce);

  int16_t shouldLoad = nsIContentPolicy::ACCEPT;
  nsresult rv =
      NS_CheckContentLoadPolicy(aTargetURI, secCheckLoadInfo, &shouldLoad,
                                nsContentUtils::GetContentPolicy());
  if (NS_FAILED(rv) || NS_CP_REJECTED(shouldLoad)) {
    // Asynchronously notify observers (e.g devtools) of CSP failure.
    nsContentUtils::AddScriptRunner(NS_NewRunnableFunction(
        "Loader::NotifyOnFailedCheckPolicy",
        [targetURI = RefPtr<nsIURI>(aTargetURI),
         requestingNode = RefPtr<nsINode>(aRequestingNode),
         contentPolicyType]() {
          nsCOMPtr<nsIChannel> channel;
          NS_NewChannel(
              getter_AddRefs(channel), targetURI, requestingNode,
              nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_INHERITS_SEC_CONTEXT,
              contentPolicyType);
          NS_SetRequestBlockingReason(
              channel, nsILoadInfo::BLOCKING_REASON_CONTENT_POLICY_GENERAL);
          nsCOMPtr<nsIObserverService> obsService =
              services::GetObserverService();
          if (obsService) {
            obsService->NotifyObservers(
                channel, "http-on-failed-opening-request", nullptr);
          }
        }));
    return NS_ERROR_CONTENT_BLOCKED;
  }
  return NS_OK;
}

static void RecordUseCountersIfNeeded(Document* aDoc,
                                      const StyleSheet& aSheet) {
  if (!aDoc) {
    return;
  }
  const StyleUseCounters* docCounters = aDoc->GetStyleUseCounters();
  if (!docCounters) {
    return;
  }
  if (aSheet.URLData()->ChromeRulesEnabled()) {
    return;
  }
  const auto* sheetCounters = aSheet.GetStyleUseCounters();
  if (!sheetCounters) {
    return;
  }
  Servo_UseCounters_Merge(docCounters, sheetCounters);
  aDoc->MaybeWarnAboutZoom();
}

/**
 * CreateSheet() creates a StyleSheet object for the given URI.
 *
 * We check for an existing style sheet object for that uri in various caches
 * and clone it if we find it.  Cloned sheets will have the title/media/enabled
 * state of the sheet they are clones off; make sure to call PrepareSheet() on
 * the result of CreateSheet().
 */
std::tuple<RefPtr<StyleSheet>, Loader::SheetState> Loader::CreateSheet(
    nsIURI* aURI, nsIContent* aLinkingContent,
    nsIPrincipal* aTriggeringPrincipal, css::SheetParsingMode aParsingMode,
    CORSMode aCORSMode, const Encoding* aPreloadOrParentDataEncoding,
    const nsAString& aIntegrity, bool aSyncLoad,
    StylePreloadKind aPreloadKind) {
  MOZ_ASSERT(aURI, "This path is not taken for inline stylesheets");
  LOG(("css::Loader::CreateSheet(%s)", aURI->GetSpecOrDefault().get()));

  SRIMetadata sriMetadata;
  if (!aIntegrity.IsEmpty()) {
    MOZ_LOG(gSriPRLog, LogLevel::Debug,
            ("css::Loader::CreateSheet, integrity=%s",
             NS_ConvertUTF16toUTF8(aIntegrity).get()));
    nsAutoCString sourceUri;
    if (mDocument && mDocument->GetDocumentURI()) {
      mDocument->GetDocumentURI()->GetAsciiSpec(sourceUri);
    }
    SRICheck::IntegrityMetadata(aIntegrity, sourceUri, mReporter, &sriMetadata);
  }

  if (mSheets) {
    SheetLoadDataHashKey key(aURI, aTriggeringPrincipal, LoaderPrincipal(),
                             PartitionedPrincipal(),
                             GetFallbackEncoding(*this, aLinkingContent,
                                                 aPreloadOrParentDataEncoding),
                             aCORSMode, aParsingMode, CompatMode(aPreloadKind),
                             sriMetadata, aPreloadKind);
    auto cacheResult = mSheets->Lookup(*this, key, aSyncLoad);
    if (cacheResult.mState != CachedSubResourceState::Miss) {
      SheetState sheetState = SheetState::Complete;
      RefPtr<StyleSheet> sheet;
      if (cacheResult.mCompleteValue) {
        sheet = cacheResult.mCompleteValue->Clone(nullptr, nullptr);
        mDocument->SetDidHitCompleteSheetCache();
        RecordUseCountersIfNeeded(mDocument, *sheet);
        mLoadsPerformed.PutEntry(key);
      } else {
        MOZ_ASSERT(cacheResult.mLoadingOrPendingValue);
        sheet = cacheResult.mLoadingOrPendingValue->ValueForCache();
        sheetState = cacheResult.mState == CachedSubResourceState::Loading
                         ? SheetState::Loading
                         : SheetState::Pending;
      }
      LOG(("  Hit cache with state: %s", gStateStrings[size_t(sheetState)]));
      return {std::move(sheet), sheetState};
    }
  }

  nsIURI* sheetURI = aURI;
  nsIURI* baseURI = aURI;
  nsIURI* originalURI = aURI;

  auto sheet = MakeRefPtr<StyleSheet>(aParsingMode, aCORSMode, sriMetadata);
  sheet->SetURIs(sheetURI, originalURI, baseURI);
  nsCOMPtr<nsIReferrerInfo> referrerInfo =
      ReferrerInfo::CreateForExternalCSSResources(sheet);
  sheet->SetReferrerInfo(referrerInfo);
  LOG(("  Needs parser"));
  return {std::move(sheet), SheetState::NeedsParser};
}

static Loader::MediaMatched MediaListMatches(const MediaList* aMediaList,
                                             const Document* aDocument) {
  if (!aMediaList || !aDocument) {
    return Loader::MediaMatched::Yes;
  }

  if (aMediaList->Matches(*aDocument)) {
    return Loader::MediaMatched::Yes;
  }

  return Loader::MediaMatched::No;
}

/**
 * PrepareSheet() handles setting the media and title on the sheet, as
 * well as setting the enabled state based on the title and whether
 * the sheet had "alternate" in its rel.
 */
Loader::MediaMatched Loader::PrepareSheet(
    StyleSheet& aSheet, const nsAString& aTitle, const nsAString& aMediaString,
    MediaList* aMediaList, IsAlternate aIsAlternate,
    IsExplicitlyEnabled aIsExplicitlyEnabled) {
  RefPtr<MediaList> mediaList(aMediaList);

  if (!aMediaString.IsEmpty()) {
    NS_ASSERTION(!aMediaList,
                 "must not provide both aMediaString and aMediaList");
    mediaList = MediaList::Create(NS_ConvertUTF16toUTF8(aMediaString));
  }

  aSheet.SetMedia(do_AddRef(mediaList));

  aSheet.SetTitle(aTitle);
  aSheet.SetEnabled(aIsAlternate == IsAlternate::No ||
                    aIsExplicitlyEnabled == IsExplicitlyEnabled::Yes);
  return MediaListMatches(mediaList, mDocument);
}

/**
 * InsertSheetInTree handles ordering of sheets in the document or shadow root.
 *
 * Here we have two types of sheets -- those with linking elements and
 * those without.  The latter are loaded by Link: headers, and are only added to
 * the document.
 *
 * The following constraints are observed:
 * 1) Any sheet with a linking element comes after all sheets without
 *    linking elements
 * 2) Sheets without linking elements are inserted in the order in
 *    which the inserting requests come in, since all of these are
 *    inserted during header data processing in the content sink
 * 3) Sheets with linking elements are ordered based on document order
 *    as determined by CompareDocumentPosition.
 */
void Loader::InsertSheetInTree(StyleSheet& aSheet) {
  LOG(("css::Loader::InsertSheetInTree"));
  MOZ_ASSERT(mDocument, "Must have a document to insert into");

  nsINode* owningNode = aSheet.GetOwnerNode();
  MOZ_ASSERT(!owningNode || owningNode->IsInUncomposedDoc() ||
                 owningNode->IsInShadowTree(),
             "Why would we insert it anywhere?");
  ShadowRoot* shadow = owningNode ? owningNode->GetContainingShadow() : nullptr;

  auto& target = shadow ? static_cast<DocumentOrShadowRoot&>(*shadow)
                        : static_cast<DocumentOrShadowRoot&>(*mDocument);

  // XXX Need to cancel pending sheet loads for this element, if any

  int32_t sheetCount = target.SheetCount();

  /*
   * Start the walk at the _end_ of the list, since in the typical
   * case we'll just want to append anyway.  We want to break out of
   * the loop when insertionPoint points to just before the index we
   * want to insert at.  In other words, when we leave the loop
   * insertionPoint is the index of the stylesheet that immediately
   * precedes the one we're inserting.
   */
  int32_t insertionPoint = sheetCount - 1;
  for (; insertionPoint >= 0; --insertionPoint) {
    nsINode* sheetOwner = target.SheetAt(insertionPoint)->GetOwnerNode();
    if (sheetOwner && !owningNode) {
      // Keep moving; all sheets with a sheetOwner come after all
      // sheets without a linkingNode
      continue;
    }

    if (!sheetOwner) {
      // Aha!  The current sheet has no sheet owner, so we want to insert after
      // it no matter whether we have a linking content or not.
      break;
    }

    MOZ_ASSERT(owningNode != sheetOwner, "Why do we still have our old sheet?");

    // Have to compare
    if (nsContentUtils::PositionIsBefore(sheetOwner, owningNode)) {
      // The current sheet comes before us, and it better be the first
      // such, because now we break
      break;
    }
  }

  ++insertionPoint;

  if (shadow) {
    shadow->InsertSheetAt(insertionPoint, aSheet);
  } else {
    mDocument->InsertSheetAt(insertionPoint, aSheet);
  }

  LOG(("  Inserting into target (doc: %d) at position %d",
       target.AsNode().IsDocument(), insertionPoint));
}

/**
 * InsertChildSheet handles ordering of @import-ed sheet in their
 * parent sheets.  Here we want to just insert based on order of the
 * @import rules that imported the sheets.  In theory we can't just
 * append to the end because the CSSOM can insert @import rules.  In
 * practice, we get the call to load the child sheet before the CSSOM
 * has finished inserting the @import rule, so we have no idea where
 * to put it anyway.  So just append for now.  (In the future if we
 * want to insert the sheet at the correct position, we'll need to
 * restore CSSStyleSheet::InsertStyleSheetAt, which was removed in
 * bug 1220506.)
 */
void Loader::InsertChildSheet(StyleSheet& aSheet, StyleSheet& aParentSheet) {
  LOG(("css::Loader::InsertChildSheet"));

  // child sheets should always start out enabled, even if they got
  // cloned off of top-level sheets which were disabled
  aSheet.SetEnabled(true);
  aParentSheet.AppendStyleSheet(aSheet);

  LOG(("  Inserting into parent sheet"));
}

nsresult Loader::LoadSheetSyncInternal(SheetLoadData& aLoadData,
                                       SheetState aSheetState) {
  LOG(("  Synchronous load"));
  MOZ_ASSERT(!aLoadData.mObserver, "Observer for a sync load?");
  MOZ_ASSERT(aSheetState == SheetState::NeedsParser,
             "Sync loads can't reuse existing async loads");

  nsINode* requestingNode = aLoadData.GetRequestingNode();

  nsresult rv = NS_OK;

  // Create a StreamLoader instance to which we will feed
  // the data from the sync load.  Do this before creating the
  // channel to make error recovery simpler.
  auto streamLoader = MakeRefPtr<StreamLoader>(aLoadData);

  if (mDocument) {
    net::PredictorLearn(aLoadData.mURI, mDocument->GetDocumentURI(),
                        nsINetworkPredictor::LEARN_LOAD_SUBRESOURCE, mDocument);
  }

  // Synchronous loads should only be used internally. Therefore no CORS
  // policy is needed.
  nsSecurityFlags securityFlags =
      nsContentSecurityManager::ComputeSecurityFlags(
          CORSMode::CORS_NONE, nsContentSecurityManager::CORSSecurityMapping::
                                   CORS_NONE_MAPS_TO_INHERITED_CONTEXT);

  securityFlags |= nsILoadInfo::SEC_ALLOW_CHROME;

  nsContentPolicyType contentPolicyType =
      aLoadData.mPreloadKind == StylePreloadKind::None
          ? nsIContentPolicy::TYPE_INTERNAL_STYLESHEET
          : nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD;

  // Just load it
  nsCOMPtr<nsIChannel> channel;
  // Note that we are calling NS_NewChannelWithTriggeringPrincipal() with both
  // a node and a principal.
  // This is because of a case where the node is the document being styled and
  // the principal is the stylesheet (perhaps from a different origin) that is
  // applying the styles.
  if (requestingNode) {
    rv = NS_NewChannelWithTriggeringPrincipal(
        getter_AddRefs(channel), aLoadData.mURI, requestingNode,
        aLoadData.mTriggeringPrincipal, securityFlags, contentPolicyType);
  } else {
    MOZ_ASSERT(aLoadData.mTriggeringPrincipal->Equals(LoaderPrincipal()));
    auto result = URLPreloader::ReadURI(aLoadData.mURI);
    if (result.isOk()) {
      nsCOMPtr<nsIInputStream> stream;
      MOZ_TRY(
          NS_NewCStringInputStream(getter_AddRefs(stream), result.unwrap()));

      rv = NS_NewInputStreamChannel(
          getter_AddRefs(channel), aLoadData.mURI, stream.forget(),
          aLoadData.mTriggeringPrincipal, securityFlags, contentPolicyType);
    } else {
      rv = NS_NewChannel(getter_AddRefs(channel), aLoadData.mURI,
                         aLoadData.mTriggeringPrincipal, securityFlags,
                         contentPolicyType);
    }
  }
  if (NS_FAILED(rv)) {
    LOG_ERROR(("  Failed to create channel"));
    streamLoader->ChannelOpenFailed(rv);
    SheetComplete(aLoadData, rv);
    return rv;
  }

  nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
  loadInfo->SetCspNonce(aLoadData.Nonce());

  nsCOMPtr<nsIInputStream> stream;
  rv = channel->Open(getter_AddRefs(stream));

  if (NS_FAILED(rv)) {
    LOG_ERROR(("  Failed to open URI synchronously"));
    streamLoader->ChannelOpenFailed(rv);
    SheetComplete(aLoadData, rv);
    return rv;
  }

  // Force UA sheets to be UTF-8.
  // XXX this is only necessary because the default in
  // SheetLoadData::OnDetermineCharset is wrong (bug 521039).
  channel->SetContentCharset("UTF-8"_ns);

  // Manually feed the streamloader the contents of the stream.
  // This will call back into OnStreamComplete
  // and thence to ParseSheet.  Regardless of whether this fails,
  // SheetComplete has been called.
  return nsSyncLoadService::PushSyncStreamToListener(stream.forget(),
                                                     streamLoader, channel);
}

bool Loader::MaybeDeferLoad(SheetLoadData& aLoadData, SheetState aSheetState,
                            PendingLoad aPendingLoad,
                            const SheetLoadDataHashKey& aKey) {
  MOZ_ASSERT(mSheets);

  // If we have at least one other load ongoing, then we can defer it until
  // all non-pending loads are done.
  if (aSheetState == SheetState::NeedsParser &&
      aPendingLoad == PendingLoad::No && aLoadData.ShouldDefer() &&
      mOngoingLoadCount > mPendingLoadCount + 1) {
    LOG(("  Deferring sheet load"));
    ++mPendingLoadCount;
    mSheets->DeferLoad(aKey, aLoadData);
    return true;
  }
  return false;
}

bool Loader::MaybeCoalesceLoadAndNotifyOpen(SheetLoadData& aLoadData,
                                            SheetState aSheetState,
                                            const SheetLoadDataHashKey& aKey,
                                            const PreloadHashKey& aPreloadKey) {
  bool coalescedLoad = false;
  auto cacheState = [&aSheetState] {
    switch (aSheetState) {
      case SheetState::Complete:
        return CachedSubResourceState::Complete;
      case SheetState::Pending:
        return CachedSubResourceState::Pending;
      case SheetState::Loading:
        return CachedSubResourceState::Loading;
      case SheetState::NeedsParser:
        return CachedSubResourceState::Miss;
    }
    MOZ_ASSERT_UNREACHABLE("wat");
    return CachedSubResourceState::Miss;
  }();

  if ((coalescedLoad = mSheets->CoalesceLoad(aKey, aLoadData, cacheState))) {
    if (aSheetState == SheetState::Pending) {
      ++mPendingLoadCount;
    } else {
      aLoadData.NotifyOpen(
          aPreloadKey, mDocument,
          aLoadData.IsLinkRelPreload() /* TODO: why not `IsPreload()`?*/);
    }
  }
  return coalescedLoad;
}

/**
 * LoadSheet handles the actual load of a sheet.  If the load is
 * supposed to be synchronous it just opens a channel synchronously
 * using the given uri, wraps the resulting stream in a converter
 * stream and calls ParseSheet.  Otherwise it tries to look for an
 * existing load for this URI and piggyback on it.  Failing all that,
 * a new load is kicked off asynchronously.
 */
nsresult Loader::LoadSheet(SheetLoadData& aLoadData, SheetState aSheetState,
                           uint64_t aEarlyHintPreloaderId,
                           PendingLoad aPendingLoad) {
  LOG(("css::Loader::LoadSheet"));
  MOZ_ASSERT(aLoadData.mURI, "Need a URI to load");
  MOZ_ASSERT(aLoadData.mSheet, "Need a sheet to load into");
  MOZ_ASSERT(aSheetState != SheetState::Complete, "Why bother?");
  MOZ_ASSERT(!aLoadData.mUseSystemPrincipal || aLoadData.mSyncLoad,
             "Shouldn't use system principal for async loads");

  LOG_URI("  Load from: '%s'", aLoadData.mURI);

  // If we're firing a pending load, this load is already accounted for the
  // first time it went through this function.
  if (aPendingLoad == PendingLoad::No) {
    if (aLoadData.BlocksLoadEvent()) {
      IncrementOngoingLoadCountAndMaybeBlockOnload();
    }

    // We technically never defer non-top-level sheets, so this condition could
    // be outside the branch, but conceptually it should be here.
    if (aLoadData.mParentData) {
      ++aLoadData.mParentData->mPendingChildren;
    }
  }

  if (!mDocument && !aLoadData.mIsNonDocumentSheet) {
    // No point starting the load; just release all the data and such.
    LOG_WARN(("  No document and not non-document sheet; pre-dropping load"));
    SheetComplete(aLoadData, NS_BINDING_ABORTED);
    return NS_BINDING_ABORTED;
  }

  if (aLoadData.mSyncLoad) {
    return LoadSheetSyncInternal(aLoadData, aSheetState);
  }

  SheetLoadDataHashKey key(aLoadData);

  auto preloadKey = PreloadHashKey::CreateAsStyle(aLoadData);
  if (mSheets) {
    if (MaybeDeferLoad(aLoadData, aSheetState, aPendingLoad, key)) {
      return NS_OK;
    }

    if (MaybeCoalesceLoadAndNotifyOpen(aLoadData, aSheetState, key,
                                       preloadKey)) {
      // All done here; once the load completes we'll be marked complete
      // automatically.
      return NS_OK;
    }
  }

  aLoadData.NotifyOpen(preloadKey, mDocument, aLoadData.IsLinkRelPreload());

  return LoadSheetAsyncInternal(aLoadData, aEarlyHintPreloaderId, key);
}

void Loader::AdjustPriority(const SheetLoadData& aLoadData,
                            nsIChannel* aChannel) {
  if (!aLoadData.ShouldDefer() && aLoadData.IsLinkRelPreload()) {
    SheetLoadData::PrioritizeAsPreload(aChannel);
  }

  if (!StaticPrefs::network_fetchpriority_enabled()) {
    return;
  }

  nsCOMPtr<nsISupportsPriority> sp = do_QueryInterface(aChannel);

  if (!sp) {
    return;
  }

  // Adjusting priorites is specified as implementation-defined.
  // See corresponding preferences in StaticPrefList.yaml for more context.
  const int32_t supportsPriorityDelta = [&]() {
    if (aLoadData.ShouldDefer()) {
      return FETCH_PRIORITY_ADJUSTMENT_FOR(deferred_style,
                                           aLoadData.mFetchPriority);
    }
    if (aLoadData.IsLinkRelPreload()) {
      return FETCH_PRIORITY_ADJUSTMENT_FOR(link_preload_style,
                                           aLoadData.mFetchPriority);
    }
    return FETCH_PRIORITY_ADJUSTMENT_FOR(non_deferred_style,
                                         aLoadData.mFetchPriority);
  }();

  sp->AdjustPriority(supportsPriorityDelta);
#ifdef DEBUG
  int32_t adjustedPriority;
  sp->GetPriority(&adjustedPriority);
  LogPriorityMapping(sCssLoaderLog, aLoadData.mFetchPriority, adjustedPriority);
#endif
}

nsresult Loader::LoadSheetAsyncInternal(SheetLoadData& aLoadData,
                                        uint64_t aEarlyHintPreloaderId,
                                        const SheetLoadDataHashKey& aKey) {
  nsresult rv = NS_OK;

  SRIMetadata sriMetadata;
  aLoadData.mSheet->GetIntegrity(sriMetadata);

  nsINode* requestingNode = aLoadData.GetRequestingNode();

  nsCOMPtr<nsILoadGroup> loadGroup;
  nsCOMPtr<nsICookieJarSettings> cookieJarSettings;
  if (mDocument) {
    loadGroup = mDocument->GetDocumentLoadGroup();
    // load for a document with no loadgrup indicates that something is
    // completely bogus, let's bail out early.
    if (!loadGroup) {
      LOG_ERROR(("  Failed to query loadGroup from document"));
      SheetComplete(aLoadData, NS_ERROR_UNEXPECTED);
      return NS_ERROR_UNEXPECTED;
    }

    cookieJarSettings = mDocument->CookieJarSettings();
  }

#ifdef DEBUG
  AutoRestore<bool> syncCallbackGuard(mSyncCallback);
  mSyncCallback = true;
#endif

  nsSecurityFlags securityFlags =
      nsContentSecurityManager::ComputeSecurityFlags(
          aLoadData.mSheet->GetCORSMode(),
          nsContentSecurityManager::CORSSecurityMapping::
              CORS_NONE_MAPS_TO_INHERITED_CONTEXT);

  securityFlags |= nsILoadInfo::SEC_ALLOW_CHROME;

  nsContentPolicyType contentPolicyType =
      aLoadData.mPreloadKind == StylePreloadKind::None
          ? nsIContentPolicy::TYPE_INTERNAL_STYLESHEET
          : nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD;

  nsCOMPtr<nsIChannel> channel;
  // Note we are calling NS_NewChannelWithTriggeringPrincipal here with a node
  // and a principal. This is because of a case where the node is the document
  // being styled and the principal is the stylesheet (perhaps from a different
  // origin)  that is applying the styles.
  if (requestingNode) {
    rv = NS_NewChannelWithTriggeringPrincipal(
        getter_AddRefs(channel), aLoadData.mURI, requestingNode,
        aLoadData.mTriggeringPrincipal, securityFlags, contentPolicyType,
        /* PerformanceStorage */ nullptr, loadGroup);
  } else {
    MOZ_ASSERT(aLoadData.mTriggeringPrincipal->Equals(LoaderPrincipal()));
    rv = NS_NewChannel(getter_AddRefs(channel), aLoadData.mURI,
                       aLoadData.mTriggeringPrincipal, securityFlags,
                       contentPolicyType, cookieJarSettings,
                       /* aPerformanceStorage */ nullptr, loadGroup);
  }

  if (NS_FAILED(rv)) {
    LOG_ERROR(("  Failed to create channel"));
    SheetComplete(aLoadData, rv);
    return rv;
  }

  nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
  loadInfo->SetCspNonce(aLoadData.Nonce());

  if (!aLoadData.ShouldDefer()) {
    if (nsCOMPtr<nsIClassOfService> cos = do_QueryInterface(channel)) {
      cos->AddClassFlags(nsIClassOfService::Leader);
    }

    if (aLoadData.IsLinkRelPreload()) {
      SheetLoadData::AddLoadBackgroundFlag(channel);
    }
  }

  AdjustPriority(aLoadData, channel);

  if (nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(channel)) {
    if (nsCOMPtr<nsIReferrerInfo> referrerInfo = aLoadData.ReferrerInfo()) {
      rv = httpChannel->SetReferrerInfo(referrerInfo);
      Unused << NS_WARN_IF(NS_FAILED(rv));
    }

    nsCOMPtr<nsIHttpChannelInternal> internalChannel =
        do_QueryInterface(httpChannel);
    if (internalChannel) {
      rv = internalChannel->SetIntegrityMetadata(
          sriMetadata.GetIntegrityString());
      NS_ENSURE_SUCCESS(rv, rv);
    }

    // Set the initiator type
    if (nsCOMPtr<nsITimedChannel> timedChannel =
            do_QueryInterface(httpChannel)) {
      if (aLoadData.mParentData) {
        timedChannel->SetInitiatorType(u"css"_ns);

        // This is a child sheet load.
        //
        // The resource timing of the sub-resources that a document loads
        // should normally be reported to the document.  One exception is any
        // sub-resources of any cross-origin resources that are loaded.  We
        // don't mind reporting timing data for a direct child cross-origin
        // resource since the resource that linked to it (and hence potentially
        // anything in that parent origin) is aware that the cross-origin
        // resources is to be loaded.  However, we do not want to report
        // timings for any sub-resources that a cross-origin resource may load
        // since that obviously leaks information about what the cross-origin
        // resource loads, which is bad.
        //
        // In addition to checking whether we're an immediate child resource of
        // a cross-origin resource (by checking if mIsCrossOriginNoCORS is set
        // to true on our parent), we also check our parent to see whether it
        // itself is a sub-resource of a cross-origin resource by checking
        // mBlockResourceTiming.  If that is set then we too are such a
        // sub-resource and so we set the flag on ourself too to propagate it
        // on down.
        if (aLoadData.mParentData->mIsCrossOriginNoCORS ||
            aLoadData.mParentData->mBlockResourceTiming) {
          // Set a flag so any other stylesheet triggered by this one will
          // not be reported
          aLoadData.mBlockResourceTiming = true;

          // Mark the channel so PerformanceMainThread::AddEntry will not
          // report the resource.
          timedChannel->SetReportResourceTiming(false);
        }

      } else if (aEarlyHintPreloaderId) {
        timedChannel->SetInitiatorType(u"early-hints"_ns);
      } else {
        timedChannel->SetInitiatorType(u"link"_ns);
      }
    }
  }

  // Now tell the channel we expect text/css data back....  We do
  // this before opening it, so it's only treated as a hint.
  channel->SetContentType("text/css"_ns);

  // We don't have to hold on to the stream loader.  The ownership
  // model is: Necko owns the stream loader, which owns the load data,
  // which owns us
  auto streamLoader = MakeRefPtr<StreamLoader>(aLoadData);
  if (mDocument) {
    net::PredictorLearn(aLoadData.mURI, mDocument->GetDocumentURI(),
                        nsINetworkPredictor::LEARN_LOAD_SUBRESOURCE, mDocument);
  }

  if (aEarlyHintPreloaderId) {
    nsCOMPtr<nsIHttpChannelInternal> channelInternal =
        do_QueryInterface(channel);
    NS_ENSURE_TRUE(channelInternal != nullptr, NS_ERROR_FAILURE);

    rv = channelInternal->SetEarlyHintPreloaderId(aEarlyHintPreloaderId);
    NS_ENSURE_SUCCESS(rv, rv);
  }
  rv = channel->AsyncOpen(streamLoader);
  if (NS_FAILED(rv)) {
    LOG_ERROR(("  Failed to create stream loader"));
    streamLoader->ChannelOpenFailed(rv);
    // NOTE: NotifyStop will be done in SheetComplete -> NotifyObservers.
    aLoadData.NotifyStart(channel);
    SheetComplete(aLoadData, rv);
    return rv;
  }

#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
  if (nsCOMPtr<nsIHttpChannelInternal> hci = do_QueryInterface(channel)) {
    hci->DoDiagnosticAssertWhenOnStopNotCalledOnDestroy();
  }
#endif

  if (mSheets) {
    mSheets->LoadStarted(aKey, aLoadData);
  }
  return NS_OK;
}

/**
 * ParseSheet handles parsing the data stream.
 */
Loader::Completed Loader::ParseSheet(
    const nsACString& aBytes, const RefPtr<SheetLoadDataHolder>& aLoadData,
    AllowAsyncParse aAllowAsync) {
  LOG(("css::Loader::ParseSheet"));
  SheetLoadData* loadData = aLoadData->get();
  MOZ_ASSERT(loadData);

  if (loadData->mURI) {
    LOG_URI("  Load succeeded for URI: '%s', parsing", loadData->mURI);
  }
  AUTO_PROFILER_LABEL_CATEGORY_PAIR_RELEVANT_FOR_JS(LAYOUT_CSSParsing);

  ++mParsedSheetCount;

  loadData->mIsBeingParsed = true;

  StyleSheet* sheet = loadData->mSheet;
  MOZ_ASSERT(sheet);

  // Some cases, like inline style and UA stylesheets, need to be parsed
  // synchronously. The former may trigger child loads, the latter must not.
  if (loadData->mSyncLoad || aAllowAsync == AllowAsyncParse::No) {
    sheet->ParseSheetSync(this, aBytes, loadData);
    loadData->mIsBeingParsed = false;

    bool noPendingChildren = loadData->mPendingChildren == 0;
    MOZ_ASSERT_IF(loadData->mSyncLoad, noPendingChildren);
    if (noPendingChildren) {
      SheetComplete(*loadData, NS_OK);
      return Completed::Yes;
    }
    return Completed::No;
  }

  // This parse does not need to be synchronous. \o/
  //
  // Note that load is already blocked from
  // IncrementOngoingLoadCountAndMaybeBlockOnload(), and will be unblocked from
  // SheetFinishedParsingAsync which will end up in NotifyObservers as needed.
  sheet->ParseSheet(*this, aBytes, aLoadData)
      ->Then(
          GetMainThreadSerialEventTarget(), __func__,
          [loadData = aLoadData](bool aDummy) {
            MOZ_ASSERT(NS_IsMainThread());
            loadData->get()->SheetFinishedParsingAsync();
          },
          [] { MOZ_CRASH("rejected parse promise"); });
  return Completed::No;
}

void Loader::NotifyObservers(SheetLoadData& aData, nsresult aStatus) {
  RecordUseCountersIfNeeded(mDocument, *aData.mSheet);
  RefPtr loadDispatcher = aData.PrepareLoadEventIfNeeded();
  if (aData.mURI) {
    mLoadsPerformed.PutEntry(SheetLoadDataHashKey(aData));
    aData.NotifyStop(aStatus);
    // NOTE(emilio): This needs to happen before notifying observers, as
    // FontFaceSet for example checks for pending sheet loads from the
    // StyleSheetLoaded callback.
    if (aData.BlocksLoadEvent()) {
      DecrementOngoingLoadCountAndMaybeUnblockOnload();
      if (mPendingLoadCount && mPendingLoadCount == mOngoingLoadCount) {
        LOG(("  No more loading sheets; starting deferred loads"));
        StartDeferredLoads();
      }
    }
  }
  if (!aData.mTitle.IsEmpty() && NS_SUCCEEDED(aStatus)) {
    nsContentUtils::AddScriptRunner(NS_NewRunnableFunction(
        "Loader::NotifyObservers - Create PageStyle actor",
        [doc = RefPtr{mDocument}] {
          // Force creating the page style actor, if available.
          // This will no-op if no actor with this name is registered (outside
          // of desktop Firefox).
          nsCOMPtr<nsISupports> pageStyleActor =
              do_QueryActor("PageStyle", doc);
          Unused << pageStyleActor;
        }));
  }
  if (aData.mMustNotify) {
    if (nsCOMPtr<nsICSSLoaderObserver> observer = std::move(aData.mObserver)) {
      LOG(("  Notifying observer %p for data %p.  deferred: %d", observer.get(),
           &aData, aData.ShouldDefer()));
      observer->StyleSheetLoaded(aData.mSheet, aData.ShouldDefer(), aStatus);
    }

    for (nsCOMPtr<nsICSSLoaderObserver> obs : mObservers.ForwardRange()) {
      LOG(("  Notifying global observer %p for data %p.  deferred: %d",
           obs.get(), &aData, aData.ShouldDefer()));
      obs->StyleSheetLoaded(aData.mSheet, aData.ShouldDefer(), aStatus);
    }

    if (loadDispatcher) {
      loadDispatcher->RunDOMEventWhenSafe();
    }
  } else if (loadDispatcher) {
    loadDispatcher->PostDOMEvent();
  }
}

/**
 * SheetComplete is the do-it-all cleanup function.  It removes the
 * load data from the "loading" hashtable, adds the sheet to the
 * "completed" hashtable, massages the XUL cache, handles siblings of
 * the load data (other loads for the same URI), handles unblocking
 * blocked parent loads as needed, and most importantly calls
 * NS_RELEASE on the load data to destroy the whole mess.
 */
void Loader::SheetComplete(SheetLoadData& aLoadData, nsresult aStatus) {
  LOG(("css::Loader::SheetComplete, status: 0x%" PRIx32,
       static_cast<uint32_t>(aStatus)));
  SharedStyleSheetCache::LoadCompleted(mSheets.get(), aLoadData, aStatus);
}

// static
void Loader::MarkLoadTreeFailed(SheetLoadData& aLoadData,
                                Loader* aOnlyForLoader) {
  if (aLoadData.mURI) {
    LOG_URI("  Load failed: '%s'", aLoadData.mURI);
  }

  SheetLoadData* data = &aLoadData;
  do {
    if (!aOnlyForLoader || aOnlyForLoader == data->mLoader) {
      data->mLoadFailed = true;
      data->mSheet->MaybeRejectReplacePromise();
    }

    if (data->mParentData) {
      MarkLoadTreeFailed(*data->mParentData, aOnlyForLoader);
    }

    data = data->mNext;
  } while (data);
}

RefPtr<StyleSheet> Loader::LookupInlineSheetInCache(
    const nsAString& aBuffer, nsIPrincipal* aSheetPrincipal) {
  auto result = mInlineSheets.Lookup(aBuffer);
  if (!result) {
    return nullptr;
  }
  StyleSheet* sheet = result.Data();
  if (NS_WARN_IF(sheet->HasModifiedRules())) {
    // Remove it now that we know that we're never going to use this stylesheet
    // again.
    result.Remove();
    return nullptr;
  }
  if (NS_WARN_IF(!sheet->Principal()->Equals(aSheetPrincipal))) {
    // If the sheet is going to have different access rights, don't return it
    // from the cache.
    return nullptr;
  }
  return sheet->Clone(nullptr, nullptr);
}

void Loader::MaybeNotifyPreloadUsed(SheetLoadData& aData) {
  if (!mDocument) {
    return;
  }

  auto key = PreloadHashKey::CreateAsStyle(aData);
  RefPtr<PreloaderBase> preload = mDocument->Preloads().LookupPreload(key);
  if (!preload) {
    return;
  }

  preload->NotifyUsage(mDocument);
}

Result<Loader::LoadSheetResult, nsresult> Loader::LoadInlineStyle(
    const SheetInfo& aInfo, const nsAString& aBuffer,
    nsICSSLoaderObserver* aObserver) {
  LOG(("css::Loader::LoadInlineStyle"));
  MOZ_ASSERT(aInfo.mContent);

  if (!mEnabled) {
    LOG_WARN(("  Not enabled"));
    return Err(NS_ERROR_NOT_AVAILABLE);
  }

  if (!mDocument) {
    return Err(NS_ERROR_NOT_INITIALIZED);
  }

  MOZ_ASSERT(LinkStyle::FromNodeOrNull(aInfo.mContent),
             "Element is not a style linking element!");

  // Since we're not planning to load a URI, no need to hand a principal to the
  // load data or to CreateSheet().

  // Check IsAlternateSheet now, since it can mutate our document.
  auto isAlternate = IsAlternateSheet(aInfo.mTitle, aInfo.mHasAlternateRel);
  LOG(("  Sheet is alternate: %d", static_cast<int>(isAlternate)));

  // Use the document's base URL so that @import in the inline sheet picks up
  // the right base.
  nsIURI* baseURI = aInfo.mContent->GetBaseURI();
  nsIURI* sheetURI = aInfo.mContent->OwnerDoc()->GetDocumentURI();
  nsIURI* originalURI = nullptr;

  MOZ_ASSERT(aInfo.mIntegrity.IsEmpty());
  nsIPrincipal* loadingPrincipal = LoaderPrincipal();
  nsIPrincipal* principal = aInfo.mTriggeringPrincipal
                                ? aInfo.mTriggeringPrincipal.get()
                                : loadingPrincipal;
  nsIPrincipal* sheetPrincipal = [&] {
    // The triggering principal may be an expanded principal, which is safe to
    // use for URL security checks, but not as the loader principal for a
    // stylesheet. So treat this as principal inheritance, and downgrade if
    // necessary.
    //
    // FIXME(emilio): Why doing this for inline sheets but not for links?
    if (aInfo.mTriggeringPrincipal) {
      return BasePrincipal::Cast(aInfo.mTriggeringPrincipal)
          ->PrincipalToInherit();
    }
    return LoaderPrincipal();
  }();

  // We only cache sheets if in shadow trees, since regular document sheets are
  // likely to be unique.
  const bool isWorthCaching =
      StaticPrefs::layout_css_inline_style_caching_always_enabled() ||
      aInfo.mContent->IsInShadowTree();
  RefPtr<StyleSheet> sheet;
  if (isWorthCaching) {
    sheet = LookupInlineSheetInCache(aBuffer, sheetPrincipal);
  }
  const bool isSheetFromCache = !!sheet;
  if (!isSheetFromCache) {
    sheet = MakeRefPtr<StyleSheet>(eAuthorSheetFeatures, aInfo.mCORSMode,
                                   SRIMetadata{});
    sheet->SetURIs(sheetURI, originalURI, baseURI);
    nsIReferrerInfo* referrerInfo =
        aInfo.mContent->OwnerDoc()->ReferrerInfoForInternalCSSAndSVGResources();
    sheet->SetReferrerInfo(referrerInfo);
    // We never actually load this, so just set its principal directly.
    sheet->SetPrincipal(sheetPrincipal);
  }

  auto matched = PrepareSheet(*sheet, aInfo.mTitle, aInfo.mMedia, nullptr,
                              isAlternate, aInfo.mIsExplicitlyEnabled);
  if (auto* linkStyle = LinkStyle::FromNode(*aInfo.mContent)) {
    linkStyle->SetStyleSheet(sheet);
  }
  MOZ_ASSERT(sheet->IsComplete() == isSheetFromCache);

  Completed completed;
  auto data = MakeRefPtr<SheetLoadData>(
      this, aInfo.mTitle, /* aURI = */ nullptr, sheet, SyncLoad::No,
      aInfo.mContent, isAlternate, matched, StylePreloadKind::None, aObserver,
      principal, aInfo.mReferrerInfo, aInfo.mNonce, aInfo.mFetchPriority);
  MOZ_ASSERT(data->GetRequestingNode() == aInfo.mContent);
  if (isSheetFromCache) {
    MOZ_ASSERT(sheet->IsComplete());
    MOZ_ASSERT(sheet->GetOwnerNode() == aInfo.mContent);
    completed = Completed::Yes;
    InsertSheetInTree(*sheet);
    NotifyOfCachedLoad(std::move(data));
  } else {
    // Parse completion releases the load data.
    //
    // Note that we need to parse synchronously, since the web expects that the
    // effects of inline stylesheets are visible immediately (aside from
    // @imports).
    NS_ConvertUTF16toUTF8 utf8(aBuffer);
    RefPtr<SheetLoadDataHolder> holder(
        new nsMainThreadPtrHolder<css::SheetLoadData>(__func__, data.get(),
                                                      true));
    completed = ParseSheet(utf8, holder, AllowAsyncParse::No);
    if (completed == Completed::Yes) {
      if (isWorthCaching) {
        mInlineSheets.InsertOrUpdate(aBuffer, std::move(sheet));
      }
    } else {
      data->mMustNotify = true;
    }
  }

  return LoadSheetResult{completed, isAlternate, matched};
}

Result<Loader::LoadSheetResult, nsresult> Loader::LoadStyleLink(
    const SheetInfo& aInfo, nsICSSLoaderObserver* aObserver) {
  MOZ_ASSERT(aInfo.mURI, "Must have URL to load");
  LOG(("css::Loader::LoadStyleLink"));
  LOG_URI("  Link uri: '%s'", aInfo.mURI);
  LOG(("  Link title: '%s'", NS_ConvertUTF16toUTF8(aInfo.mTitle).get()));
  LOG(("  Link media: '%s'", NS_ConvertUTF16toUTF8(aInfo.mMedia).get()));
  LOG(("  Link alternate rel: %d", aInfo.mHasAlternateRel));

  if (!mEnabled) {
    LOG_WARN(("  Not enabled"));
    return Err(NS_ERROR_NOT_AVAILABLE);
  }

  if (!mDocument) {
    return Err(NS_ERROR_NOT_INITIALIZED);
  }

  MOZ_ASSERT_IF(aInfo.mContent,
                aInfo.mContent->NodePrincipal() == mDocument->NodePrincipal());
  nsIPrincipal* loadingPrincipal = LoaderPrincipal();
  nsIPrincipal* principal = aInfo.mTriggeringPrincipal
                                ? aInfo.mTriggeringPrincipal.get()
                                : loadingPrincipal;

  nsINode* requestingNode =
      aInfo.mContent ? static_cast<nsINode*>(aInfo.mContent) : mDocument;
  const bool syncLoad = [&] {
    if (!aInfo.mContent) {
      return false;
    }
    const bool privilegedShadowTree =
        aInfo.mContent->IsInShadowTree() &&
        (aInfo.mContent->ChromeOnlyAccess() ||
         aInfo.mContent->OwnerDoc()->ChromeRulesEnabled());
    if (!privilegedShadowTree) {
      return false;
    }
    if (!IsPrivilegedURI(aInfo.mURI)) {
      return false;
    }
    // We're loading a chrome/resource URI in a chrome doc shadow tree or UA
    // widget. Load synchronously to avoid FOUC.
    return true;
  }();
  LOG(("  Link sync load: '%s'", syncLoad ? "true" : "false"));
  MOZ_ASSERT_IF(syncLoad, !aObserver);

  nsresult rv =
      CheckContentPolicy(loadingPrincipal, principal, aInfo.mURI,
                         requestingNode, aInfo.mNonce, StylePreloadKind::None);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    // Don't fire the error event if our document is loaded as data.  We're
    // supposed to not even try to do loads in that case... Unfortunately, we
    // implement that via nsDataDocumentContentPolicy, which doesn't have a good
    // way to communicate back to us that _it_ is the thing that blocked the
    // load.
    if (aInfo.mContent && !mDocument->IsLoadedAsData()) {
      // Fire an async error event on it.
      RefPtr<AsyncEventDispatcher> loadBlockingAsyncDispatcher =
          new LoadBlockingAsyncEventDispatcher(aInfo.mContent, u"error"_ns,
                                               CanBubble::eNo,
                                               ChromeOnlyDispatch::eNo);
      loadBlockingAsyncDispatcher->PostDOMEvent();
    }
    return Err(rv);
  }

  // Check IsAlternateSheet now, since it can mutate our document and make
  // pending sheets go to the non-pending state.
  auto isAlternate = IsAlternateSheet(aInfo.mTitle, aInfo.mHasAlternateRel);
  auto [sheet, state] = CreateSheet(aInfo, eAuthorSheetFeatures, syncLoad,
                                    StylePreloadKind::None);

  LOG(("  Sheet is alternate: %d", static_cast<int>(isAlternate)));

  auto matched = PrepareSheet(*sheet, aInfo.mTitle, aInfo.mMedia, nullptr,
                              isAlternate, aInfo.mIsExplicitlyEnabled);

  if (auto* linkStyle = LinkStyle::FromNodeOrNull(aInfo.mContent)) {
    linkStyle->SetStyleSheet(sheet);
  }
  MOZ_ASSERT(sheet->IsComplete() == (state == SheetState::Complete));

  // We may get here with no content for Link: headers for example.
  MOZ_ASSERT(!aInfo.mContent || LinkStyle::FromNode(*aInfo.mContent),
             "If there is any node, it should be a LinkStyle");
  auto data = MakeRefPtr<SheetLoadData>(
      this, aInfo.mTitle, aInfo.mURI, sheet, SyncLoad(syncLoad), aInfo.mContent,
      isAlternate, matched, StylePreloadKind::None, aObserver, principal,
      aInfo.mReferrerInfo, aInfo.mNonce, aInfo.mFetchPriority);

  MOZ_ASSERT(data->GetRequestingNode() == requestingNode);

  MaybeNotifyPreloadUsed(*data);

  if (state == SheetState::Complete) {
    LOG(("  Sheet already complete: 0x%p", sheet.get()));
    MOZ_ASSERT(sheet->GetOwnerNode() == aInfo.mContent);
    InsertSheetInTree(*sheet);
    NotifyOfCachedLoad(std::move(data));
    return LoadSheetResult{Completed::Yes, isAlternate, matched};
  }

  // Now we need to actually load it.
  auto result = LoadSheetResult{Completed::No, isAlternate, matched};

  MOZ_ASSERT(result.ShouldBlock() == !data->ShouldDefer(),
             "These should better match!");

  // Load completion will free the data
  rv = LoadSheet(*data, state, 0);
  if (NS_FAILED(rv)) {
    return Err(rv);
  }

  if (!syncLoad) {
    data->mMustNotify = true;
  }
  return result;
}

static bool HaveAncestorDataWithURI(SheetLoadData& aData, nsIURI* aURI) {
  if (!aData.mURI) {
    // Inline style; this won't have any ancestors
    MOZ_ASSERT(!aData.mParentData, "How does inline style have a parent?");
    return false;
  }

  bool equal;
  if (NS_FAILED(aData.mURI->Equals(aURI, &equal)) || equal) {
    return true;
  }

  // Datas down the mNext chain have the same URI as aData, so we
  // don't have to compare to them.  But they might have different
  // parents, and we have to check all of those.
  SheetLoadData* data = &aData;
  do {
    if (data->mParentData &&
        HaveAncestorDataWithURI(*data->mParentData, aURI)) {
      return true;
    }

    data = data->mNext;
  } while (data);

  return false;
}

nsresult Loader::LoadChildSheet(StyleSheet& aParentSheet,
                                SheetLoadData* aParentData, nsIURI* aURL,
                                dom::MediaList* aMedia,
                                LoaderReusableStyleSheets* aReusableSheets) {
  LOG(("css::Loader::LoadChildSheet"));
  MOZ_ASSERT(aURL, "Must have a URI to load");

  if (!mEnabled) {
    LOG_WARN(("  Not enabled"));
    return NS_ERROR_NOT_AVAILABLE;
  }

  LOG_URI("  Child uri: '%s'", aURL);

  nsCOMPtr<nsINode> owningNode;

  nsINode* requestingNode = aParentSheet.GetOwnerNodeOfOutermostSheet();
  if (requestingNode) {
    MOZ_ASSERT(LoaderPrincipal() == requestingNode->NodePrincipal());
  } else {
    requestingNode = mDocument;
  }

  nsIPrincipal* principal = aParentSheet.Principal();
  nsresult rv =
      CheckContentPolicy(LoaderPrincipal(), principal, aURL, requestingNode,
                         /* aNonce = */ u""_ns, StylePreloadKind::None);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    if (aParentData) {
      MarkLoadTreeFailed(*aParentData);
    }
    return rv;
  }

  nsCOMPtr<nsICSSLoaderObserver> observer;

  if (aParentData) {
    LOG(("  Have a parent load"));
    // Check for cycles
    if (HaveAncestorDataWithURI(*aParentData, aURL)) {
      // Houston, we have a loop, blow off this child and pretend this never
      // happened
      LOG_ERROR(("  @import cycle detected, dropping load"));
      return NS_OK;
    }

    NS_ASSERTION(aParentData->mSheet == &aParentSheet,
                 "Unexpected call to LoadChildSheet");
  } else {
    LOG(("  No parent load; must be CSSOM"));
    // No parent load data, so the sheet will need to be notified when
    // we finish, if it can be, if we do the load asynchronously.
    observer = &aParentSheet;
  }

  // Now that we know it's safe to load this (passes security check and not a
  // loop) do so.
  RefPtr<StyleSheet> sheet;
  SheetState state;
  if (aReusableSheets && aReusableSheets->FindReusableStyleSheet(aURL, sheet)) {
    state = SheetState::Complete;
  } else {
    // For now, use CORS_NONE for child sheets
    std::tie(sheet, state) = CreateSheet(
        aURL, nullptr, principal, aParentSheet.ParsingMode(), CORS_NONE,
        aParentData ? aParentData->mEncoding : nullptr,
        u""_ns,  // integrity is only checked on main sheet
        aParentData && aParentData->mSyncLoad, StylePreloadKind::None);
    PrepareSheet(*sheet, u""_ns, u""_ns, aMedia, IsAlternate::No,
                 IsExplicitlyEnabled::No);
  }

  MOZ_ASSERT(sheet);
  InsertChildSheet(*sheet, aParentSheet);

  auto data =
      MakeRefPtr<SheetLoadData>(this, aURL, sheet, aParentData, observer,
                                principal, aParentSheet.GetReferrerInfo());
  MOZ_ASSERT(data->GetRequestingNode() == requestingNode);

  MaybeNotifyPreloadUsed(*data);

  if (state == SheetState::Complete) {
    LOG(("  Sheet already complete"));
    // We're completely done.  No need to notify, even, since the
    // @import rule addition/modification will trigger the right style
    // changes automatically.
    data->mIntentionallyDropped = true;
    return NS_OK;
  }

  bool syncLoad = data->mSyncLoad;

  // Load completion will release the data
  rv = LoadSheet(*data, state, 0);
  NS_ENSURE_SUCCESS(rv, rv);

  if (!syncLoad) {
    data->mMustNotify = true;
  }
  return rv;
}

Result<RefPtr<StyleSheet>, nsresult> Loader::LoadSheetSync(
    nsIURI* aURL, SheetParsingMode aParsingMode,
    UseSystemPrincipal aUseSystemPrincipal) {
  LOG(("css::Loader::LoadSheetSync"));
  nsCOMPtr<nsIReferrerInfo> referrerInfo = new ReferrerInfo(nullptr);
  return InternalLoadNonDocumentSheet(
      aURL, StylePreloadKind::None, aParsingMode, aUseSystemPrincipal, nullptr,
      referrerInfo, nullptr, CORS_NONE, u""_ns, u""_ns, 0, FetchPriority::Auto);
}

Result<RefPtr<StyleSheet>, nsresult> Loader::LoadSheet(
    nsIURI* aURI, SheetParsingMode aParsingMode,
    UseSystemPrincipal aUseSystemPrincipal, nsICSSLoaderObserver* aObserver) {
  nsCOMPtr<nsIReferrerInfo> referrerInfo = new ReferrerInfo(nullptr);
  return InternalLoadNonDocumentSheet(
      aURI, StylePreloadKind::None, aParsingMode, aUseSystemPrincipal, nullptr,
      referrerInfo, aObserver, CORS_NONE, u""_ns, u""_ns, 0,
      FetchPriority::Auto);
}

Result<RefPtr<StyleSheet>, nsresult> Loader::LoadSheet(
    nsIURI* aURL, StylePreloadKind aPreloadKind,
    const Encoding* aPreloadEncoding, nsIReferrerInfo* aReferrerInfo,
    nsICSSLoaderObserver* aObserver, uint64_t aEarlyHintPreloaderId,
    CORSMode aCORSMode, const nsAString& aNonce, const nsAString& aIntegrity,
    FetchPriority aFetchPriority) {
  LOG(("css::Loader::LoadSheet(aURL, aObserver) api call"));
  return InternalLoadNonDocumentSheet(
      aURL, aPreloadKind, eAuthorSheetFeatures, UseSystemPrincipal::No,
      aPreloadEncoding, aReferrerInfo, aObserver, aCORSMode, aNonce, aIntegrity,
      aEarlyHintPreloaderId, aFetchPriority);
}

Result<RefPtr<StyleSheet>, nsresult> Loader::InternalLoadNonDocumentSheet(
    nsIURI* aURL, StylePreloadKind aPreloadKind, SheetParsingMode aParsingMode,
    UseSystemPrincipal aUseSystemPrincipal, const Encoding* aPreloadEncoding,
    nsIReferrerInfo* aReferrerInfo, nsICSSLoaderObserver* aObserver,
    CORSMode aCORSMode, const nsAString& aNonce, const nsAString& aIntegrity,
    uint64_t aEarlyHintPreloaderId, FetchPriority aFetchPriority) {
  MOZ_ASSERT(aURL, "Must have a URI to load");
  MOZ_ASSERT(aUseSystemPrincipal == UseSystemPrincipal::No || !aObserver,
             "Shouldn't load system-principal sheets async");
  MOZ_ASSERT(aReferrerInfo, "Must have referrerInfo");

  LOG_URI("  Non-document sheet uri: '%s'", aURL);

  if (!mEnabled) {
    LOG_WARN(("  Not enabled"));
    return Err(NS_ERROR_NOT_AVAILABLE);
  }

  nsIPrincipal* loadingPrincipal = LoaderPrincipal();
  nsIPrincipal* triggeringPrincipal = loadingPrincipal;
  nsresult rv = CheckContentPolicy(loadingPrincipal, triggeringPrincipal, aURL,
                                   mDocument, aNonce, aPreloadKind);
  if (NS_FAILED(rv)) {
    return Err(rv);
  }

  bool syncLoad = !aObserver;
  auto [sheet, state] =
      CreateSheet(aURL, nullptr, triggeringPrincipal, aParsingMode, aCORSMode,
                  aPreloadEncoding, aIntegrity, syncLoad, aPreloadKind);

  PrepareSheet(*sheet, u""_ns, u""_ns, nullptr, IsAlternate::No,
               IsExplicitlyEnabled::No);

  auto data = MakeRefPtr<SheetLoadData>(
      this, aURL, sheet, SyncLoad(syncLoad), aUseSystemPrincipal, aPreloadKind,
      aPreloadEncoding, aObserver, triggeringPrincipal, aReferrerInfo, aNonce,
      aFetchPriority);
  MOZ_ASSERT(data->GetRequestingNode() == mDocument);
  if (state == SheetState::Complete) {
    LOG(("  Sheet already complete"));
    NotifyOfCachedLoad(std::move(data));
    return sheet;
  }

  rv = LoadSheet(*data, state, aEarlyHintPreloaderId);
  if (NS_FAILED(rv)) {
    return Err(rv);
  }
  if (aObserver) {
    data->mMustNotify = true;
  }
  return sheet;
}

void Loader::NotifyOfCachedLoad(RefPtr<SheetLoadData> aLoadData) {
  LOG(("css::Loader::PostLoadEvent"));
  MOZ_ASSERT(aLoadData->mSheet->IsComplete(),
             "Only expected to be used for cached sheets");
  // If we get to this code, the stylesheet loaded correctly at some point, so
  // we can just schedule a load event and don't need to touch the data's
  // mLoadFailed.
  // Note that we do this here and not from inside our SheetComplete so that we
  // don't end up running the load event more async than needed.
  MOZ_ASSERT(!aLoadData->mLoadFailed, "Why are we marked as failed?");
  aLoadData->mSheetAlreadyComplete = true;

  // We need to check mURI to match
  // DecrementOngoingLoadCountAndMaybeUnblockOnload().
  if (aLoadData->mURI && aLoadData->BlocksLoadEvent()) {
    IncrementOngoingLoadCountAndMaybeBlockOnload();
  }
  SheetComplete(*aLoadData, NS_OK);
}

void Loader::Stop() {
  if (mSheets) {
    mSheets->CancelLoadsForLoader(*this);
  }
}

bool Loader::HasPendingLoads() { return mOngoingLoadCount; }

void Loader::AddObserver(nsICSSLoaderObserver* aObserver) {
  MOZ_ASSERT(aObserver, "Must have observer");
  mObservers.AppendElementUnlessExists(aObserver);
}

void Loader::RemoveObserver(nsICSSLoaderObserver* aObserver) {
  mObservers.RemoveElement(aObserver);
}

void Loader::StartDeferredLoads() {
  if (mSheets && mPendingLoadCount) {
    mSheets->StartPendingLoadsForLoader(
        *this, [](const SheetLoadData&) { return true; });
  }
}

NS_IMPL_CYCLE_COLLECTION_CLASS(Loader)

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(Loader)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSheets);
  for (const auto& data : tmp->mInlineSheets.Values()) {
    NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "Inline sheet cache in Loader");
    cb.NoteXPCOMChild(data);
  }
  for (nsCOMPtr<nsICSSLoaderObserver>& obs : tmp->mObservers.ForwardRange()) {
    ImplCycleCollectionTraverse(cb, obs, "mozilla::css::Loader.mObservers");
  }
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocGroup)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(Loader)
  if (tmp->mSheets) {
    if (tmp->mDocument) {
      tmp->DeregisterFromSheetCache();
    }
    tmp->mSheets = nullptr;
  }
  tmp->mInlineSheets.Clear();
  tmp->mObservers.Clear();
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocGroup)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END

size_t Loader::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
  size_t n = aMallocSizeOf(this);

  n += mObservers.ShallowSizeOfExcludingThis(aMallocSizeOf);

  n += mInlineSheets.ShallowSizeOfExcludingThis(aMallocSizeOf);
  for (const auto& entry : mInlineSheets) {
    n += entry.GetKey().SizeOfExcludingThisIfUnshared(aMallocSizeOf);
    // If the sheet has a parent, then its parent will report it so we don't
    // have to worry about it here.
    const StyleSheet* sheet = entry.GetWeak();
    MOZ_ASSERT(!sheet->GetParentSheet(),
               "How did an @import rule end up here?");
    if (!sheet->GetOwnerNode()) {
      n += sheet->SizeOfIncludingThis(aMallocSizeOf);
    }
  }

  // Measurement of the following members may be added later if DMD finds it is
  // worthwhile:
  // The following members aren't measured:
  // - mDocument, because it's a weak backpointer

  return n;
}

nsIPrincipal* Loader::LoaderPrincipal() const {
  if (mDocument) {
    return mDocument->NodePrincipal();
  }
  // Loaders without a document do system loads.
  return nsContentUtils::GetSystemPrincipal();
}

nsIPrincipal* Loader::PartitionedPrincipal() const {
  if (mDocument && StaticPrefs::privacy_partition_network_state()) {
    return mDocument->PartitionedPrincipal();
  }
  return LoaderPrincipal();
}

bool Loader::ShouldBypassCache() const {
  if (!mDocument) {
    return false;
  }
  RefPtr<nsILoadGroup> lg = mDocument->GetDocumentLoadGroup();
  if (!lg) {
    return false;
  }
  nsLoadFlags flags;
  if (NS_FAILED(lg->GetLoadFlags(&flags))) {
    return false;
  }
  return flags & (nsIRequest::LOAD_BYPASS_CACHE |
                  nsICachingChannel::LOAD_BYPASS_LOCAL_CACHE);
}

void Loader::BlockOnload() {
  if (mDocument) {
    mDocument->BlockOnload();
  }
}

void Loader::UnblockOnload(bool aFireSync) {
  if (mDocument) {
    mDocument->UnblockOnload(aFireSync);
  }
}

}  // namespace css
}  // namespace mozilla