This repository has been archived by the owner on Aug 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathScriptLoader.cpp
3081 lines (2659 loc) · 101 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 "ScriptLoadRequest.h"
#include "ScriptTrace.h"
#include "ModuleLoadRequest.h"
#include "ModuleScript.h"
#include "prsystem.h"
#include "jsapi.h"
#include "jsfriendapi.h"
#include "js/Utility.h"
#include "xpcpublic.h"
#include "nsCycleCollectionParticipant.h"
#include "nsIContent.h"
#include "nsJSUtils.h"
#include "mozilla/dom/DocGroup.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/SRILogHelper.h"
#include "nsGkAtoms.h"
#include "nsNetUtil.h"
#include "nsIScriptGlobalObject.h"
#include "nsIScriptContext.h"
#include "nsIScriptSecurityManager.h"
#include "nsIPrincipal.h"
#include "nsJSPrincipals.h"
#include "nsContentPolicyUtils.h"
#include "nsIHttpChannel.h"
#include "nsIHttpChannelInternal.h"
#include "nsIClassOfService.h"
#include "nsICacheInfoChannel.h"
#include "nsITimedChannel.h"
#include "nsIScriptElement.h"
#include "nsIDOMHTMLScriptElement.h"
#include "nsIDocShell.h"
#include "nsContentUtils.h"
#include "nsUnicharUtils.h"
#include "nsAutoPtr.h"
#include "nsIXPConnect.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 "mozilla/ConsoleReportCollector.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/Attributes.h"
#include "mozilla/Telemetry.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/Unused.h"
#include "nsIScriptError.h"
#include "nsIOutputStream.h"
using JS::SourceBufferHolder;
namespace mozilla {
namespace dom {
LazyLogModule ScriptLoader::gCspPRLog("CSP");
LazyLogModule ScriptLoader::gScriptLoaderLog("ScriptLoader");
#define LOG(args) \
MOZ_LOG(gScriptLoaderLog, mozilla::LogLevel::Debug, args)
// Alternate Data MIME type used by the ScriptLoader to register that we want to
// store bytecode without reading it.
static NS_NAMED_LITERAL_CSTRING(kNullMimeType, "javascript/null");
//////////////////////////////////////////////////////////////
// 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,
mDeferRequests,
mXSLTRequests,
mParserBlockingRequest,
mPreloads,
mPendingChildLoaders,
mFetchedModules)
NS_IMPL_CYCLE_COLLECTING_ADDREF(ScriptLoader)
NS_IMPL_CYCLE_COLLECTING_RELEASE(ScriptLoader)
ScriptLoader::ScriptLoader(nsIDocument *aDocument)
: mDocument(aDocument),
mParserBlockingBlockerCount(0),
mBlockerCount(0),
mNumberOfProcessors(0),
mEnabled(true),
mDeferEnabled(false),
mDocumentParsingDone(false),
mBlockingDOMContentLoaded(false),
mLoadEventFired(false),
mReporter(new ConsoleReportCollector())
{
}
ScriptLoader::~ScriptLoader()
{
mObservers.Clear();
if (mParserBlockingRequest) {
mParserBlockingRequest->FireScriptAvailable(NS_ERROR_ABORT);
}
for (ScriptLoadRequest* req = mXSLTRequests.getFirst(); req;
req = req->getNext()) {
req->FireScriptAvailable(NS_ERROR_ABORT);
}
for (ScriptLoadRequest* req = mDeferRequests.getFirst(); req;
req = req->getNext()) {
req->FireScriptAvailable(NS_ERROR_ABORT);
}
for (ScriptLoadRequest* req = mLoadingAsyncRequests.getFirst(); req;
req = req->getNext()) {
req->FireScriptAvailable(NS_ERROR_ABORT);
}
for (ScriptLoadRequest* req = mLoadedAsyncRequests.getFirst(); req;
req = req->getNext()) {
req->FireScriptAvailable(NS_ERROR_ABORT);
}
for(ScriptLoadRequest* req = mNonAsyncExternalScriptInsertedRequests.getFirst();
req;
req = req->getNext()) {
req->FireScriptAvailable(NS_ERROR_ABORT);
}
// 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();
}
}
// 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(nsIIncrementalStreamLoader* aLoader,
ScriptLoadRequest* aRequest)
{
using namespace mozilla::Telemetry;
// Skip this function if we are not running telemetry.
if (!CanRecordExtended()) {
return;
}
// Report the type of source, as well as the size of the source.
if (aRequest->IsLoadingSource()) {
if (aRequest->mIsInline) {
AccumulateCategorical(LABELS_DOM_SCRIPT_LOADING_SOURCE::Inline);
nsAutoString inlineData;
aRequest->mElement->GetScriptText(inlineData);
Accumulate(DOM_SCRIPT_INLINE_SIZE, inlineData.Length());
} else {
AccumulateCategorical(LABELS_DOM_SCRIPT_LOADING_SOURCE::SourceFallback);
Accumulate(DOM_SCRIPT_SOURCE_SIZE, aRequest->mScriptText.length());
}
} else {
MOZ_ASSERT(aRequest->IsLoading());
if (aRequest->IsSource()) {
AccumulateCategorical(LABELS_DOM_SCRIPT_LOADING_SOURCE::Source);
Accumulate(DOM_SCRIPT_SOURCE_SIZE, aRequest->mScriptText.length());
} else {
MOZ_ASSERT(aRequest->IsBytecode());
AccumulateCategorical(LABELS_DOM_SCRIPT_LOADING_SOURCE::AltData);
Accumulate(DOM_SCRIPT_BYTECODE_SIZE, aRequest->mScriptBytecode.length());
}
}
// Skip if we do not have any cache information for the given script.
if (!aLoader) {
return;
}
nsCOMPtr<nsIRequest> channel;
aLoader->GetRequest(getter_AddRefs(channel));
nsCOMPtr<nsICacheInfoChannel> cic(do_QueryInterface(channel));
if (!cic) {
return;
}
int32_t fetchCount = 0;
if (NS_SUCCEEDED(cic->GetCacheTokenFetchCount(&fetchCount))) {
Accumulate(DOM_SCRIPT_FETCH_COUNT, fetchCount);
}
}
// 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(nsIContent* aScriptElement)
{
if (!aScriptElement->IsHTMLElement()) {
return false;
}
nsAutoString forAttr, eventAttr;
if (!aScriptElement->GetAttr(kNameSpaceID_None, nsGkAtoms::_for, forAttr) ||
!aScriptElement->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, NS_LITERAL_STRING("onload"),
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;
}
nsresult
ScriptLoader::CheckContentPolicy(nsIDocument* aDocument,
nsISupports* aContext,
nsIURI* aURI,
const nsAString& aType,
bool aIsPreLoad)
{
nsContentPolicyType contentPolicyType = aIsPreLoad
? nsIContentPolicy::TYPE_INTERNAL_SCRIPT_PRELOAD
: nsIContentPolicy::TYPE_INTERNAL_SCRIPT;
int16_t shouldLoad = nsIContentPolicy::ACCEPT;
nsresult rv = NS_CheckContentLoadPolicy(contentPolicyType,
aURI,
aDocument->NodePrincipal(),
aContext,
NS_LossyConvertUTF16toASCII(aType),
nullptr, //extra
&shouldLoad,
nsContentUtils::GetContentPolicy(),
nsContentUtils::GetSecurityManager());
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;
}
bool
ScriptLoader::ModuleScriptsEnabled()
{
static bool sEnabledForContent = false;
static bool sCachedPref = false;
if (!sCachedPref) {
sCachedPref = true;
Preferences::AddBoolVarCache(&sEnabledForContent, "dom.moduleScripts.enabled", false);
}
return nsContentUtils::IsChromeDoc(mDocument) || sEnabledForContent;
}
bool
ScriptLoader::ModuleMapContainsModule(ModuleLoadRequest* aRequest) const
{
// Returns whether we have fetched, or are currently fetching, a module script
// for the request's URL.
return mFetchingModules.Contains(aRequest->mURI) ||
mFetchedModules.Contains(aRequest->mURI);
}
bool
ScriptLoader::IsFetchingModule(ModuleLoadRequest* aRequest) const
{
bool fetching = mFetchingModules.Contains(aRequest->mURI);
MOZ_ASSERT_IF(fetching, !mFetchedModules.Contains(aRequest->mURI));
return fetching;
}
void
ScriptLoader::SetModuleFetchStarted(ModuleLoadRequest* aRequest)
{
// Update the module map to indicate that a module is currently being fetched.
MOZ_ASSERT(aRequest->IsLoading());
MOZ_ASSERT(!ModuleMapContainsModule(aRequest));
mFetchingModules.Put(aRequest->mURI, nullptr);
}
void
ScriptLoader::SetModuleFetchFinishedAndResumeWaitingRequests(ModuleLoadRequest* aRequest,
nsresult aResult)
{
// Update module map with the result of fetching a single module script. The
// module script pointer is nullptr on error.
MOZ_ASSERT(!aRequest->IsReadyToRun());
RefPtr<GenericPromise::Private> promise;
MOZ_ALWAYS_TRUE(mFetchingModules.Remove(aRequest->mURI, getter_AddRefs(promise)));
RefPtr<ModuleScript> ms(aRequest->mModuleScript);
MOZ_ASSERT(NS_SUCCEEDED(aResult) == (ms != nullptr));
mFetchedModules.Put(aRequest->mURI, ms);
if (promise) {
if (ms) {
promise->Resolve(true, __func__);
} else {
promise->Reject(aResult, __func__);
}
}
}
RefPtr<GenericPromise>
ScriptLoader::WaitForModuleFetch(ModuleLoadRequest* aRequest)
{
MOZ_ASSERT(ModuleMapContainsModule(aRequest));
if (auto entry = mFetchingModules.Lookup(aRequest->mURI)) {
if (!entry.Data()) {
entry.Data() = new GenericPromise::Private(__func__);
}
return entry.Data();
}
RefPtr<ModuleScript> ms;
MOZ_ALWAYS_TRUE(mFetchedModules.Get(aRequest->mURI, getter_AddRefs(ms)));
if (!ms || ms->InstantiationFailed()) {
return GenericPromise::CreateAndReject(NS_ERROR_FAILURE, __func__);
}
return GenericPromise::CreateAndResolve(true, __func__);
}
ModuleScript*
ScriptLoader::GetFetchedModule(nsIURI* aURL) const
{
bool found;
ModuleScript* ms = mFetchedModules.GetWeak(aURL, &found);
MOZ_ASSERT(found);
return ms;
}
nsresult
ScriptLoader::ProcessFetchedModuleSource(ModuleLoadRequest* aRequest)
{
MOZ_ASSERT(!aRequest->mModuleScript);
nsresult rv = CreateModuleScript(aRequest);
SetModuleFetchFinishedAndResumeWaitingRequests(aRequest, rv);
aRequest->mScriptText.clearAndFree();
if (NS_SUCCEEDED(rv)) {
StartFetchingModuleDependencies(aRequest);
}
return rv;
}
nsresult
ScriptLoader::CreateModuleScript(ModuleLoadRequest* aRequest)
{
MOZ_ASSERT(!aRequest->mModuleScript);
MOZ_ASSERT(aRequest->mBaseURL);
nsCOMPtr<nsIScriptGlobalObject> globalObject = GetScriptGlobalObject();
if (!globalObject) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIScriptContext> context = globalObject->GetScriptContext();
if (!context) {
return NS_ERROR_FAILURE;
}
nsAutoMicroTask mt;
AutoEntryScript aes(globalObject, "CompileModule", true);
bool oldProcessingScriptTag = context->GetProcessingScriptTag();
context->SetProcessingScriptTag(true);
nsresult rv;
{
// Update our current script.
AutoCurrentScriptUpdater scriptUpdater(this, aRequest->mElement);
JSContext* cx = aes.cx();
JS::Rooted<JSObject*> module(cx);
if (aRequest->mWasCompiledOMT) {
module = JS::FinishOffThreadModule(cx, aRequest->mOffThreadToken);
aRequest->mOffThreadToken = nullptr;
rv = module ? NS_OK : NS_ERROR_FAILURE;
} else {
JS::Rooted<JSObject*> global(cx, globalObject->GetGlobalJSObject());
JS::CompileOptions options(cx);
rv = FillCompileOptionsForRequest(aes, aRequest, global, &options);
if (NS_SUCCEEDED(rv)) {
nsAutoString inlineData;
SourceBufferHolder srcBuf = GetScriptSource(aRequest, inlineData);
rv = nsJSUtils::CompileModule(cx, srcBuf, global, options, &module);
}
}
MOZ_ASSERT(NS_SUCCEEDED(rv) == (module != nullptr));
if (module) {
aRequest->mModuleScript =
new ModuleScript(this, aRequest->mBaseURL, module);
}
}
context->SetProcessingScriptTag(oldProcessingScriptTag);
return rv;
}
static bool
ThrowTypeError(JSContext* aCx, ModuleScript* aScript,
const nsString& aMessage)
{
JS::Rooted<JSObject*> module(aCx, aScript->ModuleRecord());
JS::Rooted<JSScript*> script(aCx, JS::GetModuleScript(aCx, module));
JS::Rooted<JSString*> filename(aCx);
filename = JS_NewStringCopyZ(aCx, JS_GetScriptFilename(script));
if (!filename) {
return false;
}
JS::Rooted<JSString*> message(aCx, JS_NewUCStringCopyZ(aCx, aMessage.get()));
if (!message) {
return false;
}
JS::Rooted<JS::Value> error(aCx);
if (!JS::CreateError(aCx, JSEXN_TYPEERR, nullptr, filename, 0, 0, nullptr,
message, &error)) {
return false;
}
JS_SetPendingException(aCx, error);
return false;
}
static bool
HandleResolveFailure(JSContext* aCx, ModuleScript* aScript,
const nsAString& aSpecifier)
{
// TODO: How can we get the line number of the failed import?
nsAutoString message(NS_LITERAL_STRING("Error resolving module specifier: "));
message.Append(aSpecifier);
return ThrowTypeError(aCx, aScript, message);
}
static bool
HandleModuleNotFound(JSContext* aCx, ModuleScript* aScript,
const nsAString& aSpecifier)
{
// TODO: How can we get the line number of the failed import?
nsAutoString message(NS_LITERAL_STRING("Resolved module not found in map: "));
message.Append(aSpecifier);
return ThrowTypeError(aCx, aScript, message);
}
static already_AddRefed<nsIURI>
ResolveModuleSpecifier(ModuleScript* aScript,
const nsAString& aSpecifier)
{
// The following module specifiers are allowed by the spec:
// - a valid absolute URL
// - a valid relative URL that starts with "/", "./" or "../"
//
// Bareword module specifiers are currently disallowed as these may be given
// special meanings in the future.
nsCOMPtr<nsIURI> uri;
nsresult rv = NS_NewURI(getter_AddRefs(uri), aSpecifier);
if (NS_SUCCEEDED(rv)) {
return uri.forget();
}
if (rv != NS_ERROR_MALFORMED_URI) {
return nullptr;
}
if (!StringBeginsWith(aSpecifier, NS_LITERAL_STRING("/")) &&
!StringBeginsWith(aSpecifier, NS_LITERAL_STRING("./")) &&
!StringBeginsWith(aSpecifier, NS_LITERAL_STRING("../"))) {
return nullptr;
}
rv = NS_NewURI(getter_AddRefs(uri), aSpecifier, nullptr, aScript->BaseURL());
if (NS_SUCCEEDED(rv)) {
return uri.forget();
}
return nullptr;
}
static nsresult
RequestedModuleIsInAncestorList(ModuleLoadRequest* aRequest, nsIURI* aURL, bool* aResult)
{
const size_t ImportDepthLimit = 100;
*aResult = false;
size_t depth = 0;
while (aRequest) {
if (depth++ == ImportDepthLimit) {
return NS_ERROR_FAILURE;
}
bool equal;
nsresult rv = aURL->Equals(aRequest->mURI, &equal);
NS_ENSURE_SUCCESS(rv, rv);
if (equal) {
*aResult = true;
return NS_OK;
}
aRequest = aRequest->mParent;
}
return NS_OK;
}
static nsresult
ResolveRequestedModules(ModuleLoadRequest* aRequest, nsCOMArray<nsIURI>& aUrls)
{
ModuleScript* ms = aRequest->mModuleScript;
AutoJSAPI jsapi;
if (!jsapi.Init(ms->ModuleRecord())) {
return NS_ERROR_FAILURE;
}
JSContext* cx = jsapi.cx();
JS::Rooted<JSObject*> moduleRecord(cx, ms->ModuleRecord());
JS::Rooted<JSObject*> specifiers(cx, JS::GetRequestedModules(cx, moduleRecord));
uint32_t length;
if (!JS_GetArrayLength(cx, specifiers, &length)) {
return NS_ERROR_FAILURE;
}
JS::Rooted<JS::Value> val(cx);
for (uint32_t i = 0; i < length; i++) {
if (!JS_GetElement(cx, specifiers, i, &val)) {
return NS_ERROR_FAILURE;
}
nsAutoJSString specifier;
if (!specifier.init(cx, val)) {
return NS_ERROR_FAILURE;
}
// Let url be the result of resolving a module specifier given module script and requested.
ModuleScript* ms = aRequest->mModuleScript;
nsCOMPtr<nsIURI> uri = ResolveModuleSpecifier(ms, specifier);
if (!uri) {
HandleResolveFailure(cx, ms, specifier);
return NS_ERROR_FAILURE;
}
bool isAncestor;
nsresult rv = RequestedModuleIsInAncestorList(aRequest, uri, &isAncestor);
NS_ENSURE_SUCCESS(rv, rv);
if (!isAncestor) {
aUrls.AppendElement(uri.forget());
}
}
return NS_OK;
}
void
ScriptLoader::StartFetchingModuleDependencies(ModuleLoadRequest* aRequest)
{
MOZ_ASSERT(aRequest->mModuleScript);
MOZ_ASSERT(!aRequest->mModuleScript->InstantiationFailed());
MOZ_ASSERT(!aRequest->IsReadyToRun());
aRequest->mProgress = ModuleLoadRequest::Progress::FetchingImports;
nsCOMArray<nsIURI> urls;
nsresult rv = ResolveRequestedModules(aRequest, urls);
if (NS_FAILED(rv)) {
aRequest->LoadFailed();
return;
}
if (urls.Length() == 0) {
// There are no descendents to load so this request is ready.
aRequest->DependenciesLoaded();
return;
}
// For each url in urls, fetch a module script tree given url, module script's
// CORS setting, and module script's settings object.
nsTArray<RefPtr<GenericPromise>> importsReady;
for (size_t i = 0; i < urls.Length(); i++) {
RefPtr<GenericPromise> childReady =
StartFetchingModuleAndDependencies(aRequest, urls[i]);
importsReady.AppendElement(childReady);
}
// Wait for all imports to become ready.
RefPtr<GenericPromise::AllPromiseType> allReady =
GenericPromise::All(GetMainThreadSerialEventTarget(), importsReady);
allReady->Then(GetMainThreadSerialEventTarget(), __func__, aRequest,
&ModuleLoadRequest::DependenciesLoaded,
&ModuleLoadRequest::LoadFailed);
}
RefPtr<GenericPromise>
ScriptLoader::StartFetchingModuleAndDependencies(ModuleLoadRequest* aRequest,
nsIURI* aURI)
{
MOZ_ASSERT(aURI);
RefPtr<ModuleLoadRequest> childRequest =
new ModuleLoadRequest(aRequest->mElement, aRequest->mJSVersion,
aRequest->mCORSMode, aRequest->mIntegrity, this);
childRequest->mIsTopLevel = false;
childRequest->mURI = aURI;
childRequest->mIsInline = false;
childRequest->mReferrerPolicy = aRequest->mReferrerPolicy;
childRequest->mParent = aRequest;
RefPtr<GenericPromise> ready = childRequest->mReady.Ensure(__func__);
nsresult rv = StartLoad(childRequest);
if (NS_FAILED(rv)) {
childRequest->mReady.Reject(rv, __func__);
return ready;
}
aRequest->mImports.AppendElement(childRequest);
return ready;
}
bool
HostResolveImportedModule(JSContext* aCx, unsigned argc, JS::Value* vp)
{
MOZ_ASSERT(argc == 2);
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::Rooted<JSObject*> module(aCx, &args[0].toObject());
JS::Rooted<JSString*> specifier(aCx, args[1].toString());
// Let referencing module script be referencingModule.[[HostDefined]].
JS::Value value = JS::GetModuleHostDefinedField(module);
auto script = static_cast<ModuleScript*>(value.toPrivate());
MOZ_ASSERT(script->ModuleRecord() == module);
// Let url be the result of resolving a module specifier given referencing
// module script and specifier. If the result is failure, throw a TypeError
// exception and abort these steps.
nsAutoJSString string;
if (!string.init(aCx, specifier)) {
return false;
}
nsCOMPtr<nsIURI> uri = ResolveModuleSpecifier(script, string);
if (!uri) {
return HandleResolveFailure(aCx, script, string);
}
// Let resolved module script be the value of the entry in module map whose
// key is url. If no such entry exists, throw a TypeError exception and abort
// these steps.
ModuleScript* ms = script->Loader()->GetFetchedModule(uri);
if (!ms) {
return HandleModuleNotFound(aCx, script, string);
}
if (ms->InstantiationFailed()) {
JS::Rooted<JS::Value> exception(aCx, ms->Exception());
JS_SetPendingException(aCx, exception);
return false;
}
*vp = JS::ObjectValue(*ms->ModuleRecord());
return true;
}
static nsresult
EnsureModuleResolveHook(JSContext* aCx)
{
if (JS::GetModuleResolveHook(aCx)) {
return NS_OK;
}
JS::Rooted<JSFunction*> func(aCx);
func = JS_NewFunction(aCx, HostResolveImportedModule, 2, 0,
"HostResolveImportedModule");
if (!func) {
return NS_ERROR_FAILURE;
}
JS::SetModuleResolveHook(aCx, func);
return NS_OK;
}
void
ScriptLoader::ProcessLoadedModuleTree(ModuleLoadRequest* aRequest)
{
if (aRequest->IsTopLevel()) {
MaybeMoveToLoadedList(aRequest);
ProcessPendingRequests();
}
if (aRequest->mWasCompiledOMT) {
mDocument->UnblockOnload(false);
}
}
bool
ScriptLoader::InstantiateModuleTree(ModuleLoadRequest* aRequest)
{
// Perform eager instantiation of the loaded module tree.
MOZ_ASSERT(aRequest);
ModuleScript* ms = aRequest->mModuleScript;
MOZ_ASSERT(ms);
if (!ms->ModuleRecord()) {
return false;
}
AutoJSAPI jsapi;
if (NS_WARN_IF(!jsapi.Init(ms->ModuleRecord()))) {
return false;
}
nsresult rv = EnsureModuleResolveHook(jsapi.cx());
NS_ENSURE_SUCCESS(rv, false);
JS::Rooted<JSObject*> module(jsapi.cx(), ms->ModuleRecord());
bool ok = NS_SUCCEEDED(nsJSUtils::ModuleDeclarationInstantiation(jsapi.cx(), module));
JS::RootedValue exception(jsapi.cx());
if (!ok) {
MOZ_ASSERT(jsapi.HasException());
if (!jsapi.StealException(&exception)) {
return false;
}
MOZ_ASSERT(!exception.isUndefined());
}
// Mark this module and any uninstantiated dependencies found via depth-first
// search as instantiated and record any error.
mozilla::Vector<ModuleLoadRequest*, 1> requests;
if (!requests.append(aRequest)) {
return false;
}
while (!requests.empty()) {
ModuleLoadRequest* request = requests.popCopy();
ModuleScript* ms = request->mModuleScript;
if (!ms->IsUninstantiated()) {
continue;
}
ms->SetInstantiationResult(exception);
for (auto import : request->mImports) {
if (import->mModuleScript->IsUninstantiated() &&
!requests.append(import))
{
return false;
}
}
}
return true;
}
nsresult
ScriptLoader::RestartLoad(ScriptLoadRequest* aRequest)
{
MOZ_ASSERT(aRequest->IsBytecode());
aRequest->mScriptBytecode.clearAndFree();
TRACE_FOR_TEST(aRequest->mElement, "scriptloader_fallback");
// Start a new channel from which we explicitly request to stream the source
// instead of the bytecode.
aRequest->mProgress = ScriptLoadRequest::Progress::Loading_Source;
nsresult rv = StartLoad(aRequest);
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)
{
MOZ_ASSERT(aRequest->IsLoading());
NS_ENSURE_TRUE(mDocument, NS_ERROR_NULL_POINTER);
aRequest->mDataType = ScriptLoadRequest::DataType::Unknown;
// If this document is sandboxed without 'allow-scripts', abort.
if (mDocument->HasScriptsBlockedBySandbox()) {
return NS_OK;
}
if (aRequest->IsModuleRequest()) {
// Check whether the module has been fetched or is currently being fetched,
// and if so wait for it.
ModuleLoadRequest* request = aRequest->AsModuleRequest();
if (ModuleMapContainsModule(request)) {
WaitForModuleFetch(request)
->Then(GetMainThreadSerialEventTarget(), __func__, request,
&ModuleLoadRequest::ModuleLoaded,
&ModuleLoadRequest::LoadFailed);
return NS_OK;
}
// Otherwise put the URL in the module map and mark it as fetching.
SetModuleFetchStarted(request);
}
nsContentPolicyType contentPolicyType = aRequest->IsPreload()
? nsIContentPolicy::TYPE_INTERNAL_SCRIPT_PRELOAD
: nsIContentPolicy::TYPE_INTERNAL_SCRIPT;
nsCOMPtr<nsINode> context;
if (aRequest->mElement) {
context = do_QueryInterface(aRequest->mElement);
}
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));
nsSecurityFlags securityFlags;
if (aRequest->IsModuleRequest()) {
// According to the spec, module scripts have different behaviour to classic
// scripts and always use CORS.
securityFlags = nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS;
if (aRequest->mCORSMode == CORS_NONE) {
securityFlags |= nsILoadInfo::SEC_COOKIES_OMIT;
} else if (aRequest->mCORSMode == CORS_ANONYMOUS) {
securityFlags |= nsILoadInfo::SEC_COOKIES_SAME_ORIGIN;
} else {
MOZ_ASSERT(aRequest->mCORSMode == CORS_USE_CREDENTIALS);
securityFlags |= nsILoadInfo::SEC_COOKIES_INCLUDE;
}
} else {
securityFlags = aRequest->mCORSMode == CORS_NONE
? nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL
: nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS;
if (aRequest->mCORSMode == CORS_ANONYMOUS) {
securityFlags |= nsILoadInfo::SEC_COOKIES_SAME_ORIGIN;
} else if (aRequest->mCORSMode == CORS_USE_CREDENTIALS) {
securityFlags |= nsILoadInfo::SEC_COOKIES_INCLUDE;
}
}
securityFlags |= nsILoadInfo::SEC_ALLOW_CHROME;
nsCOMPtr<nsIChannel> channel;
nsresult rv = NS_NewChannel(getter_AddRefs(channel),
aRequest->mURI,
context,
securityFlags,
contentPolicyType,
loadGroup,
prompter,
nsIRequest::LOAD_NORMAL |
nsIChannel::LOAD_CLASSIFY_URI);
NS_ENSURE_SUCCESS(rv, rv);
// To avoid decoding issues, the JSVersion is explicitly guarded here, and the
// build-id is part of the JSBytecodeMimeType constant.
aRequest->mCacheInfo = nullptr;
nsCOMPtr<nsICacheInfoChannel> cic(do_QueryInterface(channel));
if (cic && nsContentUtils::IsBytecodeCacheEnabled() &&
aRequest->mJSVersion == JSVERSION_DEFAULT) {
if (!aRequest->IsLoadingSource()) {
// 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(nsContentUtils::JSBytecodeMimeType());
} 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);
}
}
nsIScriptElement* script = aRequest->mElement;
nsCOMPtr<nsIClassOfService> cos(do_QueryInterface(channel));
if (cos) {
if (aRequest->mScriptFromHead &&
!(script && (script->GetScriptAsync() || script->GetScriptDeferred()))) {
// synchronous head scripts block loading of most other non js/css
// content such as images
cos->AddClassFlags(nsIClassOfService::Leader);
} else if (!(script && script->GetScriptDeferred())) {
// other scripts are neither blocked nor prioritized unless marked deferred
cos->AddClassFlags(nsIClassOfService::Unblocked);
}
}
nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(channel));
if (httpChannel) {
// HTTP content negotation has little value in this context.
rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Accept"),
NS_LITERAL_CSTRING("*/*"),
false);
MOZ_ASSERT(NS_SUCCEEDED(rv));
rv = httpChannel->SetReferrerWithPolicy(mDocument->GetDocumentURI(),
aRequest->mReferrerPolicy);
MOZ_ASSERT(NS_SUCCEEDED(rv));