1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
|
/* -*- 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/. */
#ifndef mozilla_dom_workers_workerprivate_h__
#define mozilla_dom_workers_workerprivate_h__
#include <bitset>
#include "MainThreadUtils.h"
#include "ScriptLoader.h"
#include "js/ContextOptions.h"
#include "mozilla/Attributes.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/CondVar.h"
#include "mozilla/DOMEventTargetHelper.h"
#include "mozilla/Maybe.h"
#include "mozilla/MozPromise.h"
#include "mozilla/OriginTrials.h"
#include "mozilla/PerformanceCounter.h"
#include "mozilla/RelativeTimeline.h"
#include "mozilla/Result.h"
#include "mozilla/StorageAccess.h"
#include "mozilla/ThreadBound.h"
#include "mozilla/ThreadSafeWeakPtr.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/UseCounter.h"
#include "mozilla/dom/ClientSource.h"
#include "mozilla/dom/FlippedOnce.h"
#include "mozilla/dom/Timeout.h"
#include "mozilla/dom/quota/CheckedUnsafePtr.h"
#include "mozilla/dom/Worker.h"
#include "mozilla/dom/WorkerCommon.h"
#include "mozilla/dom/WorkerLoadInfo.h"
#include "mozilla/dom/WorkerStatus.h"
#include "mozilla/dom/workerinternals/JSSettings.h"
#include "mozilla/dom/workerinternals/Queue.h"
#include "mozilla/dom/JSExecutionManager.h"
#include "mozilla/StaticPrefs_extensions.h"
#include "nsContentUtils.h"
#include "nsIChannel.h"
#include "nsIContentSecurityPolicy.h"
#include "nsIEventTarget.h"
#include "nsILoadInfo.h"
#include "nsTObserverArray.h"
class nsIThreadInternal;
namespace JS {
struct RuntimeStats;
}
namespace mozilla {
class ThrottledEventQueue;
namespace dom {
class RemoteWorkerChild;
// If you change this, the corresponding list in nsIWorkerDebugger.idl needs
// to be updated too. And histograms enum for worker use counters uses the same
// order of worker kind. Please also update dom/base/usecounters.py.
enum WorkerKind { WorkerKindDedicated, WorkerKindShared, WorkerKindService };
class ClientInfo;
class ClientSource;
class Function;
class JSExecutionManager;
class MessagePort;
class UniqueMessagePortId;
class PerformanceStorage;
class TimeoutHandler;
class WorkerControlRunnable;
class WorkerCSPEventListener;
class WorkerDebugger;
class WorkerDebuggerGlobalScope;
class WorkerErrorReport;
class WorkerEventTarget;
class WorkerGlobalScope;
class WorkerRef;
class WorkerRunnable;
class WorkerDebuggeeRunnable;
class WorkerThread;
// SharedMutex is a small wrapper around an (internal) reference-counted Mutex
// object. It exists to avoid changing a lot of code to use Mutex* instead of
// Mutex&.
class MOZ_CAPABILITY("mutex") SharedMutex {
using Mutex = mozilla::Mutex;
class MOZ_CAPABILITY("mutex") RefCountedMutex final : public Mutex {
public:
explicit RefCountedMutex(const char* aName) : Mutex(aName) {}
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(RefCountedMutex)
private:
~RefCountedMutex() = default;
};
const RefPtr<RefCountedMutex> mMutex;
public:
explicit SharedMutex(const char* aName)
: mMutex(new RefCountedMutex(aName)) {}
SharedMutex(const SharedMutex& aOther) = default;
operator Mutex&() MOZ_RETURN_CAPABILITY(this) { return *mMutex; }
operator const Mutex&() const MOZ_RETURN_CAPABILITY(this) { return *mMutex; }
// We need these to make thread-safety analysis work
void Lock() MOZ_CAPABILITY_ACQUIRE() { mMutex->Lock(); }
void Unlock() MOZ_CAPABILITY_RELEASE() { mMutex->Unlock(); }
// We can assert we own 'this', but we can't assert we hold mMutex
void AssertCurrentThreadOwns() const
MOZ_ASSERT_CAPABILITY(this) MOZ_NO_THREAD_SAFETY_ANALYSIS {
mMutex->AssertCurrentThreadOwns();
}
};
nsString ComputeWorkerPrivateId();
class WorkerPrivate final
: public RelativeTimeline,
public SupportsCheckedUnsafePtr<CheckIf<DiagnosticAssertEnabled>> {
public:
struct LocationInfo {
nsCString mHref;
nsCString mProtocol;
nsCString mHost;
nsCString mHostname;
nsCString mPort;
nsCString mPathname;
nsCString mSearch;
nsCString mHash;
nsString mOrigin;
};
NS_INLINE_DECL_REFCOUNTING(WorkerPrivate)
static already_AddRefed<WorkerPrivate> Constructor(
JSContext* aCx, const nsAString& aScriptURL, bool aIsChromeWorker,
WorkerKind aWorkerKind, const nsAString& aWorkerName,
const nsACString& aServiceWorkerScope, WorkerLoadInfo* aLoadInfo,
ErrorResult& aRv, nsString aId = u""_ns);
enum LoadGroupBehavior { InheritLoadGroup, OverrideLoadGroup };
static nsresult GetLoadInfo(JSContext* aCx, nsPIDOMWindowInner* aWindow,
WorkerPrivate* aParent,
const nsAString& aScriptURL, bool aIsChromeWorker,
LoadGroupBehavior aLoadGroupBehavior,
WorkerKind aWorkerKind,
WorkerLoadInfo* aLoadInfo);
void Traverse(nsCycleCollectionTraversalCallback& aCb);
void ClearSelfAndParentEventTargetRef() {
AssertIsOnParentThread();
MOZ_ASSERT(mSelfRef);
mParentEventTargetRef = nullptr;
mSelfRef = nullptr;
}
// May be called on any thread...
bool Start();
// Called on the parent thread.
bool Notify(WorkerStatus aStatus);
bool Cancel() { return Notify(Canceling); }
bool Close() MOZ_REQUIRES(mMutex);
// The passed principal must be the Worker principal in case of a
// ServiceWorker and the loading principal for any other type.
static void OverrideLoadInfoLoadGroup(WorkerLoadInfo& aLoadInfo,
nsIPrincipal* aPrincipal);
bool IsDebuggerRegistered() MOZ_NO_THREAD_SAFETY_ANALYSIS {
AssertIsOnMainThread();
// No need to lock here since this is only ever modified by the same thread.
return mDebuggerRegistered; // would give a thread-safety warning
}
bool ExtensionAPIAllowed() {
return (
StaticPrefs::extensions_backgroundServiceWorker_enabled_AtStartup() &&
mExtensionAPIAllowed);
}
void SetIsDebuggerRegistered(bool aDebuggerRegistered) {
AssertIsOnMainThread();
MutexAutoLock lock(mMutex);
MOZ_ASSERT(mDebuggerRegistered != aDebuggerRegistered);
mDebuggerRegistered = aDebuggerRegistered;
mCondVar.Notify();
}
void WaitForIsDebuggerRegistered(bool aDebuggerRegistered) {
AssertIsOnParentThread();
// Yield so that the main thread won't be blocked.
AutoYieldJSThreadExecution yield;
MOZ_ASSERT(!NS_IsMainThread());
MutexAutoLock lock(mMutex);
while (mDebuggerRegistered != aDebuggerRegistered) {
mCondVar.Wait();
}
}
nsresult SetIsDebuggerReady(bool aReady);
WorkerDebugger* Debugger() const {
AssertIsOnMainThread();
MOZ_ASSERT(mDebugger);
return mDebugger;
}
const OriginTrials& Trials() const { return mLoadInfo.mTrials; }
void SetDebugger(WorkerDebugger* aDebugger) {
AssertIsOnMainThread();
MOZ_ASSERT(mDebugger != aDebugger);
mDebugger = aDebugger;
}
JS::UniqueChars AdoptDefaultLocale() {
MOZ_ASSERT(mDefaultLocale,
"the default locale must have been successfully set for anyone "
"to be trying to adopt it");
return std::move(mDefaultLocale);
}
/**
* Invoked by WorkerThreadPrimaryRunnable::Run if it already called
* SetWorkerPrivateInWorkerThread but has to bail out on initialization before
* calling DoRunLoop because PBackground failed to initialize or something
* like that. Note that there's currently no point earlier than this that
* failure can be reported.
*
* When this happens, the worker will need to be deleted, plus the call to
* SetWorkerPrivateInWorkerThread will have scheduled all the
* mPreStartRunnables which need to be cleaned up after, as well as any
* scheduled control runnables. We're somewhat punting on debugger runnables
* for now, which may leak, but the intent is to moot this whole scenario via
* shutdown blockers, so we don't want the extra complexity right now.
*/
void RunLoopNeverRan();
MOZ_CAN_RUN_SCRIPT
void DoRunLoop(JSContext* aCx);
void UnrootGlobalScopes();
bool InterruptCallback(JSContext* aCx);
bool IsOnCurrentThread();
void CloseInternal();
bool FreezeInternal();
bool ThawInternal();
void PropagateStorageAccessPermissionGrantedInternal();
void TraverseTimeouts(nsCycleCollectionTraversalCallback& aCallback);
void UnlinkTimeouts();
bool ModifyBusyCountFromWorker(bool aIncrease);
bool AddChildWorker(WorkerPrivate& aChildWorker);
void RemoveChildWorker(WorkerPrivate& aChildWorker);
void PostMessageToParent(JSContext* aCx, JS::Handle<JS::Value> aMessage,
const Sequence<JSObject*>& aTransferable,
ErrorResult& aRv);
void PostMessageToParentMessagePort(JSContext* aCx,
JS::Handle<JS::Value> aMessage,
const Sequence<JSObject*>& aTransferable,
ErrorResult& aRv);
MOZ_CAN_RUN_SCRIPT void EnterDebuggerEventLoop();
void LeaveDebuggerEventLoop();
void PostMessageToDebugger(const nsAString& aMessage);
void SetDebuggerImmediate(Function& aHandler, ErrorResult& aRv);
void ReportErrorToDebugger(const nsAString& aFilename, uint32_t aLineno,
const nsAString& aMessage);
bool NotifyInternal(WorkerStatus aStatus);
void ReportError(JSContext* aCx, JS::ConstUTF8CharsZ aToStringResult,
JSErrorReport* aReport);
static void ReportErrorToConsole(const char* aMessage);
static void ReportErrorToConsole(const char* aMessage,
const nsTArray<nsString>& aParams);
int32_t SetTimeout(JSContext* aCx, TimeoutHandler* aHandler, int32_t aTimeout,
bool aIsInterval, Timeout::Reason aReason,
ErrorResult& aRv);
void ClearTimeout(int32_t aId, Timeout::Reason aReason);
MOZ_CAN_RUN_SCRIPT bool RunExpiredTimeouts(JSContext* aCx);
bool RescheduleTimeoutTimer(JSContext* aCx);
void UpdateContextOptionsInternal(JSContext* aCx,
const JS::ContextOptions& aContextOptions);
void UpdateLanguagesInternal(const nsTArray<nsString>& aLanguages);
void UpdateJSWorkerMemoryParameterInternal(JSContext* aCx, JSGCParamKey key,
Maybe<uint32_t> aValue);
enum WorkerRanOrNot { WorkerNeverRan = 0, WorkerRan };
void ScheduleDeletion(WorkerRanOrNot aRanOrNot);
bool CollectRuntimeStats(JS::RuntimeStats* aRtStats, bool aAnonymize);
#ifdef JS_GC_ZEAL
void UpdateGCZealInternal(JSContext* aCx, uint8_t aGCZeal,
uint32_t aFrequency);
#endif
void SetLowMemoryStateInternal(JSContext* aCx, bool aState);
void GarbageCollectInternal(JSContext* aCx, bool aShrinking,
bool aCollectChildren);
void CycleCollectInternal(bool aCollectChildren);
void OfflineStatusChangeEventInternal(bool aIsOffline);
void MemoryPressureInternal();
typedef MozPromise<uint64_t, nsresult, true> JSMemoryUsagePromise;
RefPtr<JSMemoryUsagePromise> GetJSMemoryUsage();
void SetFetchHandlerWasAdded() {
MOZ_ASSERT(IsServiceWorker());
AssertIsOnWorkerThread();
mFetchHandlerWasAdded = true;
}
bool FetchHandlerWasAdded() const {
MOZ_ASSERT(IsServiceWorker());
AssertIsOnWorkerThread();
return mFetchHandlerWasAdded;
}
JSContext* GetJSContext() const MOZ_NO_THREAD_SAFETY_ANALYSIS {
// mJSContext is only modified on the worker thread, so workerthread code
// can safely read it without a lock
AssertIsOnWorkerThread();
return mJSContext;
}
WorkerGlobalScope* GlobalScope() const {
auto data = mWorkerThreadAccessible.Access();
return data->mScope;
}
WorkerDebuggerGlobalScope* DebuggerGlobalScope() const {
auto data = mWorkerThreadAccessible.Access();
return data->mDebuggerScope;
}
// Get the global associated with the current nested event loop. Will return
// null if we're not in a nested event loop or that nested event loop does not
// have an associated global.
nsIGlobalObject* GetCurrentEventLoopGlobal() const {
auto data = mWorkerThreadAccessible.Access();
return data->mCurrentEventLoopGlobal;
}
nsICSPEventListener* CSPEventListener() const;
void SetThread(WorkerThread* aThread);
void SetWorkerPrivateInWorkerThread(WorkerThread* aThread);
void ResetWorkerPrivateInWorkerThread();
bool IsOnWorkerThread() const;
void AssertIsOnWorkerThread() const
#ifdef DEBUG
;
#else
{
}
#endif
// This may block!
void BeginCTypesCall();
// This may block!
void EndCTypesCall();
void BeginCTypesCallback();
void EndCTypesCallback();
bool ConnectMessagePort(JSContext* aCx, UniqueMessagePortId& aIdentifier);
WorkerGlobalScope* GetOrCreateGlobalScope(JSContext* aCx);
WorkerDebuggerGlobalScope* CreateDebuggerGlobalScope(JSContext* aCx);
bool RegisterBindings(JSContext* aCx, JS::Handle<JSObject*> aGlobal);
bool RegisterDebuggerBindings(JSContext* aCx, JS::Handle<JSObject*> aGlobal);
bool OnLine() const {
auto data = mWorkerThreadAccessible.Access();
return data->mOnLine;
}
void StopSyncLoop(nsIEventTarget* aSyncLoopTarget, nsresult aResult);
bool AllPendingRunnablesShouldBeCanceled() const {
return mCancelAllPendingRunnables;
}
void ClearMainEventQueue(WorkerRanOrNot aRanOrNot);
void ClearDebuggerEventQueue();
void OnProcessNextEvent();
void AfterProcessNextEvent();
void AssertValidSyncLoop(nsIEventTarget* aSyncLoopTarget)
#ifdef DEBUG
;
#else
{
}
#endif
void SetWorkerScriptExecutedSuccessfully() {
AssertIsOnWorkerThread();
// Should only be called once!
MOZ_ASSERT(!mWorkerScriptExecutedSuccessfully);
mWorkerScriptExecutedSuccessfully = true;
}
// Only valid after CompileScriptRunnable has finished running!
bool WorkerScriptExecutedSuccessfully() const {
AssertIsOnWorkerThread();
return mWorkerScriptExecutedSuccessfully;
}
// Get the event target to use when dispatching to the main thread
// from this Worker thread. This may be the main thread itself or
// a ThrottledEventQueue to the main thread.
nsIEventTarget* MainThreadEventTargetForMessaging();
nsresult DispatchToMainThreadForMessaging(
nsIRunnable* aRunnable, uint32_t aFlags = NS_DISPATCH_NORMAL);
nsresult DispatchToMainThreadForMessaging(
already_AddRefed<nsIRunnable> aRunnable,
uint32_t aFlags = NS_DISPATCH_NORMAL);
nsIEventTarget* MainThreadEventTarget();
nsresult DispatchToMainThread(nsIRunnable* aRunnable,
uint32_t aFlags = NS_DISPATCH_NORMAL);
nsresult DispatchToMainThread(already_AddRefed<nsIRunnable> aRunnable,
uint32_t aFlags = NS_DISPATCH_NORMAL);
nsresult DispatchDebuggeeToMainThread(
already_AddRefed<WorkerDebuggeeRunnable> aRunnable,
uint32_t aFlags = NS_DISPATCH_NORMAL);
// Get an event target that will dispatch runnables as control runnables on
// the worker thread. Implement nsICancelableRunnable if you wish to take
// action on cancelation.
nsISerialEventTarget* ControlEventTarget();
// Get an event target that will attempt to dispatch a normal WorkerRunnable,
// but if that fails will then fall back to a control runnable.
nsISerialEventTarget* HybridEventTarget();
void DumpCrashInformation(nsACString& aString);
ClientType GetClientType() const;
bool EnsureCSPEventListener();
void EnsurePerformanceStorage();
bool GetExecutionGranted() const;
void SetExecutionGranted(bool aGranted);
void ScheduleTimeSliceExpiration(uint32_t aDelay);
void CancelTimeSliceExpiration();
JSExecutionManager* GetExecutionManager() const;
void SetExecutionManager(JSExecutionManager* aManager);
void ExecutionReady();
PerformanceStorage* GetPerformanceStorage();
PerformanceCounter& MutablePerformanceCounterRef() const {
return *mPerformanceCounter;
}
const PerformanceCounter& PerformanceCounterRef() const {
return MutablePerformanceCounterRef();
}
bool IsAcceptingEvents() {
AssertIsOnParentThread();
MutexAutoLock lock(mMutex);
return mParentStatus < Canceling;
}
WorkerStatus ParentStatusProtected() {
AssertIsOnParentThread();
MutexAutoLock lock(mMutex);
return mParentStatus;
}
WorkerStatus ParentStatus() const MOZ_REQUIRES(mMutex) {
mMutex.AssertCurrentThreadOwns();
return mParentStatus;
}
Worker* ParentEventTargetRef() const {
MOZ_DIAGNOSTIC_ASSERT(mParentEventTargetRef);
return mParentEventTargetRef;
}
void SetParentEventTargetRef(Worker* aParentEventTargetRef) {
MOZ_DIAGNOSTIC_ASSERT(aParentEventTargetRef);
MOZ_DIAGNOSTIC_ASSERT(!mParentEventTargetRef);
mParentEventTargetRef = aParentEventTargetRef;
}
bool ModifyBusyCount(bool aIncrease);
// This method is used by RuntimeService to know what is going wrong the
// shutting down.
uint32_t BusyCount() { return mBusyCount; }
// Check whether this worker is a secure context. For use from the parent
// thread only; the canonical "is secure context" boolean is stored on the
// compartment of the worker global. The only reason we don't
// AssertIsOnParentThread() here is so we can assert that this value matches
// the one on the compartment, which has to be done from the worker thread.
bool IsSecureContext() const { return mIsSecureContext; }
// Check whether we're running in automation.
bool IsInAutomation() const { return mIsInAutomation; }
bool IsPrivilegedAddonGlobal() const { return mIsPrivilegedAddonGlobal; }
TimeStamp CreationTimeStamp() const { return mCreationTimeStamp; }
DOMHighResTimeStamp CreationTime() const { return mCreationTimeHighRes; }
DOMHighResTimeStamp TimeStampToDOMHighRes(const TimeStamp& aTimeStamp) const {
MOZ_ASSERT(!aTimeStamp.IsNull());
TimeDuration duration = aTimeStamp - mCreationTimeStamp;
return duration.ToMilliseconds();
}
LocationInfo& GetLocationInfo() { return mLocationInfo; }
void CopyJSSettings(workerinternals::JSSettings& aSettings) {
mozilla::MutexAutoLock lock(mMutex);
aSettings = mJSSettings;
}
void CopyJSRealmOptions(JS::RealmOptions& aOptions) {
mozilla::MutexAutoLock lock(mMutex);
aOptions = IsChromeWorker() ? mJSSettings.chromeRealmOptions
: mJSSettings.contentRealmOptions;
}
// The ability to be a chrome worker is orthogonal to the type of
// worker [Dedicated|Shared|Service].
bool IsChromeWorker() const { return mIsChromeWorker; }
// TODO: Invariants require that the parent worker out-live any child
// worker, so WorkerPrivate* should be safe in the moment of calling.
// We would like to have stronger type-system annotated/enforced handling.
WorkerPrivate* GetParent() const { return mParent; }
bool IsFrozen() const {
AssertIsOnParentThread();
return mParentFrozen;
}
bool IsParentWindowPaused() const {
AssertIsOnParentThread();
return mParentWindowPaused;
}
// When we debug a worker, we want to disconnect the window and the worker
// communication. This happens calling this method.
// Note: this method doesn't suspend the worker! Use Freeze/Thaw instead.
void ParentWindowPaused();
void ParentWindowResumed();
const nsString& ScriptURL() const { return mScriptURL; }
const nsString& WorkerName() const { return mWorkerName; }
WorkerKind Kind() const { return mWorkerKind; }
bool IsDedicatedWorker() const { return mWorkerKind == WorkerKindDedicated; }
bool IsSharedWorker() const { return mWorkerKind == WorkerKindShared; }
bool IsServiceWorker() const { return mWorkerKind == WorkerKindService; }
nsContentPolicyType ContentPolicyType() const {
return ContentPolicyType(mWorkerKind);
}
static nsContentPolicyType ContentPolicyType(WorkerKind aWorkerKind) {
switch (aWorkerKind) {
case WorkerKindDedicated:
return nsIContentPolicy::TYPE_INTERNAL_WORKER;
case WorkerKindShared:
return nsIContentPolicy::TYPE_INTERNAL_SHARED_WORKER;
case WorkerKindService:
return nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER;
default:
MOZ_ASSERT_UNREACHABLE("Invalid worker type");
return nsIContentPolicy::TYPE_INVALID;
}
}
nsIScriptContext* GetScriptContext() const {
AssertIsOnMainThread();
return mLoadInfo.mScriptContext;
}
const nsCString& Domain() const { return mLoadInfo.mDomain; }
bool IsFromWindow() const { return mLoadInfo.mFromWindow; }
nsLoadFlags GetLoadFlags() const { return mLoadInfo.mLoadFlags; }
uint64_t WindowID() const { return mLoadInfo.mWindowID; }
uint64_t ServiceWorkerID() const { return GetServiceWorkerDescriptor().Id(); }
const nsCString& ServiceWorkerScope() const {
return GetServiceWorkerDescriptor().Scope();
}
// This value should never change after the script load completes. Before
// then, it may only be called on the main thread.
nsIURI* GetBaseURI() const { return mLoadInfo.mBaseURI; }
void SetBaseURI(nsIURI* aBaseURI);
nsIURI* GetResolvedScriptURI() const { return mLoadInfo.mResolvedScriptURI; }
const nsString& ServiceWorkerCacheName() const {
MOZ_DIAGNOSTIC_ASSERT(IsServiceWorker());
AssertIsOnMainThread();
return mLoadInfo.mServiceWorkerCacheName;
}
const ServiceWorkerDescriptor& GetServiceWorkerDescriptor() const {
MOZ_DIAGNOSTIC_ASSERT(IsServiceWorker());
MOZ_DIAGNOSTIC_ASSERT(mLoadInfo.mServiceWorkerDescriptor.isSome());
return mLoadInfo.mServiceWorkerDescriptor.ref();
}
const ServiceWorkerRegistrationDescriptor&
GetServiceWorkerRegistrationDescriptor() const {
MOZ_DIAGNOSTIC_ASSERT(IsServiceWorker());
MOZ_DIAGNOSTIC_ASSERT(
mLoadInfo.mServiceWorkerRegistrationDescriptor.isSome());
return mLoadInfo.mServiceWorkerRegistrationDescriptor.ref();
}
void UpdateServiceWorkerState(ServiceWorkerState aState) {
MOZ_DIAGNOSTIC_ASSERT(IsServiceWorker());
MOZ_DIAGNOSTIC_ASSERT(mLoadInfo.mServiceWorkerDescriptor.isSome());
return mLoadInfo.mServiceWorkerDescriptor.ref().SetState(aState);
}
const Maybe<ServiceWorkerDescriptor>& GetParentController() const {
return mLoadInfo.mParentController;
}
const ChannelInfo& GetChannelInfo() const { return mLoadInfo.mChannelInfo; }
void SetChannelInfo(const ChannelInfo& aChannelInfo) {
AssertIsOnMainThread();
MOZ_ASSERT(!mLoadInfo.mChannelInfo.IsInitialized());
MOZ_ASSERT(aChannelInfo.IsInitialized());
mLoadInfo.mChannelInfo = aChannelInfo;
}
void InitChannelInfo(nsIChannel* aChannel) {
mLoadInfo.mChannelInfo.InitFromChannel(aChannel);
}
void InitChannelInfo(const ChannelInfo& aChannelInfo) {
mLoadInfo.mChannelInfo = aChannelInfo;
}
nsIPrincipal* GetPrincipal() const { return mLoadInfo.mPrincipal; }
nsIPrincipal* GetLoadingPrincipal() const {
return mLoadInfo.mLoadingPrincipal;
}
nsIPrincipal* GetPartitionedPrincipal() const {
return mLoadInfo.mPartitionedPrincipal;
}
nsIPrincipal* GetEffectiveStoragePrincipal() const;
nsILoadGroup* GetLoadGroup() const {
AssertIsOnMainThread();
return mLoadInfo.mLoadGroup;
}
bool UsesSystemPrincipal() const {
return GetPrincipal()->IsSystemPrincipal();
}
bool UsesAddonOrExpandedAddonPrincipal() const {
return GetPrincipal()->GetIsAddonOrExpandedAddonPrincipal();
}
const mozilla::ipc::PrincipalInfo& GetPrincipalInfo() const {
return *mLoadInfo.mPrincipalInfo;
}
const mozilla::ipc::PrincipalInfo& GetPartitionedPrincipalInfo() const {
return *mLoadInfo.mPartitionedPrincipalInfo;
}
const mozilla::ipc::PrincipalInfo& GetEffectiveStoragePrincipalInfo() const;
already_AddRefed<nsIChannel> ForgetWorkerChannel() {
AssertIsOnMainThread();
return mLoadInfo.mChannel.forget();
}
nsPIDOMWindowInner* GetWindow() const {
AssertIsOnMainThread();
return mLoadInfo.mWindow;
}
nsPIDOMWindowInner* GetAncestorWindow() const;
void EvictFromBFCache();
nsIContentSecurityPolicy* GetCsp() const {
AssertIsOnMainThread();
return mLoadInfo.mCSP;
}
void SetCsp(nsIContentSecurityPolicy* aCSP);
nsresult SetCSPFromHeaderValues(const nsACString& aCSPHeaderValue,
const nsACString& aCSPReportOnlyHeaderValue);
void StoreCSPOnClient();
const mozilla::ipc::CSPInfo& GetCSPInfo() const {
return *mLoadInfo.mCSPInfo;
}
void UpdateReferrerInfoFromHeader(
const nsACString& aReferrerPolicyHeaderValue);
nsIReferrerInfo* GetReferrerInfo() const { return mLoadInfo.mReferrerInfo; }
ReferrerPolicy GetReferrerPolicy() const {
return mLoadInfo.mReferrerInfo->ReferrerPolicy();
}
void SetReferrerInfo(nsIReferrerInfo* aReferrerInfo) {
mLoadInfo.mReferrerInfo = aReferrerInfo;
}
bool IsEvalAllowed() const { return mLoadInfo.mEvalAllowed; }
void SetEvalAllowed(bool aAllowed) { mLoadInfo.mEvalAllowed = aAllowed; }
bool GetReportEvalCSPViolations() const {
return mLoadInfo.mReportEvalCSPViolations;
}
void SetReportEvalCSPViolations(bool aReport) {
mLoadInfo.mReportEvalCSPViolations = aReport;
}
bool IsWasmEvalAllowed() const { return mLoadInfo.mWasmEvalAllowed; }
void SetWasmEvalAllowed(bool aAllowed) {
mLoadInfo.mWasmEvalAllowed = aAllowed;
}
bool GetReportWasmEvalCSPViolations() const {
return mLoadInfo.mReportWasmEvalCSPViolations;
}
void SetReportWasmEvalCSPViolations(bool aReport) {
mLoadInfo.mReportWasmEvalCSPViolations = aReport;
}
bool XHRParamsAllowed() const { return mLoadInfo.mXHRParamsAllowed; }
void SetXHRParamsAllowed(bool aAllowed) {
mLoadInfo.mXHRParamsAllowed = aAllowed;
}
mozilla::StorageAccess StorageAccess() const {
AssertIsOnWorkerThread();
if (mLoadInfo.mHasStorageAccessPermissionGranted) {
return mozilla::StorageAccess::eAllow;
}
return mLoadInfo.mStorageAccess;
}
bool UseRegularPrincipal() const {
AssertIsOnWorkerThread();
return mLoadInfo.mUseRegularPrincipal;
}
bool HasStorageAccessPermissionGranted() const {
AssertIsOnWorkerThread();
return mLoadInfo.mHasStorageAccessPermissionGranted;
}
nsICookieJarSettings* CookieJarSettings() const {
// Any thread.
MOZ_ASSERT(mLoadInfo.mCookieJarSettings);
return mLoadInfo.mCookieJarSettings;
}
const OriginAttributes& GetOriginAttributes() const {
return mLoadInfo.mOriginAttributes;
}
// Determine if the SW testing per-window flag is set by devtools
bool ServiceWorkersTestingInWindow() const {
return mLoadInfo.mServiceWorkersTestingInWindow;
}
// Determine if the worker was created under a third-party context.
bool IsThirdPartyContextToTopWindow() const {
return mLoadInfo.mIsThirdPartyContextToTopWindow;
}
bool IsWatchedByDevTools() const { return mLoadInfo.mWatchedByDevTools; }
RemoteWorkerChild* GetRemoteWorkerController();
void SetRemoteWorkerController(RemoteWorkerChild* aController);
void SetRemoteWorkerControllerWeakRef(
ThreadSafeWeakPtr<RemoteWorkerChild> aWeakRef);
ThreadSafeWeakPtr<RemoteWorkerChild> GetRemoteWorkerControllerWeakRef();
RefPtr<GenericPromise> SetServiceWorkerSkipWaitingFlag();
// We can assume that an nsPIDOMWindow will be available for Freeze, Thaw
// as these are only used for globals going in and out of the bfcache.
bool Freeze(const nsPIDOMWindowInner* aWindow);
bool Thaw(const nsPIDOMWindowInner* aWindow);
void PropagateStorageAccessPermissionGranted();
void EnableDebugger();
void DisableDebugger();
already_AddRefed<WorkerRunnable> MaybeWrapAsWorkerRunnable(
already_AddRefed<nsIRunnable> aRunnable);
bool ProxyReleaseMainThreadObjects();
void SetLowMemoryState(bool aState);
void GarbageCollect(bool aShrinking);
void CycleCollect();
nsresult SetPrincipalsAndCSPOnMainThread(nsIPrincipal* aPrincipal,
nsIPrincipal* aPartitionedPrincipal,
nsILoadGroup* aLoadGroup,
nsIContentSecurityPolicy* aCsp);
nsresult SetPrincipalsAndCSPFromChannel(nsIChannel* aChannel);
bool FinalChannelPrincipalIsValid(nsIChannel* aChannel);
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
bool PrincipalURIMatchesScriptURL();
#endif
void UpdateOverridenLoadGroup(nsILoadGroup* aBaseLoadGroup);
void WorkerScriptLoaded();
Document* GetDocument() const;
void MemoryPressure();
void UpdateContextOptions(const JS::ContextOptions& aContextOptions);
void UpdateLanguages(const nsTArray<nsString>& aLanguages);
void UpdateJSWorkerMemoryParameter(JSGCParamKey key, Maybe<uint32_t> value);
#ifdef JS_GC_ZEAL
void UpdateGCZeal(uint8_t aGCZeal, uint32_t aFrequency);
#endif
void OfflineStatusChangeEvent(bool aIsOffline);
nsresult Dispatch(already_AddRefed<WorkerRunnable> aRunnable,
nsIEventTarget* aSyncLoopTarget = nullptr);
nsresult DispatchControlRunnable(
already_AddRefed<WorkerControlRunnable> aWorkerControlRunnable);
nsresult DispatchDebuggerRunnable(
already_AddRefed<WorkerRunnable> aDebuggerRunnable);
#ifdef DEBUG
void AssertIsOnParentThread() const;
void AssertInnerWindowIsCorrect() const;
#else
void AssertIsOnParentThread() const {}
void AssertInnerWindowIsCorrect() const {}
#endif
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
bool PrincipalIsValid() const;
#endif
void StartCancelingTimer();
const nsAString& Id();
const nsID& AgentClusterId() const { return mAgentClusterId; }
bool IsSharedMemoryAllowed() const;
// https://whatpr.org/html/4734/structured-data.html#cross-origin-isolated
bool CrossOriginIsolated() const;
void SetUseCounter(UseCounterWorker aUseCounter) {
MOZ_ASSERT(!mReportedUseCounters);
MOZ_ASSERT(aUseCounter > UseCounterWorker::Unknown);
AssertIsOnWorkerThread();
mUseCounters[static_cast<size_t>(aUseCounter)] = true;
}
/**
* COEP Methods
*
* If browser.tabs.remote.useCrossOriginEmbedderPolicy=false, these methods
* will, depending on the return type, return a value that will avoid
* assertion failures or a value that won't block loads.
*/
nsILoadInfo::CrossOriginEmbedderPolicy GetEmbedderPolicy() const;
// Fails if a policy has already been set or if `aPolicy` violates the owner's
// policy, if an owner exists.
mozilla::Result<Ok, nsresult> SetEmbedderPolicy(
nsILoadInfo::CrossOriginEmbedderPolicy aPolicy);
// `aRequest` is the request loading the worker and must be QI-able to
// `nsIChannel*`. It's used to verify that the worker can indeed inherit its
// owner's COEP (when an owner exists).
//
// TODO: remove `aRequest`; currently, it's required because instances may not
// always know its final, resolved script URL or have access internally to
// `aRequest`.
void InheritOwnerEmbedderPolicyOrNull(nsIRequest* aRequest);
// Requires a policy to already have been set.
bool MatchEmbedderPolicy(
nsILoadInfo::CrossOriginEmbedderPolicy aPolicy) const;
nsILoadInfo::CrossOriginEmbedderPolicy GetOwnerEmbedderPolicy() const;
void SetCCCollectedAnything(bool collectedAnything);
uint32_t GetCurrentTimerNestingLevel() const {
auto data = mWorkerThreadAccessible.Access();
return data->mCurrentTimerNestingLevel;
}
void IncreaseTopLevelWorkerFinishedRunnableCount() {
++mTopLevelWorkerFinishedRunnableCount;
}
void DecreaseTopLevelWorkerFinishedRunnableCount() {
--mTopLevelWorkerFinishedRunnableCount;
}
void IncreaseWorkerFinishedRunnableCount() { ++mWorkerFinishedRunnableCount; }
void DecreaseWorkerFinishedRunnableCount() { --mWorkerFinishedRunnableCount; }
void RunShutdownTasks();
private:
WorkerPrivate(
WorkerPrivate* aParent, const nsAString& aScriptURL, bool aIsChromeWorker,
WorkerKind aWorkerKind, const nsAString& aWorkerName,
const nsACString& aServiceWorkerScope, WorkerLoadInfo& aLoadInfo,
nsString&& aId, const nsID& aAgentClusterId,
const nsILoadInfo::CrossOriginOpenerPolicy aAgentClusterOpenerPolicy);
~WorkerPrivate();
struct AgentClusterIdAndCoop {
nsID mId;
nsILoadInfo::CrossOriginOpenerPolicy mCoop;
};
static AgentClusterIdAndCoop ComputeAgentClusterIdAndCoop(
WorkerPrivate* aParent, WorkerKind aWorkerKind,
WorkerLoadInfo* aLoadInfo);
bool MayContinueRunning() {
AssertIsOnWorkerThread();
WorkerStatus status;
{
MutexAutoLock lock(mMutex);
status = mStatus;
}
if (status < Canceling) {
return true;
}
return false;
}
void CancelAllTimeouts();
enum class ProcessAllControlRunnablesResult {
// We did not process anything.
Nothing,
// We did process something, states may have changed, but we can keep
// executing script.
MayContinue,
// We did process something, and should not continue executing script.
Abort
};
ProcessAllControlRunnablesResult ProcessAllControlRunnables() {
MutexAutoLock lock(mMutex);
return ProcessAllControlRunnablesLocked();
}
ProcessAllControlRunnablesResult ProcessAllControlRunnablesLocked()
MOZ_REQUIRES(mMutex);
void EnableMemoryReporter();
void DisableMemoryReporter();
void WaitForWorkerEvents() MOZ_REQUIRES(mMutex);
// If the worker shutdown status is equal or greater then aFailStatus, this
// operation will fail and nullptr will be returned. See WorkerStatus.h for
// more information about the correct value to use.
already_AddRefed<nsISerialEventTarget> CreateNewSyncLoop(
WorkerStatus aFailStatus);
nsresult RunCurrentSyncLoop();
nsresult DestroySyncLoop(uint32_t aLoopIndex);
void InitializeGCTimers();
enum GCTimerMode { PeriodicTimer = 0, IdleTimer, NoTimer };
void SetGCTimerMode(GCTimerMode aMode);
void ShutdownGCTimers();
friend class WorkerRef;
bool AddWorkerRef(WorkerRef* aWorkerRefer, WorkerStatus aFailStatus);
void RemoveWorkerRef(WorkerRef* aWorkerRef);
void NotifyWorkerRefs(WorkerStatus aStatus);
bool HasActiveWorkerRefs() {
auto data = mWorkerThreadAccessible.Access();
return !(data->mChildWorkers.IsEmpty() && data->mTimeouts.IsEmpty() &&
data->mWorkerRefs.IsEmpty());
}
friend class WorkerEventTarget;
bool RegisterShutdownTask(nsITargetShutdownTask* aTask);
bool UnregisterShutdownTask(nsITargetShutdownTask* aTask);
// Internal logic to dispatch a runnable. This is separate from Dispatch()
// to allow runnables to be atomically dispatched in bulk.
nsresult DispatchLockHeld(already_AddRefed<WorkerRunnable> aRunnable,
nsIEventTarget* aSyncLoopTarget,
const MutexAutoLock& aProofOfLock)
MOZ_REQUIRES(mMutex);
// This method dispatches a simple runnable that starts the shutdown procedure
// after a self.close(). This method is called after a ClearMainEventQueue()
// to be sure that the canceling runnable is the only one in the queue. We
// need this async operation to be sure that all the current JS code is
// executed.
void DispatchCancelingRunnable();
bool GetUseCounter(UseCounterWorker aUseCounter) {
MOZ_ASSERT(aUseCounter > UseCounterWorker::Unknown);
AssertIsOnWorkerThread();
return mUseCounters[static_cast<size_t>(aUseCounter)];
}
void ReportUseCounters();
UniquePtr<ClientSource> CreateClientSource();
// This method is called when corresponding script loader processes the COEP
// header for the worker.
// This method should be called only once in the main thread.
// After this method is called the COEP value owner(window/parent worker) is
// cached in mOwnerEmbedderPolicy such that it can be accessed in other
// threads, i.e. WorkerThread.
void EnsureOwnerEmbedderPolicy();
class EventTarget;
friend class EventTarget;
friend class AutoSyncLoopHolder;
struct TimeoutInfo;
class MemoryReporter;
friend class MemoryReporter;
friend class mozilla::dom::WorkerThread;
SharedMutex mMutex;
mozilla::CondVar mCondVar MOZ_GUARDED_BY(mMutex);
// We cannot make this CheckedUnsafePtr<WorkerPrivate> as this would violate
// our static assert
MOZ_NON_OWNING_REF WorkerPrivate* const mParent;
const nsString mScriptURL;
// This is the worker name for shared workers and dedicated workers.
const nsString mWorkerName;
const WorkerKind mWorkerKind;
// The worker is owned by its thread, which is represented here. This is set
// in Constructor() and emptied by WorkerFinishedRunnable, and conditionally
// traversed by the cycle collector if the busy count is zero.
//
// There are 4 ways a worker can be terminated:
// 1. GC/CC - When the worker is in idle state (busycount == 0), it allows to
// traverse the 'hidden' mParentEventTargetRef pointer. This is the exposed
// Worker webidl object. Doing this, CC will be able to detect a cycle and
// Unlink is called. In Unlink, Worker calls Cancel().
// 2. Worker::Cancel() is called - the shutdown procedure starts immediately.
// 3. WorkerScope::Close() is called - Similar to point 2.
// 4. xpcom-shutdown notification - We call Kill().
RefPtr<Worker> mParentEventTargetRef;
RefPtr<WorkerPrivate> mSelfRef;
// The lifetime of these objects within LoadInfo is managed explicitly;
// they do not need to be cycle collected.
WorkerLoadInfo mLoadInfo;
LocationInfo mLocationInfo;
// Protected by mMutex.
workerinternals::JSSettings mJSSettings MOZ_GUARDED_BY(mMutex);
WorkerDebugger* mDebugger;
workerinternals::Queue<WorkerControlRunnable*, 4> mControlQueue;
workerinternals::Queue<WorkerRunnable*, 4> mDebuggerQueue;
// Touched on multiple threads, protected with mMutex. Only modified on the
// worker thread
JSContext* mJSContext MOZ_GUARDED_BY(mMutex);
// mThread is only modified on the Worker thread, before calling DoRunLoop
RefPtr<WorkerThread> mThread MOZ_GUARDED_BY(mMutex);
// mPRThread is only modified on another thread in ScheduleWorker(), and is
// constant for the duration of DoRunLoop. Static mutex analysis doesn't help
// here
PRThread* mPRThread;
// Accessed from main thread
RefPtr<ThrottledEventQueue> mMainThreadEventTargetForMessaging;
RefPtr<ThrottledEventQueue> mMainThreadEventTarget;
// Accessed from worker thread and destructing thread
RefPtr<WorkerEventTarget> mWorkerControlEventTarget;
RefPtr<WorkerEventTarget> mWorkerHybridEventTarget;
// A pauseable queue for WorkerDebuggeeRunnables directed at the main thread.
// See WorkerDebuggeeRunnable for details.
RefPtr<ThrottledEventQueue> mMainThreadDebuggeeEventTarget;
struct SyncLoopInfo {
explicit SyncLoopInfo(EventTarget* aEventTarget);
RefPtr<EventTarget> mEventTarget;
nsresult mResult;
bool mCompleted;
#ifdef DEBUG
bool mHasRun;
#endif
};
// This is only modified on the worker thread, but in DEBUG builds
// AssertValidSyncLoop function iterates it on other threads. Therefore
// modifications are done with mMutex held *only* in DEBUG builds.
nsTArray<UniquePtr<SyncLoopInfo>> mSyncLoopStack;
nsCOMPtr<nsITimer> mCancelingTimer;
// fired on the main thread if the worker script fails to load
nsCOMPtr<nsIRunnable> mLoadFailedRunnable;
RefPtr<PerformanceStorage> mPerformanceStorage;
RefPtr<WorkerCSPEventListener> mCSPEventListener;
// Protected by mMutex.
nsTArray<RefPtr<WorkerRunnable>> mPreStartRunnables MOZ_GUARDED_BY(mMutex);
// Only touched on the parent thread. This is set only if IsSharedWorker().
RefPtr<RemoteWorkerChild> mRemoteWorkerController;
// This is set only if IsServiceWorker().
ThreadSafeWeakPtr<RemoteWorkerChild> mRemoteWorkerControllerWeakRef;
JS::UniqueChars mDefaultLocale; // nulled during worker JSContext init
TimeStamp mKillTime;
WorkerStatus mParentStatus MOZ_GUARDED_BY(mMutex);
WorkerStatus mStatus MOZ_GUARDED_BY(mMutex);
// This is touched on parent thread only, but it can be read on a different
// thread before crashing because hanging.
Atomic<uint64_t> mBusyCount;
TimeStamp mCreationTimeStamp;
DOMHighResTimeStamp mCreationTimeHighRes;
// Flags for use counters used directly by this worker.
static_assert(sizeof(UseCounterWorker) <= sizeof(size_t),
"UseCounterWorker is too big");
static_assert(UseCounterWorker::Count >= static_cast<UseCounterWorker>(0),
"Should be non-negative value and safe to cast to unsigned");
std::bitset<static_cast<size_t>(UseCounterWorker::Count)> mUseCounters;
bool mReportedUseCounters;
// This is created while creating the WorkerPrivate, so it's safe to be
// touched on any thread.
const nsID mAgentClusterId;
// Things touched on worker thread only.
struct WorkerThreadAccessible {
explicit WorkerThreadAccessible(WorkerPrivate* aParent);
RefPtr<WorkerGlobalScope> mScope;
RefPtr<WorkerDebuggerGlobalScope> mDebuggerScope;
// We cannot make this CheckedUnsafePtr<WorkerPrivate> as this would violate
// our static assert
nsTArray<WorkerPrivate*> mChildWorkers;
nsTObserverArray<WorkerRef*> mWorkerRefs;
nsTArray<UniquePtr<TimeoutInfo>> mTimeouts;
nsCOMPtr<nsITimer> mTimer;
nsCOMPtr<nsITimerCallback> mTimerRunnable;
nsCOMPtr<nsITimer> mGCTimer;
RefPtr<MemoryReporter> mMemoryReporter;
// While running a nested event loop, whether a sync loop or a debugger
// event loop we want to keep track of which global is running it, if any,
// so runnables that run off that event loop can get at that information. In
// practice this only matters for various worker debugger runnables running
// against sandboxes, because all other runnables know which globals they
// belong to already. We could also address this by threading the relevant
// global through the chains of runnables involved, but we'd need to thread
// it through some runnables that run on the main thread, and that would
// require some care to make sure things get released on the correct thread,
// which we'd rather avoid. This member is only accessed on the worker
// thread.
nsCOMPtr<nsIGlobalObject> mCurrentEventLoopGlobal;
// Timer that triggers an interrupt on expiration of the current time slice
nsCOMPtr<nsITimer> mTSTimer;
// Execution manager used to regulate execution for this worker.
RefPtr<JSExecutionManager> mExecutionManager;
// Used to relinguish clearance for CTypes Callbacks.
nsTArray<AutoYieldJSThreadExecution> mYieldJSThreadExecution;
uint32_t mNumWorkerRefsPreventingShutdownStart;
uint32_t mDebuggerEventLoopLevel;
uint32_t mErrorHandlerRecursionCount;
int32_t mNextTimeoutId;
// Tracks the current setTimeout/setInterval nesting level.
// When there isn't a TimeoutHandler on the stack, this will be 0.
// Whenever setTimeout/setInterval are called, a new TimeoutInfo will be
// created with a nesting level one more than the current nesting level,
// saturating at the kClampTimeoutNestingLevel.
//
// When RunExpiredTimeouts is run, it sets this value to the
// TimeoutInfo::mNestingLevel for the duration of
// the WorkerScriptTimeoutHandler::Call which will explicitly trigger a
// microtask checkpoint so that any immediately-resolved promises will
// still see the nesting level.
uint32_t mCurrentTimerNestingLevel;
bool mFrozen;
bool mTimerRunning;
bool mRunningExpiredTimeouts;
bool mPeriodicGCTimerRunning;
bool mIdleGCTimerRunning;
bool mOnLine;
bool mJSThreadExecutionGranted;
bool mCCCollectedAnything;
FlippedOnce<false> mDeletionScheduled;
};
ThreadBound<WorkerThreadAccessible> mWorkerThreadAccessible;
class MOZ_RAII AutoPushEventLoopGlobal {
public:
AutoPushEventLoopGlobal(WorkerPrivate* aWorkerPrivate, JSContext* aCx);
~AutoPushEventLoopGlobal();
private:
// We cannot make this CheckedUnsafePtr<WorkerPrivate> as this would violate
// our static assert
MOZ_NON_OWNING_REF WorkerPrivate* mWorkerPrivate;
nsCOMPtr<nsIGlobalObject> mOldEventLoopGlobal;
};
friend class AutoPushEventLoopGlobal;
uint32_t mPostSyncLoopOperations;
// List of operations to do at the end of the last sync event loop.
enum {
ePendingEventQueueClearing = 0x01,
eDispatchCancelingRunnable = 0x02,
};
bool mParentWindowPaused;
bool mCancelAllPendingRunnables;
bool mWorkerScriptExecutedSuccessfully;
bool mFetchHandlerWasAdded;
bool mMainThreadObjectsForgotten;
bool mIsChromeWorker;
bool mParentFrozen;
// mIsSecureContext is set once in our constructor; after that it can be read
// from various threads.
//
// It's a bit unfortunate that we have to have an out-of-band boolean for
// this, but we need access to this state from the parent thread, and we can't
// use our global object's secure state there.
const bool mIsSecureContext;
bool mDebuggerRegistered MOZ_GUARDED_BY(mMutex);
// During registration, this worker may be marked as not being ready to
// execute debuggee runnables or content.
//
// Protected by mMutex.
bool mDebuggerReady;
nsTArray<RefPtr<WorkerRunnable>> mDelayedDebuggeeRunnables;
// Whether this worker should have access to the WebExtension API bindings
// (currently only the Extension Background ServiceWorker declared in the
// extension manifest is allowed to access any WebExtension API bindings).
// This default to false, and it is eventually set to true by
// RemoteWorkerChild::ExecWorkerOnMainThread if the needed conditions
// are met.
bool mExtensionAPIAllowed;
// mIsInAutomation is true when we're running in test automation.
// We expose some extra testing functions in that case.
bool mIsInAutomation;
const RefPtr<PerformanceCounter> mPerformanceCounter =
MakeRefPtr<PerformanceCounter>(nsPrintfCString(
"Worker:%s", NS_ConvertUTF16toUTF8(mWorkerName).get()));
nsString mId;
// This is used to check if it's allowed to share the memory across the agent
// cluster.
const nsILoadInfo::CrossOriginOpenerPolicy mAgentClusterOpenerPolicy;
// Member variable of this class rather than the worker global scope because
// it's received on the main thread, but the global scope is thread-bound
// to the worker thread, so storing the value in the global scope would
// involve sacrificing the thread-bound-ness or using a WorkerRunnable, and
// there isn't a strong reason to store it on the global scope other than
// better consistency with the COEP spec.
Maybe<nsILoadInfo::CrossOriginEmbedderPolicy> mEmbedderPolicy;
Maybe<nsILoadInfo::CrossOriginEmbedderPolicy> mOwnerEmbedderPolicy;
/* Privileged add-on flag extracted from the AddonPolicy on the nsIPrincipal
* on the main thread when constructing a top-level worker. The flag is
* propagated to nested workers. The flag is only allowed to take effect in
* extension processes and is forbidden in content scripts in content
* processes. The flag may be read on either the parent/owner thread as well
* as on the worker thread itself. When bug 1443925 is fixed allowing
* nsIPrincipal to be used OMT, it may be possible to remove this flag. */
bool mIsPrivilegedAddonGlobal;
Atomic<uint32_t> mTopLevelWorkerFinishedRunnableCount;
Atomic<uint32_t> mWorkerFinishedRunnableCount;
nsTArray<nsCOMPtr<nsITargetShutdownTask>> mShutdownTasks
MOZ_GUARDED_BY(mMutex);
bool mRunShutdownTasksStarted MOZ_GUARDED_BY(mMutex) = false;
bool mRunShutdownTasksFinished MOZ_GUARDED_BY(mMutex) = false;
};
class AutoSyncLoopHolder {
CheckedUnsafePtr<WorkerPrivate> mWorkerPrivate;
nsCOMPtr<nsISerialEventTarget> mTarget;
uint32_t mIndex;
public:
// See CreateNewSyncLoop() for more information about the correct value to use
// for aFailStatus.
AutoSyncLoopHolder(WorkerPrivate* aWorkerPrivate, WorkerStatus aFailStatus)
: mWorkerPrivate(aWorkerPrivate),
mTarget(aWorkerPrivate->CreateNewSyncLoop(aFailStatus)),
mIndex(aWorkerPrivate->mSyncLoopStack.Length() - 1) {
aWorkerPrivate->AssertIsOnWorkerThread();
}
~AutoSyncLoopHolder() {
if (mWorkerPrivate && mTarget) {
mWorkerPrivate->AssertIsOnWorkerThread();
mWorkerPrivate->StopSyncLoop(mTarget, NS_ERROR_FAILURE);
mWorkerPrivate->DestroySyncLoop(mIndex);
}
}
nsresult Run() {
CheckedUnsafePtr<WorkerPrivate> workerPrivate = mWorkerPrivate;
mWorkerPrivate = nullptr;
workerPrivate->AssertIsOnWorkerThread();
return workerPrivate->RunCurrentSyncLoop();
}
nsISerialEventTarget* GetSerialEventTarget() const {
// This can be null if CreateNewSyncLoop() fails.
return mTarget;
}
};
} // namespace dom
} // namespace mozilla
#endif /* mozilla_dom_workers_workerprivate_h__ */
|