forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScriptLoader.cpp
3669 lines (3114 loc) · 128 KB
/
ScriptLoader.cpp
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "ScriptLoader.h"
#include "ScriptLoadHandler.h"
#include "ScriptTrace.h"
#include "ModuleLoader.h"
#include "nsIChildChannel.h"
#include "zlib.h"
#include "prsystem.h"
#include "jsapi.h"
#include "jsfriendapi.h"
#include "js/Array.h" // JS::GetArrayLength
#include "js/CompilationAndEvaluation.h"
#include "js/ContextOptions.h" // JS::ContextOptionsRef
#include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
#include "js/loader/ScriptLoadRequest.h"
#include "ScriptCompression.h"
#include "js/loader/LoadedScript.h"
#include "js/loader/ModuleLoadRequest.h"
#include "js/MemoryFunctions.h"
#include "js/Modules.h"
#include "js/OffThreadScriptCompilation.h"
#include "js/PropertyAndElement.h" // JS_DefineProperty
#include "js/Realm.h"
#include "js/SourceText.h"
#include "js/Transcoding.h"
#include "js/Utility.h"
#include "xpcpublic.h"
#include "GeckoProfiler.h"
#include "nsContentSecurityManager.h"
#include "nsCycleCollectionParticipant.h"
#include "nsIContent.h"
#include "nsJSUtils.h"
#include "mozilla/dom/AutoEntryScript.h"
#include "mozilla/dom/DocGroup.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/JSExecutionContext.h"
#include "mozilla/dom/ScriptDecoding.h" // mozilla::dom::ScriptDecoding
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/SRILogHelper.h"
#include "mozilla/dom/WindowContext.h"
#include "mozilla/net/UrlClassifierFeatureFactory.h"
#include "mozilla/Preferences.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_javascript.h"
#include "mozilla/StaticPrefs_network.h"
#include "nsAboutProtocolUtils.h"
#include "nsGkAtoms.h"
#include "nsNetUtil.h"
#include "nsGlobalWindowInner.h"
#include "nsIScriptGlobalObject.h"
#include "nsIScriptContext.h"
#include "nsIPrincipal.h"
#include "nsJSPrincipals.h"
#include "nsContentPolicyUtils.h"
#include "nsIClassifiedChannel.h"
#include "nsIHttpChannel.h"
#include "nsIHttpChannelInternal.h"
#include "nsIClassOfService.h"
#include "nsICacheInfoChannel.h"
#include "nsITimedChannel.h"
#include "nsIScriptElement.h"
#include "nsISupportsPriority.h"
#include "nsIDocShell.h"
#include "nsContentUtils.h"
#include "nsUnicharUtils.h"
#include "nsError.h"
#include "nsThreadUtils.h"
#include "nsDocShellCID.h"
#include "nsIContentSecurityPolicy.h"
#include "mozilla/Logging.h"
#include "nsCRT.h"
#include "nsContentCreatorFunctions.h"
#include "nsProxyRelease.h"
#include "nsSandboxFlags.h"
#include "nsContentTypeParser.h"
#include "nsINetworkPredictor.h"
#include "nsMimeTypes.h"
#include "mozilla/ConsoleReportCollector.h"
#include "mozilla/CycleCollectedJSContext.h"
#include "mozilla/LoadInfo.h"
#include "ReferrerInfo.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/Attributes.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/Telemetry.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/Unused.h"
#include "mozilla/Utf8.h" // mozilla::Utf8Unit
#include "nsIScriptError.h"
#include "nsIAsyncOutputStream.h"
using JS::SourceText;
using namespace JS::loader;
using mozilla::Telemetry::LABELS_DOM_SCRIPT_PRELOAD_RESULT;
namespace mozilla::dom {
LazyLogModule ScriptLoader::gCspPRLog("CSP");
LazyLogModule ScriptLoader::gScriptLoaderLog("ScriptLoader");
#undef LOG
#define LOG(args) \
MOZ_LOG(ScriptLoader::gScriptLoaderLog, mozilla::LogLevel::Debug, args)
#define LOG_ENABLED() \
MOZ_LOG_TEST(ScriptLoader::gScriptLoaderLog, mozilla::LogLevel::Debug)
// Alternate Data MIME type used by the ScriptLoader to register that we want to
// store bytecode without reading it.
static constexpr auto kNullMimeType = "javascript/null"_ns;
/////////////////////////////////////////////////////////////
// AsyncCompileShutdownObserver
/////////////////////////////////////////////////////////////
NS_IMPL_ISUPPORTS(AsyncCompileShutdownObserver, nsIObserver)
void AsyncCompileShutdownObserver::OnShutdown() {
if (mScriptLoader) {
mScriptLoader->Destroy();
MOZ_ASSERT(!mScriptLoader);
}
}
void AsyncCompileShutdownObserver::Unregister() {
if (mScriptLoader) {
mScriptLoader = nullptr;
nsContentUtils::UnregisterShutdownObserver(this);
}
}
NS_IMETHODIMP
AsyncCompileShutdownObserver::Observe(nsISupports* aSubject, const char* aTopic,
const char16_t* aData) {
OnShutdown();
return NS_OK;
}
//////////////////////////////////////////////////////////////
// ScriptLoader::PreloadInfo
//////////////////////////////////////////////////////////////
inline void ImplCycleCollectionUnlink(ScriptLoader::PreloadInfo& aField) {
ImplCycleCollectionUnlink(aField.mRequest);
}
inline void ImplCycleCollectionTraverse(
nsCycleCollectionTraversalCallback& aCallback,
ScriptLoader::PreloadInfo& aField, const char* aName, uint32_t aFlags = 0) {
ImplCycleCollectionTraverse(aCallback, aField.mRequest, aName, aFlags);
}
//////////////////////////////////////////////////////////////
// ScriptLoader
//////////////////////////////////////////////////////////////
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(ScriptLoader)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTION(ScriptLoader, mNonAsyncExternalScriptInsertedRequests,
mLoadingAsyncRequests, mLoadedAsyncRequests,
mOffThreadCompilingRequests, mDeferRequests,
mXSLTRequests, mParserBlockingRequest,
mBytecodeEncodingQueue, mPreloads,
mPendingChildLoaders, mModuleLoader,
mWebExtModuleLoaders, mShadowRealmModuleLoaders)
NS_IMPL_CYCLE_COLLECTING_ADDREF(ScriptLoader)
NS_IMPL_CYCLE_COLLECTING_RELEASE(ScriptLoader)
ScriptLoader::ScriptLoader(Document* aDocument)
: mDocument(aDocument),
mParserBlockingBlockerCount(0),
mBlockerCount(0),
mNumberOfProcessors(0),
mTotalFullParseSize(0),
mPhysicalSizeOfMemory(-1),
mEnabled(true),
mDeferEnabled(false),
mSpeculativeOMTParsingEnabled(false),
mDeferCheckpointReached(false),
mBlockingDOMContentLoaded(false),
mLoadEventFired(false),
mGiveUpEncoding(false),
mReporter(new ConsoleReportCollector()) {
LOG(("ScriptLoader::ScriptLoader %p", this));
mSpeculativeOMTParsingEnabled = StaticPrefs::
dom_script_loader_external_scripts_speculative_omt_parse_enabled();
mShutdownObserver = new AsyncCompileShutdownObserver(this);
nsContentUtils::RegisterShutdownObserver(mShutdownObserver);
}
ScriptLoader::~ScriptLoader() {
LOG(("ScriptLoader::~ScriptLoader %p", this));
mObservers.Clear();
if (mParserBlockingRequest) {
FireScriptAvailable(NS_ERROR_ABORT, mParserBlockingRequest);
}
for (ScriptLoadRequest* req = mXSLTRequests.getFirst(); req;
req = req->getNext()) {
FireScriptAvailable(NS_ERROR_ABORT, req);
}
for (ScriptLoadRequest* req = mDeferRequests.getFirst(); req;
req = req->getNext()) {
FireScriptAvailable(NS_ERROR_ABORT, req);
}
for (ScriptLoadRequest* req = mLoadingAsyncRequests.getFirst(); req;
req = req->getNext()) {
FireScriptAvailable(NS_ERROR_ABORT, req);
}
for (ScriptLoadRequest* req = mLoadedAsyncRequests.getFirst(); req;
req = req->getNext()) {
FireScriptAvailable(NS_ERROR_ABORT, req);
}
for (ScriptLoadRequest* req =
mNonAsyncExternalScriptInsertedRequests.getFirst();
req; req = req->getNext()) {
FireScriptAvailable(NS_ERROR_ABORT, req);
}
// Unblock the kids, in case any of them moved to a different document
// subtree in the meantime and therefore aren't actually going away.
for (uint32_t j = 0; j < mPendingChildLoaders.Length(); ++j) {
mPendingChildLoaders[j]->RemoveParserBlockingScriptExecutionBlocker();
}
for (size_t i = 0; i < mPreloads.Length(); i++) {
AccumulateCategorical(LABELS_DOM_SCRIPT_PRELOAD_RESULT::NotUsed);
}
if (mShutdownObserver) {
mShutdownObserver->Unregister();
mShutdownObserver = nullptr;
}
mModuleLoader = nullptr;
}
void ScriptLoader::SetGlobalObject(nsIGlobalObject* aGlobalObject) {
if (!aGlobalObject) {
// The document is being detached.
return;
}
MOZ_ASSERT(!HasPendingRequests());
if (mModuleLoader) {
MOZ_ASSERT(mModuleLoader->GetGlobalObject() == aGlobalObject);
return;
}
// The module loader is associated with a global object, so don't create it
// until we have a global set.
mModuleLoader = new ModuleLoader(this, aGlobalObject, ModuleLoader::Normal);
}
void ScriptLoader::RegisterContentScriptModuleLoader(ModuleLoader* aLoader) {
MOZ_ASSERT(aLoader);
MOZ_ASSERT(aLoader->GetScriptLoader() == this);
mWebExtModuleLoaders.AppendElement(aLoader);
}
void ScriptLoader::RegisterShadowRealmModuleLoader(ModuleLoader* aLoader) {
MOZ_ASSERT(aLoader);
MOZ_ASSERT(aLoader->GetScriptLoader() == this);
mShadowRealmModuleLoaders.AppendElement(aLoader);
}
// Collect telemtry data about the cache information, and the kind of source
// which are being loaded, and where it is being loaded from.
static void CollectScriptTelemetry(ScriptLoadRequest* aRequest) {
using namespace mozilla::Telemetry;
MOZ_ASSERT(aRequest->IsFetching());
// Skip this function if we are not running telemetry.
if (!CanRecordExtended()) {
return;
}
// Report the script kind.
if (aRequest->IsModuleRequest()) {
AccumulateCategorical(LABELS_DOM_SCRIPT_KIND::ModuleScript);
} else {
AccumulateCategorical(LABELS_DOM_SCRIPT_KIND::ClassicScript);
}
// Report the type of source. This is used to monitor the status of the
// JavaScript Start-up Bytecode Cache, with the expectation of an almost zero
// source-fallback and alternate-data being roughtly equal to source loads.
if (aRequest->mFetchSourceOnly) {
if (aRequest->GetScriptLoadContext()->mIsInline) {
AccumulateCategorical(LABELS_DOM_SCRIPT_LOADING_SOURCE::Inline);
} else if (aRequest->IsTextSource()) {
AccumulateCategorical(LABELS_DOM_SCRIPT_LOADING_SOURCE::SourceFallback);
}
} else {
if (aRequest->IsTextSource()) {
AccumulateCategorical(LABELS_DOM_SCRIPT_LOADING_SOURCE::Source);
} else if (aRequest->IsBytecode()) {
AccumulateCategorical(LABELS_DOM_SCRIPT_LOADING_SOURCE::AltData);
}
}
}
// Helper method for checking if the script element is an event-handler
// This means that it has both a for-attribute and a event-attribute.
// Also, if the for-attribute has a value that matches "\s*window\s*",
// and the event-attribute matches "\s*onload([ \(].*)?" then it isn't an
// eventhandler. (both matches are case insensitive).
// This is how IE seems to filter out a window's onload handler from a
// <script for=... event=...> element.
static bool IsScriptEventHandler(ScriptKind kind, nsIContent* aScriptElement) {
if (kind != ScriptKind::eClassic) {
return false;
}
if (!aScriptElement->IsHTMLElement()) {
return false;
}
nsAutoString forAttr, eventAttr;
if (!aScriptElement->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::_for,
forAttr) ||
!aScriptElement->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::event,
eventAttr)) {
return false;
}
const nsAString& for_str =
nsContentUtils::TrimWhitespace<nsCRT::IsAsciiSpace>(forAttr);
if (!for_str.LowerCaseEqualsLiteral("window")) {
return true;
}
// We found for="window", now check for event="onload".
const nsAString& event_str =
nsContentUtils::TrimWhitespace<nsCRT::IsAsciiSpace>(eventAttr, false);
if (!StringBeginsWith(event_str, u"onload"_ns,
nsCaseInsensitiveStringComparator)) {
// It ain't "onload.*".
return true;
}
nsAutoString::const_iterator start, end;
event_str.BeginReading(start);
event_str.EndReading(end);
start.advance(6); // advance past "onload"
if (start != end && *start != '(' && *start != ' ') {
// We got onload followed by something other than space or
// '('. Not good enough.
return true;
}
return false;
}
nsContentPolicyType ScriptLoadRequestToContentPolicyType(
ScriptLoadRequest* aRequest) {
if (aRequest->GetScriptLoadContext()->IsPreload()) {
return aRequest->IsModuleRequest()
? nsIContentPolicy::TYPE_INTERNAL_MODULE_PRELOAD
: nsIContentPolicy::TYPE_INTERNAL_SCRIPT_PRELOAD;
}
return aRequest->IsModuleRequest() ? nsIContentPolicy::TYPE_INTERNAL_MODULE
: nsIContentPolicy::TYPE_INTERNAL_SCRIPT;
}
nsresult ScriptLoader::CheckContentPolicy(Document* aDocument,
nsISupports* aContext,
const nsAString& aType,
ScriptLoadRequest* aRequest) {
nsContentPolicyType contentPolicyType =
ScriptLoadRequestToContentPolicyType(aRequest);
nsCOMPtr<nsINode> requestingNode = do_QueryInterface(aContext);
nsCOMPtr<nsILoadInfo> secCheckLoadInfo = new net::LoadInfo(
aDocument->NodePrincipal(), // loading principal
aDocument->NodePrincipal(), // triggering principal
requestingNode, nsILoadInfo::SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK,
contentPolicyType);
// snapshot the nonce at load start time for performing CSP checks
if (contentPolicyType == nsIContentPolicy::TYPE_INTERNAL_SCRIPT ||
contentPolicyType == nsIContentPolicy::TYPE_INTERNAL_MODULE) {
nsCOMPtr<nsINode> node = do_QueryInterface(aContext);
if (node) {
nsString* cspNonce =
static_cast<nsString*>(node->GetProperty(nsGkAtoms::nonce));
if (cspNonce) {
secCheckLoadInfo->SetCspNonce(*cspNonce);
}
}
}
int16_t shouldLoad = nsIContentPolicy::ACCEPT;
nsresult rv = NS_CheckContentLoadPolicy(
aRequest->mURI, secCheckLoadInfo, NS_LossyConvertUTF16toASCII(aType),
&shouldLoad, nsContentUtils::GetContentPolicy());
if (NS_FAILED(rv) || NS_CP_REJECTED(shouldLoad)) {
if (NS_FAILED(rv) || shouldLoad != nsIContentPolicy::REJECT_TYPE) {
return NS_ERROR_CONTENT_BLOCKED;
}
return NS_ERROR_CONTENT_BLOCKED_SHOW_ALT;
}
return NS_OK;
}
/* static */
bool ScriptLoader::IsAboutPageLoadingChromeURI(ScriptLoadRequest* aRequest,
Document* aDocument) {
// if the uri to be loaded is not of scheme chrome:, there is nothing to do.
if (!aRequest->mURI->SchemeIs("chrome")) {
return false;
}
// we can either get here with a regular contentPrincipal or with a
// NullPrincipal in case we are showing an error page in a sandboxed iframe.
// In either case if the about: page is linkable from content, there is
// nothing to do.
uint32_t aboutModuleFlags = 0;
nsresult rv = NS_OK;
nsCOMPtr<nsIPrincipal> triggeringPrincipal = aRequest->TriggeringPrincipal();
if (triggeringPrincipal->GetIsContentPrincipal()) {
if (!triggeringPrincipal->SchemeIs("about")) {
return false;
}
rv = triggeringPrincipal->GetAboutModuleFlags(&aboutModuleFlags);
NS_ENSURE_SUCCESS(rv, false);
} else if (triggeringPrincipal->GetIsNullPrincipal()) {
nsCOMPtr<nsIURI> docURI = aDocument->GetDocumentURI();
if (!docURI->SchemeIs("about")) {
return false;
}
nsCOMPtr<nsIAboutModule> aboutModule;
rv = NS_GetAboutModule(docURI, getter_AddRefs(aboutModule));
if (NS_FAILED(rv) || !aboutModule) {
return false;
}
rv = aboutModule->GetURIFlags(docURI, &aboutModuleFlags);
NS_ENSURE_SUCCESS(rv, false);
} else {
return false;
}
if (aboutModuleFlags & nsIAboutModule::MAKE_LINKABLE) {
return false;
}
// seems like an about page wants to load a chrome URI.
return true;
}
nsIURI* ScriptLoader::GetBaseURI() const {
MOZ_ASSERT(mDocument);
return mDocument->GetDocBaseURI();
}
class ScriptRequestProcessor : public Runnable {
private:
RefPtr<ScriptLoader> mLoader;
RefPtr<ScriptLoadRequest> mRequest;
public:
ScriptRequestProcessor(ScriptLoader* aLoader, ScriptLoadRequest* aRequest)
: Runnable("dom::ScriptRequestProcessor"),
mLoader(aLoader),
mRequest(aRequest) {}
NS_IMETHOD Run() override { return mLoader->ProcessRequest(mRequest); }
};
void ScriptLoader::RunScriptWhenSafe(ScriptLoadRequest* aRequest) {
auto* runnable = new ScriptRequestProcessor(this, aRequest);
nsContentUtils::AddScriptRunner(runnable);
}
nsresult ScriptLoader::RestartLoad(ScriptLoadRequest* aRequest) {
MOZ_ASSERT(aRequest->IsBytecode());
aRequest->mScriptBytecode.clearAndFree();
TRACE_FOR_TEST(aRequest->GetScriptLoadContext()->GetScriptElement(),
"scriptloader_fallback");
// Notify preload restart so that we can register this preload request again.
aRequest->GetScriptLoadContext()->NotifyRestart(mDocument);
// Start a new channel from which we explicitly request to stream the source
// instead of the bytecode.
aRequest->mFetchSourceOnly = true;
nsresult rv;
if (aRequest->IsModuleRequest()) {
rv = aRequest->AsModuleRequest()->RestartModuleLoad();
} else {
rv = StartLoad(aRequest, 0);
}
if (NS_FAILED(rv)) {
return rv;
}
// Close the current channel and this ScriptLoadHandler as we created a new
// one for the same request.
return NS_BINDING_RETARGETED;
}
nsresult ScriptLoader::StartLoad(ScriptLoadRequest* aRequest,
uint64_t aEarlyHintPreloaderId) {
if (aRequest->IsModuleRequest()) {
return aRequest->AsModuleRequest()->StartModuleLoad();
}
return StartClassicLoad(aRequest, aEarlyHintPreloaderId);
}
nsresult ScriptLoader::StartClassicLoad(ScriptLoadRequest* aRequest,
uint64_t aEarlyHintPreloaderId) {
MOZ_ASSERT(aRequest->IsFetching());
NS_ENSURE_TRUE(mDocument, NS_ERROR_NULL_POINTER);
aRequest->SetUnknownDataType();
// If this document is sandboxed without 'allow-scripts', abort.
if (mDocument->HasScriptsBlockedBySandbox()) {
return NS_OK;
}
if (LOG_ENABLED()) {
nsAutoCString url;
aRequest->mURI->GetAsciiSpec(url);
LOG(("ScriptLoadRequest (%p): Start Classic Load (url = %s)", aRequest,
url.get()));
}
nsSecurityFlags securityFlags =
nsContentSecurityManager::ComputeSecurityFlags(
aRequest->CORSMode(), nsContentSecurityManager::CORSSecurityMapping::
CORS_NONE_MAPS_TO_DISABLED_CORS_CHECKS);
securityFlags |= nsILoadInfo::SEC_ALLOW_CHROME;
nsresult rv =
StartLoadInternal(aRequest, securityFlags, aEarlyHintPreloaderId);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
static bool IsWebExtensionRequest(ScriptLoadRequest* aRequest) {
if (!aRequest->IsModuleRequest()) {
return false;
}
ModuleLoader* loader =
ModuleLoader::From(aRequest->AsModuleRequest()->mLoader);
return loader->GetKind() == ModuleLoader::WebExtension;
}
nsresult ScriptLoader::StartLoadInternal(ScriptLoadRequest* aRequest,
nsSecurityFlags securityFlags,
uint64_t aEarlyHintPreloaderId) {
nsContentPolicyType contentPolicyType =
ScriptLoadRequestToContentPolicyType(aRequest);
nsCOMPtr<nsINode> context;
if (aRequest->GetScriptLoadContext()->GetScriptElement()) {
context =
do_QueryInterface(aRequest->GetScriptLoadContext()->GetScriptElement());
} else {
context = mDocument;
}
nsCOMPtr<nsILoadGroup> loadGroup = mDocument->GetDocumentLoadGroup();
nsCOMPtr<nsPIDOMWindowOuter> window = mDocument->GetWindow();
NS_ENSURE_TRUE(window, NS_ERROR_NULL_POINTER);
nsIDocShell* docshell = window->GetDocShell();
nsCOMPtr<nsIInterfaceRequestor> prompter(do_QueryInterface(docshell));
nsCOMPtr<nsIChannel> channel;
nsresult rv = NS_NewChannelWithTriggeringPrincipal(
getter_AddRefs(channel), aRequest->mURI, context,
aRequest->TriggeringPrincipal(), securityFlags, contentPolicyType,
nullptr, // aPerformanceStorage
loadGroup, prompter);
NS_ENSURE_SUCCESS(rv, rv);
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);
}
// snapshot the nonce at load start time for performing CSP checks
if (contentPolicyType == nsIContentPolicy::TYPE_INTERNAL_SCRIPT ||
contentPolicyType == nsIContentPolicy::TYPE_INTERNAL_MODULE) {
if (context) {
nsString* cspNonce =
static_cast<nsString*>(context->GetProperty(nsGkAtoms::nonce));
if (cspNonce) {
nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
loadInfo->SetCspNonce(*cspNonce);
}
}
}
nsCOMPtr<nsIScriptGlobalObject> scriptGlobal = GetScriptGlobalObject();
if (!scriptGlobal) {
return NS_ERROR_FAILURE;
}
// To avoid decoding issues, the build-id is part of the bytecode MIME type
// constant.
aRequest->mCacheInfo = nullptr;
nsCOMPtr<nsICacheInfoChannel> cic(do_QueryInterface(channel));
if (cic && StaticPrefs::dom_script_loader_bytecode_cache_enabled()) {
MOZ_ASSERT(!IsWebExtensionRequest(aRequest),
"Can not bytecode cache WebExt code");
if (!aRequest->mFetchSourceOnly) {
// Inform the HTTP cache that we prefer to have information coming from
// the bytecode cache instead of the sources, if such entry is already
// registered.
LOG(("ScriptLoadRequest (%p): Maybe request bytecode", aRequest));
cic->PreferAlternativeDataType(
BytecodeMimeTypeFor(aRequest), ""_ns,
nsICacheInfoChannel::PreferredAlternativeDataDeliveryType::ASYNC);
} else {
// If we are explicitly loading from the sources, such as after a
// restarted request, we might still want to save the bytecode after.
//
// The following tell the cache to look for an alternative data type which
// does not exist, such that we can later save the bytecode with a
// different alternative data type.
LOG(("ScriptLoadRequest (%p): Request saving bytecode later", aRequest));
cic->PreferAlternativeDataType(
kNullMimeType, ""_ns,
nsICacheInfoChannel::PreferredAlternativeDataDeliveryType::ASYNC);
}
}
LOG(("ScriptLoadRequest (%p): mode=%u tracking=%d", aRequest,
unsigned(aRequest->GetScriptLoadContext()->mScriptMode),
aRequest->GetScriptLoadContext()->IsTracking()));
if (aRequest->GetScriptLoadContext()->IsLinkPreloadScript()) {
// This is <link rel="preload" as="script"> initiated speculative load,
// put it to the group that is not blocked by leaders and doesn't block
// follower at the same time. Giving it a much higher priority will make
// this request be processed ahead of other Unblocked requests, but with
// the same weight as Leaders. This will make us behave similar way for
// both http2 and http1.
ScriptLoadContext::PrioritizeAsPreload(channel);
ScriptLoadContext::AddLoadBackgroundFlag(channel);
} else if (nsCOMPtr<nsIClassOfService> cos = do_QueryInterface(channel)) {
if (aRequest->GetScriptLoadContext()->mScriptFromHead &&
aRequest->GetScriptLoadContext()->IsBlockingScript()) {
// synchronous head scripts block loading of most other non js/css
// content such as images, Leader implicitely disallows tailing
cos->AddClassFlags(nsIClassOfService::Leader);
} else if (aRequest->GetScriptLoadContext()->IsDeferredScript() &&
!StaticPrefs::network_http_tailing_enabled()) {
// Bug 1395525 and the !StaticPrefs::network_http_tailing_enabled() bit:
// We want to make sure that turing tailing off by the pref makes the
// browser behave exactly the same way as before landing the tailing
// patch.
// head/body deferred scripts are blocked by leaders but are not
// allowed tailing because they block DOMContentLoaded
cos->AddClassFlags(nsIClassOfService::TailForbidden);
} else {
// other scripts (=body sync or head/body async) are neither blocked
// nor prioritized
cos->AddClassFlags(nsIClassOfService::Unblocked);
if (aRequest->GetScriptLoadContext()->IsAsyncScript()) {
// async scripts are allowed tailing, since those and only those
// don't block DOMContentLoaded; this flag doesn't enforce tailing,
// just overweights the Unblocked flag when the channel is found
// to be a thrird-party tracker and thus set the Tail flag to engage
// tailing.
cos->AddClassFlags(nsIClassOfService::TailAllowed);
}
}
}
nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(channel));
if (httpChannel) {
// HTTP content negotation has little value in this context.
nsAutoCString acceptTypes("*/*");
rv = httpChannel->SetRequestHeader("Accept"_ns, acceptTypes, false);
MOZ_ASSERT(NS_SUCCEEDED(rv));
nsCOMPtr<nsIReferrerInfo> referrerInfo =
new ReferrerInfo(aRequest->mReferrer, aRequest->ReferrerPolicy());
rv = httpChannel->SetReferrerInfoWithoutClone(referrerInfo);
MOZ_ASSERT(NS_SUCCEEDED(rv));
nsCOMPtr<nsIHttpChannelInternal> internalChannel(
do_QueryInterface(httpChannel));
if (internalChannel) {
rv = internalChannel->SetIntegrityMetadata(
aRequest->mIntegrity.GetIntegrityString());
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
}
mozilla::net::PredictorLearn(
aRequest->mURI, mDocument->GetDocumentURI(),
nsINetworkPredictor::LEARN_LOAD_SUBRESOURCE,
mDocument->NodePrincipal()->OriginAttributesRef());
// Set the initiator type
nsCOMPtr<nsITimedChannel> timedChannel(do_QueryInterface(httpChannel));
if (timedChannel) {
if (aEarlyHintPreloaderId) {
timedChannel->SetInitiatorType(u"early-hints"_ns);
} else if (aRequest->GetScriptLoadContext()->IsLinkPreloadScript()) {
timedChannel->SetInitiatorType(u"link"_ns);
} else {
timedChannel->SetInitiatorType(u"script"_ns);
}
}
UniquePtr<mozilla::dom::SRICheckDataVerifier> sriDataVerifier;
if (!aRequest->mIntegrity.IsEmpty()) {
nsAutoCString sourceUri;
if (mDocument->GetDocumentURI()) {
mDocument->GetDocumentURI()->GetAsciiSpec(sourceUri);
}
sriDataVerifier = MakeUnique<SRICheckDataVerifier>(aRequest->mIntegrity,
sourceUri, mReporter);
}
RefPtr<ScriptLoadHandler> handler =
new ScriptLoadHandler(this, aRequest, std::move(sriDataVerifier));
nsCOMPtr<nsIIncrementalStreamLoader> loader;
rv = NS_NewIncrementalStreamLoader(getter_AddRefs(loader), handler);
NS_ENSURE_SUCCESS(rv, rv);
auto key = PreloadHashKey::CreateAsScript(
aRequest->mURI, aRequest->CORSMode(), aRequest->mKind);
aRequest->GetScriptLoadContext()->NotifyOpen(
key, channel, mDocument,
aRequest->GetScriptLoadContext()->IsLinkPreloadScript());
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(loader);
if (NS_FAILED(rv)) {
// Make sure to inform any <link preload> tags about failure to load the
// resource.
aRequest->GetScriptLoadContext()->NotifyStart(channel);
aRequest->GetScriptLoadContext()->NotifyStop(rv);
}
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
bool ScriptLoader::PreloadURIComparator::Equals(const PreloadInfo& aPi,
nsIURI* const& aURI) const {
bool same;
return NS_SUCCEEDED(aPi.mRequest->mURI->Equals(aURI, &same)) && same;
}
static bool CSPAllowsInlineScript(nsIScriptElement* aElement,
Document* aDocument) {
nsCOMPtr<nsIContentSecurityPolicy> csp = aDocument->GetCsp();
if (!csp) {
// no CSP --> allow
return true;
}
// query the nonce
nsCOMPtr<Element> scriptContent = do_QueryInterface(aElement);
nsAutoString nonce;
if (scriptContent) {
nsString* cspNonce =
static_cast<nsString*>(scriptContent->GetProperty(nsGkAtoms::nonce));
if (cspNonce) {
nonce = *cspNonce;
}
}
bool parserCreated =
aElement->GetParserCreated() != mozilla::dom::NOT_FROM_PARSER;
bool allowInlineScript = false;
nsresult rv = csp->GetAllowsInline(
nsIContentSecurityPolicy::SCRIPT_SRC_ELEM_DIRECTIVE,
false /* aHasUnsafeHash */, nonce, parserCreated, scriptContent,
nullptr /* nsICSPEventListener */, u""_ns,
aElement->GetScriptLineNumber(), aElement->GetScriptColumnNumber(),
&allowInlineScript);
return NS_SUCCEEDED(rv) && allowInlineScript;
}
already_AddRefed<ScriptLoadRequest> ScriptLoader::CreateLoadRequest(
ScriptKind aKind, nsIURI* aURI, nsIScriptElement* aElement,
nsIPrincipal* aTriggeringPrincipal, CORSMode aCORSMode,
const SRIMetadata& aIntegrity, ReferrerPolicy aReferrerPolicy) {
nsIURI* referrer = mDocument->GetDocumentURIAsReferrer();
nsCOMPtr<Element> domElement = do_QueryInterface(aElement);
RefPtr<ScriptFetchOptions> fetchOptions = new ScriptFetchOptions(
aCORSMode, aReferrerPolicy, aTriggeringPrincipal, domElement);
RefPtr<ScriptLoadContext> context = new ScriptLoadContext();
if (aKind == ScriptKind::eClassic || aKind == ScriptKind::eImportMap) {
RefPtr<ScriptLoadRequest> aRequest = new ScriptLoadRequest(
aKind, aURI, fetchOptions, aIntegrity, referrer, context);
return aRequest.forget();
}
MOZ_ASSERT(aKind == ScriptKind::eModule);
RefPtr<ModuleLoadRequest> aRequest = ModuleLoader::CreateTopLevel(
aURI, fetchOptions, aIntegrity, referrer, this, context);
return aRequest.forget();
}
bool ScriptLoader::ProcessScriptElement(nsIScriptElement* aElement) {
// We need a document to evaluate scripts.
NS_ENSURE_TRUE(mDocument, false);
// Check to see if scripts has been turned off.
if (!mEnabled || !mDocument->IsScriptEnabled()) {
return false;
}
NS_ASSERTION(!aElement->IsMalformed(), "Executing malformed script");
nsCOMPtr<nsIContent> scriptContent = do_QueryInterface(aElement);
nsAutoString type;
bool hasType = aElement->GetScriptType(type);
ScriptKind scriptKind;
if (aElement->GetScriptIsModule()) {
scriptKind = ScriptKind::eModule;
} else if (aElement->GetScriptIsImportMap()) {
scriptKind = ScriptKind::eImportMap;
} else {
scriptKind = ScriptKind::eClassic;
}
// Step 13. Check that the script is not an eventhandler
if (IsScriptEventHandler(scriptKind, scriptContent)) {
return false;
}
// For classic scripts, check the type attribute to determine language and
// version. If type exists, it trumps the deprecated 'language='
if (scriptKind == ScriptKind::eClassic) {
if (!type.IsEmpty()) {
NS_ENSURE_TRUE(nsContentUtils::IsJavascriptMIMEType(type), false);
} else if (!hasType) {
// no 'type=' element
// "language" is a deprecated attribute of HTML, so we check it only for
// HTML script elements.
if (scriptContent->IsHTMLElement()) {
nsAutoString language;
scriptContent->AsElement()->GetAttr(kNameSpaceID_None,
nsGkAtoms::language, language);
if (!language.IsEmpty()) {
if (!nsContentUtils::IsJavaScriptLanguage(language)) {
return false;
}
}
}
}
}
// "In modern user agents that support module scripts, the script element with
// the nomodule attribute will be ignored".
// "The nomodule attribute must not be specified on module scripts (and will
// be ignored if it is)."
if (mDocument->ModuleScriptsEnabled() && scriptKind == ScriptKind::eClassic &&
scriptContent->IsHTMLElement() &&
scriptContent->AsElement()->HasAttr(kNameSpaceID_None,
nsGkAtoms::nomodule)) {
return false;
}
// Step 15. and later in the HTML5 spec
if (aElement->GetScriptExternal()) {
return ProcessExternalScript(aElement, scriptKind, type, scriptContent);
}
return ProcessInlineScript(aElement, scriptKind);
}
bool ScriptLoader::ProcessExternalScript(nsIScriptElement* aElement,
ScriptKind aScriptKind,
const nsAutoString& aTypeAttr,
nsIContent* aScriptContent) {
LOG(("ScriptLoader (%p): Process external script for element %p", this,
aElement));
// https://html.spec.whatwg.org/multipage/scripting.html#prepare-the-script-element
// Step 30.1. If el's type is "importmap", then queue an element task on the
// DOM manipulation task source given el to fire an event named error at el,
// and return.
if (aScriptKind == ScriptKind::eImportMap) {
NS_DispatchToCurrentThread(
NewRunnableMethod("nsIScriptElement::FireErrorEvent", aElement,
&nsIScriptElement::FireErrorEvent));
nsContentUtils::ReportToConsole(
nsIScriptError::warningFlag, "Script Loader"_ns, mDocument,
nsContentUtils::eDOM_PROPERTIES, "ImportMapExternalNotSupported");
return false;
}
nsCOMPtr<nsIURI> scriptURI = aElement->GetScriptURI();
if (!scriptURI) {
// Asynchronously report the failure to create a URI object
NS_DispatchToCurrentThread(
NewRunnableMethod("nsIScriptElement::FireErrorEvent", aElement,
&nsIScriptElement::FireErrorEvent));
return false;
}
SRIMetadata sriMetadata;
{
nsAutoString integrity;
aScriptContent->AsElement()->GetAttr(kNameSpaceID_None,
nsGkAtoms::integrity, integrity);
GetSRIMetadata(integrity, &sriMetadata);
}
RefPtr<ScriptLoadRequest> request =
LookupPreloadRequest(aElement, aScriptKind, sriMetadata);
if (request &&
NS_FAILED(CheckContentPolicy(mDocument, aElement, aTypeAttr, request))) {
LOG(("ScriptLoader (%p): content policy check failed for preload", this));
// Probably plans have changed; even though the preload was allowed seems
// like the actual load is not; let's cancel the preload request.
request->Cancel();
AccumulateCategorical(LABELS_DOM_SCRIPT_PRELOAD_RESULT::RejectedByPolicy);
return false;
}
if (request) {
// Use the preload request.
LOG(("ScriptLoadRequest (%p): Using preload request", request.get()));
// https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-module-script-tree
// Step 1. Disallow further import maps given settings object.
if (request->IsModuleRequest()) {
LOG(("ScriptLoadRequest (%p): Disallow further import maps.",
request.get()));
mModuleLoader->DisallowImportMaps();
}
// It's possible these attributes changed since we started the preload so
// update them here.
request->GetScriptLoadContext()->SetScriptMode(
aElement->GetScriptDeferred(), aElement->GetScriptAsync(), false);
// The request will be added to another list or set as