File: ModuleLoader.cpp

package info (click to toggle)
firefox 144.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,637,504 kB
  • sloc: cpp: 7,576,692; javascript: 6,430,831; ansic: 3,748,119; python: 1,398,978; xml: 628,810; asm: 438,679; java: 186,194; sh: 63,212; makefile: 19,159; objc: 13,086; perl: 12,986; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; exp: 762; php: 436; lisp: 258; awk: 247; sql: 66; sed: 53; csh: 10
file content (432 lines) | stat: -rw-r--r-- 15,577 bytes parent folder | download | duplicates (2)
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
/* -*- 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 "ModuleLoader.h"

#include "GeckoProfiler.h"
#include "ScriptLoader.h"
#include "js/CompileOptions.h"  // JS::CompileOptions, JS::InstantiateOptions
#include "js/ContextOptions.h"  // JS::ContextOptionsRef
#include "js/MemoryFunctions.h"
#include "js/Modules.h"  // JS::FinishDynamicModuleImport, JS::{G,S}etModuleResolveHook, JS::Get{ModulePrivate,ModuleScript,RequestedModule{s,Specifier,SourcePos}}, JS::SetModule{DynamicImport,Metadata}Hook
#include "js/PropertyAndElement.h"  // JS_DefineProperty
#include "js/Realm.h"
#include "js/SourceText.h"
#include "js/experimental/JSStencil.h"  // JS::Stencil, JS::CompileModuleScriptToStencil, JS::InstantiateModuleStencil
#include "js/friend/ErrorMessages.h"  // js::GetErrorMessage, JSMSG_*
#include "js/loader/LoadedScript.h"
#include "js/loader/ModuleLoadRequest.h"
#include "js/loader/ModuleLoaderBase.h"
#include "js/loader/ScriptLoadRequest.h"
#include "jsapi.h"
#include "mozilla/Assertions.h"
#include "mozilla/CycleCollectedJSContext.h"
#include "mozilla/LoadInfo.h"
#include "mozilla/Maybe.h"
#include "mozilla/dom/AutoEntryScript.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/RequestBinding.h"
#include "nsContentSecurityManager.h"
#include "nsError.h"
#include "nsIContent.h"
#include "nsIPrincipal.h"
#include "nsJSUtils.h"
#include "xpcpublic.h"

using JS::SourceText;
using namespace JS::loader;

namespace mozilla::dom {

#undef LOG
#define LOG(args) \
  MOZ_LOG(ScriptLoader::gScriptLoaderLog, mozilla::LogLevel::Debug, args)

#define LOG_ENABLED() \
  MOZ_LOG_TEST(ScriptLoader::gScriptLoaderLog, mozilla::LogLevel::Debug)

//////////////////////////////////////////////////////////////
// DOM module loader
//////////////////////////////////////////////////////////////

ModuleLoader::ModuleLoader(ScriptLoader* aLoader,
                           nsIGlobalObject* aGlobalObject, Kind aKind)
    : ModuleLoaderBase(aLoader, aGlobalObject), mKind(aKind) {}

ScriptLoader* ModuleLoader::GetScriptLoader() {
  return static_cast<ScriptLoader*>(mLoader.get());
}

bool ModuleLoader::CanStartLoad(ModuleLoadRequest* aRequest, nsresult* aRvOut) {
  if (!GetScriptLoader()->GetDocument()) {
    *aRvOut = NS_ERROR_NULL_POINTER;
    return false;
  }

  // If this document is sandboxed without 'allow-scripts', abort.
  if (GetScriptLoader()->GetDocument()->HasScriptsBlockedBySandbox()) {
    *aRvOut = NS_OK;
    return false;
  }

  // To prevent dynamic code execution, content scripts can only
  // load moz-extension URLs.
  nsCOMPtr<nsIPrincipal> principal = aRequest->TriggeringPrincipal();
  if (BasePrincipal::Cast(principal)->ContentScriptAddonPolicy() &&
      !aRequest->mURI->SchemeIs("moz-extension")) {
    *aRvOut = NS_ERROR_DOM_WEBEXT_CONTENT_SCRIPT_URI;
    return false;
  }

  if (LOG_ENABLED()) {
    nsAutoCString url;
    aRequest->mURI->GetAsciiSpec(url);
    LOG(("ScriptLoadRequest (%p): Start Module Load (url = %s)", aRequest,
         url.get()));
  }

  return true;
}

nsresult ModuleLoader::StartFetch(ModuleLoadRequest* aRequest) {
  if (aRequest->IsStencil()) {
    GetScriptLoader()->EmulateNetworkEvents(aRequest);
    SetModuleFetchStarted(aRequest);
    return aRequest->OnFetchComplete(NS_OK);
  }

  // According to the spec, module scripts have different behaviour to classic
  // scripts and always use CORS. Only exception: Non linkable about: pages
  // which load local module scripts.
  bool isAboutPageLoadingChromeURI = ScriptLoader::IsAboutPageLoadingChromeURI(
      aRequest, GetScriptLoader()->GetDocument());

  nsContentSecurityManager::CORSSecurityMapping corsMapping =
      isAboutPageLoadingChromeURI
          ? nsContentSecurityManager::CORSSecurityMapping::DISABLE_CORS_CHECKS
          : nsContentSecurityManager::CORSSecurityMapping::REQUIRE_CORS_CHECKS;

  nsSecurityFlags securityFlags =
      nsContentSecurityManager::ComputeSecurityFlags(aRequest->CORSMode(),
                                                     corsMapping);

  securityFlags |= nsILoadInfo::SEC_ALLOW_CHROME;

  // Delegate Shared Behavior to base ScriptLoader
  //
  // aCharsetForPreload is passed as Nothing() because this is not a preload
  // and `StartLoadInternal` is able to find the charset by using `aRequest`
  // for this case.
  nsresult rv = GetScriptLoader()->StartLoadInternal(
      aRequest, securityFlags, Nothing() /* aCharsetForPreload */);
  NS_ENSURE_SUCCESS(rv, rv);

  // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-an-import()-module-script-graph
  // Step 1. Disallow further import maps given settings object.
  if (!aRequest->GetScriptLoadContext()->IsPreload()) {
    LOG(("ScriptLoadRequest (%p): Disallow further import maps.", aRequest));
    DisallowImportMaps();
  }

  LOG(("ScriptLoadRequest (%p): Start fetching module", aRequest));

  return NS_OK;
}

void ModuleLoader::AsyncExecuteInlineModule(ModuleLoadRequest* aRequest) {
  MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(
      mozilla::NewRunnableMethod<RefPtr<ModuleLoadRequest>>(
          "ModuleLoader::ExecuteInlineModule", this,
          &ModuleLoader::ExecuteInlineModule, aRequest)));
}

void ModuleLoader::ExecuteInlineModule(ModuleLoadRequest* aRequest) {
  MOZ_ASSERT(aRequest->IsFinished());
  MOZ_ASSERT(aRequest->IsTopLevel());
  MOZ_ASSERT(aRequest->GetScriptLoadContext()->mIsInline);

  if (aRequest->GetScriptLoadContext()->GetParserCreated() == NOT_FROM_PARSER) {
    GetScriptLoader()->RunScriptWhenSafe(aRequest);
  } else {
    GetScriptLoader()->MaybeMoveToLoadedList(aRequest);
    GetScriptLoader()->ProcessPendingRequests();
  }

  aRequest->GetScriptLoadContext()->MaybeUnblockOnload();
}

void ModuleLoader::OnModuleLoadComplete(ModuleLoadRequest* aRequest) {
  MOZ_ASSERT(aRequest->IsFinished());

  if (aRequest->IsTopLevel()) {
    if (aRequest->GetScriptLoadContext()->mIsInline &&
        aRequest->GetScriptLoadContext()->GetParserCreated() ==
            NOT_FROM_PARSER) {
      // https://html.spec.whatwg.org/#prepare-the-script-element
      // Step 32.2.
      //    type: "module":
      //    3.1. Queue an element task on the networking task source given
      //         el to perform the following steps:
      //        1. Mark as ready el given result.
      //
      // Step 33. If ... el's type is "module":
      //    ...
      //    3. Otherwise, if el is not parser-inserted:
      //      3. Set el's steps to run when the result is ready to the
      //         following:
      //        ...
      //        2.1. Execute the script element scripts[0].
      AsyncExecuteInlineModule(aRequest);
      return;
    } else if (aRequest->GetScriptLoadContext()->mIsInline &&
               aRequest->GetScriptLoadContext()->GetParserCreated() !=
                   NOT_FROM_PARSER &&
               !nsContentUtils::IsSafeToRunScript()) {
      // Avoid giving inline async module scripts that don't have
      // external dependencies a guaranteed execution time relative
      // to the HTML parse. That is, deliberately avoid guaranteeing
      // that the script would always observe a DOM shape where the
      // parser has not added further elements to the DOM.
      // (If `nsContentUtils::IsSafeToRunScript()` returns `true`,
      // we come here synchronously from the parser. If it returns
      // `false` we come here from an external dependency completing
      // its fetch, in which case we already are at an unspecific
      // point relative to the parse.)
      AsyncExecuteInlineModule(aRequest);
      return;
    } else {
      GetScriptLoader()->MaybeMoveToLoadedList(aRequest);
      GetScriptLoader()->ProcessPendingRequestsAsync();
    }
  }

  aRequest->GetScriptLoadContext()->MaybeUnblockOnload();
}

nsresult ModuleLoader::CompileFetchedModule(
    JSContext* aCx, JS::Handle<JSObject*> aGlobal, JS::CompileOptions& aOptions,
    ModuleLoadRequest* aRequest, JS::MutableHandle<JSObject*> aModuleOut) {
  if (!nsJSUtils::IsScriptable(aGlobal)) {
    return NS_ERROR_FAILURE;
  }

  switch (aRequest->mModuleType) {
    case JS::ModuleType::Unknown:
      MOZ_CRASH("Unexpected module type");
    case JS::ModuleType::JavaScript:
      return CompileJavaScriptModule(aCx, aOptions, aRequest, aModuleOut);
    case JS::ModuleType::JSON: {
      return CompileJsonModule(aCx, aOptions, aRequest, aModuleOut);
    }
  }

  MOZ_CRASH("Unhandled module type");
}

nsresult ModuleLoader::CompileJavaScriptModule(
    JSContext* aCx, JS::CompileOptions& aOptions, ModuleLoadRequest* aRequest,
    JS::MutableHandle<JSObject*> aModuleOut) {
  GetScriptLoader()->CalculateCacheFlag(aRequest);

  if (aRequest->IsStencil()) {
    JS::InstantiateOptions instantiateOptions(aOptions);
    RefPtr<JS::Stencil> stencil = aRequest->GetStencil();
    aModuleOut.set(
        JS::InstantiateModuleStencil(aCx, instantiateOptions, stencil));
    if (!aModuleOut) {
      return NS_ERROR_FAILURE;
    }

    bool alreadyStarted;
    if (!JS::StartCollectingDelazifications(aCx, aModuleOut, stencil,
                                            alreadyStarted)) {
      return NS_ERROR_FAILURE;
    }
    (void)alreadyStarted;

    return NS_OK;
  }

  if (aRequest->GetScriptLoadContext()->mWasCompiledOMT) {
    JS::InstantiationStorage storage;
    RefPtr<JS::Stencil> stencil =
        aRequest->GetScriptLoadContext()->StealOffThreadResult(aCx, &storage);
    if (!stencil) {
      return NS_ERROR_FAILURE;
    }

    JS::InstantiateOptions instantiateOptions(aOptions);
    aModuleOut.set(JS::InstantiateModuleStencil(aCx, instantiateOptions,
                                                stencil, &storage));
    if (!aModuleOut) {
      return NS_ERROR_FAILURE;
    }

    if (aRequest->PassedConditionForCache()) {
      bool alreadyStarted;
      if (!JS::StartCollectingDelazifications(aCx, aModuleOut, stencil,
                                              alreadyStarted)) {
        return NS_ERROR_FAILURE;
      }
      MOZ_ASSERT(!alreadyStarted);
    }

    GetScriptLoader()->TryCacheRequest(aRequest, stencil);

    return NS_OK;
  }

  RefPtr<JS::Stencil> stencil;
  if (aRequest->IsTextSource()) {
    MaybeSourceText maybeSource;
    nsresult rv = aRequest->GetScriptSource(aCx, &maybeSource,
                                            aRequest->mLoadContext.get());
    NS_ENSURE_SUCCESS(rv, rv);

    auto compile = [&](auto& source) {
      return JS::CompileModuleScriptToStencil(aCx, aOptions, source);
    };
    stencil = maybeSource.mapNonEmpty(compile);
  } else {
    MOZ_ASSERT(aRequest->IsBytecode());
    JS::DecodeOptions decodeOptions(aOptions);
    decodeOptions.borrowBuffer = true;

    JS::TranscodeRange range = aRequest->Bytecode();
    JS::TranscodeResult tr =
        JS::DecodeStencil(aCx, decodeOptions, range, getter_AddRefs(stencil));
    if (tr != JS::TranscodeResult::Ok) {
      return NS_ERROR_DOM_JS_DECODING_ERROR;
    }
  }

  if (!stencil) {
    return NS_ERROR_FAILURE;
  }

  JS::InstantiateOptions instantiateOptions(aOptions);
  aModuleOut.set(
      JS::InstantiateModuleStencil(aCx, instantiateOptions, stencil));
  if (!aModuleOut) {
    return NS_ERROR_FAILURE;
  }

  if (aRequest->PassedConditionForCache()) {
    bool alreadyStarted;
    if (!JS::StartCollectingDelazifications(aCx, aModuleOut, stencil,
                                            alreadyStarted)) {
      return NS_ERROR_FAILURE;
    }
    MOZ_ASSERT(!alreadyStarted);
  }

  GetScriptLoader()->TryCacheRequest(aRequest, stencil);

  return NS_OK;
}

nsresult ModuleLoader::CompileJsonModule(
    JSContext* aCx, JS::CompileOptions& aOptions, ModuleLoadRequest* aRequest,
    JS::MutableHandle<JSObject*> aModuleOut) {
  MOZ_ASSERT(!aRequest->GetScriptLoadContext()->mWasCompiledOMT);

  MOZ_ASSERT(aRequest->IsTextSource());
  ModuleLoader::MaybeSourceText maybeSource;
  nsresult rv = aRequest->GetScriptSource(aCx, &maybeSource,
                                          aRequest->mLoadContext.get());
  NS_ENSURE_SUCCESS(rv, rv);

  auto compile = [&](auto& source) {
    return JS::CompileJsonModule(aCx, aOptions, source);
  };

  auto* jsonModule = maybeSource.mapNonEmpty(compile);
  if (!jsonModule) {
    return NS_ERROR_FAILURE;
  }

  aModuleOut.set(jsonModule);
  return NS_OK;
}

already_AddRefed<ModuleLoadRequest> ModuleLoader::CreateTopLevel(
    nsIURI* aURI, nsIScriptElement* aElement, ReferrerPolicy aReferrerPolicy,
    ScriptFetchOptions* aFetchOptions, const SRIMetadata& aIntegrity,
    nsIURI* aReferrer, ScriptLoadContext* aContext,
    ScriptLoadRequestType aRequestType) {
  RefPtr<ModuleLoadRequest> request =
      new ModuleLoadRequest(aURI, JS::ModuleType::JavaScript, aReferrerPolicy,
                            aFetchOptions, aIntegrity, aReferrer, aContext,
                            ModuleLoadRequest::Kind::TopLevel, this, nullptr);

  GetScriptLoader()->TryUseCache(request, aElement, aFetchOptions->mNonce,
                                 aRequestType);

  return request.forget();
}

already_AddRefed<ModuleLoadRequest> ModuleLoader::CreateRequest(
    JSContext* aCx, nsIURI* aURI, JS::Handle<JSObject*> aModuleRequest,
    JS::Handle<JS::Value> aHostDefined, JS::Handle<JS::Value> aPayload,
    bool aIsDynamicImport, ScriptFetchOptions* aOptions,
    ReferrerPolicy aReferrerPolicy, nsIURI* aBaseURL,
    const SRIMetadata& aSriMetadata) {
  RefPtr<ScriptLoadContext> context = new ScriptLoadContext();
  context->mIsInline = false;
  ModuleLoadRequest::Kind kind;
  ModuleLoadRequest* root = nullptr;
  if (aIsDynamicImport) {
    context->mScriptMode = ScriptLoadContext::ScriptMode::eAsync;
    kind = ModuleLoadRequest::Kind::DynamicImport;
  } else {
    MOZ_ASSERT(!aHostDefined.isUndefined());
    root = static_cast<ModuleLoadRequest*>(aHostDefined.toPrivate());
    MOZ_ASSERT(root);
    LoadContextBase* loadContext = root->mLoadContext;
    context->mScriptMode = loadContext->AsWindowContext()->mScriptMode;
    kind = ModuleLoadRequest::Kind::StaticImport;
  }

  JS::ModuleType moduleType = GetModuleRequestType(aCx, aModuleRequest);
  RefPtr<ModuleLoadRequest> request =
      new ModuleLoadRequest(aURI, moduleType, aReferrerPolicy, aOptions,
                            aSriMetadata, aBaseURL, context, kind, this, root);

  GetScriptLoader()->TryUseCache(request);

  return request.forget();
}

already_AddRefed<ScriptFetchOptions>
ModuleLoader::CreateDefaultScriptFetchOptions() {
  RefPtr<ScriptFetchOptions> options = ScriptFetchOptions::CreateDefault();
  nsCOMPtr<nsIPrincipal> principal = GetGlobalObject()->PrincipalOrNull();
  options->SetTriggeringPrincipal(principal);
  return options.forget();
}

nsIURI* ModuleLoader::GetClientReferrerURI() {
  Document* document = GetScriptLoader()->GetDocument();
#ifdef DEBUG
  nsCOMPtr<nsIPrincipal> principal = GetGlobalObject()->PrincipalOrNull();
#endif  // DEBUG
  MOZ_ASSERT_IF(GetKind() == WebExtension,
                BasePrincipal::Cast(principal)->ContentScriptAddonPolicy());
  MOZ_ASSERT_IF(GetKind() == Normal, principal == document->NodePrincipal());

  return document->GetDocBaseURI();
}

ModuleLoader::~ModuleLoader() {
  LOG(("ModuleLoader::~ModuleLoader %p", this));
  mLoader = nullptr;
}

#undef LOG
#undef LOG_ENABLED

}  // namespace mozilla::dom