mirror of
https://github.com/roytam1/palemoon27.git
synced 2026-05-26 22:48:57 +00:00
049b3235ac
- Bug 1207494 - Part 8: Remove use of expression closure from dom/identity/. r=ferjm (34fac889f8) - minor crash thing (13fe2827c2) - Bug 1243359 - initialize mScrollSeriesNumber in all ScrollWheelInput constructors. r=roc (94163d8eca) - fix misspatch (b380a7bbe4) - Bug 1207412 - Make SystemTimeConverter use TimeStamp::Now() when converting times; r=karlt (f408549605) - Bug 1212102 - Drop unnecessary assertion comparing timestamps in SystemTimeConverter; r=karlt (1efaa04b3f) - Bug 1241302 - Slightly modernize this code. r=jst (c1e97bc069) - bug 1216916 clean up when InvokeDragSessionWithImage/Selection() fails r=roc (9cdf71b717) - Bug 1231329 - run ConvertToUnscaledDevPixels if *aPresContext is valid. r=roc (d10f23633b) - Bug 1245927: Innerize before creating DOM files from the file picker. r=baku (8754128362) - Bug 1155214 - Mark nsIBidiKeyboard as builtinclass; r=mrbkap (2d00326d2b) - reorder (c3c1ba92c9) - Bug 1236566 - add override declarations for widget/windows/GfxInfo.h; r=roc (940b40ed91) - Bug 1242659: Part 1. More information on the mismatches. r=jrmuizel (78331ddad2) - Block some Radeon drivers that crash on D3D9. (bug 1213107, r=jrmuizel) (482b66d313) - Bug 1203199 - Blacklist DXVA on some older intel drivers for causing crashes. r=jrmuizel (f1827d4498) - Bug 1203199 - Fix driver range with blacklist to avoid blacklisting other OSes. (2c2d547296) - Bug 1203199 - Bustage fix. CLOSED TREE (3233d407f3) - Bug 1178385. Enable DXVA on the G45 r=ajones (3c59a58a15) - Bug 1188442 IMMHandler::GetSelection() should use static Selection instance when IME doesn't have focus and return its or mSelection's reference r=emk (5cc4b30433) - Bug 1238899 Create hidden native caret for ATOK at composing in windowless plugin r=m_kato (40ef5bb4aa) - Bug 1257919 part 1. Kill off nsIXSLTException. r=khuey (11f37643f2) - Bug 1242072 - Change implementation of BaseProxyHandler::get() to follow ES6 [[Get]] specification. r=jorendorff (094a67f284) - Bug 489636 - Add a GC u-bench test for property tree splitting via deletion; r=sfink (9282fec25f) - Bug 1257919 part 2. Make nsIException and nsIStackFrame builtinclass, so we can start using [implicit_jscontext] on them. r=khuey (0e65fb8554) - Bug 1257919 part 3. Make the various toString methods on exceptions take an explicit JSContext. r=khuey (b342fb4930) - Bug 1257919 part 4. Stop returning StackFrame instances from exceptions::CreateStack. C++ callers of GetCurrentJSStack or exceptions::CreateStack always check for null anyway, and none of them seem to want this non-JS thing. r=khuey (d34036ccf9) - Bug 1257919 part 5. Get rid of the now-unused StackFrame class. r=khuey (aa13af0dfe) - Bug 1141222 - Create ScriptError with stack from Cu.reportError. r=bholley (b83ad26aa0) - Bug 1208641 - Extract stack from DOM/XPC exception. r=bholley (e382b5f48c) - Bug 1254380 part 1. Find the relevant window when the compartment we've got is an addon sandbox compartment in AutoJSAPI exception/warning reporting code. r=bholley (4b1f6c64a9) - Bug 1250630 - remove PBackgroundTest and ifdef ENABLE_TEST blocks. r=khuey (d7b36860a3) - Bug 1250963 part 1. Change NotifyRunnable::Dispatch to not require a JSContext. r=khuey (48e03c2fc2) - Bug 1250963 part 2. Remove the unused JSContext argument of WorkerPrivate::ModifyBusyCount. r=khuey (0f5ca42be1) - Bug 1250291 part 1. Stop pretending to report exceptions in MainThreadStopSyncLoopRunnable::PostDispatch. r=khuey (6e1c81cc06) - Bug 1250291 part 2. Stop pretending to report exceptions in MainThreadWorkerSyncRunnable::PostDispatch. r=khuey (f3d846ea31) - Bug 1250291 part 3. Stop pretending to report exceptions in WorkerDebuggerRunnable::PostDispatch. r=khuey (10bc1710d1) - Bug 1250975. Stop passing a JSContext argument to WorkerRunnable::PreDispatch and its overrides. r=khuey (71ab9046f0) - Bug 1255298. Just pass through the JSContext when passing through the NotificationOptions in notification code. r=wchen (552ae8e33e) - Bug 1250185 part 2. Remove some JSContext stuff that's no longer needed in Notification code. r=khuey (20b99ef28b) - Bug 1251045 part 8. Remove the JSContext argument from some nsINotificationStorageCallback methods. r=khuey (170c4afabc) - Bug 1227015 P7 Supress unused ErrorResult exception if the worker runnable failed to dispatch. r=catalinb (23a3cc6f45) - Bug 1251045 part 3. Remove the JSContext argument of WorkerRunnable::PostDispatch and its overrides. r=khuey (6a666d1a4a) - Bug 1251045 part 2. Remove the JSContext argument of ModifyBusyCountFromWorker. r=khuey (105bc4f59e) - Bug 1252130. Remove unnecessary JSContext argument from NotificationWorkerRunnable::WorkerRunInternal. r=khuey (642727f6f6) - Bug 1252127. Remove unnecessary JSContext argument from PromiseWorkerProxy::CleanUp. r=khuey (339e1157d1) - Bug 1251045 part 1. Make it possible to dispatch a ModifyBusyCountRunnable without a JSContext. r=khuey (665c1f81b4) - Bug 1251045 part 4. Remove the JSContext argument of WorkerRunnable::Dispatch. r=khuey (6c5cdab2b7) - Bug 1250185 part 1. nsIStructuredCloneContainer.initFromBase64 doesn't need a JSContext argument. r=khuey (d63a219209) - fix (773c0393aa) - Bug 1251045 part 5. Remove the JSContext argument from WorkerPrivateParent::Freeze/Thaw. r=khuey (cd419bfd2c) - Bug 1251045 part 6. Remove the JSContext argument from some worker debugger methods that no longer need it. r=khuey (abcc437cb9) - Bug 1251045 part 7. Remove the JSContext argument from some worker methods that no longer need it. r=khuey (3ddcbca08c) - Bug 1249652 part 1. Add a method on ErrorResult to steal an exception, if any, from a JSContext. r=khuey (9c07f5044b) - Bug 1229071 - importScripts should throw the correct error result in case the loading of one of scripts fails, r=bz (cd37645d76) - Bug 1229970 Abort script loading start requests if a load has been canceled. r=khuey (a44d9128ca) - Bug 1233171 Cancel channel when ScriptLoader is aborted during service worker script load. r=khuey (3b6ceafec7) - Bug 1249351 part 1. When doing importScripts of multiple scripts in a service worker, make sure to track the cache streams per-loadinfo, instead of trying to make them all wait on the same stream. r=bkelly (e1ccea9685) - Bug 1157544 - Fix a typo in the test; r=baku (8c0bf8f504) - Bug 1249351 part 2. Clean up test_importscript.html and add multiple-url importScript() case. r=bz (52b0a31032) - Bug 1249652 part 2. ScriptExecutorRunnable::WorkerRun should immediately move JS exceptions to its ErrorResult instead of allowing them to linger on the JSContext. r=baku,khuey (f628d3c8ba) - Bug 1249652 part 3. Simplify way we handle canceling when ScriptLoaderRunnable::RunInternal fails by canceling things with its actual failure code, so we don't have to guess which failed loads are actual failures and which are just canceled via this mechanism. r=baku,khuey (388543fbc3) - Bug 1251369. Use an AutoJSAPI that reports its own exceptions around the main runloop in workers. r=khuey (28b33287cd) - Bug 1251518. Fix js::ErrorReportToString to make a bit more sense, and change worker code to not use it anyway, so it matches the mainthread code. r=bholley,terrence (a48a40de90) - Bug 1254380 part 2. Go ahead and log the stack from our exception in AutoJSAPI::ReportException even if we don't have a window. r=bholley (64532b6017) - Bug 1212328 - Clean up some JSErrorReport-related code. r=Waldo,bz (d5aa611edc) - Bug 1255192 part 1. Remove the JSContext argument of JS::ExceptionStackOrNull. r=bholley (39b631d5ad) - bug 1252687 - make the ctor for CycleCollectorStats constexpr r=mccr8 (9e8168d8ac) - Bug 1254380 part 3. Skip firing error events for mainthread out of memory exceptions via AutoJSAPI::ReportException. r=bholley (d5e4e7dc29) - Bug 1254230 kinda-fix. Make sure to never send script errors with stacks attached to the console service if the associated windows have already had FreeInnerObjects called on them. r=bholley (8c379fe0e0) - Bug 1255192 part 2. Clean up the JSContext usage around xpc::FindExceptionStackForConsoleReport now that it just needs a JSContext for rooting. r=bholley (cade862491) - Bug 1255201. Improve the stack handling in nsXPCComponents_Utils::ReportError for the DOMException case to include the stack from the DOMException. r=bholley (fc6c065284) - Bug 1257919 part 6. Make the filename getter on JSStackFrame take an explicit JSContext. r=khuey (cde115b789) - Bug 1257919 part 7. Make the name getter on JSStackFrame take an explicit JSContext. r=khuey (d7466e9eab) - Bug 1257919 part 8. Make the line/column number getters on JSStackFrame take an explicit JSContext. r=khuey (b8766b98b2) - Bug 1257919 part 9. Make the asyncCause/asyncCaller getters on JSStackFrame take an explicit JSContext. r=khuey (b776ff9c6d) - Bug 1257919 part 10. Make the caller and formattedStack getters on JSStackFrame take an explicit JSContext. r=khuey (dc4d3d9091) - Bug 1252091. Add/RemoveFeature don't need a JSContext argument. r=khuey (5be6253a67) - Bug 1252123. Remove some unnecessary JSContext arguments from worker ScriptLoader methods. r=khuey (1657a35268) - Bug 1255181. Remove AutoJSAPI::InitWithLegacyErrorReporting. r=bholley (5ee7ac506e) - Bug 1254847 part 1. Take ownership of error reporting on the AutoEntryScript in nsXPCWrappedJSClass::DelegatedQueryInterface. r=bholley (62d987b030) - make style wrong again.... (fa4e6cfbc1) - Bug 1254847 part 2. Change nsJSNPRuntime to always use AutoEntryScript and always take ownership of error reporting. r=bholley (d24cb80622) - Bug 1251655 - Remove support for JavaScript-global-constructor-prototype-alias. r=bz. (2b354ea423) - Bug 1251655 - Remove support for JavaScript-DOM-class and JavaScript-DOM-interface. r=bz. (dd6786ea57) - Bug 1251275. Switch to using an AutoEntryScript in WorkerPrivate::RunExpiredTimeouts. r=khuey (f10d1b0dec) - Bug 1072144 part 1. Just release-assert that Promise::Resolve does not fail in service worker code. It can only do that on OOM or overrecursion anyway, and overrecursion is not likely if we're coming right off a runnable. r=khuey (ba4c89a3bc) - Bug 1072144 part 2. When UnregisterWorker tries to ScheduleWorker and that throws, just suppress the exception: there is no good place to report it anyway. r=khuey (ca563ec5cd) - Bug 1072144 part 3. Hoist the exception reporting out of WorkerRunnable::PostRun into WorkerRunnable::Run and make it unconditional. r=khuey (9914acd4a6) - Bug 1252221. When GetOrCreateGlobalScope fails while trying to run a ScriptExecutorRunnable::WorkerRun, just suppress the exception, because there is no way to report it without a compartment to work with. r=khuey (abcc9df148) - Bug 1072144 part 4. Add a WorkerRunnable::PreRun so that we can move worker global creation to it and always have an AutoEntryScript by the time we're evaluating the main worker script. r=khuey (007b528868) - Bug 1251276 part 1. Change WorkerPrivate::CancelAllTimeouts to no longer call RunExpiredTimeouts. r=khuey (6b937370a1) - Bug 1251276 part 2. Remove the JSContext argument of WorkerPrivate::CancelAllTimeouts. r=khuey (336b788e03) - Bug 1251380. Change things so that WorkerPrivate::NotifyInternal (hopefully) never throws. r=khuey (1d4863f83a) - Bug 1254846. Add an AutoEntryScript constructor that takes a JSObject instead of an nsIGlobalObject, for convenience. r=bholley (693857f9b0) - Bug 1255706 part 1. Remove JSContext argument from WorkerPrivate constructor. r=khuey (0486bdb01c) - Bug 1255706 part 2. Remove JSContext argument from WorkerPrivate::Terminate. r=khuey (f0b62de092) - Bug 1257568. Remove the JSContext argument of WorkerPrivate::Kill. r=khuey (ebe7d247b5) - Bug 1252189. Remove the unnecessary JSContext argument from WorkerPrivate::FreezeInternal/ThawInternal. r=khuey (22b137b05e) - Bug 1119490 - Expose the URL constructor to WorkerDebuggerGlobalScope;r=khuey (6f4fc13e1e) - Bug 1241841 - Clear the worker's debugger event queue before destroying its context;r=khuey (a1e8dd4b2d) - Bug 1249950 - Add Performance Markers for MessagePort - patch 1 - remove non-useful 'explicit', r=smaug (8a014b53e6) - Bug 1249950 - Add Performance Markers for MessagePort - patch 2, r=smaug, r=vporof (560caf0ae1) - bug 1250486 - make the ComponentsSH ctor constexpr r=bz (1c441dbb0f) - Bug 1257032: Make files in dom/workers actually build without unification. r=baku (6ab4ae0b65) - Bug 1241522 - handle OOM in nsExpatDriver::HandleCharacterData; r=hsivonen (b652220cdc) - Bug 1219482: Replace PRLogModuleInfo with LazyLogModule in various files.r=benjamin (5fd5e8dbc8) - Bug 1238545 - Remove nsISimpleUnicharStreamFactory; r=froydnj (f0018c5b16) - Bug 1257335. Replace some AutoSafeJSContext uses with AutoJSAPI or AutoJSContext uses. r=bholley (7baf79deb7) - Bug 1247635 - Unify PostMessageRunnable and DispatchEventRunnable in MessagePort.cpp, r=smaug (df2765c215) - Bug 1250572 - Force a parent object in MessagePort/Channel and in StructuredCloneHolder, r=smaug (2a929d59d1) - Bug 1255375 - MessagePort should not leak if DispatchMessage() fails, r=smaug (0a5cdebfb0) - Bug 1251272. Remove the dead code in ReportErrorRunnable::ReportError that could fail, and make it infallible. r=khuey (89e80694d0) - Bug 1072144 part 5. Stop fiddling with compartments on the JSContext before calling PostRun in WorkerRunnable::Run. Add some documentation explaining what's going on. r=khuey (91f4bb6a7c) - Bug 1072144 part 6. Switch WorkerRunnable::Run to calling TakeOwnershipOfErrorReporting on its AutoJSAPI/AutoEntryScript and remove the remaining JS_ReportPendingException callers in worker code. r=khuey (405d9e0282) - Bug 1179548 - Close the windows opened in private browsing worker tests; r=baku (acf3430b69) - Bug 1179753 - Use pushPrefEnv more in worker tests; r=baku (4bfd949c72) - Bug 1134224 - More test for test_bug1132395.html, r=ehsan (626eb100cd) - Bug 1134224 - onerror for test_bug1132395.html, r=ehsan (147195f57e) - Bug 1207635 - get rid of dom.workers.sharedWorkers.enabled pref, r=khuey (22fe2965c6) - Bug 1252592. JS warnings should not trigger error events on shared workers. r=khuey (7f05c2c00d) - Bug 1251308; r=luke (3cbec95738) - Bug 1246838 - Handle const qualifiers and references better in Variant. r=waldo (30da6e3ebf) - Bug 1254565 - Allow passing matchers as rvalues to Variant::match. r=froydnj (1dd799fb0a) - Bug 1246841 - Allow construction of Variant values using type inference. r=waldo (6ba3e6704c) - Bug 1250666 - Forward Variant's move constructor argument correctly to the underlying variant type. r=waldo (7353a53bf0) - Bug 1252185. Remove the dead "target" variable from CloseEventRunnable::WorkerRun. r=khuey (be172da10b) - Bug 1253059: Use fallible allocation in the worker error reporter. r=baku (963222bdd4) - Bug 1253199 - MessagePort should handle the dispatching a message when the parent window is gone, r=smaug (d552e3cd9e) - Bug 1252839 - Remove some if stmt after allocation with 'new' - patch 2, r=bz (3c7eb959bc) - Bug 1252839 - Remove some if stmt after allocation with 'new' - patch 1, r=bz (85067dbfb6) - Bug 1254855. Switch AutoEntryScripts in nsDirectoryViewer to take ownership of error reporting. r=bholley (8c10532323) - Bug 1252565 part 1. Push the script environment preparer bits up from XPCJSRuntime to CycleCollectedJSRuntime, because we need them on workers to do ctypes on workers properly. r=bholley (aecf2595dd) - Bug 1252565 part 2. Make dom::WarningOnlyErrorReporter handle workers. r=bholley (f415b8868b) - Bug 1244222 - Check for function interfaces in DelegatedQueryInterface. r=bz (d213eec83c) - Bug 1254393. Take ownership of error reporting on the AutoEntryScript in nsXPCWrappedJSClass::CallMethod. r=bholley (4765b501c0) - Bug 1251769 - Remove remaining references to MOZILLA_XPCOMRT_API from mfbt. r=froydnj (236adc1d4c) - Bug 1247835 (part 0) - Minor comment and style tweaks in BinarySearch.h. r=luke. (db04793721) - Bug 1244074 - Part 1: Move SheetParsingMode to a separate file. r=dholbert (290adaadea) - Bug 1244074 - Part 2: Add HandleRefPtr for refcounting StyleSheetHandles. r=dholbert r=waldo (8549b24392) - Bug 1244068 - Part 1: Add enum to represent the style system backend type. r=dholbert (c2e53feaf2) - Bug 1244068 - Part 2: Add skeleton ServoStyleSet and a StyleSetHandle smart pointer. r=dholbert (71a5c28629) - Bug 1244068 - Part 3: Factor out nsStyleSet getting in RestyleManager/ElementRestyler. r=dholbert (9e9f4f2e80) - Bug 1245406: In ReflowBlockFrame, use Maybe<> to destroy & reconstruct a stack-allocated object, instead of an explicit call to destructor & placement 'new'. r=dbaron (d36858b818) - Bug 1244068 - Part 4: Use StyleSetHandle instead of concrete style set class in most places. r=dholbert (93f9bcf799) - Bug 1244074 - Part 3: Add skeleton ServoStyleSheet and a StyleSheetHandle smart pointer. r=dholbert (5b4fbdce38) - Bug 1195173 - Apply CSP to preloaded styles within layout/style/Loader.cpp (r=bz) (d1ba920fd3) - Bug 1245681 - Fix addOverrideStyleSheet. r=bz (64099eac73) - Bug 1244074 - Part 4: Use StyleSheetHandle instead of concrete style sheet class in most places. r=dholberti (867470ac83) - Bug 1246013 (part 1) - Store a copy of the ETLDEntry directly in DomainEntry instead of a pointer to it. r=jduell. (587b3a9fb7) - Bug 1246013 (part 2) - Change "explicit/xpcom/effective-TLD-service" path to the more sensible "explicit/network/effective-TLD-service". r=jduell. (2e0df6f28f) - Bug 1247835 (part 1) - Use binary search instead of a hash table in nsEffectiveTLDService. r=jduell. (685dae01c0) - Bug 1257121 part 1 - Use struct for passing some params of font metrics. r=jfkthame (1dfd7a7429) - Bug 1257121 part 2 - Merge nsFontMetrics::Init to the constructor and remove unused failure handling code. r=jfkthame (0cdc441511) - Bug 1257121 part 3 - Add GetInflatedFontMetricsForFrame function to simplify a common use pattern. r=jfkthame (d9630ebd1b) - Bug 1257121 part 4 - Use return value rather than out param to retur font metrics. r=jfkthame (c9a5b1d1dd) - Bug 1257121 part 5 - Make nsDeviceContext::mFontCache a RefPtr. r=jfkthame (9c53238a6a)
2143 lines
63 KiB
C++
2143 lines
63 KiB
C++
/* -*- 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 "nsIChannel.h"
|
|
#include "nsIContentPolicy.h"
|
|
#include "nsIContentSecurityPolicy.h"
|
|
#include "nsIHttpChannel.h"
|
|
#include "nsIHttpChannelInternal.h"
|
|
#include "nsIInputStreamPump.h"
|
|
#include "nsIIOService.h"
|
|
#include "nsIProtocolHandler.h"
|
|
#include "nsIScriptError.h"
|
|
#include "nsIScriptSecurityManager.h"
|
|
#include "nsIStreamLoader.h"
|
|
#include "nsIStreamListenerTee.h"
|
|
#include "nsIThreadRetargetableRequest.h"
|
|
#include "nsIURI.h"
|
|
|
|
#include "jsapi.h"
|
|
#include "jsfriendapi.h"
|
|
#include "nsError.h"
|
|
#include "nsContentPolicyUtils.h"
|
|
#include "nsContentUtils.h"
|
|
#include "nsDocShellCID.h"
|
|
#include "nsISupportsPrimitives.h"
|
|
#include "nsNetUtil.h"
|
|
#include "nsIPipe.h"
|
|
#include "nsIOutputStream.h"
|
|
#include "nsPrintfCString.h"
|
|
#include "nsScriptLoader.h"
|
|
#include "nsString.h"
|
|
#include "nsStreamUtils.h"
|
|
#include "nsTArray.h"
|
|
#include "nsThreadUtils.h"
|
|
#include "nsXPCOM.h"
|
|
#include "xpcpublic.h"
|
|
|
|
#include "mozilla/Assertions.h"
|
|
#include "mozilla/LoadContext.h"
|
|
#include "mozilla/Maybe.h"
|
|
#include "mozilla/ipc/BackgroundUtils.h"
|
|
#include "mozilla/dom/CacheBinding.h"
|
|
#include "mozilla/dom/cache/CacheTypes.h"
|
|
#include "mozilla/dom/cache/Cache.h"
|
|
#include "mozilla/dom/cache/CacheStorage.h"
|
|
#include "mozilla/dom/ChannelInfo.h"
|
|
#include "mozilla/dom/Exceptions.h"
|
|
#include "mozilla/dom/InternalResponse.h"
|
|
#include "mozilla/dom/Promise.h"
|
|
#include "mozilla/dom/PromiseNativeHandler.h"
|
|
#include "mozilla/dom/Response.h"
|
|
#include "mozilla/dom/ScriptSettings.h"
|
|
#include "mozilla/UniquePtr.h"
|
|
#include "Principal.h"
|
|
#include "WorkerFeature.h"
|
|
#include "WorkerPrivate.h"
|
|
#include "WorkerRunnable.h"
|
|
#include "WorkerScope.h"
|
|
|
|
#define MAX_CONCURRENT_SCRIPTS 1000
|
|
|
|
USING_WORKERS_NAMESPACE
|
|
|
|
using namespace mozilla;
|
|
using namespace mozilla::dom;
|
|
using mozilla::dom::cache::Cache;
|
|
using mozilla::dom::cache::CacheStorage;
|
|
using mozilla::ipc::PrincipalInfo;
|
|
|
|
namespace {
|
|
|
|
nsIURI*
|
|
GetBaseURI(bool aIsMainScript, WorkerPrivate* aWorkerPrivate)
|
|
{
|
|
MOZ_ASSERT(aWorkerPrivate);
|
|
nsIURI* baseURI;
|
|
WorkerPrivate* parentWorker = aWorkerPrivate->GetParent();
|
|
if (aIsMainScript) {
|
|
if (parentWorker) {
|
|
baseURI = parentWorker->GetBaseURI();
|
|
NS_ASSERTION(baseURI, "Should have been set already!");
|
|
}
|
|
else {
|
|
// May be null.
|
|
baseURI = aWorkerPrivate->GetBaseURI();
|
|
}
|
|
}
|
|
else {
|
|
baseURI = aWorkerPrivate->GetBaseURI();
|
|
NS_ASSERTION(baseURI, "Should have been set already!");
|
|
}
|
|
|
|
return baseURI;
|
|
}
|
|
|
|
nsresult
|
|
ChannelFromScriptURL(nsIPrincipal* principal,
|
|
nsIURI* baseURI,
|
|
nsIDocument* parentDoc,
|
|
nsILoadGroup* loadGroup,
|
|
nsIIOService* ios,
|
|
nsIScriptSecurityManager* secMan,
|
|
const nsAString& aScriptURL,
|
|
bool aIsMainScript,
|
|
WorkerScriptType aWorkerScriptType,
|
|
nsContentPolicyType aContentPolicyType,
|
|
nsLoadFlags aLoadFlags,
|
|
nsIChannel** aChannel)
|
|
{
|
|
AssertIsOnMainThread();
|
|
|
|
nsresult rv;
|
|
nsCOMPtr<nsIURI> uri;
|
|
rv = nsContentUtils::NewURIWithDocumentCharset(getter_AddRefs(uri),
|
|
aScriptURL, parentDoc,
|
|
baseURI);
|
|
if (NS_FAILED(rv)) {
|
|
return NS_ERROR_DOM_SYNTAX_ERR;
|
|
}
|
|
|
|
// If we have the document, use it. Unfortunately, for dedicated workers
|
|
// 'parentDoc' ends up being the parent document, which is not the document
|
|
// that we want to use. So make sure to avoid using 'parentDoc' in that
|
|
// situation.
|
|
if (parentDoc && parentDoc->NodePrincipal() != principal) {
|
|
parentDoc = nullptr;
|
|
}
|
|
|
|
aLoadFlags |= nsIChannel::LOAD_CLASSIFY_URI;
|
|
uint32_t secFlags = aIsMainScript ? nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED
|
|
: nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS;
|
|
|
|
if (aWorkerScriptType == DebuggerScript) {
|
|
// A DebuggerScript needs to be a local resource like chrome: or resource:
|
|
bool isUIResource = false;
|
|
rv = NS_URIChainHasFlags(uri, nsIProtocolHandler::URI_IS_UI_RESOURCE,
|
|
&isUIResource);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return rv;
|
|
}
|
|
|
|
if (!isUIResource) {
|
|
return NS_ERROR_DOM_SECURITY_ERR;
|
|
}
|
|
|
|
secFlags |= nsILoadInfo::SEC_ALLOW_CHROME;
|
|
}
|
|
|
|
// Note: this is for backwards compatibility and goes against spec.
|
|
// We should find a better solution.
|
|
bool isData = false;
|
|
if (aIsMainScript && NS_SUCCEEDED(uri->SchemeIs("data", &isData)) && isData) {
|
|
secFlags = nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL;
|
|
}
|
|
|
|
nsCOMPtr<nsIChannel> channel;
|
|
// If we have the document, use it. Unfortunately, for dedicated workers
|
|
// 'parentDoc' ends up being the parent document, which is not the document
|
|
// that we want to use. So make sure to avoid using 'parentDoc' in that
|
|
// situation.
|
|
if (parentDoc && parentDoc->NodePrincipal() == principal) {
|
|
rv = NS_NewChannel(getter_AddRefs(channel),
|
|
uri,
|
|
parentDoc,
|
|
secFlags,
|
|
aContentPolicyType,
|
|
loadGroup,
|
|
nullptr, // aCallbacks
|
|
aLoadFlags,
|
|
ios);
|
|
} else {
|
|
// We must have a loadGroup with a load context for the principal to
|
|
// traverse the channel correctly.
|
|
MOZ_ASSERT(loadGroup);
|
|
MOZ_ASSERT(NS_LoadGroupMatchesPrincipal(loadGroup, principal));
|
|
|
|
rv = NS_NewChannel(getter_AddRefs(channel),
|
|
uri,
|
|
principal,
|
|
secFlags,
|
|
aContentPolicyType,
|
|
loadGroup,
|
|
nullptr, // aCallbacks
|
|
aLoadFlags,
|
|
ios);
|
|
}
|
|
|
|
NS_ENSURE_SUCCESS(rv, rv);
|
|
|
|
if (nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(channel)) {
|
|
rv = nsContentUtils::SetFetchReferrerURIWithPolicy(principal, parentDoc,
|
|
httpChannel);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return rv;
|
|
}
|
|
}
|
|
|
|
channel.forget(aChannel);
|
|
return rv;
|
|
}
|
|
|
|
struct ScriptLoadInfo
|
|
{
|
|
ScriptLoadInfo()
|
|
: mScriptTextBuf(nullptr)
|
|
, mScriptTextLength(0)
|
|
, mLoadResult(NS_ERROR_NOT_INITIALIZED)
|
|
, mLoadingFinished(false)
|
|
, mExecutionScheduled(false)
|
|
, mExecutionResult(false)
|
|
, mCacheStatus(Uncached)
|
|
{ }
|
|
|
|
~ScriptLoadInfo()
|
|
{
|
|
if (mScriptTextBuf) {
|
|
js_free(mScriptTextBuf);
|
|
}
|
|
}
|
|
|
|
bool
|
|
ReadyToExecute()
|
|
{
|
|
return !mChannel && NS_SUCCEEDED(mLoadResult) && !mExecutionScheduled;
|
|
}
|
|
|
|
nsString mURL;
|
|
|
|
// This full URL string is populated only if this object is used in a
|
|
// ServiceWorker.
|
|
nsString mFullURL;
|
|
|
|
// This promise is set only when the script is for a ServiceWorker but
|
|
// it's not in the cache yet. The promise is resolved when the full body is
|
|
// stored into the cache. mCachePromise will be set to nullptr after
|
|
// resolution.
|
|
RefPtr<Promise> mCachePromise;
|
|
|
|
// The reader stream the cache entry should be filled from, for those cases
|
|
// when we're going to have an mCachePromise.
|
|
nsCOMPtr<nsIInputStream> mCacheReadStream;
|
|
|
|
nsCOMPtr<nsIChannel> mChannel;
|
|
char16_t* mScriptTextBuf;
|
|
size_t mScriptTextLength;
|
|
|
|
nsresult mLoadResult;
|
|
bool mLoadingFinished;
|
|
bool mExecutionScheduled;
|
|
bool mExecutionResult;
|
|
|
|
enum CacheStatus {
|
|
// By default a normal script is just loaded from the network. But for
|
|
// ServiceWorkers, we have to check if the cache contains the script and
|
|
// load it from the cache.
|
|
Uncached,
|
|
|
|
WritingToCache,
|
|
|
|
ReadingFromCache,
|
|
|
|
// This script has been loaded from the ServiceWorker cache.
|
|
Cached,
|
|
|
|
// This script must be stored in the ServiceWorker cache.
|
|
ToBeCached,
|
|
|
|
// Something went wrong or the worker went away.
|
|
Cancel
|
|
};
|
|
|
|
CacheStatus mCacheStatus;
|
|
|
|
Maybe<bool> mMutedErrorFlag;
|
|
|
|
bool Finished() const
|
|
{
|
|
return mLoadingFinished && !mCachePromise && !mChannel;
|
|
}
|
|
};
|
|
|
|
class ScriptLoaderRunnable;
|
|
|
|
class ScriptExecutorRunnable final : public MainThreadWorkerSyncRunnable
|
|
{
|
|
ScriptLoaderRunnable& mScriptLoader;
|
|
bool mIsWorkerScript;
|
|
uint32_t mFirstIndex;
|
|
uint32_t mLastIndex;
|
|
|
|
public:
|
|
ScriptExecutorRunnable(ScriptLoaderRunnable& aScriptLoader,
|
|
nsIEventTarget* aSyncLoopTarget,
|
|
bool aIsWorkerScript,
|
|
uint32_t aFirstIndex,
|
|
uint32_t aLastIndex);
|
|
|
|
private:
|
|
~ScriptExecutorRunnable()
|
|
{ }
|
|
|
|
virtual bool
|
|
IsDebuggerRunnable() const override;
|
|
|
|
virtual bool
|
|
PreRun(WorkerPrivate* aWorkerPrivate) override;
|
|
|
|
virtual bool
|
|
WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override;
|
|
|
|
virtual void
|
|
PostRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate, bool aRunResult)
|
|
override;
|
|
|
|
NS_DECL_NSICANCELABLERUNNABLE
|
|
|
|
void
|
|
ShutdownScriptLoader(JSContext* aCx,
|
|
WorkerPrivate* aWorkerPrivate,
|
|
bool aResult,
|
|
bool aMutedError);
|
|
|
|
void LogExceptionToConsole(JSContext* aCx,
|
|
WorkerPrivate* WorkerPrivate);
|
|
};
|
|
|
|
class CacheScriptLoader;
|
|
|
|
class CacheCreator final : public PromiseNativeHandler
|
|
{
|
|
public:
|
|
NS_DECL_ISUPPORTS
|
|
|
|
explicit CacheCreator(WorkerPrivate* aWorkerPrivate)
|
|
: mCacheName(aWorkerPrivate->ServiceWorkerCacheName())
|
|
, mPrivateBrowsing(aWorkerPrivate->IsInPrivateBrowsing())
|
|
{
|
|
MOZ_ASSERT(aWorkerPrivate->IsServiceWorker());
|
|
MOZ_ASSERT(aWorkerPrivate->LoadScriptAsPartOfLoadingServiceWorkerScript());
|
|
AssertIsOnMainThread();
|
|
}
|
|
|
|
void
|
|
AddLoader(CacheScriptLoader* aLoader)
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(!mCacheStorage);
|
|
mLoaders.AppendElement(aLoader);
|
|
}
|
|
|
|
virtual void
|
|
ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override;
|
|
|
|
virtual void
|
|
RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override;
|
|
|
|
// Try to load from cache with aPrincipal used for cache access.
|
|
nsresult
|
|
Load(nsIPrincipal* aPrincipal);
|
|
|
|
Cache*
|
|
Cache_() const
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(mCache);
|
|
return mCache;
|
|
}
|
|
|
|
nsIGlobalObject*
|
|
Global() const
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(mSandboxGlobalObject);
|
|
return mSandboxGlobalObject;
|
|
}
|
|
|
|
void
|
|
DeleteCache();
|
|
|
|
private:
|
|
~CacheCreator()
|
|
{
|
|
}
|
|
|
|
nsresult
|
|
CreateCacheStorage(nsIPrincipal* aPrincipal);
|
|
|
|
void
|
|
FailLoaders(nsresult aRv);
|
|
|
|
RefPtr<Cache> mCache;
|
|
RefPtr<CacheStorage> mCacheStorage;
|
|
nsCOMPtr<nsIGlobalObject> mSandboxGlobalObject;
|
|
nsTArray<RefPtr<CacheScriptLoader>> mLoaders;
|
|
|
|
nsString mCacheName;
|
|
bool mPrivateBrowsing;
|
|
};
|
|
|
|
NS_IMPL_ISUPPORTS0(CacheCreator)
|
|
|
|
class CacheScriptLoader final : public PromiseNativeHandler
|
|
, public nsIStreamLoaderObserver
|
|
{
|
|
public:
|
|
NS_DECL_ISUPPORTS
|
|
NS_DECL_NSISTREAMLOADEROBSERVER
|
|
|
|
CacheScriptLoader(WorkerPrivate* aWorkerPrivate, ScriptLoadInfo& aLoadInfo,
|
|
uint32_t aIndex, bool aIsWorkerScript,
|
|
ScriptLoaderRunnable* aRunnable)
|
|
: mLoadInfo(aLoadInfo)
|
|
, mIndex(aIndex)
|
|
, mRunnable(aRunnable)
|
|
, mIsWorkerScript(aIsWorkerScript)
|
|
, mFailed(false)
|
|
{
|
|
MOZ_ASSERT(aWorkerPrivate->IsServiceWorker());
|
|
mBaseURI = GetBaseURI(mIsWorkerScript, aWorkerPrivate);
|
|
AssertIsOnMainThread();
|
|
}
|
|
|
|
void
|
|
Fail(nsresult aRv);
|
|
|
|
void
|
|
Load(Cache* aCache);
|
|
|
|
virtual void
|
|
ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override;
|
|
|
|
virtual void
|
|
RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override;
|
|
|
|
private:
|
|
~CacheScriptLoader()
|
|
{
|
|
AssertIsOnMainThread();
|
|
}
|
|
|
|
ScriptLoadInfo& mLoadInfo;
|
|
uint32_t mIndex;
|
|
RefPtr<ScriptLoaderRunnable> mRunnable;
|
|
bool mIsWorkerScript;
|
|
bool mFailed;
|
|
nsCOMPtr<nsIInputStreamPump> mPump;
|
|
nsCOMPtr<nsIURI> mBaseURI;
|
|
mozilla::dom::ChannelInfo mChannelInfo;
|
|
UniquePtr<PrincipalInfo> mPrincipalInfo;
|
|
};
|
|
|
|
NS_IMPL_ISUPPORTS(CacheScriptLoader, nsIStreamLoaderObserver)
|
|
|
|
class CachePromiseHandler final : public PromiseNativeHandler
|
|
{
|
|
public:
|
|
NS_DECL_ISUPPORTS
|
|
|
|
CachePromiseHandler(ScriptLoaderRunnable* aRunnable,
|
|
ScriptLoadInfo& aLoadInfo,
|
|
uint32_t aIndex)
|
|
: mRunnable(aRunnable)
|
|
, mLoadInfo(aLoadInfo)
|
|
, mIndex(aIndex)
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(mRunnable);
|
|
}
|
|
|
|
virtual void
|
|
ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override;
|
|
|
|
virtual void
|
|
RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override;
|
|
|
|
private:
|
|
~CachePromiseHandler()
|
|
{
|
|
AssertIsOnMainThread();
|
|
}
|
|
|
|
RefPtr<ScriptLoaderRunnable> mRunnable;
|
|
ScriptLoadInfo& mLoadInfo;
|
|
uint32_t mIndex;
|
|
};
|
|
|
|
NS_IMPL_ISUPPORTS0(CachePromiseHandler)
|
|
|
|
class LoaderListener final : public nsIStreamLoaderObserver
|
|
, public nsIRequestObserver
|
|
{
|
|
public:
|
|
NS_DECL_ISUPPORTS
|
|
|
|
LoaderListener(ScriptLoaderRunnable* aRunnable, uint32_t aIndex)
|
|
: mRunnable(aRunnable)
|
|
, mIndex(aIndex)
|
|
{
|
|
MOZ_ASSERT(mRunnable);
|
|
}
|
|
|
|
NS_IMETHOD
|
|
OnStreamComplete(nsIStreamLoader* aLoader, nsISupports* aContext,
|
|
nsresult aStatus, uint32_t aStringLen,
|
|
const uint8_t* aString) override;
|
|
|
|
NS_IMETHOD
|
|
OnStartRequest(nsIRequest* aRequest, nsISupports* aContext) override;
|
|
|
|
NS_IMETHOD
|
|
OnStopRequest(nsIRequest* aRequest, nsISupports* aContext,
|
|
nsresult aStatusCode) override
|
|
{
|
|
// Nothing to do here!
|
|
return NS_OK;
|
|
}
|
|
|
|
private:
|
|
~LoaderListener() {}
|
|
|
|
RefPtr<ScriptLoaderRunnable> mRunnable;
|
|
uint32_t mIndex;
|
|
};
|
|
|
|
NS_IMPL_ISUPPORTS(LoaderListener, nsIStreamLoaderObserver, nsIRequestObserver)
|
|
|
|
class ScriptLoaderRunnable final : public WorkerFeature
|
|
, public nsIRunnable
|
|
{
|
|
friend class ScriptExecutorRunnable;
|
|
friend class CachePromiseHandler;
|
|
friend class CacheScriptLoader;
|
|
friend class LoaderListener;
|
|
|
|
WorkerPrivate* mWorkerPrivate;
|
|
nsCOMPtr<nsIEventTarget> mSyncLoopTarget;
|
|
nsTArray<ScriptLoadInfo> mLoadInfos;
|
|
RefPtr<CacheCreator> mCacheCreator;
|
|
bool mIsMainScript;
|
|
WorkerScriptType mWorkerScriptType;
|
|
bool mCanceled;
|
|
bool mCanceledMainThread;
|
|
ErrorResult& mRv;
|
|
|
|
public:
|
|
NS_DECL_THREADSAFE_ISUPPORTS
|
|
|
|
ScriptLoaderRunnable(WorkerPrivate* aWorkerPrivate,
|
|
nsIEventTarget* aSyncLoopTarget,
|
|
nsTArray<ScriptLoadInfo>& aLoadInfos,
|
|
bool aIsMainScript,
|
|
WorkerScriptType aWorkerScriptType,
|
|
ErrorResult& aRv)
|
|
: mWorkerPrivate(aWorkerPrivate), mSyncLoopTarget(aSyncLoopTarget),
|
|
mIsMainScript(aIsMainScript), mWorkerScriptType(aWorkerScriptType),
|
|
mCanceled(false), mCanceledMainThread(false), mRv(aRv)
|
|
{
|
|
aWorkerPrivate->AssertIsOnWorkerThread();
|
|
MOZ_ASSERT(aSyncLoopTarget);
|
|
MOZ_ASSERT_IF(aIsMainScript, aLoadInfos.Length() == 1);
|
|
|
|
mLoadInfos.SwapElements(aLoadInfos);
|
|
}
|
|
|
|
private:
|
|
~ScriptLoaderRunnable()
|
|
{ }
|
|
|
|
NS_IMETHOD
|
|
Run() override
|
|
{
|
|
AssertIsOnMainThread();
|
|
|
|
nsresult rv = RunInternal();
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
CancelMainThread(rv);
|
|
}
|
|
|
|
return NS_OK;
|
|
}
|
|
|
|
void
|
|
LoadingFinished(uint32_t aIndex, nsresult aRv)
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(aIndex < mLoadInfos.Length());
|
|
ScriptLoadInfo& loadInfo = mLoadInfos[aIndex];
|
|
|
|
loadInfo.mLoadResult = aRv;
|
|
|
|
MOZ_ASSERT(!loadInfo.mLoadingFinished);
|
|
loadInfo.mLoadingFinished = true;
|
|
|
|
MaybeExecuteFinishedScripts(aIndex);
|
|
}
|
|
|
|
void
|
|
MaybeExecuteFinishedScripts(uint32_t aIndex)
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(aIndex < mLoadInfos.Length());
|
|
ScriptLoadInfo& loadInfo = mLoadInfos[aIndex];
|
|
|
|
// We execute the last step if we don't have a pending operation with the
|
|
// cache and the loading is completed.
|
|
if (loadInfo.Finished()) {
|
|
ExecuteFinishedScripts();
|
|
}
|
|
}
|
|
|
|
nsresult
|
|
OnStreamComplete(nsIStreamLoader* aLoader, uint32_t aIndex,
|
|
nsresult aStatus, uint32_t aStringLen,
|
|
const uint8_t* aString)
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(aIndex < mLoadInfos.Length());
|
|
|
|
nsresult rv = OnStreamCompleteInternal(aLoader, aStatus, aStringLen,
|
|
aString, mLoadInfos[aIndex]);
|
|
LoadingFinished(aIndex, rv);
|
|
return NS_OK;
|
|
}
|
|
|
|
nsresult
|
|
OnStartRequest(nsIRequest* aRequest, uint32_t aIndex)
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(aIndex < mLoadInfos.Length());
|
|
|
|
// If one load info cancels or hits an error, it can race with the start
|
|
// callback coming from another load info.
|
|
if (mCanceledMainThread || !mCacheCreator) {
|
|
aRequest->Cancel(NS_ERROR_FAILURE);
|
|
return NS_ERROR_FAILURE;
|
|
}
|
|
|
|
ScriptLoadInfo& loadInfo = mLoadInfos[aIndex];
|
|
|
|
nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
|
|
MOZ_ASSERT(channel == loadInfo.mChannel);
|
|
|
|
// We synthesize the result code, but its never exposed to content.
|
|
RefPtr<mozilla::dom::InternalResponse> ir =
|
|
new mozilla::dom::InternalResponse(200, NS_LITERAL_CSTRING("OK"));
|
|
ir->SetBody(loadInfo.mCacheReadStream);
|
|
// Drop our reference to the stream now that we've passed it along, so it
|
|
// doesn't hang around once the cache is done with it and keep data alive.
|
|
loadInfo.mCacheReadStream = nullptr;
|
|
|
|
// Set the channel info of the channel on the response so that it's
|
|
// saved in the cache.
|
|
ir->InitChannelInfo(channel);
|
|
|
|
// Save the principal of the channel since its URI encodes the script URI
|
|
// rather than the ServiceWorkerRegistrationInfo URI.
|
|
nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
|
|
NS_ASSERTION(ssm, "Should never be null!");
|
|
|
|
nsCOMPtr<nsIPrincipal> channelPrincipal;
|
|
nsresult rv = ssm->GetChannelResultPrincipal(channel, getter_AddRefs(channelPrincipal));
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
channel->Cancel(rv);
|
|
return rv;
|
|
}
|
|
|
|
UniquePtr<PrincipalInfo> principalInfo(new PrincipalInfo());
|
|
rv = PrincipalToPrincipalInfo(channelPrincipal, principalInfo.get());
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
channel->Cancel(rv);
|
|
return rv;
|
|
}
|
|
|
|
ir->SetPrincipalInfo(Move(principalInfo));
|
|
|
|
RefPtr<mozilla::dom::Response> response =
|
|
new mozilla::dom::Response(mCacheCreator->Global(), ir);
|
|
|
|
mozilla::dom::RequestOrUSVString request;
|
|
|
|
MOZ_ASSERT(!loadInfo.mFullURL.IsEmpty());
|
|
request.SetAsUSVString().Rebind(loadInfo.mFullURL.Data(),
|
|
loadInfo.mFullURL.Length());
|
|
|
|
ErrorResult error;
|
|
RefPtr<Promise> cachePromise =
|
|
mCacheCreator->Cache_()->Put(request, *response, error);
|
|
if (NS_WARN_IF(error.Failed())) {
|
|
nsresult rv = error.StealNSResult();
|
|
channel->Cancel(rv);
|
|
return rv;
|
|
}
|
|
|
|
RefPtr<CachePromiseHandler> promiseHandler =
|
|
new CachePromiseHandler(this, loadInfo, aIndex);
|
|
cachePromise->AppendNativeHandler(promiseHandler);
|
|
|
|
loadInfo.mCachePromise.swap(cachePromise);
|
|
loadInfo.mCacheStatus = ScriptLoadInfo::WritingToCache;
|
|
|
|
return NS_OK;
|
|
}
|
|
|
|
virtual bool
|
|
Notify(JSContext* aCx, Status aStatus) override
|
|
{
|
|
mWorkerPrivate->AssertIsOnWorkerThread();
|
|
|
|
if (aStatus >= Terminating && !mCanceled) {
|
|
mCanceled = true;
|
|
|
|
nsCOMPtr<nsIRunnable> runnable =
|
|
NS_NewRunnableMethod(this,
|
|
&ScriptLoaderRunnable::CancelMainThreadWithBindingAborted);
|
|
NS_ASSERTION(runnable, "This should never fail!");
|
|
|
|
if (NS_FAILED(NS_DispatchToMainThread(runnable))) {
|
|
JS_ReportError(aCx, "Failed to cancel script loader!");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
bool
|
|
IsMainWorkerScript() const
|
|
{
|
|
return mIsMainScript && mWorkerScriptType == WorkerScript;
|
|
}
|
|
|
|
void
|
|
CancelMainThreadWithBindingAborted()
|
|
{
|
|
CancelMainThread(NS_BINDING_ABORTED);
|
|
}
|
|
|
|
void
|
|
CancelMainThread(nsresult aCancelResult)
|
|
{
|
|
AssertIsOnMainThread();
|
|
|
|
if (mCanceledMainThread) {
|
|
return;
|
|
}
|
|
|
|
mCanceledMainThread = true;
|
|
|
|
if (mCacheCreator) {
|
|
MOZ_ASSERT(mWorkerPrivate->IsServiceWorker());
|
|
DeleteCache();
|
|
}
|
|
|
|
// Cancel all the channels that were already opened.
|
|
for (uint32_t index = 0; index < mLoadInfos.Length(); index++) {
|
|
ScriptLoadInfo& loadInfo = mLoadInfos[index];
|
|
|
|
// If promise or channel is non-null, their failures will lead to
|
|
// LoadingFinished being called.
|
|
bool callLoadingFinished = true;
|
|
|
|
if (loadInfo.mCachePromise) {
|
|
MOZ_ASSERT(mWorkerPrivate->IsServiceWorker());
|
|
loadInfo.mCachePromise->MaybeReject(aCancelResult);
|
|
loadInfo.mCachePromise = nullptr;
|
|
callLoadingFinished = false;
|
|
}
|
|
|
|
if (loadInfo.mChannel) {
|
|
if (NS_SUCCEEDED(loadInfo.mChannel->Cancel(aCancelResult))) {
|
|
callLoadingFinished = false;
|
|
} else {
|
|
NS_WARNING("Failed to cancel channel!");
|
|
}
|
|
}
|
|
|
|
if (callLoadingFinished && !loadInfo.Finished()) {
|
|
LoadingFinished(index, aCancelResult);
|
|
}
|
|
}
|
|
|
|
ExecuteFinishedScripts();
|
|
}
|
|
|
|
void
|
|
DeleteCache()
|
|
{
|
|
AssertIsOnMainThread();
|
|
|
|
if (!mCacheCreator) {
|
|
return;
|
|
}
|
|
|
|
mCacheCreator->DeleteCache();
|
|
mCacheCreator = nullptr;
|
|
}
|
|
|
|
nsresult
|
|
RunInternal()
|
|
{
|
|
AssertIsOnMainThread();
|
|
|
|
if (IsMainWorkerScript() && mWorkerPrivate->IsServiceWorker()) {
|
|
mWorkerPrivate->SetLoadingWorkerScript(true);
|
|
}
|
|
|
|
if (!mWorkerPrivate->IsServiceWorker() ||
|
|
!mWorkerPrivate->LoadScriptAsPartOfLoadingServiceWorkerScript()) {
|
|
for (uint32_t index = 0, len = mLoadInfos.Length(); index < len;
|
|
++index) {
|
|
nsresult rv = LoadScript(index);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
LoadingFinished(index, rv);
|
|
return rv;
|
|
}
|
|
}
|
|
|
|
return NS_OK;
|
|
}
|
|
|
|
MOZ_ASSERT(!mCacheCreator);
|
|
mCacheCreator = new CacheCreator(mWorkerPrivate);
|
|
|
|
for (uint32_t index = 0, len = mLoadInfos.Length(); index < len; ++index) {
|
|
RefPtr<CacheScriptLoader> loader =
|
|
new CacheScriptLoader(mWorkerPrivate, mLoadInfos[index], index,
|
|
IsMainWorkerScript(), this);
|
|
mCacheCreator->AddLoader(loader);
|
|
}
|
|
|
|
// The worker may have a null principal on first load, but in that case its
|
|
// parent definitely will have one.
|
|
nsIPrincipal* principal = mWorkerPrivate->GetPrincipal();
|
|
if (!principal) {
|
|
WorkerPrivate* parentWorker = mWorkerPrivate->GetParent();
|
|
MOZ_ASSERT(parentWorker, "Must have a parent!");
|
|
principal = parentWorker->GetPrincipal();
|
|
}
|
|
|
|
nsresult rv = mCacheCreator->Load(principal);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return rv;
|
|
}
|
|
|
|
return NS_OK;
|
|
}
|
|
|
|
nsresult
|
|
LoadScript(uint32_t aIndex)
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(aIndex < mLoadInfos.Length());
|
|
|
|
WorkerPrivate* parentWorker = mWorkerPrivate->GetParent();
|
|
|
|
// Figure out which principal to use.
|
|
nsIPrincipal* principal = mWorkerPrivate->GetPrincipal();
|
|
nsCOMPtr<nsILoadGroup> loadGroup = mWorkerPrivate->GetLoadGroup();
|
|
if (!principal) {
|
|
NS_ASSERTION(parentWorker, "Must have a principal!");
|
|
NS_ASSERTION(mIsMainScript, "Must have a principal for importScripts!");
|
|
|
|
principal = parentWorker->GetPrincipal();
|
|
loadGroup = parentWorker->GetLoadGroup();
|
|
}
|
|
NS_ASSERTION(principal, "This should never be null here!");
|
|
MOZ_ASSERT(NS_LoadGroupMatchesPrincipal(loadGroup, principal));
|
|
|
|
// Figure out our base URI.
|
|
nsCOMPtr<nsIURI> baseURI = GetBaseURI(mIsMainScript, mWorkerPrivate);
|
|
|
|
// May be null.
|
|
nsCOMPtr<nsIDocument> parentDoc = mWorkerPrivate->GetDocument();
|
|
|
|
nsCOMPtr<nsIChannel> channel;
|
|
if (IsMainWorkerScript()) {
|
|
// May be null.
|
|
channel = mWorkerPrivate->ForgetWorkerChannel();
|
|
}
|
|
|
|
nsCOMPtr<nsIIOService> ios(do_GetIOService());
|
|
|
|
nsIScriptSecurityManager* secMan = nsContentUtils::GetSecurityManager();
|
|
NS_ASSERTION(secMan, "This should never be null!");
|
|
|
|
ScriptLoadInfo& loadInfo = mLoadInfos[aIndex];
|
|
nsresult& rv = loadInfo.mLoadResult;
|
|
|
|
nsLoadFlags loadFlags = nsIRequest::LOAD_NORMAL;
|
|
|
|
// If we are loading a script for a ServiceWorker then we must not
|
|
// try to intercept it. If the interception matches the current
|
|
// ServiceWorker's scope then we could deadlock the load.
|
|
if (mWorkerPrivate->IsServiceWorker()) {
|
|
loadFlags |= nsIChannel::LOAD_BYPASS_SERVICE_WORKER;
|
|
}
|
|
|
|
if (!channel) {
|
|
rv = ChannelFromScriptURL(principal, baseURI, parentDoc, loadGroup, ios,
|
|
secMan, loadInfo.mURL, IsMainWorkerScript(),
|
|
mWorkerScriptType,
|
|
mWorkerPrivate->ContentPolicyType(), loadFlags,
|
|
getter_AddRefs(channel));
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return rv;
|
|
}
|
|
}
|
|
|
|
// We need to know which index we're on in OnStreamComplete so we know
|
|
// where to put the result.
|
|
RefPtr<LoaderListener> listener = new LoaderListener(this, aIndex);
|
|
|
|
// We don't care about progress so just use the simple stream loader for
|
|
// OnStreamComplete notification only.
|
|
nsCOMPtr<nsIStreamLoader> loader;
|
|
rv = NS_NewStreamLoader(getter_AddRefs(loader), listener);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return rv;
|
|
}
|
|
|
|
if (loadInfo.mCacheStatus != ScriptLoadInfo::ToBeCached) {
|
|
rv = channel->AsyncOpen2(loader);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return rv;
|
|
}
|
|
} else {
|
|
nsCOMPtr<nsIOutputStream> writer;
|
|
|
|
// In case we return early.
|
|
loadInfo.mCacheStatus = ScriptLoadInfo::Cancel;
|
|
|
|
rv = NS_NewPipe(getter_AddRefs(loadInfo.mCacheReadStream),
|
|
getter_AddRefs(writer), 0,
|
|
UINT32_MAX, // unlimited size to avoid writer WOULD_BLOCK case
|
|
true, false); // non-blocking reader, blocking writer
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return rv;
|
|
}
|
|
|
|
nsCOMPtr<nsIStreamListenerTee> tee =
|
|
do_CreateInstance(NS_STREAMLISTENERTEE_CONTRACTID);
|
|
rv = tee->Init(loader, writer, listener);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return rv;
|
|
}
|
|
|
|
nsresult rv = channel->AsyncOpen2(tee);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return rv;
|
|
}
|
|
}
|
|
|
|
loadInfo.mChannel.swap(channel);
|
|
|
|
return NS_OK;
|
|
}
|
|
|
|
nsresult
|
|
OnStreamCompleteInternal(nsIStreamLoader* aLoader, nsresult aStatus,
|
|
uint32_t aStringLen, const uint8_t* aString,
|
|
ScriptLoadInfo& aLoadInfo)
|
|
{
|
|
AssertIsOnMainThread();
|
|
|
|
if (!aLoadInfo.mChannel) {
|
|
return NS_BINDING_ABORTED;
|
|
}
|
|
|
|
aLoadInfo.mChannel = nullptr;
|
|
|
|
if (NS_FAILED(aStatus)) {
|
|
return aStatus;
|
|
}
|
|
|
|
NS_ASSERTION(aString, "This should never be null!");
|
|
|
|
nsCOMPtr<nsIRequest> request;
|
|
nsresult rv = aLoader->GetRequest(getter_AddRefs(request));
|
|
NS_ENSURE_SUCCESS(rv, rv);
|
|
|
|
nsCOMPtr<nsIChannel> channel = do_QueryInterface(request);
|
|
MOZ_ASSERT(channel);
|
|
|
|
nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
|
|
NS_ASSERTION(ssm, "Should never be null!");
|
|
|
|
nsCOMPtr<nsIPrincipal> channelPrincipal;
|
|
rv = ssm->GetChannelResultPrincipal(channel, getter_AddRefs(channelPrincipal));
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return rv;
|
|
}
|
|
|
|
nsIPrincipal* principal = mWorkerPrivate->GetPrincipal();
|
|
if (!principal) {
|
|
WorkerPrivate* parentWorker = mWorkerPrivate->GetParent();
|
|
MOZ_ASSERT(parentWorker, "Must have a parent!");
|
|
principal = parentWorker->GetPrincipal();
|
|
}
|
|
|
|
// We don't mute the main worker script becase we've already done
|
|
// same-origin checks on them so we should be able to see their errors.
|
|
// Note that for data: url, where we allow it through the same-origin check
|
|
// but then give it a different origin.
|
|
aLoadInfo.mMutedErrorFlag.emplace(IsMainWorkerScript()
|
|
? false
|
|
: !principal->Subsumes(channelPrincipal));
|
|
|
|
// Make sure we're not seeing the result of a 404 or something by checking
|
|
// the 'requestSucceeded' attribute on the http channel.
|
|
nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(request);
|
|
if (httpChannel) {
|
|
bool requestSucceeded;
|
|
rv = httpChannel->GetRequestSucceeded(&requestSucceeded);
|
|
NS_ENSURE_SUCCESS(rv, rv);
|
|
|
|
if (!requestSucceeded) {
|
|
return NS_ERROR_NOT_AVAILABLE;
|
|
}
|
|
}
|
|
|
|
// May be null.
|
|
nsIDocument* parentDoc = mWorkerPrivate->GetDocument();
|
|
|
|
// Use the regular nsScriptLoader for this grunt work! Should be just fine
|
|
// because we're running on the main thread.
|
|
// Unlike <script> tags, Worker scripts are always decoded as UTF-8,
|
|
// per spec. So we explicitly pass in the charset hint.
|
|
rv = nsScriptLoader::ConvertToUTF16(aLoadInfo.mChannel, aString, aStringLen,
|
|
NS_LITERAL_STRING("UTF-8"), parentDoc,
|
|
aLoadInfo.mScriptTextBuf,
|
|
aLoadInfo.mScriptTextLength);
|
|
if (NS_FAILED(rv)) {
|
|
return rv;
|
|
}
|
|
|
|
if (!aLoadInfo.mScriptTextLength && !aLoadInfo.mScriptTextBuf) {
|
|
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
|
|
NS_LITERAL_CSTRING("DOM"), parentDoc,
|
|
nsContentUtils::eDOM_PROPERTIES,
|
|
"EmptyWorkerSourceWarning");
|
|
} else if (!aLoadInfo.mScriptTextBuf) {
|
|
return NS_ERROR_FAILURE;
|
|
}
|
|
|
|
// Figure out what we actually loaded.
|
|
nsCOMPtr<nsIURI> finalURI;
|
|
rv = NS_GetFinalChannelURI(channel, getter_AddRefs(finalURI));
|
|
NS_ENSURE_SUCCESS(rv, rv);
|
|
|
|
if (principal->Subsumes(channelPrincipal)) {
|
|
nsCString filename;
|
|
rv = finalURI->GetSpec(filename);
|
|
NS_ENSURE_SUCCESS(rv, rv);
|
|
|
|
if (!filename.IsEmpty()) {
|
|
// This will help callers figure out what their script url resolved to in
|
|
// case of errors.
|
|
aLoadInfo.mURL.Assign(NS_ConvertUTF8toUTF16(filename));
|
|
}
|
|
}
|
|
|
|
// Update the principal of the worker and its base URI if we just loaded the
|
|
// worker's primary script.
|
|
if (IsMainWorkerScript()) {
|
|
// Take care of the base URI first.
|
|
mWorkerPrivate->SetBaseURI(finalURI);
|
|
|
|
// Store the channel info if needed.
|
|
mWorkerPrivate->InitChannelInfo(channel);
|
|
|
|
// Now to figure out which principal to give this worker.
|
|
WorkerPrivate* parent = mWorkerPrivate->GetParent();
|
|
|
|
NS_ASSERTION(mWorkerPrivate->GetPrincipal() || parent,
|
|
"Must have one of these!");
|
|
|
|
nsCOMPtr<nsIPrincipal> loadPrincipal = mWorkerPrivate->GetPrincipal() ?
|
|
mWorkerPrivate->GetPrincipal() :
|
|
parent->GetPrincipal();
|
|
|
|
nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
|
|
NS_ASSERTION(ssm, "Should never be null!");
|
|
|
|
nsCOMPtr<nsIPrincipal> channelPrincipal;
|
|
rv = ssm->GetChannelResultPrincipal(channel, getter_AddRefs(channelPrincipal));
|
|
NS_ENSURE_SUCCESS(rv, rv);
|
|
|
|
nsCOMPtr<nsILoadGroup> channelLoadGroup;
|
|
rv = channel->GetLoadGroup(getter_AddRefs(channelLoadGroup));
|
|
NS_ENSURE_SUCCESS(rv, rv);
|
|
MOZ_ASSERT(channelLoadGroup);
|
|
|
|
// If the load principal is the system principal then the channel
|
|
// principal must also be the system principal (we do not allow chrome
|
|
// code to create workers with non-chrome scripts, and if we ever decide
|
|
// to change this we need to make sure we don't always set
|
|
// mPrincipalIsSystem to true in WorkerPrivate::GetLoadInfo()). Otherwise
|
|
// this channel principal must be same origin with the load principal (we
|
|
// check again here in case redirects changed the location of the script).
|
|
if (nsContentUtils::IsSystemPrincipal(loadPrincipal)) {
|
|
if (!nsContentUtils::IsSystemPrincipal(channelPrincipal)) {
|
|
// See if this is a resource URI. Since JSMs usually come from
|
|
// resource:// URIs we're currently considering all URIs with the
|
|
// URI_IS_UI_RESOURCE flag as valid for creating privileged workers.
|
|
bool isResource;
|
|
rv = NS_URIChainHasFlags(finalURI,
|
|
nsIProtocolHandler::URI_IS_UI_RESOURCE,
|
|
&isResource);
|
|
NS_ENSURE_SUCCESS(rv, rv);
|
|
|
|
if (isResource) {
|
|
// Assign the system principal to the resource:// worker only if it
|
|
// was loaded from code using the system principal.
|
|
channelPrincipal = loadPrincipal;
|
|
} else {
|
|
return NS_ERROR_DOM_BAD_URI;
|
|
}
|
|
}
|
|
}
|
|
|
|
// The principal can change, but it should still match the original
|
|
// load group's appId and browser element flag.
|
|
MOZ_ASSERT(NS_LoadGroupMatchesPrincipal(channelLoadGroup, channelPrincipal));
|
|
|
|
mWorkerPrivate->SetPrincipal(channelPrincipal, channelLoadGroup);
|
|
}
|
|
|
|
DataReceived();
|
|
return NS_OK;
|
|
}
|
|
|
|
void
|
|
DataReceivedFromCache(uint32_t aIndex, const uint8_t* aString,
|
|
uint32_t aStringLen,
|
|
const mozilla::dom::ChannelInfo& aChannelInfo,
|
|
UniquePtr<PrincipalInfo> aPrincipalInfo)
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(aIndex < mLoadInfos.Length());
|
|
ScriptLoadInfo& loadInfo = mLoadInfos[aIndex];
|
|
MOZ_ASSERT(loadInfo.mCacheStatus == ScriptLoadInfo::Cached);
|
|
|
|
nsCOMPtr<nsIPrincipal> responsePrincipal =
|
|
PrincipalInfoToPrincipal(*aPrincipalInfo);
|
|
|
|
nsIPrincipal* principal = mWorkerPrivate->GetPrincipal();
|
|
if (!principal) {
|
|
WorkerPrivate* parentWorker = mWorkerPrivate->GetParent();
|
|
MOZ_ASSERT(parentWorker, "Must have a parent!");
|
|
principal = parentWorker->GetPrincipal();
|
|
}
|
|
|
|
loadInfo.mMutedErrorFlag.emplace(!principal->Subsumes(responsePrincipal));
|
|
|
|
// May be null.
|
|
nsIDocument* parentDoc = mWorkerPrivate->GetDocument();
|
|
|
|
MOZ_ASSERT(!loadInfo.mScriptTextBuf);
|
|
|
|
nsresult rv =
|
|
nsScriptLoader::ConvertToUTF16(nullptr, aString, aStringLen,
|
|
NS_LITERAL_STRING("UTF-8"), parentDoc,
|
|
loadInfo.mScriptTextBuf,
|
|
loadInfo.mScriptTextLength);
|
|
if (NS_SUCCEEDED(rv) && IsMainWorkerScript()) {
|
|
nsCOMPtr<nsIURI> finalURI;
|
|
rv = NS_NewURI(getter_AddRefs(finalURI), loadInfo.mFullURL, nullptr, nullptr);
|
|
if (NS_SUCCEEDED(rv)) {
|
|
mWorkerPrivate->SetBaseURI(finalURI);
|
|
}
|
|
|
|
mozilla::DebugOnly<nsIPrincipal*> principal = mWorkerPrivate->GetPrincipal();
|
|
MOZ_ASSERT(principal);
|
|
nsILoadGroup* loadGroup = mWorkerPrivate->GetLoadGroup();
|
|
MOZ_ASSERT(loadGroup);
|
|
|
|
mozilla::DebugOnly<bool> equal = false;
|
|
MOZ_ASSERT(responsePrincipal && NS_SUCCEEDED(responsePrincipal->Equals(principal, &equal)));
|
|
MOZ_ASSERT(equal);
|
|
|
|
mWorkerPrivate->InitChannelInfo(aChannelInfo);
|
|
mWorkerPrivate->SetPrincipal(responsePrincipal, loadGroup);
|
|
}
|
|
|
|
if (NS_SUCCEEDED(rv)) {
|
|
DataReceived();
|
|
}
|
|
|
|
LoadingFinished(aIndex, rv);
|
|
}
|
|
|
|
void
|
|
DataReceived()
|
|
{
|
|
if (IsMainWorkerScript()) {
|
|
WorkerPrivate* parent = mWorkerPrivate->GetParent();
|
|
|
|
if (parent) {
|
|
// XHR Params Allowed
|
|
mWorkerPrivate->SetXHRParamsAllowed(parent->XHRParamsAllowed());
|
|
|
|
// Set Eval and ContentSecurityPolicy
|
|
mWorkerPrivate->SetCSP(parent->GetCSP());
|
|
mWorkerPrivate->SetEvalAllowed(parent->IsEvalAllowed());
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
ExecuteFinishedScripts()
|
|
{
|
|
AssertIsOnMainThread();
|
|
|
|
if (IsMainWorkerScript()) {
|
|
mWorkerPrivate->WorkerScriptLoaded();
|
|
}
|
|
|
|
uint32_t firstIndex = UINT32_MAX;
|
|
uint32_t lastIndex = UINT32_MAX;
|
|
|
|
// Find firstIndex based on whether mExecutionScheduled is unset.
|
|
for (uint32_t index = 0; index < mLoadInfos.Length(); index++) {
|
|
if (!mLoadInfos[index].mExecutionScheduled) {
|
|
firstIndex = index;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Find lastIndex based on whether mChannel is set, and update
|
|
// mExecutionScheduled on the ones we're about to schedule.
|
|
if (firstIndex != UINT32_MAX) {
|
|
for (uint32_t index = firstIndex; index < mLoadInfos.Length(); index++) {
|
|
ScriptLoadInfo& loadInfo = mLoadInfos[index];
|
|
|
|
if (!loadInfo.Finished()) {
|
|
break;
|
|
}
|
|
|
|
// We can execute this one.
|
|
loadInfo.mExecutionScheduled = true;
|
|
|
|
lastIndex = index;
|
|
}
|
|
}
|
|
|
|
// This is the last index, we can unused things before the exection of the
|
|
// script and the stopping of the sync loop.
|
|
if (lastIndex == mLoadInfos.Length() - 1) {
|
|
mCacheCreator = nullptr;
|
|
}
|
|
|
|
if (firstIndex != UINT32_MAX && lastIndex != UINT32_MAX) {
|
|
RefPtr<ScriptExecutorRunnable> runnable =
|
|
new ScriptExecutorRunnable(*this, mSyncLoopTarget, IsMainWorkerScript(),
|
|
firstIndex, lastIndex);
|
|
if (!runnable->Dispatch()) {
|
|
MOZ_ASSERT(false, "This should never fail!");
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
NS_IMPL_ISUPPORTS(ScriptLoaderRunnable, nsIRunnable)
|
|
|
|
NS_IMETHODIMP
|
|
LoaderListener::OnStreamComplete(nsIStreamLoader* aLoader, nsISupports* aContext,
|
|
nsresult aStatus, uint32_t aStringLen,
|
|
const uint8_t* aString)
|
|
{
|
|
return mRunnable->OnStreamComplete(aLoader, mIndex, aStatus, aStringLen, aString);
|
|
}
|
|
|
|
NS_IMETHODIMP
|
|
LoaderListener::OnStartRequest(nsIRequest* aRequest, nsISupports* aContext)
|
|
{
|
|
return mRunnable->OnStartRequest(aRequest, mIndex);
|
|
}
|
|
|
|
void
|
|
CachePromiseHandler::ResolvedCallback(JSContext* aCx,
|
|
JS::Handle<JS::Value> aValue)
|
|
{
|
|
AssertIsOnMainThread();
|
|
// May already have been canceled by CacheScriptLoader::Fail from
|
|
// CancelMainThread.
|
|
MOZ_ASSERT(mLoadInfo.mCacheStatus == ScriptLoadInfo::WritingToCache ||
|
|
mLoadInfo.mCacheStatus == ScriptLoadInfo::Cancel);
|
|
MOZ_ASSERT_IF(mLoadInfo.mCacheStatus == ScriptLoadInfo::Cancel, !mLoadInfo.mCachePromise);
|
|
|
|
if (mLoadInfo.mCachePromise) {
|
|
mLoadInfo.mCacheStatus = ScriptLoadInfo::Cached;
|
|
mLoadInfo.mCachePromise = nullptr;
|
|
mRunnable->MaybeExecuteFinishedScripts(mIndex);
|
|
}
|
|
}
|
|
|
|
void
|
|
CachePromiseHandler::RejectedCallback(JSContext* aCx,
|
|
JS::Handle<JS::Value> aValue)
|
|
{
|
|
AssertIsOnMainThread();
|
|
// May already have been canceled by CacheScriptLoader::Fail from
|
|
// CancelMainThread.
|
|
MOZ_ASSERT(mLoadInfo.mCacheStatus == ScriptLoadInfo::WritingToCache ||
|
|
mLoadInfo.mCacheStatus == ScriptLoadInfo::Cancel);
|
|
mLoadInfo.mCacheStatus = ScriptLoadInfo::Cancel;
|
|
|
|
mLoadInfo.mCachePromise = nullptr;
|
|
|
|
// This will delete the cache object and will call LoadingFinished() with an
|
|
// error for each ongoing operation.
|
|
mRunnable->DeleteCache();
|
|
}
|
|
|
|
nsresult
|
|
CacheCreator::CreateCacheStorage(nsIPrincipal* aPrincipal)
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(!mCacheStorage);
|
|
MOZ_ASSERT(aPrincipal);
|
|
|
|
nsIXPConnect* xpc = nsContentUtils::XPConnect();
|
|
MOZ_ASSERT(xpc, "This should never be null!");
|
|
|
|
mozilla::AutoSafeJSContext cx;
|
|
JS::Rooted<JSObject*> sandbox(cx);
|
|
nsresult rv = xpc->CreateSandbox(cx, aPrincipal, sandbox.address());
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return rv;
|
|
}
|
|
|
|
mSandboxGlobalObject = xpc::NativeGlobal(sandbox);
|
|
if (NS_WARN_IF(!mSandboxGlobalObject)) {
|
|
return NS_ERROR_FAILURE;
|
|
}
|
|
|
|
// If we're in private browsing mode, don't even try to create the
|
|
// CacheStorage. Instead, just fail immediately to terminate the
|
|
// ServiceWorker load.
|
|
if (NS_WARN_IF(mPrivateBrowsing)) {
|
|
return NS_ERROR_DOM_SECURITY_ERR;
|
|
}
|
|
|
|
// Create a CacheStorage bypassing its trusted origin checks. The
|
|
// ServiceWorker has already performed its own checks before getting
|
|
// to this point.
|
|
ErrorResult error;
|
|
mCacheStorage =
|
|
CacheStorage::CreateOnMainThread(mozilla::dom::cache::CHROME_ONLY_NAMESPACE,
|
|
mSandboxGlobalObject,
|
|
aPrincipal, mPrivateBrowsing,
|
|
true /* force trusted origin */,
|
|
error);
|
|
if (NS_WARN_IF(error.Failed())) {
|
|
return error.StealNSResult();
|
|
}
|
|
|
|
return NS_OK;
|
|
}
|
|
|
|
nsresult
|
|
CacheCreator::Load(nsIPrincipal* aPrincipal)
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(!mLoaders.IsEmpty());
|
|
|
|
nsresult rv = CreateCacheStorage(aPrincipal);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
return rv;
|
|
}
|
|
|
|
ErrorResult error;
|
|
MOZ_ASSERT(!mCacheName.IsEmpty());
|
|
RefPtr<Promise> promise = mCacheStorage->Open(mCacheName, error);
|
|
if (NS_WARN_IF(error.Failed())) {
|
|
return error.StealNSResult();
|
|
}
|
|
|
|
promise->AppendNativeHandler(this);
|
|
return NS_OK;
|
|
}
|
|
|
|
void
|
|
CacheCreator::FailLoaders(nsresult aRv)
|
|
{
|
|
AssertIsOnMainThread();
|
|
|
|
// Fail() can call LoadingFinished() which may call ExecuteFinishedScripts()
|
|
// which sets mCacheCreator to null, so hold a ref.
|
|
RefPtr<CacheCreator> kungfuDeathGrip = this;
|
|
|
|
for (uint32_t i = 0, len = mLoaders.Length(); i < len; ++i) {
|
|
mLoaders[i]->Fail(aRv);
|
|
}
|
|
|
|
mLoaders.Clear();
|
|
}
|
|
|
|
void
|
|
CacheCreator::RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue)
|
|
{
|
|
AssertIsOnMainThread();
|
|
FailLoaders(NS_ERROR_FAILURE);
|
|
}
|
|
|
|
void
|
|
CacheCreator::ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue)
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(aValue.isObject());
|
|
|
|
JS::Rooted<JSObject*> obj(aCx, &aValue.toObject());
|
|
Cache* cache = nullptr;
|
|
nsresult rv = UNWRAP_OBJECT(Cache, obj, cache);
|
|
MOZ_ALWAYS_TRUE(NS_SUCCEEDED(rv));
|
|
|
|
mCache = cache;
|
|
MOZ_ASSERT(mCache);
|
|
|
|
// If the worker is canceled, CancelMainThread() will have cleared the
|
|
// loaders.
|
|
for (uint32_t i = 0, len = mLoaders.Length(); i < len; ++i) {
|
|
mLoaders[i]->Load(cache);
|
|
}
|
|
}
|
|
|
|
void
|
|
CacheCreator::DeleteCache()
|
|
{
|
|
AssertIsOnMainThread();
|
|
|
|
ErrorResult rv;
|
|
|
|
// It's safe to do this while Cache::Match() and Cache::Put() calls are
|
|
// running.
|
|
RefPtr<Promise> promise = mCacheStorage->Delete(mCacheName, rv);
|
|
if (NS_WARN_IF(rv.Failed())) {
|
|
return;
|
|
}
|
|
|
|
// We don't care to know the result of the promise object.
|
|
FailLoaders(NS_ERROR_FAILURE);
|
|
}
|
|
|
|
void
|
|
CacheScriptLoader::Fail(nsresult aRv)
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(NS_FAILED(aRv));
|
|
|
|
if (mFailed) {
|
|
return;
|
|
}
|
|
|
|
mFailed = true;
|
|
|
|
if (mPump) {
|
|
MOZ_ASSERT(mLoadInfo.mCacheStatus == ScriptLoadInfo::ReadingFromCache);
|
|
mPump->Cancel(aRv);
|
|
mPump = nullptr;
|
|
}
|
|
|
|
mLoadInfo.mCacheStatus = ScriptLoadInfo::Cancel;
|
|
|
|
// Stop if the load was aborted on the main thread.
|
|
// Can't use Finished() because mCachePromise may still be true.
|
|
if (mLoadInfo.mLoadingFinished) {
|
|
MOZ_ASSERT(!mLoadInfo.mChannel);
|
|
MOZ_ASSERT_IF(mLoadInfo.mCachePromise,
|
|
mLoadInfo.mCacheStatus == ScriptLoadInfo::WritingToCache ||
|
|
mLoadInfo.mCacheStatus == ScriptLoadInfo::Cancel);
|
|
return;
|
|
}
|
|
|
|
mRunnable->LoadingFinished(mIndex, aRv);
|
|
}
|
|
|
|
void
|
|
CacheScriptLoader::Load(Cache* aCache)
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(aCache);
|
|
|
|
nsCOMPtr<nsIURI> uri;
|
|
nsresult rv = NS_NewURI(getter_AddRefs(uri), mLoadInfo.mURL, nullptr,
|
|
mBaseURI);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
Fail(rv);
|
|
return;
|
|
}
|
|
|
|
nsAutoCString spec;
|
|
rv = uri->GetSpec(spec);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
Fail(rv);
|
|
return;
|
|
}
|
|
|
|
MOZ_ASSERT(mLoadInfo.mFullURL.IsEmpty());
|
|
CopyUTF8toUTF16(spec, mLoadInfo.mFullURL);
|
|
|
|
mozilla::dom::RequestOrUSVString request;
|
|
request.SetAsUSVString().Rebind(mLoadInfo.mFullURL.Data(),
|
|
mLoadInfo.mFullURL.Length());
|
|
|
|
mozilla::dom::CacheQueryOptions params;
|
|
|
|
ErrorResult error;
|
|
RefPtr<Promise> promise = aCache->Match(request, params, error);
|
|
if (NS_WARN_IF(error.Failed())) {
|
|
Fail(error.StealNSResult());
|
|
return;
|
|
}
|
|
|
|
promise->AppendNativeHandler(this);
|
|
}
|
|
|
|
void
|
|
CacheScriptLoader::RejectedCallback(JSContext* aCx,
|
|
JS::Handle<JS::Value> aValue)
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(mLoadInfo.mCacheStatus == ScriptLoadInfo::Uncached);
|
|
Fail(NS_ERROR_FAILURE);
|
|
}
|
|
|
|
void
|
|
CacheScriptLoader::ResolvedCallback(JSContext* aCx,
|
|
JS::Handle<JS::Value> aValue)
|
|
{
|
|
AssertIsOnMainThread();
|
|
// If we have already called 'Fail', we should not proceed.
|
|
if (mFailed) {
|
|
return;
|
|
}
|
|
|
|
MOZ_ASSERT(mLoadInfo.mCacheStatus == ScriptLoadInfo::Uncached);
|
|
|
|
nsresult rv;
|
|
|
|
if (aValue.isUndefined()) {
|
|
mLoadInfo.mCacheStatus = ScriptLoadInfo::ToBeCached;
|
|
rv = mRunnable->LoadScript(mIndex);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
Fail(rv);
|
|
}
|
|
return;
|
|
}
|
|
|
|
MOZ_ASSERT(aValue.isObject());
|
|
|
|
JS::Rooted<JSObject*> obj(aCx, &aValue.toObject());
|
|
mozilla::dom::Response* response = nullptr;
|
|
rv = UNWRAP_OBJECT(Response, obj, response);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
Fail(rv);
|
|
return;
|
|
}
|
|
|
|
nsCOMPtr<nsIInputStream> inputStream;
|
|
response->GetBody(getter_AddRefs(inputStream));
|
|
mChannelInfo = response->GetChannelInfo();
|
|
const UniquePtr<PrincipalInfo>& pInfo = response->GetPrincipalInfo();
|
|
if (pInfo) {
|
|
mPrincipalInfo = mozilla::MakeUnique<PrincipalInfo>(*pInfo);
|
|
}
|
|
|
|
if (!inputStream) {
|
|
mLoadInfo.mCacheStatus = ScriptLoadInfo::Cached;
|
|
mRunnable->DataReceivedFromCache(mIndex, (uint8_t*)"", 0, mChannelInfo,
|
|
Move(mPrincipalInfo));
|
|
return;
|
|
}
|
|
|
|
MOZ_ASSERT(!mPump);
|
|
rv = NS_NewInputStreamPump(getter_AddRefs(mPump), inputStream);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
Fail(rv);
|
|
return;
|
|
}
|
|
|
|
nsCOMPtr<nsIStreamLoader> loader;
|
|
rv = NS_NewStreamLoader(getter_AddRefs(loader), this);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
Fail(rv);
|
|
return;
|
|
}
|
|
|
|
rv = mPump->AsyncRead(loader, nullptr);
|
|
if (NS_WARN_IF(NS_FAILED(rv))) {
|
|
mPump = nullptr;
|
|
Fail(rv);
|
|
return;
|
|
}
|
|
|
|
|
|
nsCOMPtr<nsIThreadRetargetableRequest> rr = do_QueryInterface(mPump);
|
|
if (rr) {
|
|
nsCOMPtr<nsIEventTarget> sts =
|
|
do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
|
|
rv = rr->RetargetDeliveryTo(sts);
|
|
if (NS_FAILED(rv)) {
|
|
NS_WARNING("Failed to dispatch the nsIInputStreamPump to a IO thread.");
|
|
}
|
|
}
|
|
|
|
mLoadInfo.mCacheStatus = ScriptLoadInfo::ReadingFromCache;
|
|
}
|
|
|
|
NS_IMETHODIMP
|
|
CacheScriptLoader::OnStreamComplete(nsIStreamLoader* aLoader, nsISupports* aContext,
|
|
nsresult aStatus, uint32_t aStringLen,
|
|
const uint8_t* aString)
|
|
{
|
|
AssertIsOnMainThread();
|
|
MOZ_ASSERT(mLoadInfo.mCacheStatus == ScriptLoadInfo::ReadingFromCache);
|
|
|
|
mPump = nullptr;
|
|
|
|
if (NS_FAILED(aStatus)) {
|
|
Fail(aStatus);
|
|
return NS_OK;
|
|
}
|
|
|
|
mLoadInfo.mCacheStatus = ScriptLoadInfo::Cached;
|
|
|
|
MOZ_ASSERT(mPrincipalInfo);
|
|
mRunnable->DataReceivedFromCache(mIndex, aString, aStringLen, mChannelInfo,
|
|
Move(mPrincipalInfo));
|
|
return NS_OK;
|
|
}
|
|
|
|
class ChannelGetterRunnable final : public nsRunnable
|
|
{
|
|
WorkerPrivate* mParentWorker;
|
|
nsCOMPtr<nsIEventTarget> mSyncLoopTarget;
|
|
const nsAString& mScriptURL;
|
|
nsIChannel** mChannel;
|
|
nsresult mResult;
|
|
|
|
public:
|
|
ChannelGetterRunnable(WorkerPrivate* aParentWorker,
|
|
nsIEventTarget* aSyncLoopTarget,
|
|
const nsAString& aScriptURL,
|
|
nsIChannel** aChannel)
|
|
: mParentWorker(aParentWorker), mSyncLoopTarget(aSyncLoopTarget),
|
|
mScriptURL(aScriptURL), mChannel(aChannel), mResult(NS_ERROR_FAILURE)
|
|
{
|
|
MOZ_ASSERT(mParentWorker);
|
|
aParentWorker->AssertIsOnWorkerThread();
|
|
MOZ_ASSERT(aSyncLoopTarget);
|
|
}
|
|
|
|
NS_IMETHOD
|
|
Run() override
|
|
{
|
|
AssertIsOnMainThread();
|
|
|
|
nsIPrincipal* principal = mParentWorker->GetPrincipal();
|
|
MOZ_ASSERT(principal);
|
|
|
|
// Figure out our base URI.
|
|
nsCOMPtr<nsIURI> baseURI = mParentWorker->GetBaseURI();
|
|
MOZ_ASSERT(baseURI);
|
|
|
|
// May be null.
|
|
nsCOMPtr<nsIDocument> parentDoc = mParentWorker->GetDocument();
|
|
|
|
nsCOMPtr<nsILoadGroup> loadGroup = mParentWorker->GetLoadGroup();
|
|
|
|
nsCOMPtr<nsIChannel> channel;
|
|
mResult =
|
|
scriptloader::ChannelFromScriptURLMainThread(principal, baseURI,
|
|
parentDoc, loadGroup,
|
|
mScriptURL,
|
|
// Nested workers are always dedicated.
|
|
nsIContentPolicy::TYPE_INTERNAL_WORKER,
|
|
getter_AddRefs(channel));
|
|
if (NS_SUCCEEDED(mResult)) {
|
|
channel.forget(mChannel);
|
|
}
|
|
|
|
RefPtr<MainThreadStopSyncLoopRunnable> runnable =
|
|
new MainThreadStopSyncLoopRunnable(mParentWorker,
|
|
mSyncLoopTarget.forget(), true);
|
|
if (!runnable->Dispatch()) {
|
|
NS_ERROR("This should never fail!");
|
|
}
|
|
|
|
return NS_OK;
|
|
}
|
|
|
|
nsresult
|
|
GetResult() const
|
|
{
|
|
return mResult;
|
|
}
|
|
|
|
private:
|
|
virtual ~ChannelGetterRunnable()
|
|
{ }
|
|
};
|
|
|
|
ScriptExecutorRunnable::ScriptExecutorRunnable(
|
|
ScriptLoaderRunnable& aScriptLoader,
|
|
nsIEventTarget* aSyncLoopTarget,
|
|
bool aIsWorkerScript,
|
|
uint32_t aFirstIndex,
|
|
uint32_t aLastIndex)
|
|
: MainThreadWorkerSyncRunnable(aScriptLoader.mWorkerPrivate, aSyncLoopTarget),
|
|
mScriptLoader(aScriptLoader), mIsWorkerScript(aIsWorkerScript),
|
|
mFirstIndex(aFirstIndex), mLastIndex(aLastIndex)
|
|
{
|
|
MOZ_ASSERT(aFirstIndex <= aLastIndex);
|
|
MOZ_ASSERT(aLastIndex < aScriptLoader.mLoadInfos.Length());
|
|
}
|
|
|
|
bool
|
|
ScriptExecutorRunnable::IsDebuggerRunnable() const
|
|
{
|
|
// ScriptExecutorRunnable is used to execute both worker and debugger scripts.
|
|
// In the latter case, the runnable needs to be dispatched to the debugger
|
|
// queue.
|
|
return mScriptLoader.mWorkerScriptType == DebuggerScript;
|
|
}
|
|
|
|
bool
|
|
ScriptExecutorRunnable::PreRun(WorkerPrivate* aWorkerPrivate)
|
|
{
|
|
aWorkerPrivate->AssertIsOnWorkerThread();
|
|
|
|
if (!mIsWorkerScript) {
|
|
return true;
|
|
}
|
|
|
|
if (!aWorkerPrivate->GetJSContext()) {
|
|
return false;
|
|
}
|
|
|
|
MOZ_ASSERT(mFirstIndex == 0);
|
|
MOZ_ASSERT(!mScriptLoader.mRv.Failed());
|
|
|
|
AutoJSAPI jsapi;
|
|
jsapi.Init();
|
|
jsapi.TakeOwnershipOfErrorReporting();
|
|
|
|
WorkerGlobalScope* globalScope =
|
|
aWorkerPrivate->GetOrCreateGlobalScope(jsapi.cx());
|
|
if (NS_WARN_IF(!globalScope)) {
|
|
NS_WARNING("Failed to make global!");
|
|
// There's no way to report the exception on jsapi right now, because there
|
|
// is no way to even enter a compartment on this thread anymore. Just clear
|
|
// the exception. We'll report some sort of error to our caller thread in
|
|
// ShutdownScriptLoader.
|
|
jsapi.ClearException();
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
bool
|
|
ScriptExecutorRunnable::WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate)
|
|
{
|
|
aWorkerPrivate->AssertIsOnWorkerThread();
|
|
|
|
nsTArray<ScriptLoadInfo>& loadInfos = mScriptLoader.mLoadInfos;
|
|
|
|
// Don't run if something else has already failed.
|
|
for (uint32_t index = 0; index < mFirstIndex; index++) {
|
|
ScriptLoadInfo& loadInfo = loadInfos.ElementAt(index);
|
|
|
|
NS_ASSERTION(!loadInfo.mChannel, "Should no longer have a channel!");
|
|
NS_ASSERTION(loadInfo.mExecutionScheduled, "Should be scheduled!");
|
|
|
|
if (!loadInfo.mExecutionResult) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
// If nothing else has failed, our ErrorResult better not be a failure either.
|
|
MOZ_ASSERT(!mScriptLoader.mRv.Failed(), "Who failed it and why?");
|
|
|
|
// Slightly icky action at a distance, but there's no better place to stash
|
|
// this value, really.
|
|
JS::Rooted<JSObject*> global(aCx, JS::CurrentGlobalOrNull(aCx));
|
|
MOZ_ASSERT(global);
|
|
|
|
for (uint32_t index = mFirstIndex; index <= mLastIndex; index++) {
|
|
ScriptLoadInfo& loadInfo = loadInfos.ElementAt(index);
|
|
|
|
NS_ASSERTION(!loadInfo.mChannel, "Should no longer have a channel!");
|
|
NS_ASSERTION(loadInfo.mExecutionScheduled, "Should be scheduled!");
|
|
NS_ASSERTION(!loadInfo.mExecutionResult, "Should not have executed yet!");
|
|
|
|
MOZ_ASSERT(!mScriptLoader.mRv.Failed(), "Who failed it and why?");
|
|
mScriptLoader.mRv.MightThrowJSException();
|
|
if (NS_FAILED(loadInfo.mLoadResult)) {
|
|
scriptloader::ReportLoadError(mScriptLoader.mRv,
|
|
loadInfo.mLoadResult, loadInfo.mURL);
|
|
// Top level scripts only!
|
|
if (mIsWorkerScript) {
|
|
aWorkerPrivate->MaybeDispatchLoadFailedRunnable();
|
|
}
|
|
return true;
|
|
}
|
|
|
|
NS_ConvertUTF16toUTF8 filename(loadInfo.mURL);
|
|
|
|
JS::CompileOptions options(aCx);
|
|
options.setFileAndLine(filename.get(), 1)
|
|
.setNoScriptRval(true);
|
|
|
|
if (mScriptLoader.mWorkerScriptType == DebuggerScript) {
|
|
options.setVersion(JSVERSION_LATEST);
|
|
}
|
|
|
|
MOZ_ASSERT(loadInfo.mMutedErrorFlag.isSome());
|
|
options.setMutedErrors(loadInfo.mMutedErrorFlag.valueOr(true));
|
|
|
|
JS::SourceBufferHolder srcBuf(loadInfo.mScriptTextBuf,
|
|
loadInfo.mScriptTextLength,
|
|
JS::SourceBufferHolder::GiveOwnership);
|
|
loadInfo.mScriptTextBuf = nullptr;
|
|
loadInfo.mScriptTextLength = 0;
|
|
|
|
// Our ErrorResult still shouldn't be a failure.
|
|
MOZ_ASSERT(!mScriptLoader.mRv.Failed(), "Who failed it and why?");
|
|
JS::Rooted<JS::Value> unused(aCx);
|
|
if (!JS::Evaluate(aCx, options, srcBuf, &unused)) {
|
|
mScriptLoader.mRv.StealExceptionFromJSContext(aCx);
|
|
return true;
|
|
}
|
|
|
|
loadInfo.mExecutionResult = true;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
void
|
|
ScriptExecutorRunnable::PostRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate,
|
|
bool aRunResult)
|
|
{
|
|
aWorkerPrivate->AssertIsOnWorkerThread();
|
|
MOZ_ASSERT(!JS_IsExceptionPending(aCx), "Who left an exception on there?");
|
|
|
|
nsTArray<ScriptLoadInfo>& loadInfos = mScriptLoader.mLoadInfos;
|
|
|
|
if (mLastIndex == loadInfos.Length() - 1) {
|
|
// All done. If anything failed then return false.
|
|
bool result = true;
|
|
bool mutedError = false;
|
|
for (uint32_t index = 0; index < loadInfos.Length(); index++) {
|
|
if (!loadInfos[index].mExecutionResult) {
|
|
mutedError = loadInfos[index].mMutedErrorFlag.valueOr(true);
|
|
result = false;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// The only way we can get here with "result" false but without
|
|
// mScriptLoader.mRv being a failure is if we're loading the main worker
|
|
// script and GetOrCreateGlobalScope() fails. In that case we would have
|
|
// returned false from WorkerRun, so assert that.
|
|
MOZ_ASSERT_IF(!result && !mScriptLoader.mRv.Failed(),
|
|
!aRunResult);
|
|
ShutdownScriptLoader(aCx, aWorkerPrivate, result, mutedError);
|
|
}
|
|
}
|
|
|
|
NS_IMETHODIMP
|
|
ScriptExecutorRunnable::Cancel()
|
|
{
|
|
if (mLastIndex == mScriptLoader.mLoadInfos.Length() - 1) {
|
|
ShutdownScriptLoader(mWorkerPrivate->GetJSContext(), mWorkerPrivate,
|
|
false, false);
|
|
}
|
|
return MainThreadWorkerSyncRunnable::Cancel();
|
|
}
|
|
|
|
void
|
|
ScriptExecutorRunnable::ShutdownScriptLoader(JSContext* aCx,
|
|
WorkerPrivate* aWorkerPrivate,
|
|
bool aResult,
|
|
bool aMutedError)
|
|
{
|
|
aWorkerPrivate->AssertIsOnWorkerThread();
|
|
|
|
MOZ_ASSERT(mLastIndex == mScriptLoader.mLoadInfos.Length() - 1);
|
|
|
|
if (mIsWorkerScript && aWorkerPrivate->IsServiceWorker()) {
|
|
aWorkerPrivate->SetLoadingWorkerScript(false);
|
|
}
|
|
|
|
if (!aResult) {
|
|
// At this point there are two possibilities:
|
|
//
|
|
// 1) mScriptLoader.mRv.Failed(). In that case we just want to leave it
|
|
// as-is, except if it has a JS exception and we need to mute JS
|
|
// exceptions. In that case, we log the exception without firing any
|
|
// events and then replace it on the ErrorResult with a generic
|
|
// NS_ERROR_FAILURE for lack of anything better. XXXbz: This should
|
|
// throw a NetworkError per spec updates. See bug 1249673.
|
|
//
|
|
// 2) mScriptLoader.mRv succeeded. As far as I can tell, this can only
|
|
// happen when loading the main worker script and
|
|
// GetOrCreateGlobalScope() fails or if ScriptExecutorRunnable::Cancel
|
|
// got called. Does it matter what we throw in this case? I'm not
|
|
// sure...
|
|
if (mScriptLoader.mRv.Failed()) {
|
|
if (aMutedError && mScriptLoader.mRv.IsJSException()) {
|
|
LogExceptionToConsole(aCx, aWorkerPrivate);
|
|
mScriptLoader.mRv.Throw(NS_ERROR_FAILURE);
|
|
}
|
|
} else {
|
|
mScriptLoader.mRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
|
|
}
|
|
}
|
|
|
|
aWorkerPrivate->RemoveFeature(&mScriptLoader);
|
|
aWorkerPrivate->StopSyncLoop(mSyncLoopTarget, aResult);
|
|
}
|
|
|
|
void
|
|
ScriptExecutorRunnable::LogExceptionToConsole(JSContext* aCx,
|
|
WorkerPrivate* aWorkerPrivate)
|
|
{
|
|
aWorkerPrivate->AssertIsOnWorkerThread();
|
|
|
|
MOZ_ASSERT(mScriptLoader.mRv.IsJSException());
|
|
|
|
JS::Rooted<JS::Value> exn(aCx);
|
|
if (!ToJSValue(aCx, mScriptLoader.mRv, &exn)) {
|
|
return;
|
|
}
|
|
|
|
// Now the exception state should all be in exn.
|
|
MOZ_ASSERT(!JS_IsExceptionPending(aCx));
|
|
MOZ_ASSERT(!mScriptLoader.mRv.Failed());
|
|
|
|
js::ErrorReport report(aCx);
|
|
if (!report.init(aCx, exn)) {
|
|
JS_ClearPendingException(aCx);
|
|
return;
|
|
}
|
|
|
|
RefPtr<xpc::ErrorReport> xpcReport = new xpc::ErrorReport();
|
|
xpcReport->Init(report.report(), report.message(),
|
|
aWorkerPrivate->IsChromeWorker(), aWorkerPrivate->WindowID());
|
|
|
|
RefPtr<AsyncErrorReporter> r = new AsyncErrorReporter(xpcReport);
|
|
NS_DispatchToMainThread(r);
|
|
}
|
|
|
|
void
|
|
LoadAllScripts(WorkerPrivate* aWorkerPrivate,
|
|
nsTArray<ScriptLoadInfo>& aLoadInfos, bool aIsMainScript,
|
|
WorkerScriptType aWorkerScriptType, ErrorResult& aRv)
|
|
{
|
|
aWorkerPrivate->AssertIsOnWorkerThread();
|
|
NS_ASSERTION(!aLoadInfos.IsEmpty(), "Bad arguments!");
|
|
|
|
AutoSyncLoopHolder syncLoop(aWorkerPrivate);
|
|
|
|
RefPtr<ScriptLoaderRunnable> loader =
|
|
new ScriptLoaderRunnable(aWorkerPrivate, syncLoop.EventTarget(),
|
|
aLoadInfos, aIsMainScript, aWorkerScriptType,
|
|
aRv);
|
|
|
|
NS_ASSERTION(aLoadInfos.IsEmpty(), "Should have swapped!");
|
|
|
|
if (!aWorkerPrivate->AddFeature(loader)) {
|
|
aRv.Throw(NS_ERROR_FAILURE);
|
|
return;
|
|
}
|
|
|
|
if (NS_FAILED(NS_DispatchToMainThread(loader))) {
|
|
NS_ERROR("Failed to dispatch!");
|
|
|
|
aWorkerPrivate->RemoveFeature(loader);
|
|
aRv.Throw(NS_ERROR_FAILURE);
|
|
return;
|
|
}
|
|
|
|
syncLoop.Run();
|
|
}
|
|
|
|
} /* anonymous namespace */
|
|
|
|
BEGIN_WORKERS_NAMESPACE
|
|
|
|
namespace scriptloader {
|
|
|
|
nsresult
|
|
ChannelFromScriptURLMainThread(nsIPrincipal* aPrincipal,
|
|
nsIURI* aBaseURI,
|
|
nsIDocument* aParentDoc,
|
|
nsILoadGroup* aLoadGroup,
|
|
const nsAString& aScriptURL,
|
|
nsContentPolicyType aContentPolicyType,
|
|
nsIChannel** aChannel)
|
|
{
|
|
AssertIsOnMainThread();
|
|
|
|
nsCOMPtr<nsIIOService> ios(do_GetIOService());
|
|
|
|
nsIScriptSecurityManager* secMan = nsContentUtils::GetSecurityManager();
|
|
NS_ASSERTION(secMan, "This should never be null!");
|
|
|
|
return ChannelFromScriptURL(aPrincipal, aBaseURI, aParentDoc, aLoadGroup,
|
|
ios, secMan, aScriptURL, true, WorkerScript,
|
|
aContentPolicyType, nsIRequest::LOAD_NORMAL,
|
|
aChannel);
|
|
}
|
|
|
|
nsresult
|
|
ChannelFromScriptURLWorkerThread(JSContext* aCx,
|
|
WorkerPrivate* aParent,
|
|
const nsAString& aScriptURL,
|
|
nsIChannel** aChannel)
|
|
{
|
|
aParent->AssertIsOnWorkerThread();
|
|
|
|
AutoSyncLoopHolder syncLoop(aParent);
|
|
|
|
RefPtr<ChannelGetterRunnable> getter =
|
|
new ChannelGetterRunnable(aParent, syncLoop.EventTarget(), aScriptURL,
|
|
aChannel);
|
|
|
|
if (NS_FAILED(NS_DispatchToMainThread(getter))) {
|
|
NS_ERROR("Failed to dispatch!");
|
|
return NS_ERROR_FAILURE;
|
|
}
|
|
|
|
if (!syncLoop.Run()) {
|
|
return NS_ERROR_FAILURE;
|
|
}
|
|
|
|
return getter->GetResult();
|
|
}
|
|
|
|
void ReportLoadError(ErrorResult& aRv, nsresult aLoadResult,
|
|
const nsAString& aScriptURL)
|
|
{
|
|
MOZ_ASSERT(!aRv.Failed());
|
|
|
|
switch (aLoadResult) {
|
|
case NS_ERROR_FILE_NOT_FOUND:
|
|
case NS_ERROR_NOT_AVAILABLE:
|
|
aLoadResult = NS_ERROR_DOM_NETWORK_ERR;
|
|
break;
|
|
|
|
case NS_ERROR_MALFORMED_URI:
|
|
aLoadResult = NS_ERROR_DOM_SYNTAX_ERR;
|
|
break;
|
|
|
|
case NS_BINDING_ABORTED:
|
|
// Note: we used to pretend like we didn't set an exception for
|
|
// NS_BINDING_ABORTED, but then ShutdownScriptLoader did it anyway. The
|
|
// other callsite, in WorkerPrivate::Constructor, never passed in
|
|
// NS_BINDING_ABORTED. So just throw it directly here. Consumers will
|
|
// deal as needed. But note that we do NOT want to ThrowDOMException()
|
|
// for this case, because that will make it impossible for consumers to
|
|
// realize that our error was NS_BINDING_ABORTED.
|
|
aRv.Throw(aLoadResult);
|
|
return;
|
|
|
|
case NS_ERROR_DOM_SECURITY_ERR:
|
|
case NS_ERROR_DOM_SYNTAX_ERR:
|
|
break;
|
|
|
|
case NS_ERROR_DOM_BAD_URI:
|
|
// This is actually a security error.
|
|
aLoadResult = NS_ERROR_DOM_SECURITY_ERR;
|
|
break;
|
|
|
|
default:
|
|
// For lack of anything better, go ahead and throw a NetworkError here.
|
|
// We don't want to throw a JS exception, because for toplevel script
|
|
// loads that would get squelched.
|
|
aRv.ThrowDOMException(NS_ERROR_DOM_NETWORK_ERR,
|
|
nsPrintfCString("Failed to load worker script at %s (nsresult = 0x%x)",
|
|
NS_ConvertUTF16toUTF8(aScriptURL).get(),
|
|
aLoadResult));
|
|
return;
|
|
}
|
|
|
|
aRv.ThrowDOMException(aLoadResult,
|
|
NS_LITERAL_CSTRING("Failed to load worker script at \"") +
|
|
NS_ConvertUTF16toUTF8(aScriptURL) +
|
|
NS_LITERAL_CSTRING("\""));
|
|
}
|
|
|
|
void
|
|
LoadMainScript(WorkerPrivate* aWorkerPrivate,
|
|
const nsAString& aScriptURL,
|
|
WorkerScriptType aWorkerScriptType,
|
|
ErrorResult& aRv)
|
|
{
|
|
nsTArray<ScriptLoadInfo> loadInfos;
|
|
|
|
ScriptLoadInfo* info = loadInfos.AppendElement();
|
|
info->mURL = aScriptURL;
|
|
|
|
LoadAllScripts(aWorkerPrivate, loadInfos, true, aWorkerScriptType, aRv);
|
|
}
|
|
|
|
void
|
|
Load(WorkerPrivate* aWorkerPrivate,
|
|
const nsTArray<nsString>& aScriptURLs, WorkerScriptType aWorkerScriptType,
|
|
ErrorResult& aRv)
|
|
{
|
|
const uint32_t urlCount = aScriptURLs.Length();
|
|
|
|
if (!urlCount) {
|
|
return;
|
|
}
|
|
|
|
if (urlCount > MAX_CONCURRENT_SCRIPTS) {
|
|
aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
|
|
return;
|
|
}
|
|
|
|
nsTArray<ScriptLoadInfo> loadInfos;
|
|
loadInfos.SetLength(urlCount);
|
|
|
|
for (uint32_t index = 0; index < urlCount; index++) {
|
|
loadInfos[index].mURL = aScriptURLs[index];
|
|
}
|
|
|
|
LoadAllScripts(aWorkerPrivate, loadInfos, false, aWorkerScriptType, aRv);
|
|
}
|
|
|
|
} // namespace scriptloader
|
|
|
|
END_WORKERS_NAMESPACE
|