ScriptLoader.cpp 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #include "ScriptLoader.h"
  6. #include "nsIChannel.h"
  7. #include "nsIContentPolicy.h"
  8. #include "nsIContentSecurityPolicy.h"
  9. #include "nsIDocShell.h"
  10. #include "nsIDOMDocument.h"
  11. #include "nsIHttpChannel.h"
  12. #include "nsIHttpChannelInternal.h"
  13. #include "nsIInputStreamPump.h"
  14. #include "nsIIOService.h"
  15. #include "nsIProtocolHandler.h"
  16. #include "nsIScriptError.h"
  17. #include "nsIScriptSecurityManager.h"
  18. #include "nsIStreamLoader.h"
  19. #include "nsIStreamListenerTee.h"
  20. #include "nsIThreadRetargetableRequest.h"
  21. #include "nsIURI.h"
  22. #include "jsapi.h"
  23. #include "jsfriendapi.h"
  24. #include "nsError.h"
  25. #include "nsContentPolicyUtils.h"
  26. #include "nsContentUtils.h"
  27. #include "nsDocShellCID.h"
  28. #include "nsISupportsPrimitives.h"
  29. #include "nsNetUtil.h"
  30. #include "nsIPipe.h"
  31. #include "nsIOutputStream.h"
  32. #include "nsPrintfCString.h"
  33. #include "nsString.h"
  34. #include "nsStreamUtils.h"
  35. #include "nsTArray.h"
  36. #include "nsThreadUtils.h"
  37. #include "nsXPCOM.h"
  38. #include "xpcpublic.h"
  39. #include "mozilla/Assertions.h"
  40. #include "mozilla/LoadContext.h"
  41. #include "mozilla/Maybe.h"
  42. #include "mozilla/ipc/BackgroundUtils.h"
  43. #include "mozilla/dom/CacheBinding.h"
  44. #include "mozilla/dom/cache/CacheTypes.h"
  45. #include "mozilla/dom/cache/Cache.h"
  46. #include "mozilla/dom/cache/CacheStorage.h"
  47. #include "mozilla/dom/ChannelInfo.h"
  48. #include "mozilla/dom/Exceptions.h"
  49. #include "mozilla/dom/InternalResponse.h"
  50. #include "mozilla/dom/nsCSPService.h"
  51. #include "mozilla/dom/nsCSPUtils.h"
  52. #include "mozilla/dom/Promise.h"
  53. #include "mozilla/dom/PromiseNativeHandler.h"
  54. #include "mozilla/dom/Response.h"
  55. #include "mozilla/dom/ScriptLoader.h"
  56. #include "mozilla/dom/ScriptSettings.h"
  57. #include "mozilla/dom/SRILogHelper.h"
  58. #include "mozilla/UniquePtr.h"
  59. #include "Principal.h"
  60. #include "WorkerHolder.h"
  61. #include "WorkerPrivate.h"
  62. #include "WorkerRunnable.h"
  63. #include "WorkerScope.h"
  64. #define MAX_CONCURRENT_SCRIPTS 1000
  65. USING_WORKERS_NAMESPACE
  66. using namespace mozilla;
  67. using namespace mozilla::dom;
  68. using mozilla::dom::cache::Cache;
  69. using mozilla::dom::cache::CacheStorage;
  70. using mozilla::ipc::PrincipalInfo;
  71. namespace {
  72. nsIURI*
  73. GetBaseURI(bool aIsMainScript, WorkerPrivate* aWorkerPrivate)
  74. {
  75. MOZ_ASSERT(aWorkerPrivate);
  76. nsIURI* baseURI;
  77. WorkerPrivate* parentWorker = aWorkerPrivate->GetParent();
  78. if (aIsMainScript) {
  79. if (parentWorker) {
  80. baseURI = parentWorker->GetBaseURI();
  81. NS_ASSERTION(baseURI, "Should have been set already!");
  82. }
  83. else {
  84. // May be null.
  85. baseURI = aWorkerPrivate->GetBaseURI();
  86. }
  87. }
  88. else {
  89. baseURI = aWorkerPrivate->GetBaseURI();
  90. NS_ASSERTION(baseURI, "Should have been set already!");
  91. }
  92. return baseURI;
  93. }
  94. nsresult
  95. ChannelFromScriptURL(nsIPrincipal* principal,
  96. nsIURI* baseURI,
  97. nsIDocument* parentDoc,
  98. nsILoadGroup* loadGroup,
  99. nsIIOService* ios,
  100. nsIScriptSecurityManager* secMan,
  101. const nsAString& aScriptURL,
  102. bool aIsMainScript,
  103. WorkerScriptType aWorkerScriptType,
  104. nsContentPolicyType aContentPolicyType,
  105. nsLoadFlags aLoadFlags,
  106. bool aDefaultURIEncoding,
  107. nsIChannel** aChannel)
  108. {
  109. AssertIsOnMainThread();
  110. nsresult rv;
  111. nsCOMPtr<nsIURI> uri;
  112. if (aDefaultURIEncoding) {
  113. rv = NS_NewURI(getter_AddRefs(uri), aScriptURL, nullptr, baseURI);
  114. } else {
  115. rv = nsContentUtils::NewURIWithDocumentCharset(getter_AddRefs(uri),
  116. aScriptURL, parentDoc,
  117. baseURI);
  118. }
  119. if (NS_FAILED(rv)) {
  120. return NS_ERROR_DOM_SYNTAX_ERR;
  121. }
  122. // If we have the document, use it. Unfortunately, for dedicated workers
  123. // 'parentDoc' ends up being the parent document, which is not the document
  124. // that we want to use. So make sure to avoid using 'parentDoc' in that
  125. // situation.
  126. if (parentDoc && parentDoc->NodePrincipal() != principal) {
  127. parentDoc = nullptr;
  128. }
  129. aLoadFlags |= nsIChannel::LOAD_CLASSIFY_URI;
  130. uint32_t secFlags = aIsMainScript ? nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED
  131. : nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS;
  132. if (aWorkerScriptType == DebuggerScript) {
  133. // A DebuggerScript needs to be a local resource like chrome: or resource:
  134. bool isUIResource = false;
  135. rv = NS_URIChainHasFlags(uri, nsIProtocolHandler::URI_IS_UI_RESOURCE,
  136. &isUIResource);
  137. if (NS_WARN_IF(NS_FAILED(rv))) {
  138. return rv;
  139. }
  140. if (!isUIResource) {
  141. return NS_ERROR_DOM_SECURITY_ERR;
  142. }
  143. secFlags |= nsILoadInfo::SEC_ALLOW_CHROME;
  144. }
  145. // Note: this is for backwards compatibility and goes against spec.
  146. // We should find a better solution.
  147. bool isData = false;
  148. if (aIsMainScript && NS_SUCCEEDED(uri->SchemeIs("data", &isData)) && isData) {
  149. secFlags = nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL;
  150. }
  151. nsCOMPtr<nsIChannel> channel;
  152. // If we have the document, use it. Unfortunately, for dedicated workers
  153. // 'parentDoc' ends up being the parent document, which is not the document
  154. // that we want to use. So make sure to avoid using 'parentDoc' in that
  155. // situation.
  156. if (parentDoc && parentDoc->NodePrincipal() == principal) {
  157. rv = NS_NewChannel(getter_AddRefs(channel),
  158. uri,
  159. parentDoc,
  160. secFlags,
  161. aContentPolicyType,
  162. loadGroup,
  163. nullptr, // aCallbacks
  164. aLoadFlags,
  165. ios);
  166. } else {
  167. // We must have a loadGroup with a load context for the principal to
  168. // traverse the channel correctly.
  169. MOZ_ASSERT(loadGroup);
  170. MOZ_ASSERT(NS_LoadGroupMatchesPrincipal(loadGroup, principal));
  171. rv = NS_NewChannel(getter_AddRefs(channel),
  172. uri,
  173. principal,
  174. secFlags,
  175. aContentPolicyType,
  176. loadGroup,
  177. nullptr, // aCallbacks
  178. aLoadFlags,
  179. ios);
  180. }
  181. NS_ENSURE_SUCCESS(rv, rv);
  182. if (nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(channel)) {
  183. rv = nsContentUtils::SetFetchReferrerURIWithPolicy(principal, parentDoc,
  184. httpChannel, mozilla::net::RP_Default);
  185. if (NS_WARN_IF(NS_FAILED(rv))) {
  186. return rv;
  187. }
  188. }
  189. channel.forget(aChannel);
  190. return rv;
  191. }
  192. struct ScriptLoadInfo
  193. {
  194. ScriptLoadInfo()
  195. : mScriptTextBuf(nullptr)
  196. , mScriptTextLength(0)
  197. , mLoadResult(NS_ERROR_NOT_INITIALIZED)
  198. , mLoadingFinished(false)
  199. , mExecutionScheduled(false)
  200. , mExecutionResult(false)
  201. , mCacheStatus(Uncached)
  202. { }
  203. ~ScriptLoadInfo()
  204. {
  205. if (mScriptTextBuf) {
  206. js_free(mScriptTextBuf);
  207. }
  208. }
  209. bool
  210. ReadyToExecute()
  211. {
  212. return !mChannel && NS_SUCCEEDED(mLoadResult) && !mExecutionScheduled;
  213. }
  214. nsString mURL;
  215. // This full URL string is populated only if this object is used in a
  216. // ServiceWorker.
  217. nsString mFullURL;
  218. // This promise is set only when the script is for a ServiceWorker but
  219. // it's not in the cache yet. The promise is resolved when the full body is
  220. // stored into the cache. mCachePromise will be set to nullptr after
  221. // resolution.
  222. RefPtr<Promise> mCachePromise;
  223. // The reader stream the cache entry should be filled from, for those cases
  224. // when we're going to have an mCachePromise.
  225. nsCOMPtr<nsIInputStream> mCacheReadStream;
  226. nsCOMPtr<nsIChannel> mChannel;
  227. char16_t* mScriptTextBuf;
  228. size_t mScriptTextLength;
  229. nsresult mLoadResult;
  230. bool mLoadingFinished;
  231. bool mExecutionScheduled;
  232. bool mExecutionResult;
  233. enum CacheStatus {
  234. // By default a normal script is just loaded from the network. But for
  235. // ServiceWorkers, we have to check if the cache contains the script and
  236. // load it from the cache.
  237. Uncached,
  238. WritingToCache,
  239. ReadingFromCache,
  240. // This script has been loaded from the ServiceWorker cache.
  241. Cached,
  242. // This script must be stored in the ServiceWorker cache.
  243. ToBeCached,
  244. // Something went wrong or the worker went away.
  245. Cancel
  246. };
  247. CacheStatus mCacheStatus;
  248. Maybe<bool> mMutedErrorFlag;
  249. bool Finished() const
  250. {
  251. return mLoadingFinished && !mCachePromise && !mChannel;
  252. }
  253. };
  254. class ScriptLoaderRunnable;
  255. class ScriptExecutorRunnable final : public MainThreadWorkerSyncRunnable
  256. {
  257. ScriptLoaderRunnable& mScriptLoader;
  258. bool mIsWorkerScript;
  259. uint32_t mFirstIndex;
  260. uint32_t mLastIndex;
  261. public:
  262. ScriptExecutorRunnable(ScriptLoaderRunnable& aScriptLoader,
  263. nsIEventTarget* aSyncLoopTarget,
  264. bool aIsWorkerScript,
  265. uint32_t aFirstIndex,
  266. uint32_t aLastIndex);
  267. private:
  268. ~ScriptExecutorRunnable()
  269. { }
  270. virtual bool
  271. IsDebuggerRunnable() const override;
  272. virtual bool
  273. PreRun(WorkerPrivate* aWorkerPrivate) override;
  274. virtual bool
  275. WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override;
  276. virtual void
  277. PostRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate, bool aRunResult)
  278. override;
  279. nsresult
  280. Cancel() override;
  281. void
  282. ShutdownScriptLoader(JSContext* aCx,
  283. WorkerPrivate* aWorkerPrivate,
  284. bool aResult,
  285. bool aMutedError);
  286. void LogExceptionToConsole(JSContext* aCx,
  287. WorkerPrivate* WorkerPrivate);
  288. };
  289. class CacheScriptLoader;
  290. class CacheCreator final : public PromiseNativeHandler
  291. {
  292. public:
  293. NS_DECL_ISUPPORTS
  294. explicit CacheCreator(WorkerPrivate* aWorkerPrivate)
  295. : mCacheName(aWorkerPrivate->ServiceWorkerCacheName())
  296. , mOriginAttributes(aWorkerPrivate->GetOriginAttributes())
  297. {
  298. MOZ_ASSERT(aWorkerPrivate->IsServiceWorker());
  299. MOZ_ASSERT(aWorkerPrivate->LoadScriptAsPartOfLoadingServiceWorkerScript());
  300. AssertIsOnMainThread();
  301. }
  302. void
  303. AddLoader(CacheScriptLoader* aLoader)
  304. {
  305. AssertIsOnMainThread();
  306. MOZ_ASSERT(!mCacheStorage);
  307. mLoaders.AppendElement(aLoader);
  308. }
  309. virtual void
  310. ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override;
  311. virtual void
  312. RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override;
  313. // Try to load from cache with aPrincipal used for cache access.
  314. nsresult
  315. Load(nsIPrincipal* aPrincipal);
  316. Cache*
  317. Cache_() const
  318. {
  319. AssertIsOnMainThread();
  320. MOZ_ASSERT(mCache);
  321. return mCache;
  322. }
  323. nsIGlobalObject*
  324. Global() const
  325. {
  326. AssertIsOnMainThread();
  327. MOZ_ASSERT(mSandboxGlobalObject);
  328. return mSandboxGlobalObject;
  329. }
  330. void
  331. DeleteCache();
  332. private:
  333. ~CacheCreator()
  334. {
  335. }
  336. nsresult
  337. CreateCacheStorage(nsIPrincipal* aPrincipal);
  338. void
  339. FailLoaders(nsresult aRv);
  340. RefPtr<Cache> mCache;
  341. RefPtr<CacheStorage> mCacheStorage;
  342. nsCOMPtr<nsIGlobalObject> mSandboxGlobalObject;
  343. nsTArray<RefPtr<CacheScriptLoader>> mLoaders;
  344. nsString mCacheName;
  345. PrincipalOriginAttributes mOriginAttributes;
  346. };
  347. NS_IMPL_ISUPPORTS0(CacheCreator)
  348. class CacheScriptLoader final : public PromiseNativeHandler
  349. , public nsIStreamLoaderObserver
  350. {
  351. public:
  352. NS_DECL_ISUPPORTS
  353. NS_DECL_NSISTREAMLOADEROBSERVER
  354. CacheScriptLoader(WorkerPrivate* aWorkerPrivate, ScriptLoadInfo& aLoadInfo,
  355. uint32_t aIndex, bool aIsWorkerScript,
  356. ScriptLoaderRunnable* aRunnable)
  357. : mLoadInfo(aLoadInfo)
  358. , mIndex(aIndex)
  359. , mRunnable(aRunnable)
  360. , mIsWorkerScript(aIsWorkerScript)
  361. , mFailed(false)
  362. {
  363. MOZ_ASSERT(aWorkerPrivate->IsServiceWorker());
  364. mBaseURI = GetBaseURI(mIsWorkerScript, aWorkerPrivate);
  365. AssertIsOnMainThread();
  366. }
  367. void
  368. Fail(nsresult aRv);
  369. void
  370. Load(Cache* aCache);
  371. virtual void
  372. ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override;
  373. virtual void
  374. RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override;
  375. private:
  376. ~CacheScriptLoader()
  377. {
  378. AssertIsOnMainThread();
  379. }
  380. ScriptLoadInfo& mLoadInfo;
  381. uint32_t mIndex;
  382. RefPtr<ScriptLoaderRunnable> mRunnable;
  383. bool mIsWorkerScript;
  384. bool mFailed;
  385. nsCOMPtr<nsIInputStreamPump> mPump;
  386. nsCOMPtr<nsIURI> mBaseURI;
  387. mozilla::dom::ChannelInfo mChannelInfo;
  388. UniquePtr<PrincipalInfo> mPrincipalInfo;
  389. };
  390. NS_IMPL_ISUPPORTS(CacheScriptLoader, nsIStreamLoaderObserver)
  391. class CachePromiseHandler final : public PromiseNativeHandler
  392. {
  393. public:
  394. NS_DECL_ISUPPORTS
  395. CachePromiseHandler(ScriptLoaderRunnable* aRunnable,
  396. ScriptLoadInfo& aLoadInfo,
  397. uint32_t aIndex)
  398. : mRunnable(aRunnable)
  399. , mLoadInfo(aLoadInfo)
  400. , mIndex(aIndex)
  401. {
  402. AssertIsOnMainThread();
  403. MOZ_ASSERT(mRunnable);
  404. }
  405. virtual void
  406. ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override;
  407. virtual void
  408. RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override;
  409. private:
  410. ~CachePromiseHandler()
  411. {
  412. AssertIsOnMainThread();
  413. }
  414. RefPtr<ScriptLoaderRunnable> mRunnable;
  415. ScriptLoadInfo& mLoadInfo;
  416. uint32_t mIndex;
  417. };
  418. NS_IMPL_ISUPPORTS0(CachePromiseHandler)
  419. class LoaderListener final : public nsIStreamLoaderObserver
  420. , public nsIRequestObserver
  421. {
  422. public:
  423. NS_DECL_ISUPPORTS
  424. LoaderListener(ScriptLoaderRunnable* aRunnable, uint32_t aIndex)
  425. : mRunnable(aRunnable)
  426. , mIndex(aIndex)
  427. {
  428. MOZ_ASSERT(mRunnable);
  429. }
  430. NS_IMETHOD
  431. OnStreamComplete(nsIStreamLoader* aLoader, nsISupports* aContext,
  432. nsresult aStatus, uint32_t aStringLen,
  433. const uint8_t* aString) override;
  434. NS_IMETHOD
  435. OnStartRequest(nsIRequest* aRequest, nsISupports* aContext) override;
  436. NS_IMETHOD
  437. OnStopRequest(nsIRequest* aRequest, nsISupports* aContext,
  438. nsresult aStatusCode) override
  439. {
  440. // Nothing to do here!
  441. return NS_OK;
  442. }
  443. private:
  444. ~LoaderListener() {}
  445. RefPtr<ScriptLoaderRunnable> mRunnable;
  446. uint32_t mIndex;
  447. };
  448. NS_IMPL_ISUPPORTS(LoaderListener, nsIStreamLoaderObserver, nsIRequestObserver)
  449. class ScriptLoaderHolder;
  450. class ScriptLoaderRunnable final : public nsIRunnable
  451. {
  452. friend class ScriptExecutorRunnable;
  453. friend class ScriptLoaderHolder;
  454. friend class CachePromiseHandler;
  455. friend class CacheScriptLoader;
  456. friend class LoaderListener;
  457. WorkerPrivate* mWorkerPrivate;
  458. nsCOMPtr<nsIEventTarget> mSyncLoopTarget;
  459. nsTArray<ScriptLoadInfo> mLoadInfos;
  460. RefPtr<CacheCreator> mCacheCreator;
  461. bool mIsMainScript;
  462. WorkerScriptType mWorkerScriptType;
  463. bool mCanceled;
  464. bool mCanceledMainThread;
  465. ErrorResult& mRv;
  466. public:
  467. NS_DECL_THREADSAFE_ISUPPORTS
  468. ScriptLoaderRunnable(WorkerPrivate* aWorkerPrivate,
  469. nsIEventTarget* aSyncLoopTarget,
  470. nsTArray<ScriptLoadInfo>& aLoadInfos,
  471. bool aIsMainScript,
  472. WorkerScriptType aWorkerScriptType,
  473. ErrorResult& aRv)
  474. : mWorkerPrivate(aWorkerPrivate), mSyncLoopTarget(aSyncLoopTarget),
  475. mIsMainScript(aIsMainScript), mWorkerScriptType(aWorkerScriptType),
  476. mCanceled(false), mCanceledMainThread(false), mRv(aRv)
  477. {
  478. aWorkerPrivate->AssertIsOnWorkerThread();
  479. MOZ_ASSERT(aSyncLoopTarget);
  480. MOZ_ASSERT_IF(aIsMainScript, aLoadInfos.Length() == 1);
  481. mLoadInfos.SwapElements(aLoadInfos);
  482. }
  483. private:
  484. ~ScriptLoaderRunnable()
  485. { }
  486. NS_IMETHOD
  487. Run() override
  488. {
  489. AssertIsOnMainThread();
  490. nsresult rv = RunInternal();
  491. if (NS_WARN_IF(NS_FAILED(rv))) {
  492. CancelMainThread(rv);
  493. }
  494. return NS_OK;
  495. }
  496. void
  497. LoadingFinished(uint32_t aIndex, nsresult aRv)
  498. {
  499. AssertIsOnMainThread();
  500. MOZ_ASSERT(aIndex < mLoadInfos.Length());
  501. ScriptLoadInfo& loadInfo = mLoadInfos[aIndex];
  502. loadInfo.mLoadResult = aRv;
  503. MOZ_ASSERT(!loadInfo.mLoadingFinished);
  504. loadInfo.mLoadingFinished = true;
  505. MaybeExecuteFinishedScripts(aIndex);
  506. }
  507. void
  508. MaybeExecuteFinishedScripts(uint32_t aIndex)
  509. {
  510. AssertIsOnMainThread();
  511. MOZ_ASSERT(aIndex < mLoadInfos.Length());
  512. ScriptLoadInfo& loadInfo = mLoadInfos[aIndex];
  513. // We execute the last step if we don't have a pending operation with the
  514. // cache and the loading is completed.
  515. if (loadInfo.Finished()) {
  516. ExecuteFinishedScripts();
  517. }
  518. }
  519. nsresult
  520. OnStreamComplete(nsIStreamLoader* aLoader, uint32_t aIndex,
  521. nsresult aStatus, uint32_t aStringLen,
  522. const uint8_t* aString)
  523. {
  524. AssertIsOnMainThread();
  525. MOZ_ASSERT(aIndex < mLoadInfos.Length());
  526. nsresult rv = OnStreamCompleteInternal(aLoader, aStatus, aStringLen,
  527. aString, mLoadInfos[aIndex]);
  528. LoadingFinished(aIndex, rv);
  529. return NS_OK;
  530. }
  531. nsresult
  532. OnStartRequest(nsIRequest* aRequest, uint32_t aIndex)
  533. {
  534. AssertIsOnMainThread();
  535. MOZ_ASSERT(aIndex < mLoadInfos.Length());
  536. // If one load info cancels or hits an error, it can race with the start
  537. // callback coming from another load info.
  538. if (mCanceledMainThread || !mCacheCreator) {
  539. aRequest->Cancel(NS_ERROR_FAILURE);
  540. return NS_ERROR_FAILURE;
  541. }
  542. ScriptLoadInfo& loadInfo = mLoadInfos[aIndex];
  543. nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
  544. MOZ_ASSERT(channel == loadInfo.mChannel);
  545. // We synthesize the result code, but its never exposed to content.
  546. RefPtr<mozilla::dom::InternalResponse> ir =
  547. new mozilla::dom::InternalResponse(200, NS_LITERAL_CSTRING("OK"));
  548. ir->SetBody(loadInfo.mCacheReadStream, InternalResponse::UNKNOWN_BODY_SIZE);
  549. // Drop our reference to the stream now that we've passed it along, so it
  550. // doesn't hang around once the cache is done with it and keep data alive.
  551. loadInfo.mCacheReadStream = nullptr;
  552. // Set the channel info of the channel on the response so that it's
  553. // saved in the cache.
  554. ir->InitChannelInfo(channel);
  555. // Save the principal of the channel since its URI encodes the script URI
  556. // rather than the ServiceWorkerRegistrationInfo URI.
  557. nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
  558. NS_ASSERTION(ssm, "Should never be null!");
  559. nsCOMPtr<nsIPrincipal> channelPrincipal;
  560. nsresult rv = ssm->GetChannelResultPrincipal(channel, getter_AddRefs(channelPrincipal));
  561. if (NS_WARN_IF(NS_FAILED(rv))) {
  562. channel->Cancel(rv);
  563. return rv;
  564. }
  565. UniquePtr<PrincipalInfo> principalInfo(new PrincipalInfo());
  566. rv = PrincipalToPrincipalInfo(channelPrincipal, principalInfo.get());
  567. if (NS_WARN_IF(NS_FAILED(rv))) {
  568. channel->Cancel(rv);
  569. return rv;
  570. }
  571. ir->SetPrincipalInfo(Move(principalInfo));
  572. RefPtr<mozilla::dom::Response> response =
  573. new mozilla::dom::Response(mCacheCreator->Global(), ir, nullptr);
  574. mozilla::dom::RequestOrUSVString request;
  575. MOZ_ASSERT(!loadInfo.mFullURL.IsEmpty());
  576. request.SetAsUSVString().Rebind(loadInfo.mFullURL.Data(),
  577. loadInfo.mFullURL.Length());
  578. ErrorResult error;
  579. RefPtr<Promise> cachePromise =
  580. mCacheCreator->Cache_()->Put(request, *response, error);
  581. if (NS_WARN_IF(error.Failed())) {
  582. nsresult rv = error.StealNSResult();
  583. channel->Cancel(rv);
  584. return rv;
  585. }
  586. RefPtr<CachePromiseHandler> promiseHandler =
  587. new CachePromiseHandler(this, loadInfo, aIndex);
  588. cachePromise->AppendNativeHandler(promiseHandler);
  589. loadInfo.mCachePromise.swap(cachePromise);
  590. loadInfo.mCacheStatus = ScriptLoadInfo::WritingToCache;
  591. return NS_OK;
  592. }
  593. bool
  594. Notify(Status aStatus)
  595. {
  596. mWorkerPrivate->AssertIsOnWorkerThread();
  597. if (aStatus >= Terminating && !mCanceled) {
  598. mCanceled = true;
  599. MOZ_ALWAYS_SUCCEEDS(
  600. NS_DispatchToMainThread(NewRunnableMethod(this,
  601. &ScriptLoaderRunnable::CancelMainThreadWithBindingAborted)));
  602. }
  603. return true;
  604. }
  605. bool
  606. IsMainWorkerScript() const
  607. {
  608. return mIsMainScript && mWorkerScriptType == WorkerScript;
  609. }
  610. void
  611. CancelMainThreadWithBindingAborted()
  612. {
  613. CancelMainThread(NS_BINDING_ABORTED);
  614. }
  615. void
  616. CancelMainThread(nsresult aCancelResult)
  617. {
  618. AssertIsOnMainThread();
  619. if (mCanceledMainThread) {
  620. return;
  621. }
  622. mCanceledMainThread = true;
  623. if (mCacheCreator) {
  624. MOZ_ASSERT(mWorkerPrivate->IsServiceWorker());
  625. DeleteCache();
  626. }
  627. // Cancel all the channels that were already opened.
  628. for (uint32_t index = 0; index < mLoadInfos.Length(); index++) {
  629. ScriptLoadInfo& loadInfo = mLoadInfos[index];
  630. // If promise or channel is non-null, their failures will lead to
  631. // LoadingFinished being called.
  632. bool callLoadingFinished = true;
  633. if (loadInfo.mCachePromise) {
  634. MOZ_ASSERT(mWorkerPrivate->IsServiceWorker());
  635. loadInfo.mCachePromise->MaybeReject(aCancelResult);
  636. loadInfo.mCachePromise = nullptr;
  637. callLoadingFinished = false;
  638. }
  639. if (loadInfo.mChannel) {
  640. if (NS_SUCCEEDED(loadInfo.mChannel->Cancel(aCancelResult))) {
  641. callLoadingFinished = false;
  642. } else {
  643. NS_WARNING("Failed to cancel channel!");
  644. }
  645. }
  646. if (callLoadingFinished && !loadInfo.Finished()) {
  647. LoadingFinished(index, aCancelResult);
  648. }
  649. }
  650. ExecuteFinishedScripts();
  651. }
  652. void
  653. DeleteCache()
  654. {
  655. AssertIsOnMainThread();
  656. if (!mCacheCreator) {
  657. return;
  658. }
  659. mCacheCreator->DeleteCache();
  660. mCacheCreator = nullptr;
  661. }
  662. nsresult
  663. RunInternal()
  664. {
  665. AssertIsOnMainThread();
  666. if (IsMainWorkerScript() && mWorkerPrivate->IsServiceWorker()) {
  667. mWorkerPrivate->SetLoadingWorkerScript(true);
  668. }
  669. if (!mWorkerPrivate->IsServiceWorker() ||
  670. !mWorkerPrivate->LoadScriptAsPartOfLoadingServiceWorkerScript()) {
  671. for (uint32_t index = 0, len = mLoadInfos.Length(); index < len;
  672. ++index) {
  673. nsresult rv = LoadScript(index);
  674. if (NS_WARN_IF(NS_FAILED(rv))) {
  675. LoadingFinished(index, rv);
  676. return rv;
  677. }
  678. }
  679. return NS_OK;
  680. }
  681. MOZ_ASSERT(!mCacheCreator);
  682. mCacheCreator = new CacheCreator(mWorkerPrivate);
  683. for (uint32_t index = 0, len = mLoadInfos.Length(); index < len; ++index) {
  684. RefPtr<CacheScriptLoader> loader =
  685. new CacheScriptLoader(mWorkerPrivate, mLoadInfos[index], index,
  686. IsMainWorkerScript(), this);
  687. mCacheCreator->AddLoader(loader);
  688. }
  689. // The worker may have a null principal on first load, but in that case its
  690. // parent definitely will have one.
  691. nsIPrincipal* principal = mWorkerPrivate->GetPrincipal();
  692. if (!principal) {
  693. WorkerPrivate* parentWorker = mWorkerPrivate->GetParent();
  694. MOZ_ASSERT(parentWorker, "Must have a parent!");
  695. principal = parentWorker->GetPrincipal();
  696. }
  697. nsresult rv = mCacheCreator->Load(principal);
  698. if (NS_WARN_IF(NS_FAILED(rv))) {
  699. return rv;
  700. }
  701. return NS_OK;
  702. }
  703. nsresult
  704. LoadScript(uint32_t aIndex)
  705. {
  706. AssertIsOnMainThread();
  707. MOZ_ASSERT(aIndex < mLoadInfos.Length());
  708. WorkerPrivate* parentWorker = mWorkerPrivate->GetParent();
  709. // Figure out which principal to use.
  710. nsIPrincipal* principal = mWorkerPrivate->GetPrincipal();
  711. nsCOMPtr<nsILoadGroup> loadGroup = mWorkerPrivate->GetLoadGroup();
  712. if (!principal) {
  713. NS_ASSERTION(parentWorker, "Must have a principal!");
  714. NS_ASSERTION(mIsMainScript, "Must have a principal for importScripts!");
  715. principal = parentWorker->GetPrincipal();
  716. loadGroup = parentWorker->GetLoadGroup();
  717. }
  718. NS_ASSERTION(principal, "This should never be null here!");
  719. MOZ_ASSERT(NS_LoadGroupMatchesPrincipal(loadGroup, principal));
  720. // Figure out our base URI.
  721. nsCOMPtr<nsIURI> baseURI = GetBaseURI(mIsMainScript, mWorkerPrivate);
  722. // May be null.
  723. nsCOMPtr<nsIDocument> parentDoc = mWorkerPrivate->GetDocument();
  724. nsCOMPtr<nsIChannel> channel;
  725. if (IsMainWorkerScript()) {
  726. // May be null.
  727. channel = mWorkerPrivate->ForgetWorkerChannel();
  728. }
  729. nsCOMPtr<nsIIOService> ios(do_GetIOService());
  730. nsIScriptSecurityManager* secMan = nsContentUtils::GetSecurityManager();
  731. NS_ASSERTION(secMan, "This should never be null!");
  732. ScriptLoadInfo& loadInfo = mLoadInfos[aIndex];
  733. nsresult& rv = loadInfo.mLoadResult;
  734. nsLoadFlags loadFlags = nsIRequest::LOAD_NORMAL;
  735. // Get the top-level worker.
  736. WorkerPrivate* topWorkerPrivate = mWorkerPrivate;
  737. WorkerPrivate* parent = topWorkerPrivate->GetParent();
  738. while (parent) {
  739. topWorkerPrivate = parent;
  740. parent = topWorkerPrivate->GetParent();
  741. }
  742. // If the top-level worker is a dedicated worker and has a window, and the
  743. // window has a docshell, the caching behavior of this worker should match
  744. // that of that docshell.
  745. if (topWorkerPrivate->IsDedicatedWorker()) {
  746. nsCOMPtr<nsPIDOMWindowInner> window = topWorkerPrivate->GetWindow();
  747. if (window) {
  748. nsCOMPtr<nsIDocShell> docShell = window->GetDocShell();
  749. if (docShell) {
  750. nsresult rv = docShell->GetDefaultLoadFlags(&loadFlags);
  751. NS_ENSURE_SUCCESS(rv, rv);
  752. }
  753. }
  754. }
  755. // If we are loading a script for a ServiceWorker then we must not
  756. // try to intercept it. If the interception matches the current
  757. // ServiceWorker's scope then we could deadlock the load.
  758. if (mWorkerPrivate->IsServiceWorker()) {
  759. loadFlags |= nsIChannel::LOAD_BYPASS_SERVICE_WORKER;
  760. }
  761. if (!channel) {
  762. // Only top level workers' main script use the document charset for the
  763. // script uri encoding. Otherwise, default encoding (UTF-8) is applied.
  764. bool useDefaultEncoding = !(!parentWorker && IsMainWorkerScript());
  765. rv = ChannelFromScriptURL(principal, baseURI, parentDoc, loadGroup, ios,
  766. secMan, loadInfo.mURL, IsMainWorkerScript(),
  767. mWorkerScriptType,
  768. mWorkerPrivate->ContentPolicyType(), loadFlags,
  769. useDefaultEncoding,
  770. getter_AddRefs(channel));
  771. if (NS_WARN_IF(NS_FAILED(rv))) {
  772. return rv;
  773. }
  774. }
  775. // We need to know which index we're on in OnStreamComplete so we know
  776. // where to put the result.
  777. RefPtr<LoaderListener> listener = new LoaderListener(this, aIndex);
  778. // We don't care about progress so just use the simple stream loader for
  779. // OnStreamComplete notification only.
  780. nsCOMPtr<nsIStreamLoader> loader;
  781. rv = NS_NewStreamLoader(getter_AddRefs(loader), listener);
  782. if (NS_WARN_IF(NS_FAILED(rv))) {
  783. return rv;
  784. }
  785. if (loadInfo.mCacheStatus != ScriptLoadInfo::ToBeCached) {
  786. rv = channel->AsyncOpen2(loader);
  787. if (NS_WARN_IF(NS_FAILED(rv))) {
  788. return rv;
  789. }
  790. } else {
  791. nsCOMPtr<nsIOutputStream> writer;
  792. // In case we return early.
  793. loadInfo.mCacheStatus = ScriptLoadInfo::Cancel;
  794. rv = NS_NewPipe(getter_AddRefs(loadInfo.mCacheReadStream),
  795. getter_AddRefs(writer), 0,
  796. UINT32_MAX, // unlimited size to avoid writer WOULD_BLOCK case
  797. true, false); // non-blocking reader, blocking writer
  798. if (NS_WARN_IF(NS_FAILED(rv))) {
  799. return rv;
  800. }
  801. nsCOMPtr<nsIStreamListenerTee> tee =
  802. do_CreateInstance(NS_STREAMLISTENERTEE_CONTRACTID);
  803. rv = tee->Init(loader, writer, listener);
  804. if (NS_WARN_IF(NS_FAILED(rv))) {
  805. return rv;
  806. }
  807. nsresult rv = channel->AsyncOpen2(tee);
  808. if (NS_WARN_IF(NS_FAILED(rv))) {
  809. return rv;
  810. }
  811. }
  812. loadInfo.mChannel.swap(channel);
  813. return NS_OK;
  814. }
  815. nsresult
  816. OnStreamCompleteInternal(nsIStreamLoader* aLoader, nsresult aStatus,
  817. uint32_t aStringLen, const uint8_t* aString,
  818. ScriptLoadInfo& aLoadInfo)
  819. {
  820. AssertIsOnMainThread();
  821. if (!aLoadInfo.mChannel) {
  822. return NS_BINDING_ABORTED;
  823. }
  824. aLoadInfo.mChannel = nullptr;
  825. if (NS_FAILED(aStatus)) {
  826. return aStatus;
  827. }
  828. NS_ASSERTION(aString, "This should never be null!");
  829. nsCOMPtr<nsIRequest> request;
  830. nsresult rv = aLoader->GetRequest(getter_AddRefs(request));
  831. NS_ENSURE_SUCCESS(rv, rv);
  832. nsCOMPtr<nsIChannel> channel = do_QueryInterface(request);
  833. MOZ_ASSERT(channel);
  834. nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
  835. NS_ASSERTION(ssm, "Should never be null!");
  836. nsCOMPtr<nsIPrincipal> channelPrincipal;
  837. rv = ssm->GetChannelResultPrincipal(channel, getter_AddRefs(channelPrincipal));
  838. if (NS_WARN_IF(NS_FAILED(rv))) {
  839. return rv;
  840. }
  841. nsIPrincipal* principal = mWorkerPrivate->GetPrincipal();
  842. if (!principal) {
  843. WorkerPrivate* parentWorker = mWorkerPrivate->GetParent();
  844. MOZ_ASSERT(parentWorker, "Must have a parent!");
  845. principal = parentWorker->GetPrincipal();
  846. }
  847. // We don't mute the main worker script becase we've already done
  848. // same-origin checks on them so we should be able to see their errors.
  849. // Note that for data: url, where we allow it through the same-origin check
  850. // but then give it a different origin.
  851. aLoadInfo.mMutedErrorFlag.emplace(IsMainWorkerScript()
  852. ? false
  853. : !principal->Subsumes(channelPrincipal));
  854. // Make sure we're not seeing the result of a 404 or something by checking
  855. // the 'requestSucceeded' attribute on the http channel.
  856. nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(request);
  857. nsAutoCString tCspHeaderValue, tCspROHeaderValue, tRPHeaderCValue;
  858. if (httpChannel) {
  859. bool requestSucceeded;
  860. rv = httpChannel->GetRequestSucceeded(&requestSucceeded);
  861. NS_ENSURE_SUCCESS(rv, rv);
  862. if (!requestSucceeded) {
  863. return NS_ERROR_NOT_AVAILABLE;
  864. }
  865. httpChannel->GetResponseHeader(
  866. NS_LITERAL_CSTRING("content-security-policy"),
  867. tCspHeaderValue);
  868. httpChannel->GetResponseHeader(
  869. NS_LITERAL_CSTRING("content-security-policy-report-only"),
  870. tCspROHeaderValue);
  871. httpChannel->GetResponseHeader(
  872. NS_LITERAL_CSTRING("referrer-policy"),
  873. tRPHeaderCValue);
  874. }
  875. // May be null.
  876. nsIDocument* parentDoc = mWorkerPrivate->GetDocument();
  877. // Use the regular ScriptLoader for this grunt work! Should be just fine
  878. // because we're running on the main thread.
  879. // Unlike <script> tags, Worker scripts are always decoded as UTF-8,
  880. // per spec. So we explicitly pass in the charset hint.
  881. rv = ScriptLoader::ConvertToUTF16(aLoadInfo.mChannel, aString, aStringLen,
  882. NS_LITERAL_STRING("UTF-8"), parentDoc,
  883. aLoadInfo.mScriptTextBuf,
  884. aLoadInfo.mScriptTextLength);
  885. if (NS_FAILED(rv)) {
  886. return rv;
  887. }
  888. if (!aLoadInfo.mScriptTextLength && !aLoadInfo.mScriptTextBuf) {
  889. nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
  890. NS_LITERAL_CSTRING("DOM"), parentDoc,
  891. nsContentUtils::eDOM_PROPERTIES,
  892. "EmptyWorkerSourceWarning");
  893. } else if (!aLoadInfo.mScriptTextBuf) {
  894. return NS_ERROR_FAILURE;
  895. }
  896. // Figure out what we actually loaded.
  897. nsCOMPtr<nsIURI> finalURI;
  898. rv = NS_GetFinalChannelURI(channel, getter_AddRefs(finalURI));
  899. NS_ENSURE_SUCCESS(rv, rv);
  900. if (principal->Subsumes(channelPrincipal)) {
  901. nsCString filename;
  902. rv = finalURI->GetSpec(filename);
  903. NS_ENSURE_SUCCESS(rv, rv);
  904. if (!filename.IsEmpty()) {
  905. // This will help callers figure out what their script url resolved to in
  906. // case of errors.
  907. aLoadInfo.mURL.Assign(NS_ConvertUTF8toUTF16(filename));
  908. }
  909. }
  910. nsCOMPtr<nsILoadInfo> chanLoadInfo = channel->GetLoadInfo();
  911. if (chanLoadInfo && chanLoadInfo->GetEnforceSRI()) {
  912. // importScripts() and the Worker constructor do not support integrity metadata
  913. // (or any fetch options). Until then, we can just block.
  914. // If we ever have those data in the future, we'll have to the check to
  915. // by using the SRICheck module
  916. MOZ_LOG(SRILogHelper::GetSriLog(), mozilla::LogLevel::Debug,
  917. ("Scriptloader::Load, SRI required but not supported in workers"));
  918. nsCOMPtr<nsIContentSecurityPolicy> wcsp;
  919. chanLoadInfo->LoadingPrincipal()->GetCsp(getter_AddRefs(wcsp));
  920. MOZ_ASSERT(wcsp, "We sould have a CSP for the worker here");
  921. if (wcsp) {
  922. wcsp->LogViolationDetails(
  923. nsIContentSecurityPolicy::VIOLATION_TYPE_REQUIRE_SRI_FOR_SCRIPT,
  924. aLoadInfo.mURL, EmptyString(), 0, EmptyString(), EmptyString());
  925. }
  926. return NS_ERROR_SRI_CORRUPT;
  927. }
  928. // Update the principal of the worker and its base URI if we just loaded the
  929. // worker's primary script.
  930. if (IsMainWorkerScript()) {
  931. // Take care of the base URI first.
  932. mWorkerPrivate->SetBaseURI(finalURI);
  933. // Store the channel info if needed.
  934. mWorkerPrivate->InitChannelInfo(channel);
  935. // Now to figure out which principal to give this worker.
  936. WorkerPrivate* parent = mWorkerPrivate->GetParent();
  937. NS_ASSERTION(mWorkerPrivate->GetPrincipal() || parent,
  938. "Must have one of these!");
  939. nsCOMPtr<nsIPrincipal> loadPrincipal = mWorkerPrivate->GetPrincipal() ?
  940. mWorkerPrivate->GetPrincipal() :
  941. parent->GetPrincipal();
  942. nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
  943. NS_ASSERTION(ssm, "Should never be null!");
  944. nsCOMPtr<nsIPrincipal> channelPrincipal;
  945. rv = ssm->GetChannelResultPrincipal(channel, getter_AddRefs(channelPrincipal));
  946. NS_ENSURE_SUCCESS(rv, rv);
  947. nsCOMPtr<nsILoadGroup> channelLoadGroup;
  948. rv = channel->GetLoadGroup(getter_AddRefs(channelLoadGroup));
  949. NS_ENSURE_SUCCESS(rv, rv);
  950. MOZ_ASSERT(channelLoadGroup);
  951. // If the load principal is the system principal then the channel
  952. // principal must also be the system principal (we do not allow chrome
  953. // code to create workers with non-chrome scripts, and if we ever decide
  954. // to change this we need to make sure we don't always set
  955. // mPrincipalIsSystem to true in WorkerPrivate::GetLoadInfo()). Otherwise
  956. // this channel principal must be same origin with the load principal (we
  957. // check again here in case redirects changed the location of the script).
  958. if (nsContentUtils::IsSystemPrincipal(loadPrincipal)) {
  959. if (!nsContentUtils::IsSystemPrincipal(channelPrincipal)) {
  960. // See if this is a resource URI. Since JSMs usually come from
  961. // resource:// URIs we're currently considering all URIs with the
  962. // URI_IS_UI_RESOURCE flag as valid for creating privileged workers.
  963. bool isResource;
  964. rv = NS_URIChainHasFlags(finalURI,
  965. nsIProtocolHandler::URI_IS_UI_RESOURCE,
  966. &isResource);
  967. NS_ENSURE_SUCCESS(rv, rv);
  968. if (isResource) {
  969. // Assign the system principal to the resource:// worker only if it
  970. // was loaded from code using the system principal.
  971. channelPrincipal = loadPrincipal;
  972. } else {
  973. return NS_ERROR_DOM_BAD_URI;
  974. }
  975. }
  976. }
  977. // The principal can change, but it should still match the original
  978. // load group's appId and browser element flag.
  979. MOZ_ASSERT(NS_LoadGroupMatchesPrincipal(channelLoadGroup, channelPrincipal));
  980. mWorkerPrivate->SetPrincipal(channelPrincipal, channelLoadGroup);
  981. // We did inherit CSP in bug 1223647. If we do not already have a CSP, we
  982. // should get it from the HTTP headers on the worker script.
  983. if (!mWorkerPrivate->GetCSP() && CSPService::sCSPEnabled) {
  984. NS_ConvertASCIItoUTF16 cspHeaderValue(tCspHeaderValue);
  985. NS_ConvertASCIItoUTF16 cspROHeaderValue(tCspROHeaderValue);
  986. nsIPrincipal* principal = mWorkerPrivate->GetPrincipal();
  987. MOZ_ASSERT(principal, "Should not be null");
  988. nsCOMPtr<nsIContentSecurityPolicy> csp;
  989. rv = principal->EnsureCSP(nullptr, getter_AddRefs(csp));
  990. if (csp) {
  991. // If there's a CSP header, apply it.
  992. if (!cspHeaderValue.IsEmpty()) {
  993. rv = CSP_AppendCSPFromHeader(csp, cspHeaderValue, false);
  994. NS_ENSURE_SUCCESS(rv, rv);
  995. }
  996. // If there's a report-only CSP header, apply it.
  997. if (!cspROHeaderValue.IsEmpty()) {
  998. rv = CSP_AppendCSPFromHeader(csp, cspROHeaderValue, true);
  999. NS_ENSURE_SUCCESS(rv, rv);
  1000. }
  1001. // Set evalAllowed, default value is set in GetAllowsEval
  1002. bool evalAllowed = false;
  1003. bool reportEvalViolations = false;
  1004. rv = csp->GetAllowsEval(&reportEvalViolations, &evalAllowed);
  1005. NS_ENSURE_SUCCESS(rv, rv);
  1006. mWorkerPrivate->SetCSP(csp);
  1007. mWorkerPrivate->SetEvalAllowed(evalAllowed);
  1008. mWorkerPrivate->SetReportCSPViolations(reportEvalViolations);
  1009. // Set ReferrerPolicy, default value is set in GetReferrerPolicy
  1010. bool hasReferrerPolicy = false;
  1011. uint32_t rp = mozilla::net::RP_Default;
  1012. rv = csp->GetReferrerPolicy(&rp, &hasReferrerPolicy);
  1013. NS_ENSURE_SUCCESS(rv, rv);
  1014. if (hasReferrerPolicy) { //FIXME bug 1307366: move RP out of CSP code
  1015. mWorkerPrivate->SetReferrerPolicy(static_cast<net::ReferrerPolicy>(rp));
  1016. }
  1017. }
  1018. }
  1019. if (parent) {
  1020. // XHR Params Allowed
  1021. mWorkerPrivate->SetXHRParamsAllowed(parent->XHRParamsAllowed());
  1022. }
  1023. }
  1024. NS_ConvertUTF8toUTF16 tRPHeaderValue(tRPHeaderCValue);
  1025. // If there's a Referrer-Policy header, apply it.
  1026. if (!tRPHeaderValue.IsEmpty()) {
  1027. net::ReferrerPolicy policy =
  1028. nsContentUtils::GetReferrerPolicyFromHeader(tRPHeaderValue);
  1029. if (policy != net::RP_Unset) {
  1030. mWorkerPrivate->SetReferrerPolicy(policy);
  1031. }
  1032. }
  1033. return NS_OK;
  1034. }
  1035. void
  1036. DataReceivedFromCache(uint32_t aIndex, const uint8_t* aString,
  1037. uint32_t aStringLen,
  1038. const mozilla::dom::ChannelInfo& aChannelInfo,
  1039. UniquePtr<PrincipalInfo> aPrincipalInfo)
  1040. {
  1041. AssertIsOnMainThread();
  1042. MOZ_ASSERT(aIndex < mLoadInfos.Length());
  1043. ScriptLoadInfo& loadInfo = mLoadInfos[aIndex];
  1044. MOZ_ASSERT(loadInfo.mCacheStatus == ScriptLoadInfo::Cached);
  1045. nsCOMPtr<nsIPrincipal> responsePrincipal =
  1046. PrincipalInfoToPrincipal(*aPrincipalInfo);
  1047. nsIPrincipal* principal = mWorkerPrivate->GetPrincipal();
  1048. if (!principal) {
  1049. WorkerPrivate* parentWorker = mWorkerPrivate->GetParent();
  1050. MOZ_ASSERT(parentWorker, "Must have a parent!");
  1051. principal = parentWorker->GetPrincipal();
  1052. }
  1053. loadInfo.mMutedErrorFlag.emplace(!principal->Subsumes(responsePrincipal));
  1054. // May be null.
  1055. nsIDocument* parentDoc = mWorkerPrivate->GetDocument();
  1056. MOZ_ASSERT(!loadInfo.mScriptTextBuf);
  1057. nsresult rv =
  1058. ScriptLoader::ConvertToUTF16(nullptr, aString, aStringLen,
  1059. NS_LITERAL_STRING("UTF-8"), parentDoc,
  1060. loadInfo.mScriptTextBuf,
  1061. loadInfo.mScriptTextLength);
  1062. if (NS_SUCCEEDED(rv) && IsMainWorkerScript()) {
  1063. nsCOMPtr<nsIURI> finalURI;
  1064. rv = NS_NewURI(getter_AddRefs(finalURI), loadInfo.mFullURL, nullptr, nullptr);
  1065. if (NS_SUCCEEDED(rv)) {
  1066. mWorkerPrivate->SetBaseURI(finalURI);
  1067. }
  1068. mozilla::DebugOnly<nsIPrincipal*> principal = mWorkerPrivate->GetPrincipal();
  1069. MOZ_ASSERT(principal);
  1070. nsILoadGroup* loadGroup = mWorkerPrivate->GetLoadGroup();
  1071. MOZ_ASSERT(loadGroup);
  1072. mozilla::DebugOnly<bool> equal = false;
  1073. MOZ_ASSERT(responsePrincipal && NS_SUCCEEDED(responsePrincipal->Equals(principal, &equal)));
  1074. MOZ_ASSERT(equal);
  1075. mWorkerPrivate->InitChannelInfo(aChannelInfo);
  1076. mWorkerPrivate->SetPrincipal(responsePrincipal, loadGroup);
  1077. }
  1078. if (NS_SUCCEEDED(rv)) {
  1079. DataReceived();
  1080. }
  1081. LoadingFinished(aIndex, rv);
  1082. }
  1083. void
  1084. DataReceived()
  1085. {
  1086. if (IsMainWorkerScript()) {
  1087. WorkerPrivate* parent = mWorkerPrivate->GetParent();
  1088. if (parent) {
  1089. // XHR Params Allowed
  1090. mWorkerPrivate->SetXHRParamsAllowed(parent->XHRParamsAllowed());
  1091. // Set Eval and ContentSecurityPolicy
  1092. mWorkerPrivate->SetCSP(parent->GetCSP());
  1093. mWorkerPrivate->SetEvalAllowed(parent->IsEvalAllowed());
  1094. }
  1095. }
  1096. }
  1097. void
  1098. ExecuteFinishedScripts()
  1099. {
  1100. AssertIsOnMainThread();
  1101. if (IsMainWorkerScript()) {
  1102. mWorkerPrivate->WorkerScriptLoaded();
  1103. }
  1104. uint32_t firstIndex = UINT32_MAX;
  1105. uint32_t lastIndex = UINT32_MAX;
  1106. // Find firstIndex based on whether mExecutionScheduled is unset.
  1107. for (uint32_t index = 0; index < mLoadInfos.Length(); index++) {
  1108. if (!mLoadInfos[index].mExecutionScheduled) {
  1109. firstIndex = index;
  1110. break;
  1111. }
  1112. }
  1113. // Find lastIndex based on whether mChannel is set, and update
  1114. // mExecutionScheduled on the ones we're about to schedule.
  1115. if (firstIndex != UINT32_MAX) {
  1116. for (uint32_t index = firstIndex; index < mLoadInfos.Length(); index++) {
  1117. ScriptLoadInfo& loadInfo = mLoadInfos[index];
  1118. if (!loadInfo.Finished()) {
  1119. break;
  1120. }
  1121. // We can execute this one.
  1122. loadInfo.mExecutionScheduled = true;
  1123. lastIndex = index;
  1124. }
  1125. }
  1126. // This is the last index, we can unused things before the exection of the
  1127. // script and the stopping of the sync loop.
  1128. if (lastIndex == mLoadInfos.Length() - 1) {
  1129. mCacheCreator = nullptr;
  1130. }
  1131. if (firstIndex != UINT32_MAX && lastIndex != UINT32_MAX) {
  1132. RefPtr<ScriptExecutorRunnable> runnable =
  1133. new ScriptExecutorRunnable(*this, mSyncLoopTarget, IsMainWorkerScript(),
  1134. firstIndex, lastIndex);
  1135. if (!runnable->Dispatch()) {
  1136. MOZ_ASSERT(false, "This should never fail!");
  1137. }
  1138. }
  1139. }
  1140. };
  1141. NS_IMPL_ISUPPORTS(ScriptLoaderRunnable, nsIRunnable)
  1142. class MOZ_STACK_CLASS ScriptLoaderHolder final : public WorkerHolder
  1143. {
  1144. // Raw pointer because this holder object follows the mRunnable life-time.
  1145. ScriptLoaderRunnable* mRunnable;
  1146. public:
  1147. explicit ScriptLoaderHolder(ScriptLoaderRunnable* aRunnable)
  1148. : mRunnable(aRunnable)
  1149. {
  1150. MOZ_ASSERT(aRunnable);
  1151. }
  1152. virtual bool
  1153. Notify(Status aStatus) override
  1154. {
  1155. mRunnable->Notify(aStatus);
  1156. return true;
  1157. }
  1158. };
  1159. NS_IMETHODIMP
  1160. LoaderListener::OnStreamComplete(nsIStreamLoader* aLoader, nsISupports* aContext,
  1161. nsresult aStatus, uint32_t aStringLen,
  1162. const uint8_t* aString)
  1163. {
  1164. return mRunnable->OnStreamComplete(aLoader, mIndex, aStatus, aStringLen, aString);
  1165. }
  1166. NS_IMETHODIMP
  1167. LoaderListener::OnStartRequest(nsIRequest* aRequest, nsISupports* aContext)
  1168. {
  1169. return mRunnable->OnStartRequest(aRequest, mIndex);
  1170. }
  1171. void
  1172. CachePromiseHandler::ResolvedCallback(JSContext* aCx,
  1173. JS::Handle<JS::Value> aValue)
  1174. {
  1175. AssertIsOnMainThread();
  1176. // May already have been canceled by CacheScriptLoader::Fail from
  1177. // CancelMainThread.
  1178. MOZ_ASSERT(mLoadInfo.mCacheStatus == ScriptLoadInfo::WritingToCache ||
  1179. mLoadInfo.mCacheStatus == ScriptLoadInfo::Cancel);
  1180. MOZ_ASSERT_IF(mLoadInfo.mCacheStatus == ScriptLoadInfo::Cancel, !mLoadInfo.mCachePromise);
  1181. if (mLoadInfo.mCachePromise) {
  1182. mLoadInfo.mCacheStatus = ScriptLoadInfo::Cached;
  1183. mLoadInfo.mCachePromise = nullptr;
  1184. mRunnable->MaybeExecuteFinishedScripts(mIndex);
  1185. }
  1186. }
  1187. void
  1188. CachePromiseHandler::RejectedCallback(JSContext* aCx,
  1189. JS::Handle<JS::Value> aValue)
  1190. {
  1191. AssertIsOnMainThread();
  1192. // May already have been canceled by CacheScriptLoader::Fail from
  1193. // CancelMainThread.
  1194. MOZ_ASSERT(mLoadInfo.mCacheStatus == ScriptLoadInfo::WritingToCache ||
  1195. mLoadInfo.mCacheStatus == ScriptLoadInfo::Cancel);
  1196. mLoadInfo.mCacheStatus = ScriptLoadInfo::Cancel;
  1197. mLoadInfo.mCachePromise = nullptr;
  1198. // This will delete the cache object and will call LoadingFinished() with an
  1199. // error for each ongoing operation.
  1200. mRunnable->DeleteCache();
  1201. }
  1202. nsresult
  1203. CacheCreator::CreateCacheStorage(nsIPrincipal* aPrincipal)
  1204. {
  1205. AssertIsOnMainThread();
  1206. MOZ_ASSERT(!mCacheStorage);
  1207. MOZ_ASSERT(aPrincipal);
  1208. nsIXPConnect* xpc = nsContentUtils::XPConnect();
  1209. MOZ_ASSERT(xpc, "This should never be null!");
  1210. mozilla::AutoSafeJSContext cx;
  1211. JS::Rooted<JSObject*> sandbox(cx);
  1212. nsresult rv = xpc->CreateSandbox(cx, aPrincipal, sandbox.address());
  1213. if (NS_WARN_IF(NS_FAILED(rv))) {
  1214. return rv;
  1215. }
  1216. mSandboxGlobalObject = xpc::NativeGlobal(sandbox);
  1217. if (NS_WARN_IF(!mSandboxGlobalObject)) {
  1218. return NS_ERROR_FAILURE;
  1219. }
  1220. // If we're in private browsing mode, don't even try to create the
  1221. // CacheStorage. Instead, just fail immediately to terminate the
  1222. // ServiceWorker load.
  1223. if (NS_WARN_IF(mOriginAttributes.mPrivateBrowsingId > 0)) {
  1224. return NS_ERROR_DOM_SECURITY_ERR;
  1225. }
  1226. // Create a CacheStorage bypassing its trusted origin checks. The
  1227. // ServiceWorker has already performed its own checks before getting
  1228. // to this point.
  1229. ErrorResult error;
  1230. mCacheStorage =
  1231. CacheStorage::CreateOnMainThread(mozilla::dom::cache::CHROME_ONLY_NAMESPACE,
  1232. mSandboxGlobalObject,
  1233. aPrincipal,
  1234. false, /* privateBrowsing can't be true here */
  1235. true /* force trusted origin */,
  1236. error);
  1237. if (NS_WARN_IF(error.Failed())) {
  1238. return error.StealNSResult();
  1239. }
  1240. return NS_OK;
  1241. }
  1242. nsresult
  1243. CacheCreator::Load(nsIPrincipal* aPrincipal)
  1244. {
  1245. AssertIsOnMainThread();
  1246. MOZ_ASSERT(!mLoaders.IsEmpty());
  1247. nsresult rv = CreateCacheStorage(aPrincipal);
  1248. if (NS_WARN_IF(NS_FAILED(rv))) {
  1249. return rv;
  1250. }
  1251. ErrorResult error;
  1252. MOZ_ASSERT(!mCacheName.IsEmpty());
  1253. RefPtr<Promise> promise = mCacheStorage->Open(mCacheName, error);
  1254. if (NS_WARN_IF(error.Failed())) {
  1255. return error.StealNSResult();
  1256. }
  1257. promise->AppendNativeHandler(this);
  1258. return NS_OK;
  1259. }
  1260. void
  1261. CacheCreator::FailLoaders(nsresult aRv)
  1262. {
  1263. AssertIsOnMainThread();
  1264. // Fail() can call LoadingFinished() which may call ExecuteFinishedScripts()
  1265. // which sets mCacheCreator to null, so hold a ref.
  1266. RefPtr<CacheCreator> kungfuDeathGrip = this;
  1267. for (uint32_t i = 0, len = mLoaders.Length(); i < len; ++i) {
  1268. mLoaders[i]->Fail(aRv);
  1269. }
  1270. mLoaders.Clear();
  1271. }
  1272. void
  1273. CacheCreator::RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue)
  1274. {
  1275. AssertIsOnMainThread();
  1276. FailLoaders(NS_ERROR_FAILURE);
  1277. }
  1278. void
  1279. CacheCreator::ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue)
  1280. {
  1281. AssertIsOnMainThread();
  1282. if (!aValue.isObject()) {
  1283. FailLoaders(NS_ERROR_FAILURE);
  1284. return;
  1285. }
  1286. JS::Rooted<JSObject*> obj(aCx, &aValue.toObject());
  1287. Cache* cache = nullptr;
  1288. nsresult rv = UNWRAP_OBJECT(Cache, &obj, cache);
  1289. if (NS_WARN_IF(NS_FAILED(rv))) {
  1290. FailLoaders(NS_ERROR_FAILURE);
  1291. return;
  1292. }
  1293. mCache = cache;
  1294. MOZ_DIAGNOSTIC_ASSERT(mCache);
  1295. // If the worker is canceled, CancelMainThread() will have cleared the
  1296. // loaders via DeleteCache().
  1297. for (uint32_t i = 0, len = mLoaders.Length(); i < len; ++i) {
  1298. MOZ_DIAGNOSTIC_ASSERT(mLoaders[i]);
  1299. mLoaders[i]->Load(cache);
  1300. }
  1301. }
  1302. void
  1303. CacheCreator::DeleteCache()
  1304. {
  1305. AssertIsOnMainThread();
  1306. // This is called when the load is canceled which can occur before
  1307. // mCacheStorage is initialized.
  1308. if (mCacheStorage) {
  1309. // It's safe to do this while Cache::Match() and Cache::Put() calls are
  1310. // running.
  1311. IgnoredErrorResult rv;
  1312. RefPtr<Promise> promise = mCacheStorage->Delete(mCacheName, rv);
  1313. // We don't care to know the result of the promise object.
  1314. }
  1315. // Always call this here to ensure the loaders array is cleared.
  1316. FailLoaders(NS_ERROR_FAILURE);
  1317. }
  1318. void
  1319. CacheScriptLoader::Fail(nsresult aRv)
  1320. {
  1321. AssertIsOnMainThread();
  1322. MOZ_ASSERT(NS_FAILED(aRv));
  1323. if (mFailed) {
  1324. return;
  1325. }
  1326. mFailed = true;
  1327. if (mPump) {
  1328. MOZ_ASSERT(mLoadInfo.mCacheStatus == ScriptLoadInfo::ReadingFromCache);
  1329. mPump->Cancel(aRv);
  1330. mPump = nullptr;
  1331. }
  1332. mLoadInfo.mCacheStatus = ScriptLoadInfo::Cancel;
  1333. // Stop if the load was aborted on the main thread.
  1334. // Can't use Finished() because mCachePromise may still be true.
  1335. if (mLoadInfo.mLoadingFinished) {
  1336. MOZ_ASSERT(!mLoadInfo.mChannel);
  1337. MOZ_ASSERT_IF(mLoadInfo.mCachePromise,
  1338. mLoadInfo.mCacheStatus == ScriptLoadInfo::WritingToCache ||
  1339. mLoadInfo.mCacheStatus == ScriptLoadInfo::Cancel);
  1340. return;
  1341. }
  1342. mRunnable->LoadingFinished(mIndex, aRv);
  1343. }
  1344. void
  1345. CacheScriptLoader::Load(Cache* aCache)
  1346. {
  1347. AssertIsOnMainThread();
  1348. MOZ_ASSERT(aCache);
  1349. nsCOMPtr<nsIURI> uri;
  1350. nsresult rv = NS_NewURI(getter_AddRefs(uri), mLoadInfo.mURL, nullptr,
  1351. mBaseURI);
  1352. if (NS_WARN_IF(NS_FAILED(rv))) {
  1353. Fail(rv);
  1354. return;
  1355. }
  1356. nsAutoCString spec;
  1357. rv = uri->GetSpec(spec);
  1358. if (NS_WARN_IF(NS_FAILED(rv))) {
  1359. Fail(rv);
  1360. return;
  1361. }
  1362. MOZ_ASSERT(mLoadInfo.mFullURL.IsEmpty());
  1363. CopyUTF8toUTF16(spec, mLoadInfo.mFullURL);
  1364. mozilla::dom::RequestOrUSVString request;
  1365. request.SetAsUSVString().Rebind(mLoadInfo.mFullURL.Data(),
  1366. mLoadInfo.mFullURL.Length());
  1367. mozilla::dom::CacheQueryOptions params;
  1368. ErrorResult error;
  1369. RefPtr<Promise> promise = aCache->Match(request, params, error);
  1370. if (NS_WARN_IF(error.Failed())) {
  1371. Fail(error.StealNSResult());
  1372. return;
  1373. }
  1374. promise->AppendNativeHandler(this);
  1375. }
  1376. void
  1377. CacheScriptLoader::RejectedCallback(JSContext* aCx,
  1378. JS::Handle<JS::Value> aValue)
  1379. {
  1380. AssertIsOnMainThread();
  1381. MOZ_ASSERT(mLoadInfo.mCacheStatus == ScriptLoadInfo::Uncached);
  1382. Fail(NS_ERROR_FAILURE);
  1383. }
  1384. void
  1385. CacheScriptLoader::ResolvedCallback(JSContext* aCx,
  1386. JS::Handle<JS::Value> aValue)
  1387. {
  1388. AssertIsOnMainThread();
  1389. // If we have already called 'Fail', we should not proceed.
  1390. if (mFailed) {
  1391. return;
  1392. }
  1393. MOZ_ASSERT(mLoadInfo.mCacheStatus == ScriptLoadInfo::Uncached);
  1394. nsresult rv;
  1395. if (aValue.isUndefined()) {
  1396. mLoadInfo.mCacheStatus = ScriptLoadInfo::ToBeCached;
  1397. rv = mRunnable->LoadScript(mIndex);
  1398. if (NS_WARN_IF(NS_FAILED(rv))) {
  1399. Fail(rv);
  1400. }
  1401. return;
  1402. }
  1403. MOZ_ASSERT(aValue.isObject());
  1404. JS::Rooted<JSObject*> obj(aCx, &aValue.toObject());
  1405. mozilla::dom::Response* response = nullptr;
  1406. rv = UNWRAP_OBJECT(Response, &obj, response);
  1407. if (NS_WARN_IF(NS_FAILED(rv))) {
  1408. Fail(rv);
  1409. return;
  1410. }
  1411. nsCOMPtr<nsIInputStream> inputStream;
  1412. response->GetBody(getter_AddRefs(inputStream));
  1413. mChannelInfo = response->GetChannelInfo();
  1414. const UniquePtr<PrincipalInfo>& pInfo = response->GetPrincipalInfo();
  1415. if (pInfo) {
  1416. mPrincipalInfo = mozilla::MakeUnique<PrincipalInfo>(*pInfo);
  1417. }
  1418. if (!inputStream) {
  1419. mLoadInfo.mCacheStatus = ScriptLoadInfo::Cached;
  1420. mRunnable->DataReceivedFromCache(mIndex, (uint8_t*)"", 0, mChannelInfo,
  1421. Move(mPrincipalInfo));
  1422. return;
  1423. }
  1424. MOZ_ASSERT(!mPump);
  1425. rv = NS_NewInputStreamPump(getter_AddRefs(mPump), inputStream);
  1426. if (NS_WARN_IF(NS_FAILED(rv))) {
  1427. Fail(rv);
  1428. return;
  1429. }
  1430. nsCOMPtr<nsIStreamLoader> loader;
  1431. rv = NS_NewStreamLoader(getter_AddRefs(loader), this);
  1432. if (NS_WARN_IF(NS_FAILED(rv))) {
  1433. Fail(rv);
  1434. return;
  1435. }
  1436. rv = mPump->AsyncRead(loader, nullptr);
  1437. if (NS_WARN_IF(NS_FAILED(rv))) {
  1438. mPump = nullptr;
  1439. Fail(rv);
  1440. return;
  1441. }
  1442. nsCOMPtr<nsIThreadRetargetableRequest> rr = do_QueryInterface(mPump);
  1443. if (rr) {
  1444. nsCOMPtr<nsIEventTarget> sts =
  1445. do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
  1446. rv = rr->RetargetDeliveryTo(sts);
  1447. if (NS_FAILED(rv)) {
  1448. NS_WARNING("Failed to dispatch the nsIInputStreamPump to a IO thread.");
  1449. }
  1450. }
  1451. mLoadInfo.mCacheStatus = ScriptLoadInfo::ReadingFromCache;
  1452. }
  1453. NS_IMETHODIMP
  1454. CacheScriptLoader::OnStreamComplete(nsIStreamLoader* aLoader, nsISupports* aContext,
  1455. nsresult aStatus, uint32_t aStringLen,
  1456. const uint8_t* aString)
  1457. {
  1458. AssertIsOnMainThread();
  1459. mPump = nullptr;
  1460. if (NS_FAILED(aStatus)) {
  1461. MOZ_ASSERT(mLoadInfo.mCacheStatus == ScriptLoadInfo::ReadingFromCache ||
  1462. mLoadInfo.mCacheStatus == ScriptLoadInfo::Cancel);
  1463. Fail(aStatus);
  1464. return NS_OK;
  1465. }
  1466. MOZ_ASSERT(mLoadInfo.mCacheStatus == ScriptLoadInfo::ReadingFromCache);
  1467. mLoadInfo.mCacheStatus = ScriptLoadInfo::Cached;
  1468. MOZ_ASSERT(mPrincipalInfo);
  1469. mRunnable->DataReceivedFromCache(mIndex, aString, aStringLen, mChannelInfo,
  1470. Move(mPrincipalInfo));
  1471. return NS_OK;
  1472. }
  1473. class ChannelGetterRunnable final : public WorkerMainThreadRunnable
  1474. {
  1475. const nsAString& mScriptURL;
  1476. nsIChannel** mChannel;
  1477. nsresult mResult;
  1478. public:
  1479. ChannelGetterRunnable(WorkerPrivate* aParentWorker,
  1480. const nsAString& aScriptURL,
  1481. nsIChannel** aChannel)
  1482. : WorkerMainThreadRunnable(aParentWorker,
  1483. NS_LITERAL_CSTRING("ScriptLoader :: ChannelGetter"))
  1484. , mScriptURL(aScriptURL)
  1485. , mChannel(aChannel)
  1486. , mResult(NS_ERROR_FAILURE)
  1487. {
  1488. MOZ_ASSERT(aParentWorker);
  1489. aParentWorker->AssertIsOnWorkerThread();
  1490. }
  1491. virtual bool
  1492. MainThreadRun() override
  1493. {
  1494. AssertIsOnMainThread();
  1495. nsIPrincipal* principal = mWorkerPrivate->GetPrincipal();
  1496. MOZ_ASSERT(principal);
  1497. // Figure out our base URI.
  1498. nsCOMPtr<nsIURI> baseURI = mWorkerPrivate->GetBaseURI();
  1499. MOZ_ASSERT(baseURI);
  1500. // May be null.
  1501. nsCOMPtr<nsIDocument> parentDoc = mWorkerPrivate->GetDocument();
  1502. nsCOMPtr<nsILoadGroup> loadGroup = mWorkerPrivate->GetLoadGroup();
  1503. nsCOMPtr<nsIChannel> channel;
  1504. mResult =
  1505. scriptloader::ChannelFromScriptURLMainThread(principal, baseURI,
  1506. parentDoc, loadGroup,
  1507. mScriptURL,
  1508. // Nested workers are always dedicated.
  1509. nsIContentPolicy::TYPE_INTERNAL_WORKER,
  1510. // Nested workers use default uri encoding.
  1511. true,
  1512. getter_AddRefs(channel));
  1513. if (NS_SUCCEEDED(mResult)) {
  1514. channel.forget(mChannel);
  1515. }
  1516. return true;
  1517. }
  1518. nsresult
  1519. GetResult() const
  1520. {
  1521. return mResult;
  1522. }
  1523. private:
  1524. virtual ~ChannelGetterRunnable()
  1525. { }
  1526. };
  1527. ScriptExecutorRunnable::ScriptExecutorRunnable(
  1528. ScriptLoaderRunnable& aScriptLoader,
  1529. nsIEventTarget* aSyncLoopTarget,
  1530. bool aIsWorkerScript,
  1531. uint32_t aFirstIndex,
  1532. uint32_t aLastIndex)
  1533. : MainThreadWorkerSyncRunnable(aScriptLoader.mWorkerPrivate, aSyncLoopTarget),
  1534. mScriptLoader(aScriptLoader), mIsWorkerScript(aIsWorkerScript),
  1535. mFirstIndex(aFirstIndex), mLastIndex(aLastIndex)
  1536. {
  1537. MOZ_ASSERT(aFirstIndex <= aLastIndex);
  1538. MOZ_ASSERT(aLastIndex < aScriptLoader.mLoadInfos.Length());
  1539. }
  1540. bool
  1541. ScriptExecutorRunnable::IsDebuggerRunnable() const
  1542. {
  1543. // ScriptExecutorRunnable is used to execute both worker and debugger scripts.
  1544. // In the latter case, the runnable needs to be dispatched to the debugger
  1545. // queue.
  1546. return mScriptLoader.mWorkerScriptType == DebuggerScript;
  1547. }
  1548. bool
  1549. ScriptExecutorRunnable::PreRun(WorkerPrivate* aWorkerPrivate)
  1550. {
  1551. aWorkerPrivate->AssertIsOnWorkerThread();
  1552. if (!mIsWorkerScript) {
  1553. return true;
  1554. }
  1555. if (!aWorkerPrivate->GetJSContext()) {
  1556. return false;
  1557. }
  1558. MOZ_ASSERT(mFirstIndex == 0);
  1559. MOZ_ASSERT(!mScriptLoader.mRv.Failed());
  1560. AutoJSAPI jsapi;
  1561. jsapi.Init();
  1562. WorkerGlobalScope* globalScope =
  1563. aWorkerPrivate->GetOrCreateGlobalScope(jsapi.cx());
  1564. if (NS_WARN_IF(!globalScope)) {
  1565. NS_WARNING("Failed to make global!");
  1566. // There's no way to report the exception on jsapi right now, because there
  1567. // is no way to even enter a compartment on this thread anymore. Just clear
  1568. // the exception. We'll report some sort of error to our caller in
  1569. // ShutdownScriptLoader, but it will get squelched for the same reason we're
  1570. // squelching here: all the error reporting machinery relies on being able
  1571. // to enter a compartment to report the error.
  1572. jsapi.ClearException();
  1573. return false;
  1574. }
  1575. return true;
  1576. }
  1577. bool
  1578. ScriptExecutorRunnable::WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate)
  1579. {
  1580. aWorkerPrivate->AssertIsOnWorkerThread();
  1581. nsTArray<ScriptLoadInfo>& loadInfos = mScriptLoader.mLoadInfos;
  1582. // Don't run if something else has already failed.
  1583. for (uint32_t index = 0; index < mFirstIndex; index++) {
  1584. ScriptLoadInfo& loadInfo = loadInfos.ElementAt(index);
  1585. NS_ASSERTION(!loadInfo.mChannel, "Should no longer have a channel!");
  1586. NS_ASSERTION(loadInfo.mExecutionScheduled, "Should be scheduled!");
  1587. if (!loadInfo.mExecutionResult) {
  1588. return true;
  1589. }
  1590. }
  1591. // If nothing else has failed, our ErrorResult better not be a failure either.
  1592. MOZ_ASSERT(!mScriptLoader.mRv.Failed(), "Who failed it and why?");
  1593. // Slightly icky action at a distance, but there's no better place to stash
  1594. // this value, really.
  1595. JS::Rooted<JSObject*> global(aCx, JS::CurrentGlobalOrNull(aCx));
  1596. MOZ_ASSERT(global);
  1597. for (uint32_t index = mFirstIndex; index <= mLastIndex; index++) {
  1598. ScriptLoadInfo& loadInfo = loadInfos.ElementAt(index);
  1599. NS_ASSERTION(!loadInfo.mChannel, "Should no longer have a channel!");
  1600. NS_ASSERTION(loadInfo.mExecutionScheduled, "Should be scheduled!");
  1601. NS_ASSERTION(!loadInfo.mExecutionResult, "Should not have executed yet!");
  1602. MOZ_ASSERT(!mScriptLoader.mRv.Failed(), "Who failed it and why?");
  1603. mScriptLoader.mRv.MightThrowJSException();
  1604. if (NS_FAILED(loadInfo.mLoadResult)) {
  1605. scriptloader::ReportLoadError(mScriptLoader.mRv,
  1606. loadInfo.mLoadResult, loadInfo.mURL);
  1607. // Top level scripts only!
  1608. if (mIsWorkerScript) {
  1609. aWorkerPrivate->MaybeDispatchLoadFailedRunnable();
  1610. }
  1611. return true;
  1612. }
  1613. NS_ConvertUTF16toUTF8 filename(loadInfo.mURL);
  1614. JS::CompileOptions options(aCx);
  1615. options.setFileAndLine(filename.get(), 1)
  1616. .setNoScriptRval(true);
  1617. if (mScriptLoader.mWorkerScriptType == DebuggerScript) {
  1618. options.setVersion(JSVERSION_LATEST);
  1619. }
  1620. MOZ_ASSERT(loadInfo.mMutedErrorFlag.isSome());
  1621. options.setMutedErrors(loadInfo.mMutedErrorFlag.valueOr(true));
  1622. JS::SourceBufferHolder srcBuf(loadInfo.mScriptTextBuf,
  1623. loadInfo.mScriptTextLength,
  1624. JS::SourceBufferHolder::GiveOwnership);
  1625. loadInfo.mScriptTextBuf = nullptr;
  1626. loadInfo.mScriptTextLength = 0;
  1627. // Our ErrorResult still shouldn't be a failure.
  1628. MOZ_ASSERT(!mScriptLoader.mRv.Failed(), "Who failed it and why?");
  1629. JS::Rooted<JS::Value> unused(aCx);
  1630. if (!JS::Evaluate(aCx, options, srcBuf, &unused)) {
  1631. mScriptLoader.mRv.StealExceptionFromJSContext(aCx);
  1632. return true;
  1633. }
  1634. loadInfo.mExecutionResult = true;
  1635. }
  1636. return true;
  1637. }
  1638. void
  1639. ScriptExecutorRunnable::PostRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate,
  1640. bool aRunResult)
  1641. {
  1642. aWorkerPrivate->AssertIsOnWorkerThread();
  1643. MOZ_ASSERT(!JS_IsExceptionPending(aCx), "Who left an exception on there?");
  1644. nsTArray<ScriptLoadInfo>& loadInfos = mScriptLoader.mLoadInfos;
  1645. if (mLastIndex == loadInfos.Length() - 1) {
  1646. // All done. If anything failed then return false.
  1647. bool result = true;
  1648. bool mutedError = false;
  1649. for (uint32_t index = 0; index < loadInfos.Length(); index++) {
  1650. if (!loadInfos[index].mExecutionResult) {
  1651. mutedError = loadInfos[index].mMutedErrorFlag.valueOr(true);
  1652. result = false;
  1653. break;
  1654. }
  1655. }
  1656. // The only way we can get here with "result" false but without
  1657. // mScriptLoader.mRv being a failure is if we're loading the main worker
  1658. // script and GetOrCreateGlobalScope() fails. In that case we would have
  1659. // returned false from WorkerRun, so assert that.
  1660. MOZ_ASSERT_IF(!result && !mScriptLoader.mRv.Failed(),
  1661. !aRunResult);
  1662. ShutdownScriptLoader(aCx, aWorkerPrivate, result, mutedError);
  1663. }
  1664. }
  1665. nsresult
  1666. ScriptExecutorRunnable::Cancel()
  1667. {
  1668. if (mLastIndex == mScriptLoader.mLoadInfos.Length() - 1) {
  1669. ShutdownScriptLoader(mWorkerPrivate->GetJSContext(), mWorkerPrivate,
  1670. false, false);
  1671. }
  1672. return MainThreadWorkerSyncRunnable::Cancel();
  1673. }
  1674. void
  1675. ScriptExecutorRunnable::ShutdownScriptLoader(JSContext* aCx,
  1676. WorkerPrivate* aWorkerPrivate,
  1677. bool aResult,
  1678. bool aMutedError)
  1679. {
  1680. aWorkerPrivate->AssertIsOnWorkerThread();
  1681. MOZ_ASSERT(mLastIndex == mScriptLoader.mLoadInfos.Length() - 1);
  1682. if (mIsWorkerScript && aWorkerPrivate->IsServiceWorker()) {
  1683. aWorkerPrivate->SetLoadingWorkerScript(false);
  1684. }
  1685. if (!aResult) {
  1686. // At this point there are two possibilities:
  1687. //
  1688. // 1) mScriptLoader.mRv.Failed(). In that case we just want to leave it
  1689. // as-is, except if it has a JS exception and we need to mute JS
  1690. // exceptions. In that case, we log the exception without firing any
  1691. // events and then replace it on the ErrorResult with a NetworkError,
  1692. // per spec.
  1693. //
  1694. // 2) mScriptLoader.mRv succeeded. As far as I can tell, this can only
  1695. // happen when loading the main worker script and
  1696. // GetOrCreateGlobalScope() fails or if ScriptExecutorRunnable::Cancel
  1697. // got called. Does it matter what we throw in this case? I'm not
  1698. // sure...
  1699. if (mScriptLoader.mRv.Failed()) {
  1700. if (aMutedError && mScriptLoader.mRv.IsJSException()) {
  1701. LogExceptionToConsole(aCx, aWorkerPrivate);
  1702. mScriptLoader.mRv.Throw(NS_ERROR_DOM_NETWORK_ERR);
  1703. }
  1704. } else {
  1705. mScriptLoader.mRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
  1706. }
  1707. }
  1708. aWorkerPrivate->StopSyncLoop(mSyncLoopTarget, aResult);
  1709. }
  1710. void
  1711. ScriptExecutorRunnable::LogExceptionToConsole(JSContext* aCx,
  1712. WorkerPrivate* aWorkerPrivate)
  1713. {
  1714. aWorkerPrivate->AssertIsOnWorkerThread();
  1715. MOZ_ASSERT(mScriptLoader.mRv.IsJSException());
  1716. JS::Rooted<JS::Value> exn(aCx);
  1717. if (!ToJSValue(aCx, mScriptLoader.mRv, &exn)) {
  1718. return;
  1719. }
  1720. // Now the exception state should all be in exn.
  1721. MOZ_ASSERT(!JS_IsExceptionPending(aCx));
  1722. MOZ_ASSERT(!mScriptLoader.mRv.Failed());
  1723. js::ErrorReport report(aCx);
  1724. if (!report.init(aCx, exn, js::ErrorReport::WithSideEffects)) {
  1725. JS_ClearPendingException(aCx);
  1726. return;
  1727. }
  1728. RefPtr<xpc::ErrorReport> xpcReport = new xpc::ErrorReport();
  1729. xpcReport->Init(report.report(), report.toStringResult().c_str(),
  1730. aWorkerPrivate->IsChromeWorker(), aWorkerPrivate->WindowID());
  1731. RefPtr<AsyncErrorReporter> r = new AsyncErrorReporter(xpcReport);
  1732. NS_DispatchToMainThread(r);
  1733. }
  1734. void
  1735. LoadAllScripts(WorkerPrivate* aWorkerPrivate,
  1736. nsTArray<ScriptLoadInfo>& aLoadInfos, bool aIsMainScript,
  1737. WorkerScriptType aWorkerScriptType, ErrorResult& aRv)
  1738. {
  1739. aWorkerPrivate->AssertIsOnWorkerThread();
  1740. NS_ASSERTION(!aLoadInfos.IsEmpty(), "Bad arguments!");
  1741. AutoSyncLoopHolder syncLoop(aWorkerPrivate, Terminating);
  1742. nsCOMPtr<nsIEventTarget> syncLoopTarget = syncLoop.GetEventTarget();
  1743. if (!syncLoopTarget) {
  1744. aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
  1745. return;
  1746. }
  1747. RefPtr<ScriptLoaderRunnable> loader =
  1748. new ScriptLoaderRunnable(aWorkerPrivate, syncLoopTarget, aLoadInfos,
  1749. aIsMainScript, aWorkerScriptType, aRv);
  1750. NS_ASSERTION(aLoadInfos.IsEmpty(), "Should have swapped!");
  1751. ScriptLoaderHolder workerHolder(loader);
  1752. if (NS_WARN_IF(!workerHolder.HoldWorker(aWorkerPrivate, Terminating))) {
  1753. aRv.Throw(NS_ERROR_FAILURE);
  1754. return;
  1755. }
  1756. if (NS_FAILED(NS_DispatchToMainThread(loader))) {
  1757. NS_ERROR("Failed to dispatch!");
  1758. aRv.Throw(NS_ERROR_FAILURE);
  1759. return;
  1760. }
  1761. syncLoop.Run();
  1762. }
  1763. } /* anonymous namespace */
  1764. BEGIN_WORKERS_NAMESPACE
  1765. namespace scriptloader {
  1766. nsresult
  1767. ChannelFromScriptURLMainThread(nsIPrincipal* aPrincipal,
  1768. nsIURI* aBaseURI,
  1769. nsIDocument* aParentDoc,
  1770. nsILoadGroup* aLoadGroup,
  1771. const nsAString& aScriptURL,
  1772. nsContentPolicyType aContentPolicyType,
  1773. bool aDefaultURIEncoding,
  1774. nsIChannel** aChannel)
  1775. {
  1776. AssertIsOnMainThread();
  1777. nsCOMPtr<nsIIOService> ios(do_GetIOService());
  1778. nsIScriptSecurityManager* secMan = nsContentUtils::GetSecurityManager();
  1779. NS_ASSERTION(secMan, "This should never be null!");
  1780. return ChannelFromScriptURL(aPrincipal, aBaseURI, aParentDoc, aLoadGroup,
  1781. ios, secMan, aScriptURL, true, WorkerScript,
  1782. aContentPolicyType, nsIRequest::LOAD_NORMAL,
  1783. aDefaultURIEncoding, aChannel);
  1784. }
  1785. nsresult
  1786. ChannelFromScriptURLWorkerThread(JSContext* aCx,
  1787. WorkerPrivate* aParent,
  1788. const nsAString& aScriptURL,
  1789. nsIChannel** aChannel)
  1790. {
  1791. aParent->AssertIsOnWorkerThread();
  1792. RefPtr<ChannelGetterRunnable> getter =
  1793. new ChannelGetterRunnable(aParent, aScriptURL, aChannel);
  1794. ErrorResult rv;
  1795. getter->Dispatch(Terminating, rv);
  1796. if (rv.Failed()) {
  1797. NS_ERROR("Failed to dispatch!");
  1798. return rv.StealNSResult();
  1799. }
  1800. return getter->GetResult();
  1801. }
  1802. void ReportLoadError(ErrorResult& aRv, nsresult aLoadResult,
  1803. const nsAString& aScriptURL)
  1804. {
  1805. MOZ_ASSERT(!aRv.Failed());
  1806. switch (aLoadResult) {
  1807. case NS_ERROR_FILE_NOT_FOUND:
  1808. case NS_ERROR_NOT_AVAILABLE:
  1809. aLoadResult = NS_ERROR_DOM_NETWORK_ERR;
  1810. break;
  1811. case NS_ERROR_MALFORMED_URI:
  1812. aLoadResult = NS_ERROR_DOM_SYNTAX_ERR;
  1813. break;
  1814. case NS_BINDING_ABORTED:
  1815. // Note: we used to pretend like we didn't set an exception for
  1816. // NS_BINDING_ABORTED, but then ShutdownScriptLoader did it anyway. The
  1817. // other callsite, in WorkerPrivate::Constructor, never passed in
  1818. // NS_BINDING_ABORTED. So just throw it directly here. Consumers will
  1819. // deal as needed. But note that we do NOT want to ThrowDOMException()
  1820. // for this case, because that will make it impossible for consumers to
  1821. // realize that our error was NS_BINDING_ABORTED.
  1822. aRv.Throw(aLoadResult);
  1823. return;
  1824. case NS_ERROR_DOM_SECURITY_ERR:
  1825. case NS_ERROR_DOM_SYNTAX_ERR:
  1826. break;
  1827. case NS_ERROR_DOM_BAD_URI:
  1828. // This is actually a security error.
  1829. aLoadResult = NS_ERROR_DOM_SECURITY_ERR;
  1830. break;
  1831. default:
  1832. // For lack of anything better, go ahead and throw a NetworkError here.
  1833. // We don't want to throw a JS exception, because for toplevel script
  1834. // loads that would get squelched.
  1835. aRv.ThrowDOMException(NS_ERROR_DOM_NETWORK_ERR,
  1836. nsPrintfCString("Failed to load worker script at %s (nsresult = 0x%x)",
  1837. NS_ConvertUTF16toUTF8(aScriptURL).get(),
  1838. aLoadResult));
  1839. return;
  1840. }
  1841. aRv.ThrowDOMException(aLoadResult,
  1842. NS_LITERAL_CSTRING("Failed to load worker script at \"") +
  1843. NS_ConvertUTF16toUTF8(aScriptURL) +
  1844. NS_LITERAL_CSTRING("\""));
  1845. }
  1846. void
  1847. LoadMainScript(WorkerPrivate* aWorkerPrivate,
  1848. const nsAString& aScriptURL,
  1849. WorkerScriptType aWorkerScriptType,
  1850. ErrorResult& aRv)
  1851. {
  1852. nsTArray<ScriptLoadInfo> loadInfos;
  1853. ScriptLoadInfo* info = loadInfos.AppendElement();
  1854. info->mURL = aScriptURL;
  1855. LoadAllScripts(aWorkerPrivate, loadInfos, true, aWorkerScriptType, aRv);
  1856. }
  1857. void
  1858. Load(WorkerPrivate* aWorkerPrivate,
  1859. const nsTArray<nsString>& aScriptURLs, WorkerScriptType aWorkerScriptType,
  1860. ErrorResult& aRv)
  1861. {
  1862. const uint32_t urlCount = aScriptURLs.Length();
  1863. if (!urlCount) {
  1864. return;
  1865. }
  1866. if (urlCount > MAX_CONCURRENT_SCRIPTS) {
  1867. aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
  1868. return;
  1869. }
  1870. nsTArray<ScriptLoadInfo> loadInfos;
  1871. loadInfos.SetLength(urlCount);
  1872. for (uint32_t index = 0; index < urlCount; index++) {
  1873. loadInfos[index].mURL = aScriptURLs[index];
  1874. }
  1875. LoadAllScripts(aWorkerPrivate, loadInfos, false, aWorkerScriptType, aRv);
  1876. }
  1877. } // namespace scriptloader
  1878. END_WORKERS_NAMESPACE