-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHelperThreads.cpp
2462 lines (2046 loc) · 76.5 KB
/
HelperThreads.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: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "vm/HelperThreads.h"
#include "mozilla/Maybe.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/Unused.h"
#include "mozilla/Utf8.h" // mozilla::Utf8Unit
#include <algorithm>
#include "frontend/BytecodeCompilation.h"
#include "jit/IonCompileTask.h"
#include "js/ContextOptions.h" // JS::ContextOptions
#include "js/SourceText.h"
#include "js/UniquePtr.h"
#include "js/Utility.h"
#include "threading/CpuCount.h"
#include "util/NativeStack.h"
#include "vm/ErrorReporting.h"
#include "vm/SharedImmutableStringsCache.h"
#include "vm/Time.h"
#include "vm/TraceLogging.h"
#include "vm/Xdr.h"
#include "wasm/WasmGenerator.h"
#include "debugger/DebugAPI-inl.h"
#include "gc/ArenaList-inl.h"
#include "vm/JSContext-inl.h"
#include "vm/JSObject-inl.h"
#include "vm/JSScript-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/Realm-inl.h"
using namespace js;
using mozilla::Maybe;
using mozilla::TimeDuration;
using mozilla::TimeStamp;
using mozilla::Unused;
using mozilla::Utf8Unit;
using JS::CompileOptions;
using JS::ReadOnlyCompileOptions;
namespace js {
GlobalHelperThreadState* gHelperThreadState = nullptr;
} // namespace js
// These macros are identical in function to the same-named ones in
// GeckoProfiler.h, but they are defined separately because SpiderMonkey can't
// use GeckoProfiler.h.
#define PROFILER_RAII_PASTE(id, line) id##line
#define PROFILER_RAII_EXPAND(id, line) PROFILER_RAII_PASTE(id, line)
#define PROFILER_RAII PROFILER_RAII_EXPAND(raiiObject, __LINE__)
#define AUTO_PROFILER_LABEL(label, categoryPair) \
HelperThread::AutoProfilerLabel PROFILER_RAII( \
this, label, JS::ProfilingCategoryPair::categoryPair)
bool js::CreateHelperThreadsState() {
MOZ_ASSERT(!gHelperThreadState);
UniquePtr<GlobalHelperThreadState> helperThreadState =
MakeUnique<GlobalHelperThreadState>();
if (!helperThreadState) {
return false;
}
gHelperThreadState = helperThreadState.release();
if (!gHelperThreadState->ensureContextListForThreadCount()) {
js_delete(gHelperThreadState);
gHelperThreadState = nullptr;
return false;
}
return true;
}
void js::DestroyHelperThreadsState() {
if (!gHelperThreadState) {
return;
}
gHelperThreadState->finish();
js_delete(gHelperThreadState);
gHelperThreadState = nullptr;
}
bool js::EnsureHelperThreadsInitialized() {
MOZ_ASSERT(gHelperThreadState);
return gHelperThreadState->ensureInitialized();
}
static size_t ClampDefaultCPUCount(size_t cpuCount) {
// It's extremely rare for SpiderMonkey to have more than a few cores worth
// of work. At higher core counts, performance can even decrease due to NUMA
// (and SpiderMonkey's lack of NUMA-awareness), contention, and general lack
// of optimization for high core counts. So to avoid wasting thread stack
// resources (and cluttering gdb and core dumps), clamp to 8 cores for now.
return std::min<size_t>(cpuCount, 8);
}
static size_t ThreadCountForCPUCount(size_t cpuCount) {
// We need at least two threads for tier-2 wasm compilations, because
// there's a master task that holds a thread while other threads do the
// compilation.
return std::max<size_t>(cpuCount, 2);
}
bool js::SetFakeCPUCount(size_t count) {
// This must be called before the threads have been initialized.
MOZ_ASSERT(!HelperThreadState().threads);
HelperThreadState().cpuCount = count;
HelperThreadState().threadCount = ThreadCountForCPUCount(count);
if (!HelperThreadState().ensureContextListForThreadCount()) {
return false;
}
return true;
}
void JS::SetProfilingThreadCallbacks(
JS::RegisterThreadCallback registerThread,
JS::UnregisterThreadCallback unregisterThread) {
HelperThreadState().registerThread = registerThread;
HelperThreadState().unregisterThread = unregisterThread;
}
bool js::StartOffThreadWasmCompile(wasm::CompileTask* task,
wasm::CompileMode mode) {
AutoLockHelperThreadState lock;
if (!HelperThreadState().wasmWorklist(lock, mode).pushBack(task)) {
return false;
}
HelperThreadState().notifyOne(GlobalHelperThreadState::PRODUCER, lock);
return true;
}
void js::StartOffThreadWasmTier2Generator(wasm::UniqueTier2GeneratorTask task) {
MOZ_ASSERT(CanUseExtraThreads());
AutoLockHelperThreadState lock;
if (!HelperThreadState().wasmTier2GeneratorWorklist(lock).append(
task.get())) {
return;
}
Unused << task.release();
HelperThreadState().notifyOne(GlobalHelperThreadState::PRODUCER, lock);
}
static void CancelOffThreadWasmTier2GeneratorLocked(
AutoLockHelperThreadState& lock) {
if (!HelperThreadState().threads) {
return;
}
// Remove pending tasks from the tier2 generator worklist and cancel and
// delete them.
{
wasm::Tier2GeneratorTaskPtrVector& worklist =
HelperThreadState().wasmTier2GeneratorWorklist(lock);
for (size_t i = 0; i < worklist.length(); i++) {
wasm::Tier2GeneratorTask* task = worklist[i];
HelperThreadState().remove(worklist, &i);
js_delete(task);
}
}
// There is at most one running Tier2Generator task and we assume that
// below.
static_assert(GlobalHelperThreadState::MaxTier2GeneratorTasks == 1,
"code must be generalized");
// If there is a running Tier2 generator task, shut it down in a predictable
// way. The task will be deleted by the normal deletion logic.
for (auto& helper : *HelperThreadState().threads) {
if (helper.wasmTier2GeneratorTask()) {
// Set a flag that causes compilation to shortcut itself.
helper.wasmTier2GeneratorTask()->cancel();
// Wait for the generator task to finish. This avoids a shutdown race
// where the shutdown code is trying to shut down helper threads and the
// ongoing tier2 compilation is trying to finish, which requires it to
// have access to helper threads.
uint32_t oldFinishedCount =
HelperThreadState().wasmTier2GeneratorsFinished(lock);
while (HelperThreadState().wasmTier2GeneratorsFinished(lock) ==
oldFinishedCount) {
HelperThreadState().wait(lock, GlobalHelperThreadState::CONSUMER);
}
// At most one of these tasks.
break;
}
}
}
void js::CancelOffThreadWasmTier2Generator() {
AutoLockHelperThreadState lock;
CancelOffThreadWasmTier2GeneratorLocked(lock);
}
bool js::StartOffThreadIonCompile(jit::IonCompileTask* task,
const AutoLockHelperThreadState& lock) {
if (!HelperThreadState().ionWorklist(lock).append(task)) {
return false;
}
// The build is moving off-thread. Freeze the LifoAlloc to prevent any
// unwanted mutations.
task->alloc().lifoAlloc()->setReadOnly();
HelperThreadState().notifyOne(GlobalHelperThreadState::PRODUCER, lock);
return true;
}
bool js::StartOffThreadIonFree(jit::IonCompileTask* task,
const AutoLockHelperThreadState& lock) {
MOZ_ASSERT(CanUseExtraThreads());
if (!HelperThreadState().ionFreeList(lock).append(task)) {
return false;
}
HelperThreadState().notifyOne(GlobalHelperThreadState::PRODUCER, lock);
return true;
}
/*
* Move an IonCompilationTask for which compilation has either finished, failed,
* or been cancelled into the global finished compilation list. All off thread
* compilations which are started must eventually be finished.
*/
void js::FinishOffThreadIonCompile(jit::IonCompileTask* task,
const AutoLockHelperThreadState& lock) {
AutoEnterOOMUnsafeRegion oomUnsafe;
if (!HelperThreadState().ionFinishedList(lock).append(task)) {
oomUnsafe.crash("FinishOffThreadIonCompile");
}
task->script()
->runtimeFromAnyThread()
->jitRuntime()
->numFinishedOffThreadTasksRef(lock)++;
}
static JSRuntime* GetSelectorRuntime(const CompilationSelector& selector) {
struct Matcher {
JSRuntime* operator()(JSScript* script) {
return script->runtimeFromMainThread();
}
JSRuntime* operator()(Realm* realm) {
return realm->runtimeFromMainThread();
}
JSRuntime* operator()(Zone* zone) { return zone->runtimeFromMainThread(); }
JSRuntime* operator()(ZonesInState zbs) { return zbs.runtime; }
JSRuntime* operator()(JSRuntime* runtime) { return runtime; }
JSRuntime* operator()(CompilationsUsingNursery cun) { return cun.runtime; }
};
return selector.match(Matcher());
}
static bool JitDataStructuresExist(const CompilationSelector& selector) {
struct Matcher {
bool operator()(JSScript* script) { return !!script->realm()->jitRealm(); }
bool operator()(Realm* realm) { return !!realm->jitRealm(); }
bool operator()(Zone* zone) { return !!zone->jitZone(); }
bool operator()(ZonesInState zbs) { return zbs.runtime->hasJitRuntime(); }
bool operator()(JSRuntime* runtime) { return runtime->hasJitRuntime(); }
bool operator()(CompilationsUsingNursery cun) {
return cun.runtime->hasJitRuntime();
}
};
return selector.match(Matcher());
}
static bool IonCompileTaskMatches(const CompilationSelector& selector,
jit::IonCompileTask* task) {
struct TaskMatches {
jit::IonCompileTask* task_;
bool operator()(JSScript* script) { return script == task_->script(); }
bool operator()(Realm* realm) { return realm == task_->script()->realm(); }
bool operator()(Zone* zone) {
return zone == task_->script()->zoneFromAnyThread();
}
bool operator()(JSRuntime* runtime) {
return runtime == task_->script()->runtimeFromAnyThread();
}
bool operator()(ZonesInState zbs) {
return zbs.runtime == task_->script()->runtimeFromAnyThread() &&
zbs.state == task_->script()->zoneFromAnyThread()->gcState();
}
bool operator()(CompilationsUsingNursery cun) {
return cun.runtime == task_->script()->runtimeFromAnyThread() &&
!task_->mirGen().safeForMinorGC();
}
};
return selector.match(TaskMatches{task});
}
static void CancelOffThreadIonCompileLocked(const CompilationSelector& selector,
AutoLockHelperThreadState& lock) {
if (!HelperThreadState().threads) {
return;
}
/* Cancel any pending entries for which processing hasn't started. */
GlobalHelperThreadState::IonCompileTaskVector& worklist =
HelperThreadState().ionWorklist(lock);
for (size_t i = 0; i < worklist.length(); i++) {
jit::IonCompileTask* task = worklist[i];
if (IonCompileTaskMatches(selector, task)) {
// Once finished, tasks are added to a Linked list which is
// allocated with the IonCompileTask class. The IonCompileTask is
// allocated in the LifoAlloc so we need the LifoAlloc to be mutable.
worklist[i]->alloc().lifoAlloc()->setReadWrite();
FinishOffThreadIonCompile(task, lock);
HelperThreadState().remove(worklist, &i);
}
}
/* Wait for in progress entries to finish up. */
bool cancelled;
do {
cancelled = false;
for (auto& helper : *HelperThreadState().threads) {
if (helper.ionCompileTask() &&
IonCompileTaskMatches(selector, helper.ionCompileTask())) {
helper.ionCompileTask()->mirGen().cancel();
cancelled = true;
}
}
if (cancelled) {
HelperThreadState().wait(lock, GlobalHelperThreadState::CONSUMER);
}
} while (cancelled);
/* Cancel code generation for any completed entries. */
GlobalHelperThreadState::IonCompileTaskVector& finished =
HelperThreadState().ionFinishedList(lock);
for (size_t i = 0; i < finished.length(); i++) {
jit::IonCompileTask* task = finished[i];
if (IonCompileTaskMatches(selector, task)) {
JSRuntime* rt = task->script()->runtimeFromAnyThread();
rt->jitRuntime()->numFinishedOffThreadTasksRef(lock)--;
jit::FinishOffThreadTask(rt, task, lock);
HelperThreadState().remove(finished, &i);
}
}
/* Cancel lazy linking for pending tasks (attached to the ionScript). */
JSRuntime* runtime = GetSelectorRuntime(selector);
jit::IonCompileTask* task =
runtime->jitRuntime()->ionLazyLinkList(runtime).getFirst();
while (task) {
jit::IonCompileTask* next = task->getNext();
if (IonCompileTaskMatches(selector, task)) {
jit::FinishOffThreadTask(runtime, task, lock);
}
task = next;
}
}
void js::CancelOffThreadIonCompile(const CompilationSelector& selector) {
if (!JitDataStructuresExist(selector)) {
return;
}
AutoLockHelperThreadState lock;
CancelOffThreadIonCompileLocked(selector, lock);
}
#ifdef DEBUG
bool js::HasOffThreadIonCompile(Realm* realm) {
AutoLockHelperThreadState lock;
if (!HelperThreadState().threads) {
return false;
}
GlobalHelperThreadState::IonCompileTaskVector& worklist =
HelperThreadState().ionWorklist(lock);
for (size_t i = 0; i < worklist.length(); i++) {
jit::IonCompileTask* task = worklist[i];
if (task->script()->realm() == realm) {
return true;
}
}
for (auto& helper : *HelperThreadState().threads) {
if (helper.ionCompileTask() &&
helper.ionCompileTask()->script()->realm() == realm) {
return true;
}
}
GlobalHelperThreadState::IonCompileTaskVector& finished =
HelperThreadState().ionFinishedList(lock);
for (size_t i = 0; i < finished.length(); i++) {
jit::IonCompileTask* task = finished[i];
if (task->script()->realm() == realm) {
return true;
}
}
JSRuntime* rt = realm->runtimeFromMainThread();
jit::IonCompileTask* task = rt->jitRuntime()->ionLazyLinkList(rt).getFirst();
while (task) {
if (task->script()->realm() == realm) {
return true;
}
task = task->getNext();
}
return false;
}
#endif
struct MOZ_RAII AutoSetContextParse {
explicit AutoSetContextParse(ParseTask* task) {
TlsContext.get()->setParseTask(task);
}
~AutoSetContextParse() { TlsContext.get()->setParseTask(nullptr); }
};
// We want our default stack size limit to be approximately 2MB, to be safe, but
// expect most threads to use much less. On Linux, however, requesting a stack
// of 2MB or larger risks the kernel allocating an entire 2MB huge page for it
// on first access, which we do not want. To avoid this possibility, we subtract
// 2 standard VM page sizes from our default.
static const uint32_t kDefaultHelperStackSize = 2048 * 1024 - 2 * 4096;
static const uint32_t kDefaultHelperStackQuota = 1800 * 1024;
// TSan enforces a minimum stack size that's just slightly larger than our
// default helper stack size. It does this to store blobs of TSan-specific
// data on each thread's stack. Unfortunately, that means that even though
// we'll actually receive a larger stack than we requested, the effective
// usable space of that stack is significantly less than what we expect.
// To offset TSan stealing our stack space from underneath us, double the
// default.
//
// Note that we don't need this for ASan/MOZ_ASAN because ASan doesn't
// require all the thread-specific state that TSan does.
#if defined(MOZ_TSAN)
static const uint32_t HELPER_STACK_SIZE = 2 * kDefaultHelperStackSize;
static const uint32_t HELPER_STACK_QUOTA = 2 * kDefaultHelperStackQuota;
#else
static const uint32_t HELPER_STACK_SIZE = kDefaultHelperStackSize;
static const uint32_t HELPER_STACK_QUOTA = kDefaultHelperStackQuota;
#endif
AutoSetHelperThreadContext::AutoSetHelperThreadContext() {
AutoLockHelperThreadState lock;
cx = HelperThreadState().getFirstUnusedContext(lock);
MOZ_ASSERT(cx);
cx->setHelperThread(lock);
cx->nativeStackBase = GetNativeStackBase();
// When we set the JSContext, we need to reset the computed stack limits for
// the current thread, so we also set the native stack quota.
JS_SetNativeStackQuota(cx, HELPER_STACK_QUOTA);
}
static const JSClass parseTaskGlobalClass = {"internal-parse-task-global",
JSCLASS_GLOBAL_FLAGS,
&JS::DefaultGlobalClassOps};
ParseTask::ParseTask(ParseTaskKind kind, JSContext* cx,
JS::OffThreadCompileCallback callback, void* callbackData)
: kind(kind),
options(cx),
parseGlobal(nullptr),
callback(callback),
callbackData(callbackData),
overRecursed(false),
outOfMemory(false) {
// Note that |cx| is the main thread context here but the parse task will
// run with a different, helper thread, context.
MOZ_ASSERT(!cx->isHelperThreadContext());
MOZ_ALWAYS_TRUE(scripts.reserve(scripts.capacity()));
MOZ_ALWAYS_TRUE(sourceObjects.reserve(sourceObjects.capacity()));
}
bool ParseTask::init(JSContext* cx, const ReadOnlyCompileOptions& options,
JSObject* global) {
MOZ_ASSERT(!cx->isHelperThreadContext());
if (!this->options.copy(cx, options)) {
return false;
}
parseGlobal = global;
return true;
}
void ParseTask::activate(JSRuntime* rt) {
rt->setUsedByHelperThread(parseGlobal->zone());
}
ParseTask::~ParseTask() = default;
void ParseTask::trace(JSTracer* trc) {
if (parseGlobal->runtimeFromAnyThread() != trc->runtime()) {
return;
}
Zone* zone = MaybeForwarded(parseGlobal)->zoneFromAnyThread();
if (zone->usedByHelperThread()) {
MOZ_ASSERT(!zone->isCollecting());
return;
}
TraceRoot(trc, &parseGlobal, "ParseTask::parseGlobal");
scripts.trace(trc);
sourceObjects.trace(trc);
}
size_t ParseTask::sizeOfExcludingThis(
mozilla::MallocSizeOf mallocSizeOf) const {
return options.sizeOfExcludingThis(mallocSizeOf) +
errors.sizeOfExcludingThis(mallocSizeOf);
}
void ParseTask::runTaskLocked(AutoLockHelperThreadState& locked) {
#ifdef DEBUG
JSRuntime* runtime = parseGlobal->runtimeFromAnyThread();
runtime->incOffThreadParsesRunning();
#endif
{
AutoUnlockHelperThreadState unlock(locked);
runTask();
}
// The callback is invoked while we are still off thread.
callback(this, callbackData);
// FinishOffThreadScript will need to be called on the script to
// migrate it into the correct compartment.
HelperThreadState().parseFinishedList(locked).insertBack(this);
#ifdef DEBUG
runtime->decOffThreadParsesRunning();
#endif
}
void ParseTask::runTask() {
AutoSetHelperThreadContext usesContext;
JSContext* cx = TlsContext.get();
JSRuntime* runtime = parseGlobal->runtimeFromAnyThread();
AutoSetContextRuntime ascr(runtime);
AutoSetContextParse parsetask(this);
gc::AutoSuppressNurseryCellAlloc noNurseryAlloc(cx);
Zone* zone = parseGlobal->zoneFromAnyThread();
zone->setHelperThreadOwnerContext(cx);
auto resetOwnerContext = mozilla::MakeScopeExit(
[&] { zone->setHelperThreadOwnerContext(nullptr); });
AutoRealm ar(cx, parseGlobal);
parse(cx);
MOZ_ASSERT(cx->tempLifoAlloc().isEmpty());
cx->tempLifoAlloc().freeAll();
cx->frontendCollectionPool().purge();
cx->atomsZoneFreeLists().clear();
}
template <typename Unit>
struct ScriptParseTask : public ParseTask {
JS::SourceText<Unit> data;
ScriptParseTask(JSContext* cx, JS::SourceText<Unit>& srcBuf,
JS::OffThreadCompileCallback callback, void* callbackData);
void parse(JSContext* cx) override;
};
template <typename Unit>
ScriptParseTask<Unit>::ScriptParseTask(JSContext* cx,
JS::SourceText<Unit>& srcBuf,
JS::OffThreadCompileCallback callback,
void* callbackData)
: ParseTask(ParseTaskKind::Script, cx, callback, callbackData),
data(std::move(srcBuf)) {}
template <typename Unit>
void ScriptParseTask<Unit>::parse(JSContext* cx) {
MOZ_ASSERT(cx->isHelperThreadContext());
ScopeKind scopeKind =
options.nonSyntacticScope ? ScopeKind::NonSyntactic : ScopeKind::Global;
LifoAllocScope allocScope(&cx->tempLifoAlloc());
frontend::CompilationInfo compilationInfo(cx, allocScope, options);
if (!compilationInfo.init(cx)) {
return;
}
// Whatever happens to the top-level script compilation (even if it fails),
// we must finish initializing the SSO. This is because there may be valid
// inner scripts observable by the debugger which reference the partially-
// initialized SSO.
sourceObjects.infallibleAppend(compilationInfo.sourceObject);
uint32_t len = data.length();
SourceExtent extent = SourceExtent::makeGlobalExtent(len, options);
frontend::GlobalSharedContext globalsc(cx, scopeKind, compilationInfo,
compilationInfo.directives, extent);
JSScript* script =
frontend::CompileGlobalScript(compilationInfo, globalsc, data);
if (script) {
scripts.infallibleAppend(script);
}
}
template <typename Unit>
struct ModuleParseTask : public ParseTask {
JS::SourceText<Unit> data;
ModuleParseTask(JSContext* cx, JS::SourceText<Unit>& srcBuf,
JS::OffThreadCompileCallback callback, void* callbackData);
void parse(JSContext* cx) override;
};
template <typename Unit>
ModuleParseTask<Unit>::ModuleParseTask(JSContext* cx,
JS::SourceText<Unit>& srcBuf,
JS::OffThreadCompileCallback callback,
void* callbackData)
: ParseTask(ParseTaskKind::Module, cx, callback, callbackData),
data(std::move(srcBuf)) {}
template <typename Unit>
void ModuleParseTask<Unit>::parse(JSContext* cx) {
MOZ_ASSERT(cx->isHelperThreadContext());
Rooted<ScriptSourceObject*> sourceObject(cx);
ModuleObject* module =
frontend::ParseModule(cx, options, data, &sourceObject.get());
if (module) {
scripts.infallibleAppend(module->script());
if (sourceObject) {
sourceObjects.infallibleAppend(sourceObject);
}
}
}
ScriptDecodeTask::ScriptDecodeTask(JSContext* cx,
const JS::TranscodeRange& range,
JS::OffThreadCompileCallback callback,
void* callbackData)
: ParseTask(ParseTaskKind::ScriptDecode, cx, callback, callbackData),
range(range) {}
void ScriptDecodeTask::parse(JSContext* cx) {
MOZ_ASSERT(cx->isHelperThreadContext());
RootedScript resultScript(cx);
Rooted<ScriptSourceObject*> sourceObject(cx);
Rooted<UniquePtr<XDROffThreadDecoder>> decoder(
cx,
js::MakeUnique<XDROffThreadDecoder>(
cx, &options, /* sourceObjectOut = */ &sourceObject.get(), range));
if (!decoder) {
ReportOutOfMemory(cx);
return;
}
XDRResult res = decoder->codeScript(&resultScript);
MOZ_ASSERT(bool(resultScript) == res.isOk());
if (res.isOk()) {
scripts.infallibleAppend(resultScript);
if (sourceObject) {
sourceObjects.infallibleAppend(sourceObject);
}
}
}
MultiScriptsDecodeTask::MultiScriptsDecodeTask(
JSContext* cx, JS::TranscodeSources& sources,
JS::OffThreadCompileCallback callback, void* callbackData)
: ParseTask(ParseTaskKind::MultiScriptsDecode, cx, callback, callbackData),
sources(&sources) {}
void MultiScriptsDecodeTask::parse(JSContext* cx) {
MOZ_ASSERT(cx->isHelperThreadContext());
if (!scripts.reserve(sources->length()) ||
!sourceObjects.reserve(sources->length())) {
ReportOutOfMemory(cx); // This sets |outOfMemory|.
return;
}
for (auto& source : *sources) {
CompileOptions opts(cx, options);
opts.setFileAndLine(source.filename, source.lineno);
RootedScript resultScript(cx);
Rooted<ScriptSourceObject*> sourceObject(cx);
Rooted<UniquePtr<XDROffThreadDecoder>> decoder(
cx, js::MakeUnique<XDROffThreadDecoder>(cx, &opts, &sourceObject.get(),
source.range));
if (!decoder) {
ReportOutOfMemory(cx);
return;
}
XDRResult res = decoder->codeScript(&resultScript);
MOZ_ASSERT(bool(resultScript) == res.isOk());
if (res.isErr()) {
break;
}
MOZ_ASSERT(resultScript);
scripts.infallibleAppend(resultScript);
sourceObjects.infallibleAppend(sourceObject);
}
}
void js::CancelOffThreadParses(JSRuntime* rt) {
AutoLockHelperThreadState lock;
if (!HelperThreadState().threads) {
return;
}
#ifdef DEBUG
GlobalHelperThreadState::ParseTaskVector& waitingOnGC =
HelperThreadState().parseWaitingOnGC(lock);
for (size_t i = 0; i < waitingOnGC.length(); i++) {
MOZ_ASSERT(!waitingOnGC[i]->runtimeMatches(rt));
}
#endif
// Instead of forcibly canceling pending parse tasks, just wait for all
// scheduled and in progress ones to complete. Otherwise the final GC may not
// collect everything due to zones being used off thread.
while (true) {
bool pending = false;
GlobalHelperThreadState::ParseTaskVector& worklist =
HelperThreadState().parseWorklist(lock);
for (size_t i = 0; i < worklist.length(); i++) {
ParseTask* task = worklist[i];
if (task->runtimeMatches(rt)) {
pending = true;
}
}
if (!pending) {
bool inProgress = false;
for (auto& thread : *HelperThreadState().threads) {
ParseTask* task = thread.parseTask();
if (task && task->runtimeMatches(rt)) {
inProgress = true;
}
}
if (!inProgress) {
break;
}
}
HelperThreadState().wait(lock, GlobalHelperThreadState::CONSUMER);
}
// Clean up any parse tasks which haven't been finished by the main thread.
auto& finished = HelperThreadState().parseFinishedList(lock);
while (true) {
bool found = false;
ParseTask* next;
ParseTask* task = finished.getFirst();
while (task) {
next = task->getNext();
if (task->runtimeMatches(rt)) {
found = true;
task->remove();
HelperThreadState().destroyParseTask(rt, task);
}
task = next;
}
if (!found) {
break;
}
}
#ifdef DEBUG
GlobalHelperThreadState::ParseTaskVector& worklist =
HelperThreadState().parseWorklist(lock);
for (size_t i = 0; i < worklist.length(); i++) {
ParseTask* task = worklist[i];
MOZ_ASSERT(!task->runtimeMatches(rt));
}
#endif
}
bool js::OffThreadParsingMustWaitForGC(JSRuntime* rt) {
// Off thread parsing can't occur during incremental collections on the
// atoms zone, to avoid triggering barriers. (Outside the atoms zone, the
// compilation will use a new zone that is never collected.) If an
// atoms-zone GC is in progress, hold off on executing the parse task until
// the atoms-zone GC completes (see EnqueuePendingParseTasksAfterGC).
return rt->activeGCInAtomsZone();
}
static bool EnsureConstructor(JSContext* cx, Handle<GlobalObject*> global,
JSProtoKey key) {
if (!GlobalObject::ensureConstructor(cx, global, key)) {
return false;
}
MOZ_ASSERT(global->getPrototype(key).toObject().isDelegate(),
"standard class prototype wasn't a delegate from birth");
return true;
}
// Initialize all classes potentially created during parsing for use in parser
// data structures, template objects, &c.
static bool EnsureParserCreatedClasses(JSContext* cx, ParseTaskKind kind) {
Handle<GlobalObject*> global = cx->global();
if (!EnsureConstructor(cx, global, JSProto_Function)) {
return false; // needed by functions, also adds object literals' proto
}
if (!EnsureConstructor(cx, global, JSProto_Array)) {
return false; // needed by array literals
}
if (!EnsureConstructor(cx, global, JSProto_RegExp)) {
return false; // needed by regular expression literals
}
if (!EnsureConstructor(cx, global, JSProto_GeneratorFunction)) {
return false; // needed by function*() {}
}
if (!EnsureConstructor(cx, global, JSProto_AsyncFunction)) {
return false; // needed by async function() {}
}
if (!EnsureConstructor(cx, global, JSProto_AsyncGeneratorFunction)) {
return false; // needed by async function*() {}
}
if (kind == ParseTaskKind::Module &&
!GlobalObject::ensureModulePrototypesCreated(cx, global)) {
return false;
}
return true;
}
class MOZ_RAII AutoSetCreatedForHelperThread {
Zone* zone;
public:
explicit AutoSetCreatedForHelperThread(JSObject* global)
: zone(global->zone()) {
zone->setCreatedForHelperThread();
}
void forget() { zone = nullptr; }
~AutoSetCreatedForHelperThread() {
if (zone) {
zone->clearUsedByHelperThread();
}
}
};
static JSObject* CreateGlobalForOffThreadParse(JSContext* cx,
const gc::AutoSuppressGC& nogc) {
JS::Realm* currentRealm = cx->realm();
JS::RealmOptions realmOptions(currentRealm->creationOptions(),
currentRealm->behaviors());
auto& creationOptions = realmOptions.creationOptions();
creationOptions.setInvisibleToDebugger(true)
.setMergeable(true)
.setNewCompartmentAndZone();
// Don't falsely inherit the host's global trace hook.
creationOptions.setTrace(nullptr);
return JS_NewGlobalObject(cx, &parseTaskGlobalClass,
currentRealm->principals(),
JS::DontFireOnNewGlobalHook, realmOptions);
}
static bool QueueOffThreadParseTask(JSContext* cx, UniquePtr<ParseTask> task) {
AutoLockHelperThreadState lock;
bool mustWait = OffThreadParsingMustWaitForGC(cx->runtime());
// Append null first, then overwrite it on success, to avoid having two
// |task| pointers (one ostensibly "unique") in flight at once. (Obviously it
// would be better if these vectors stored unique pointers themselves....)
auto& queue = mustWait ? HelperThreadState().parseWaitingOnGC(lock)
: HelperThreadState().parseWorklist(lock);
if (!queue.append(nullptr)) {
ReportOutOfMemory(cx);
return false;
}
queue.back() = task.release();
if (!mustWait) {
queue.back()->activate(cx->runtime());
HelperThreadState().notifyOne(GlobalHelperThreadState::PRODUCER, lock);
}
return true;
}
static bool StartOffThreadParseTask(JSContext* cx, UniquePtr<ParseTask> task,
const ReadOnlyCompileOptions& options) {
// Suppress GC so that calls below do not trigger a new incremental GC
// which could require barriers on the atoms zone.
gc::AutoSuppressGC nogc(cx);
gc::AutoSuppressNurseryCellAlloc noNurseryAlloc(cx);
AutoSuppressAllocationMetadataBuilder suppressMetadata(cx);
JSObject* global = CreateGlobalForOffThreadParse(cx, nogc);
if (!global) {
return false;
}
// Mark the global's zone as created for a helper thread. This prevents it
// from being collected until clearUsedByHelperThread() is called after
// parsing is complete. If this function exits due to error this state is
// cleared automatically.
AutoSetCreatedForHelperThread createdForHelper(global);
if (!task->init(cx, options, global)) {
return false;
}
if (!QueueOffThreadParseTask(cx, std::move(task))) {
return false;
}
createdForHelper.forget();
return true;
}
template <typename Unit>
static bool StartOffThreadParseScriptInternal(
JSContext* cx, const ReadOnlyCompileOptions& options,
JS::SourceText<Unit>& srcBuf, JS::OffThreadCompileCallback callback,
void* callbackData) {
auto task = cx->make_unique<ScriptParseTask<Unit>>(cx, srcBuf, callback,
callbackData);
if (!task) {
return false;
}
return StartOffThreadParseTask(cx, std::move(task), options);
}
bool js::StartOffThreadParseScript(JSContext* cx,
const ReadOnlyCompileOptions& options,
JS::SourceText<char16_t>& srcBuf,
JS::OffThreadCompileCallback callback,
void* callbackData) {
return StartOffThreadParseScriptInternal(cx, options, srcBuf, callback,
callbackData);
}
bool js::StartOffThreadParseScript(JSContext* cx,
const ReadOnlyCompileOptions& options,
JS::SourceText<Utf8Unit>& srcBuf,
JS::OffThreadCompileCallback callback,
void* callbackData) {
return StartOffThreadParseScriptInternal(cx, options, srcBuf, callback,
callbackData);
}
template <typename Unit>
static bool StartOffThreadParseModuleInternal(
JSContext* cx, const ReadOnlyCompileOptions& options,
JS::SourceText<Unit>& srcBuf, JS::OffThreadCompileCallback callback,
void* callbackData) {
auto task = cx->make_unique<ModuleParseTask<Unit>>(cx, srcBuf, callback,
callbackData);