-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathXPCJSContext.cpp
1259 lines (1067 loc) · 43.6 KB
/
XPCJSContext.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* vim: set ts=8 sts=4 et sw=4 tw=99: */
/* 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/. */
/* Per JSContext object */
#include "mozilla/MemoryReporting.h"
#include "mozilla/UniquePtr.h"
#include "xpcprivate.h"
#include "xpcpublic.h"
#include "XPCWrapper.h"
#include "XPCJSMemoryReporter.h"
#include "WrapperFactory.h"
#include "mozJSComponentLoader.h"
#include "nsAutoPtr.h"
#include "nsNetUtil.h"
#include "nsThreadUtils.h"
#include "nsIMemoryInfoDumper.h"
#include "nsIMemoryReporter.h"
#include "nsIObserverService.h"
#include "nsIDebug2.h"
#include "nsIDocShell.h"
#include "nsIRunnable.h"
#include "nsPIDOMWindow.h"
#include "nsPrintfCString.h"
#include "mozilla/Preferences.h"
#include "mozilla/Telemetry.h"
#include "mozilla/Services.h"
#include "mozilla/dom/ScriptSettings.h"
#include "nsContentUtils.h"
#include "nsCCUncollectableMarker.h"
#include "nsCycleCollectionNoteRootCallback.h"
#include "nsCycleCollector.h"
#include "jsapi.h"
#include "js/MemoryMetrics.h"
#include "mozilla/dom/GeneratedAtomList.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/ScriptLoader.h"
#include "mozilla/dom/WindowBinding.h"
#include "mozilla/extensions/WebExtensionPolicy.h"
#include "mozilla/jsipc/CrossProcessObjectWrappers.h"
#include "mozilla/Atomics.h"
#include "mozilla/Attributes.h"
#include "mozilla/ProcessHangMonitor.h"
#include "mozilla/Sprintf.h"
#include "mozilla/ThreadLocal.h"
#include "mozilla/UniquePtrExtensions.h"
#include "mozilla/Unused.h"
#include "AccessCheck.h"
#include "nsGlobalWindow.h"
#include "nsAboutProtocolUtils.h"
#include "GeckoProfiler.h"
#include "nsIInputStream.h"
#include "nsIXULRuntime.h"
#include "nsJSPrincipals.h"
#include "ExpandedPrincipal.h"
#include "SystemPrincipal.h"
#if defined(XP_LINUX) && !defined(ANDROID)
// For getrlimit and min/max.
#include <algorithm>
#include <sys/resource.h>
#endif
#ifdef XP_WIN
#include <windows.h>
#endif
static MOZ_THREAD_LOCAL(XPCJSContext*) gTlsContext;
using namespace mozilla;
using namespace xpc;
using namespace JS;
using mozilla::dom::PerThreadAtomCache;
using mozilla::dom::AutoEntryScript;
static void WatchdogMain(void* arg);
class Watchdog;
class WatchdogManager;
class MOZ_RAII AutoLockWatchdog final
{
MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
Watchdog* const mWatchdog;
public:
explicit AutoLockWatchdog(Watchdog* aWatchdog MOZ_GUARD_OBJECT_NOTIFIER_PARAM);
~AutoLockWatchdog();
};
class Watchdog
{
public:
explicit Watchdog(WatchdogManager* aManager)
: mManager(aManager)
, mLock(nullptr)
, mWakeup(nullptr)
, mThread(nullptr)
, mHibernating(false)
, mInitialized(false)
, mShuttingDown(false)
, mMinScriptRunTimeSeconds(1)
{}
~Watchdog() { MOZ_ASSERT(!Initialized()); }
WatchdogManager* Manager() { return mManager; }
bool Initialized() { return mInitialized; }
bool ShuttingDown() { return mShuttingDown; }
PRLock* GetLock() { return mLock; }
bool Hibernating() { return mHibernating; }
void WakeUp()
{
MOZ_ASSERT(Initialized());
MOZ_ASSERT(Hibernating());
mHibernating = false;
PR_NotifyCondVar(mWakeup);
}
//
// Invoked by the main thread only.
//
void Init()
{
MOZ_ASSERT(NS_IsMainThread());
mLock = PR_NewLock();
if (!mLock)
MOZ_CRASH("PR_NewLock failed.");
mWakeup = PR_NewCondVar(mLock);
if (!mWakeup)
MOZ_CRASH("PR_NewCondVar failed.");
{
AutoLockWatchdog lock(this);
// Gecko uses thread private for accounting and has to clean up at thread exit.
// Therefore, even though we don't have a return value from the watchdog, we need to
// join it on shutdown.
mThread = PR_CreateThread(PR_USER_THREAD, WatchdogMain, this,
PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD,
PR_JOINABLE_THREAD, 0);
if (!mThread)
MOZ_CRASH("PR_CreateThread failed!");
// WatchdogMain acquires the lock and then asserts mInitialized. So
// make sure to set mInitialized before releasing the lock here so
// that it's atomic with the creation of the thread.
mInitialized = true;
}
}
void Shutdown()
{
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(Initialized());
{ // Scoped lock.
AutoLockWatchdog lock(this);
// Signal to the watchdog thread that it's time to shut down.
mShuttingDown = true;
// Wake up the watchdog, and wait for it to call us back.
PR_NotifyCondVar(mWakeup);
}
PR_JoinThread(mThread);
// The thread sets mShuttingDown to false as it exits.
MOZ_ASSERT(!mShuttingDown);
// Destroy state.
mThread = nullptr;
PR_DestroyCondVar(mWakeup);
mWakeup = nullptr;
PR_DestroyLock(mLock);
mLock = nullptr;
// All done.
mInitialized = false;
}
void SetMinScriptRunTimeSeconds(int32_t seconds)
{
// This variable is atomic, and is set from the main thread without
// locking.
MOZ_ASSERT(seconds > 0);
mMinScriptRunTimeSeconds = seconds;
}
//
// Invoked by the watchdog thread only.
//
void Hibernate()
{
MOZ_ASSERT(!NS_IsMainThread());
mHibernating = true;
Sleep(PR_INTERVAL_NO_TIMEOUT);
}
void Sleep(PRIntervalTime timeout)
{
MOZ_ASSERT(!NS_IsMainThread());
MOZ_ALWAYS_TRUE(PR_WaitCondVar(mWakeup, timeout) == PR_SUCCESS);
}
void Finished()
{
MOZ_ASSERT(!NS_IsMainThread());
mShuttingDown = false;
}
int32_t MinScriptRunTimeSeconds()
{
return mMinScriptRunTimeSeconds;
}
private:
WatchdogManager* mManager;
PRLock* mLock;
PRCondVar* mWakeup;
PRThread* mThread;
bool mHibernating;
bool mInitialized;
bool mShuttingDown;
mozilla::Atomic<int32_t> mMinScriptRunTimeSeconds;
};
#define PREF_MAX_SCRIPT_RUN_TIME_CONTENT "dom.max_script_run_time"
#define PREF_MAX_SCRIPT_RUN_TIME_CHROME "dom.max_chrome_script_run_time"
#define PREF_MAX_SCRIPT_RUN_TIME_EXT_CONTENT "dom.max_ext_content_script_run_time"
class WatchdogManager : public nsIObserver
{
public:
NS_DECL_ISUPPORTS
explicit WatchdogManager()
{
// All the timestamps start at zero.
PodArrayZero(mTimestamps);
// Register ourselves as an observer to get updates on the pref.
mozilla::Preferences::AddStrongObserver(this, "dom.use_watchdog");
mozilla::Preferences::AddStrongObserver(this, PREF_MAX_SCRIPT_RUN_TIME_CONTENT);
mozilla::Preferences::AddStrongObserver(this, PREF_MAX_SCRIPT_RUN_TIME_CHROME);
mozilla::Preferences::AddStrongObserver(this, PREF_MAX_SCRIPT_RUN_TIME_EXT_CONTENT);
}
protected:
virtual ~WatchdogManager()
{
// Shutting down the watchdog requires context-switching to the watchdog
// thread, which isn't great to do in a destructor. So we require
// consumers to shut it down manually before releasing it.
MOZ_ASSERT(!mWatchdog);
}
public:
void Shutdown()
{
mozilla::Preferences::RemoveObserver(this, "dom.use_watchdog");
mozilla::Preferences::RemoveObserver(this, PREF_MAX_SCRIPT_RUN_TIME_CONTENT);
mozilla::Preferences::RemoveObserver(this, PREF_MAX_SCRIPT_RUN_TIME_CHROME);
mozilla::Preferences::RemoveObserver(this, PREF_MAX_SCRIPT_RUN_TIME_EXT_CONTENT);
}
NS_IMETHOD Observe(nsISupports* aSubject, const char* aTopic,
const char16_t* aData) override
{
RefreshWatchdog();
return NS_OK;
}
void
RegisterContext(XPCJSContext* aContext)
{
MOZ_ASSERT(NS_IsMainThread());
AutoLockWatchdog lock(mWatchdog);
if (aContext->mActive == XPCJSContext::CONTEXT_ACTIVE) {
mActiveContexts.insertBack(aContext);
} else {
mInactiveContexts.insertBack(aContext);
}
// Enable the watchdog, if appropriate.
RefreshWatchdog();
}
void
UnregisterContext(XPCJSContext* aContext)
{
MOZ_ASSERT(NS_IsMainThread());
AutoLockWatchdog lock(mWatchdog);
// aContext must be in one of our two lists, simply remove it.
aContext->LinkedListElement<XPCJSContext>::remove();
#ifdef DEBUG
// If this was the last context, we should have already shut down
// the watchdog.
if (mActiveContexts.isEmpty() && mInactiveContexts.isEmpty()) {
MOZ_ASSERT(!mWatchdog);
}
#endif
}
// Context statistics. These live on the watchdog manager, are written
// from the main thread, and are read from the watchdog thread (holding
// the lock in each case).
void RecordContextActivity(XPCJSContext* aContext, bool active)
{
// The watchdog reads this state, so acquire the lock before writing it.
MOZ_ASSERT(NS_IsMainThread());
AutoLockWatchdog lock(mWatchdog);
// Write state.
aContext->mLastStateChange = PR_Now();
aContext->mActive = active ? XPCJSContext::CONTEXT_ACTIVE :
XPCJSContext::CONTEXT_INACTIVE;
UpdateContextLists(aContext);
// The watchdog may be hibernating, waiting for the context to go
// active. Wake it up if necessary.
if (active && mWatchdog && mWatchdog->Hibernating())
mWatchdog->WakeUp();
}
bool IsAnyContextActive()
{
return !mActiveContexts.isEmpty();
}
PRTime TimeSinceLastActiveContext()
{
// Must be called on the watchdog thread with the lock held.
MOZ_ASSERT(!NS_IsMainThread());
PR_ASSERT_CURRENT_THREAD_OWNS_LOCK(mWatchdog->GetLock());
MOZ_ASSERT(mActiveContexts.isEmpty());
MOZ_ASSERT(!mInactiveContexts.isEmpty());
// We store inactive contexts with the most recently added inactive
// context at the end of the list.
return PR_Now() - mInactiveContexts.getLast()->mLastStateChange;
}
void RecordTimestamp(WatchdogTimestampCategory aCategory)
{
// Must be called on the watchdog thread with the lock held.
MOZ_ASSERT(!NS_IsMainThread());
PR_ASSERT_CURRENT_THREAD_OWNS_LOCK(mWatchdog->GetLock());
MOZ_ASSERT(aCategory != TimestampContextStateChange,
"Use RecordContextActivity to update this");
mTimestamps[aCategory] = PR_Now();
}
PRTime GetContextTimestamp(XPCJSContext* aContext,
const AutoLockWatchdog& aProofOfLock)
{
return aContext->mLastStateChange;
}
PRTime GetTimestamp(WatchdogTimestampCategory aCategory,
const AutoLockWatchdog& aProofOfLock)
{
MOZ_ASSERT(aCategory != TimestampContextStateChange,
"Use GetContextTimestamp to retrieve this");
return mTimestamps[aCategory];
}
Watchdog* GetWatchdog() { return mWatchdog; }
void RefreshWatchdog()
{
bool wantWatchdog = Preferences::GetBool("dom.use_watchdog", true);
if (wantWatchdog != !!mWatchdog) {
if (wantWatchdog)
StartWatchdog();
else
StopWatchdog();
}
if (mWatchdog) {
int32_t contentTime = Preferences::GetInt(PREF_MAX_SCRIPT_RUN_TIME_CONTENT, 10);
if (contentTime <= 0)
contentTime = INT32_MAX;
int32_t chromeTime = Preferences::GetInt(PREF_MAX_SCRIPT_RUN_TIME_CHROME, 20);
if (chromeTime <= 0)
chromeTime = INT32_MAX;
int32_t extTime = Preferences::GetInt(PREF_MAX_SCRIPT_RUN_TIME_EXT_CONTENT, 5);
if (extTime <= 0)
extTime = INT32_MAX;
mWatchdog->SetMinScriptRunTimeSeconds(std::min({contentTime, chromeTime, extTime}));
}
}
void StartWatchdog()
{
MOZ_ASSERT(!mWatchdog);
mWatchdog = new Watchdog(this);
mWatchdog->Init();
}
void StopWatchdog()
{
MOZ_ASSERT(mWatchdog);
mWatchdog->Shutdown();
mWatchdog = nullptr;
}
template<class Callback>
void ForAllActiveContexts(Callback&& aCallback)
{
// This function must be called on the watchdog thread with the lock held.
MOZ_ASSERT(!NS_IsMainThread());
PR_ASSERT_CURRENT_THREAD_OWNS_LOCK(mWatchdog->GetLock());
for (auto* context = mActiveContexts.getFirst(); context;
context = context->LinkedListElement<XPCJSContext>::getNext()) {
if (!aCallback(context)) {
return;
}
}
}
private:
void UpdateContextLists(XPCJSContext* aContext)
{
// Given aContext whose activity state or timestamp has just changed,
// put it back in the proper position in the proper list.
aContext->LinkedListElement<XPCJSContext>::remove();
auto& list = aContext->mActive == XPCJSContext::CONTEXT_ACTIVE ?
mActiveContexts : mInactiveContexts;
// Either the new list is empty or aContext must be more recent than
// the existing last element.
MOZ_ASSERT_IF(!list.isEmpty(),
list.getLast()->mLastStateChange < aContext->mLastStateChange);
list.insertBack(aContext);
}
LinkedList<XPCJSContext> mActiveContexts;
LinkedList<XPCJSContext> mInactiveContexts;
nsAutoPtr<Watchdog> mWatchdog;
// We store ContextStateChange on the contexts themselves.
PRTime mTimestamps[kWatchdogTimestampCategoryCount - 1];
};
NS_IMPL_ISUPPORTS(WatchdogManager, nsIObserver)
AutoLockWatchdog::AutoLockWatchdog(Watchdog* aWatchdog MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
: mWatchdog(aWatchdog)
{
MOZ_GUARD_OBJECT_NOTIFIER_INIT;
if (mWatchdog) {
PR_Lock(mWatchdog->GetLock());
}
}
AutoLockWatchdog::~AutoLockWatchdog()
{
if (mWatchdog) {
PR_Unlock(mWatchdog->GetLock());
}
}
static void
WatchdogMain(void* arg)
{
AUTO_PROFILER_REGISTER_THREAD("JS Watchdog");
NS_SetCurrentThreadName("JS Watchdog");
Watchdog* self = static_cast<Watchdog*>(arg);
WatchdogManager* manager = self->Manager();
// Lock lasts until we return
AutoLockWatchdog lock(self);
MOZ_ASSERT(self->Initialized());
while (!self->ShuttingDown()) {
// Sleep only 1 second if recently (or currently) active; otherwise, hibernate
if (manager->IsAnyContextActive() ||
manager->TimeSinceLastActiveContext() <= PRTime(2*PR_USEC_PER_SEC))
{
self->Sleep(PR_TicksPerSecond());
} else {
manager->RecordTimestamp(TimestampWatchdogHibernateStart);
self->Hibernate();
manager->RecordTimestamp(TimestampWatchdogHibernateStop);
}
// Rise and shine.
manager->RecordTimestamp(TimestampWatchdogWakeup);
// Don't request an interrupt callback unless the current script has
// been running long enough that we might show the slow script dialog.
// Triggering the callback from off the main thread can be expensive.
// We want to avoid showing the slow script dialog if the user's laptop
// goes to sleep in the middle of running a script. To ensure this, we
// invoke the interrupt callback after only half the timeout has
// elapsed. The callback simply records the fact that it was called in
// the mSlowScriptSecondHalf flag. Then we wait another (timeout/2)
// seconds and invoke the callback again. This time around it sees
// mSlowScriptSecondHalf is set and so it shows the slow script
// dialog. If the computer is put to sleep during one of the (timeout/2)
// periods, the script still has the other (timeout/2) seconds to
// finish.
if (!self->ShuttingDown() && manager->IsAnyContextActive()) {
bool debuggerAttached = false;
nsCOMPtr<nsIDebug2> dbg = do_GetService("@mozilla.org/xpcom/debug;1");
if (dbg)
dbg->GetIsDebuggerAttached(&debuggerAttached);
if (debuggerAttached) {
// We won't be interrupting these scripts anyway.
continue;
}
PRTime usecs = self->MinScriptRunTimeSeconds() * PR_USEC_PER_SEC / 2;
manager->ForAllActiveContexts([usecs, manager, &lock](XPCJSContext* aContext) -> bool {
auto timediff = PR_Now() - manager->GetContextTimestamp(aContext, lock);
if (timediff > usecs) {
JS_RequestInterruptCallback(aContext->Context());
return true;
}
return false;
});
}
}
// Tell the manager that we've shut down.
self->Finished();
}
PRTime
XPCJSContext::GetWatchdogTimestamp(WatchdogTimestampCategory aCategory)
{
AutoLockWatchdog lock(mWatchdogManager->GetWatchdog());
return aCategory == TimestampContextStateChange ?
mWatchdogManager->GetContextTimestamp(this, lock) :
mWatchdogManager->GetTimestamp(aCategory, lock);
}
void
xpc::SimulateActivityCallback(bool aActive)
{
XPCJSContext::ActivityCallback(XPCJSContext::Get(), aActive);
}
// static
void
XPCJSContext::ActivityCallback(void* arg, bool active)
{
if (!active) {
ProcessHangMonitor::ClearHang();
}
XPCJSContext* self = static_cast<XPCJSContext*>(arg);
self->mWatchdogManager->RecordContextActivity(self, active);
}
static inline bool
IsWebExtensionPrincipal(nsIPrincipal* principal, nsAString& addonId)
{
if (auto policy = BasePrincipal::Cast(principal)->AddonPolicy()) {
policy->GetId(addonId);
return true;
}
return false;
}
static bool
IsWebExtensionContentScript(BasePrincipal* principal, nsAString& addonId)
{
if (!principal->Is<ExpandedPrincipal>()) {
return false;
}
auto expanded = principal->As<ExpandedPrincipal>();
for (auto& prin : expanded->WhiteList()) {
if (IsWebExtensionPrincipal(prin, addonId)) {
return true;
}
}
return false;
}
// static
bool
XPCJSContext::InterruptCallback(JSContext* cx)
{
XPCJSContext* self = XPCJSContext::Get();
// Now is a good time to turn on profiling if it's pending.
PROFILER_JS_INTERRUPT_CALLBACK();
// Normally we record mSlowScriptCheckpoint when we start to process an
// event. However, we can run JS outside of event handlers. This code takes
// care of that case.
if (self->mSlowScriptCheckpoint.IsNull()) {
self->mSlowScriptCheckpoint = TimeStamp::NowLoRes();
self->mSlowScriptSecondHalf = false;
self->mSlowScriptActualWait = mozilla::TimeDuration();
self->mTimeoutAccumulated = false;
return true;
}
// Sometimes we get called back during XPConnect initialization, before Gecko
// has finished bootstrapping. Avoid crashing in nsContentUtils below.
if (!nsContentUtils::IsInitialized())
return true;
// This is at least the second interrupt callback we've received since
// returning to the event loop. See how long it's been, and what the limit
// is.
TimeDuration duration = TimeStamp::NowLoRes() - self->mSlowScriptCheckpoint;
int32_t limit;
nsString addonId;
const char* prefName;
auto principal = BasePrincipal::Cast(nsContentUtils::SubjectPrincipal(cx));
bool chrome = principal->Is<SystemPrincipal>();
if (chrome) {
prefName = PREF_MAX_SCRIPT_RUN_TIME_CHROME;
limit = Preferences::GetInt(prefName, 20);
} else if (IsWebExtensionContentScript(principal, addonId)) {
prefName = PREF_MAX_SCRIPT_RUN_TIME_EXT_CONTENT;
limit = Preferences::GetInt(prefName, 5);
} else {
prefName = PREF_MAX_SCRIPT_RUN_TIME_CONTENT;
limit = Preferences::GetInt(prefName, 10);
}
// If there's no limit, or we're within the limit, let it go.
if (limit == 0 || duration.ToSeconds() < limit / 2.0)
return true;
self->mSlowScriptActualWait += duration;
// In order to guard against time changes or laptops going to sleep, we
// don't trigger the slow script warning until (limit/2) seconds have
// elapsed twice.
if (!self->mSlowScriptSecondHalf) {
self->mSlowScriptCheckpoint = TimeStamp::NowLoRes();
self->mSlowScriptSecondHalf = true;
return true;
}
//
// This has gone on long enough! Time to take action. ;-)
//
// Get the DOM window associated with the running script. If the script is
// running in a non-DOM scope, we have to just let it keep running.
RootedObject global(cx, JS::CurrentGlobalOrNull(cx));
RefPtr<nsGlobalWindowInner> win = WindowOrNull(global);
if (!win && IsSandbox(global)) {
// If this is a sandbox associated with a DOMWindow via a
// sandboxPrototype, use that DOMWindow. This supports GreaseMonkey
// and JetPack content scripts.
JS::Rooted<JSObject*> proto(cx);
if (!JS_GetPrototype(cx, global, &proto))
return false;
if (proto && IsSandboxPrototypeProxy(proto) &&
(proto = js::CheckedUnwrap(proto, /* stopAtWindowProxy = */ false)))
{
win = WindowGlobalOrNull(proto);
}
}
if (!win) {
NS_WARNING("No active window");
return true;
}
if (win->IsDying()) {
// The window is being torn down. When that happens we try to prevent
// the dispatch of new runnables, so it also makes sense to kill any
// long-running script. The user is primarily interested in this page
// going away.
return false;
}
// Accumulate slow script invokation delay.
if (!chrome && !self->mTimeoutAccumulated) {
uint32_t delay = uint32_t(self->mSlowScriptActualWait.ToMilliseconds() - (limit * 1000.0));
Telemetry::Accumulate(Telemetry::SLOW_SCRIPT_NOTIFY_DELAY, delay);
self->mTimeoutAccumulated = true;
}
// Show the prompt to the user, and kill if requested.
nsGlobalWindowInner::SlowScriptResponse response = win->ShowSlowScriptDialog(addonId);
if (response == nsGlobalWindowInner::KillSlowScript) {
if (Preferences::GetBool("dom.global_stop_script", true))
xpc::Scriptability::Get(global).Block();
return false;
}
if (response == nsGlobalWindowInner::KillScriptGlobal) {
nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
if (!IsSandbox(global) || !obs)
return false;
// Notify the extensions framework that the sandbox should be killed.
nsIXPConnect* xpc = nsContentUtils::XPConnect();
JS::RootedObject wrapper(cx, JS_NewPlainObject(cx));
nsCOMPtr<nsISupports> supports;
// Store the sandbox object on the wrappedJSObject property of the
// subject so that JS recipients can access the JS value directly.
if (!wrapper ||
!JS_DefineProperty(cx, wrapper, "wrappedJSObject", global, JSPROP_ENUMERATE) ||
NS_FAILED(xpc->WrapJS(cx, wrapper, NS_GET_IID(nsISupports), getter_AddRefs(supports)))) {
return false;
}
obs->NotifyObservers(supports, "kill-content-script-sandbox", nullptr);
return false;
}
// The user chose to continue the script. Reset the timer, and disable this
// machinery with a pref of the user opted out of future slow-script dialogs.
if (response != nsGlobalWindowInner::ContinueSlowScriptAndKeepNotifying)
self->mSlowScriptCheckpoint = TimeStamp::NowLoRes();
if (response == nsGlobalWindowInner::AlwaysContinueSlowScript)
Preferences::SetInt(prefName, 0);
return true;
}
#define JS_OPTIONS_DOT_STR "javascript.options."
static mozilla::Atomic<bool> sDiscardSystemSource(false);
bool
xpc::ShouldDiscardSystemSource() { return sDiscardSystemSource; }
#ifdef DEBUG
static mozilla::Atomic<bool> sExtraWarningsForSystemJS(false);
bool xpc::ExtraWarningsForSystemJS() { return sExtraWarningsForSystemJS; }
#else
bool xpc::ExtraWarningsForSystemJS() { return false; }
#endif
static mozilla::Atomic<bool> sSharedMemoryEnabled(false);
bool
xpc::SharedMemoryEnabled() { return sSharedMemoryEnabled; }
static void
ReloadPrefsCallback(const char* pref, void* data)
{
XPCJSContext* xpccx = static_cast<XPCJSContext*>(data);
JSContext* cx = xpccx->Context();
bool useBaseline = Preferences::GetBool(JS_OPTIONS_DOT_STR "baselinejit");
bool useIon = Preferences::GetBool(JS_OPTIONS_DOT_STR "ion");
bool useAsmJS = Preferences::GetBool(JS_OPTIONS_DOT_STR "asmjs");
bool useWasm = Preferences::GetBool(JS_OPTIONS_DOT_STR "wasm");
bool useWasmIon = Preferences::GetBool(JS_OPTIONS_DOT_STR "wasm_ionjit");
bool useWasmBaseline = Preferences::GetBool(JS_OPTIONS_DOT_STR "wasm_baselinejit");
bool throwOnAsmJSValidationFailure = Preferences::GetBool(JS_OPTIONS_DOT_STR
"throw_on_asmjs_validation_failure");
bool useNativeRegExp = Preferences::GetBool(JS_OPTIONS_DOT_STR "native_regexp");
bool parallelParsing = Preferences::GetBool(JS_OPTIONS_DOT_STR "parallel_parsing");
bool offthreadIonCompilation = Preferences::GetBool(JS_OPTIONS_DOT_STR
"ion.offthread_compilation");
bool useBaselineEager = Preferences::GetBool(JS_OPTIONS_DOT_STR
"baselinejit.unsafe_eager_compilation");
bool useIonEager = Preferences::GetBool(JS_OPTIONS_DOT_STR "ion.unsafe_eager_compilation");
#ifdef DEBUG
bool fullJitDebugChecks = Preferences::GetBool(JS_OPTIONS_DOT_STR "jit.full_debug_checks");
#endif
int32_t baselineThreshold = Preferences::GetInt(JS_OPTIONS_DOT_STR "baselinejit.threshold", -1);
int32_t ionThreshold = Preferences::GetInt(JS_OPTIONS_DOT_STR "ion.threshold", -1);
sDiscardSystemSource = Preferences::GetBool(JS_OPTIONS_DOT_STR "discardSystemSource");
bool useAsyncStack = Preferences::GetBool(JS_OPTIONS_DOT_STR "asyncstack");
bool throwOnDebuggeeWouldRun = Preferences::GetBool(JS_OPTIONS_DOT_STR
"throw_on_debuggee_would_run");
bool dumpStackOnDebuggeeWouldRun = Preferences::GetBool(JS_OPTIONS_DOT_STR
"dump_stack_on_debuggee_would_run");
bool werror = Preferences::GetBool(JS_OPTIONS_DOT_STR "werror");
bool extraWarnings = Preferences::GetBool(JS_OPTIONS_DOT_STR "strict");
bool streams = Preferences::GetBool(JS_OPTIONS_DOT_STR "streams");
bool spectreIndexMasking = Preferences::GetBool(JS_OPTIONS_DOT_STR "spectre.index_masking");
bool spectreObjectMitigationsBarriers =
Preferences::GetBool(JS_OPTIONS_DOT_STR "spectre.object_mitigations.barriers");
bool spectreObjectMitigationsMisc =
Preferences::GetBool(JS_OPTIONS_DOT_STR "spectre.object_mitigations.misc");
bool spectreStringMitigations =
Preferences::GetBool(JS_OPTIONS_DOT_STR "spectre.string_mitigations");
bool spectreValueMasking = Preferences::GetBool(JS_OPTIONS_DOT_STR "spectre.value_masking");
bool spectreJitToCxxCalls = Preferences::GetBool(JS_OPTIONS_DOT_STR "spectre.jit_to_C++_calls");
sSharedMemoryEnabled = Preferences::GetBool(JS_OPTIONS_DOT_STR "shared_memory");
#ifdef DEBUG
sExtraWarningsForSystemJS = Preferences::GetBool(JS_OPTIONS_DOT_STR "strict.debug");
#endif
#ifdef JS_GC_ZEAL
int32_t zeal = Preferences::GetInt(JS_OPTIONS_DOT_STR "gczeal", -1);
int32_t zeal_frequency =
Preferences::GetInt(JS_OPTIONS_DOT_STR "gczeal.frequency",
JS_DEFAULT_ZEAL_FREQ);
if (zeal >= 0) {
JS_SetGCZeal(cx, (uint8_t)zeal, zeal_frequency);
}
#endif // JS_GC_ZEAL
#ifdef FUZZING
bool fuzzingEnabled = Preferences::GetBool("fuzzing.enabled");
#endif
bool arrayProtoValues = Preferences::GetBool(JS_OPTIONS_DOT_STR "array_prototype_values");
JS::ContextOptionsRef(cx).setBaseline(useBaseline)
.setIon(useIon)
.setAsmJS(useAsmJS)
.setWasm(useWasm)
.setWasmIon(useWasmIon)
.setWasmBaseline(useWasmBaseline)
.setThrowOnAsmJSValidationFailure(throwOnAsmJSValidationFailure)
.setNativeRegExp(useNativeRegExp)
.setAsyncStack(useAsyncStack)
.setThrowOnDebuggeeWouldRun(throwOnDebuggeeWouldRun)
.setDumpStackOnDebuggeeWouldRun(dumpStackOnDebuggeeWouldRun)
.setWerror(werror)
#ifdef FUZZING
.setFuzzing(fuzzingEnabled)
#endif
.setStreams(streams)
.setExtraWarnings(extraWarnings)
.setArrayProtoValues(arrayProtoValues);
nsCOMPtr<nsIXULRuntime> xr = do_GetService("@mozilla.org/xre/runtime;1");
if (xr) {
bool safeMode = false;
xr->GetInSafeMode(&safeMode);
if (safeMode) {
JS::ContextOptionsRef(cx).disableOptionsForSafeMode();
}
}
JS_SetParallelParsingEnabled(cx, parallelParsing);
JS_SetOffthreadIonCompilationEnabled(cx, offthreadIonCompilation);
JS_SetGlobalJitCompilerOption(cx, JSJITCOMPILER_BASELINE_WARMUP_TRIGGER,
useBaselineEager ? 0 : baselineThreshold);
JS_SetGlobalJitCompilerOption(cx, JSJITCOMPILER_ION_WARMUP_TRIGGER,
useIonEager ? 0 : ionThreshold);
#ifdef DEBUG
JS_SetGlobalJitCompilerOption(cx, JSJITCOMPILER_FULL_DEBUG_CHECKS, fullJitDebugChecks);
#endif
JS_SetGlobalJitCompilerOption(cx, JSJITCOMPILER_SPECTRE_INDEX_MASKING, spectreIndexMasking);
JS_SetGlobalJitCompilerOption(cx, JSJITCOMPILER_SPECTRE_OBJECT_MITIGATIONS_BARRIERS,
spectreObjectMitigationsBarriers);
JS_SetGlobalJitCompilerOption(cx, JSJITCOMPILER_SPECTRE_OBJECT_MITIGATIONS_MISC,
spectreObjectMitigationsMisc);
JS_SetGlobalJitCompilerOption(cx, JSJITCOMPILER_SPECTRE_STRING_MITIGATIONS,
spectreStringMitigations);
JS_SetGlobalJitCompilerOption(cx, JSJITCOMPILER_SPECTRE_VALUE_MASKING, spectreValueMasking);
JS_SetGlobalJitCompilerOption(cx, JSJITCOMPILER_SPECTRE_JIT_TO_CXX_CALLS,
spectreJitToCxxCalls);
}
XPCJSContext::~XPCJSContext()
{
MOZ_COUNT_DTOR_INHERITED(XPCJSContext, CycleCollectedJSContext);
// Elsewhere we abort immediately if XPCJSContext initialization fails.
// Therefore the context must be non-null.
MOZ_ASSERT(MaybeContext());
Preferences::UnregisterPrefixCallback(ReloadPrefsCallback,
JS_OPTIONS_DOT_STR,
this);
#ifdef FUZZING
Preferences::UnregisterCallback(ReloadPrefsCallback, "fuzzing.enabled", this);
#endif
js::SetActivityCallback(Context(), nullptr, nullptr);
// Clear any pending exception. It might be an XPCWrappedJS, and if we try
// to destroy it later we will crash.
SetPendingException(nullptr);
// If we're the last XPCJSContext around, clean up the watchdog manager.
if (--sInstanceCount == 0) {
if (mWatchdogManager->GetWatchdog()) {
mWatchdogManager->StopWatchdog();
}
mWatchdogManager->UnregisterContext(this);
mWatchdogManager->Shutdown();
sWatchdogInstance = nullptr;
} else {
// Otherwise, simply remove ourselves from the list.
mWatchdogManager->UnregisterContext(this);
}
if (mCallContext)
mCallContext->SystemIsBeingShutDown();
auto rtPrivate = static_cast<PerThreadAtomCache*>(JS_GetContextPrivate(Context()));
delete rtPrivate;
JS_SetContextPrivate(Context(), nullptr);
PROFILER_CLEAR_JS_CONTEXT();
gTlsContext.set(nullptr);
}
XPCJSContext::XPCJSContext()
: mCallContext(nullptr),
mAutoRoots(nullptr),
mResolveName(JSID_VOID),
mResolvingWrapper(nullptr),
mWatchdogManager(GetWatchdogManager()),
mSlowScriptSecondHalf(false),
mTimeoutAccumulated(false),
mPendingResult(NS_OK),
mActive(CONTEXT_INACTIVE),
mLastStateChange(PR_Now())
{
MOZ_COUNT_CTOR_INHERITED(XPCJSContext, CycleCollectedJSContext);
MOZ_RELEASE_ASSERT(!gTlsContext.get());
MOZ_ASSERT(mWatchdogManager);
++sInstanceCount;
mWatchdogManager->RegisterContext(this);
gTlsContext.set(this);
}
/* static */ XPCJSContext*
XPCJSContext::Get()
{
return gTlsContext.get();
}
#ifdef XP_WIN
static size_t
GetWindowsStackSize()
{
// First, get the stack base. Because the stack grows down, this is the top
// of the stack.
const uint8_t* stackTop;
#ifdef _WIN64
PNT_TIB64 pTib = reinterpret_cast<PNT_TIB64>(NtCurrentTeb());
stackTop = reinterpret_cast<const uint8_t*>(pTib->StackBase);
#else
PNT_TIB pTib = reinterpret_cast<PNT_TIB>(NtCurrentTeb());
stackTop = reinterpret_cast<const uint8_t*>(pTib->StackBase);
#endif
// Now determine the stack bottom. Note that we can't use tib->StackLimit,
// because that's the size of the committed area and we're also interested
// in the reserved pages below that.
MEMORY_BASIC_INFORMATION mbi;
if (!VirtualQuery(&mbi, &mbi, sizeof(mbi)))
MOZ_CRASH("VirtualQuery failed");
const uint8_t* stackBottom = reinterpret_cast<const uint8_t*>(mbi.AllocationBase);
// Do some sanity checks.
size_t stackSize = size_t(stackTop - stackBottom);
MOZ_RELEASE_ASSERT(stackSize >= 1 * 1024 * 1024);
MOZ_RELEASE_ASSERT(stackSize <= 32 * 1024 * 1024);
// Subtract 40 KB (Win32) or 80 KB (Win64) to account for things like
// the guard page and large PGO stack frames.
return stackSize - 10 * sizeof(uintptr_t) * 1024;
}
#endif
XPCJSRuntime*
XPCJSContext::Runtime() const