Debian Codegraph @

js/src/vm/Runtime.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #ifndef vm_Runtime_h
8 #define vm_Runtime_h
9
10 #include "mozilla/Assertions.h" // MOZ_ASSERT
11 #include "mozilla/Atomics.h"
12 #include "mozilla/Attributes.h"
13 #include "mozilla/DoublyLinkedList.h"
14 #include "mozilla/LinkedList.h"
15 #include "mozilla/Maybe.h"
16 #include "mozilla/MemoryReporting.h"
17 #include "mozilla/TimeStamp.h"
18 #include "mozilla/XorShift128PlusRNG.h"
19
20 #include <algorithm>
21 #include <utility>
22
23 #ifdef JS_HAS_INTL_API
24 # include "builtin/intl/SharedIntlData.h"
25 #endif
26 #include "frontend/ScriptIndex.h"
27 #include "gc/GCRuntime.h"
28 #include "js/AllocationRecording.h"
29 #include "js/BuildId.h" // JS::BuildIdOp
30 #include "js/Context.h"
31 #include "js/experimental/CTypes.h" // JS::CTypesActivityCallback
32 #include "js/friend/StackLimits.h" // js::ReportOverRecursed
33 #include "js/friend/UsageStatistics.h" // JSAccumulateTelemetryDataCallback
34 #include "js/GCVector.h"
35 #include "js/HashTable.h"
36 #include "js/Initialization.h"
37 #include "js/MemoryCallbacks.h"
38 #include "js/Modules.h" // JS::Module{DynamicImport,Metadata,Resolve}Hook
39 #include "js/ScriptPrivate.h"
40 #include "js/shadow/Zone.h"
41 #include "js/ShadowRealmCallbacks.h"
42 #include "js/Stack.h"
43 #include "js/StreamConsumer.h"
44 #include "js/Symbol.h"
45 #include "js/UniquePtr.h"
46 #include "js/Utility.h"
47 #include "js/WaitCallbacks.h"
48 #include "js/Warnings.h" // JS::WarningReporter
49 #include "js/Zone.h"
50 #include "vm/Caches.h" // js::RuntimeCaches
51 #include "vm/CodeCoverage.h"
52 #include "vm/GeckoProfiler.h"
53 #include "vm/InvalidatingFuse.h"
54 #include "vm/JSScript.h"
55 #include "vm/Logging.h"
56 #include "vm/OffThreadPromiseRuntimeState.h" // js::OffThreadPromiseRuntimeState
57 #include "vm/SharedScriptDataTableHolder.h" // js::SharedScriptDataTableHolder
58 #include "vm/Stack.h"
59 #include "wasm/WasmTypeDecls.h"
60
61 struct JSAtomState;
62 struct JSClass;
63 struct JSErrorInterceptor;
64 struct JSWrapObjectCallbacks;
65
66 namespace js {
67
68 class AutoAssertNoContentJS;
69 class Debugger;
70 class EnterDebuggeeNoExecute;
71 class FrontendContext;
72 class PlainObject;
73 class StaticStrings;
74
75 } // namespace js
76
77 struct DtoaState;
78 struct JSLocaleCallbacks;
79
80 #ifdef JS_SIMULATOR_ARM64
81 namespace vixl {
82 class Simulator;
83 }
84 #endif
85
86 namespace js {
87
88 extern MOZ_COLD void ReportOutOfMemory(JSContext* cx);
89 extern MOZ_COLD void ReportAllocationOverflow(JSContext* maybecx);
90 extern MOZ_COLD void ReportAllocationOverflow(FrontendContext* fc);
91 extern MOZ_COLD void ReportOversizedAllocation(JSContext* cx,
92 const unsigned errorNumber);
93
94 class Activation;
95 class ActivationIterator;
96 class Shape;
97 class SourceHook;
98
99 namespace jit {
100 class JitRuntime;
101 class JitActivation;
102 struct PcScriptCache;
103 class CompileRuntime;
104
105 #ifdef JS_SIMULATOR_ARM64
106 using vixl::Simulator;
107 #elif defined(JS_SIMULATOR)
108 class Simulator;
109 #endif
110 } // namespace jit
111
112 namespace frontend {
113 struct CompilationInput;
114 struct CompilationStencil;
115 } // namespace frontend
116
117 // [SMDOC] JS Engine Threading
118 //
119 // Threads interacting with a runtime are divided into two categories:
120 //
121 // - The main thread is capable of running JS. There's at most one main thread
122 // per runtime.
123 //
124 // - Helper threads do not run JS, and are controlled or triggered by activity
125 // on the main thread (or main threads, since all runtimes in a process share
126 // helper threads). Helper threads may have exclusive access to zones created
127 // for them, for parsing and similar tasks, but their activities do not cause
128 // observable changes in script behaviors. Activity on helper threads may be
129 // referred to as happening 'off thread' or on a background thread in some
130 // parts of the VM.
131
132 } /* namespace js */
133
134 namespace JS {
135 struct RuntimeSizes;
136 } // namespace JS
137
138 namespace js {
139
140 /*
141 * Storage for well-known symbols. It's a separate struct from the Runtime so
142 * that it can be shared across multiple runtimes. As in JSAtomState, each
143 * field is a smart pointer that's immutable once initialized.
144 * `rt->wellKnownSymbols->iterator` is convertible to Handle<Symbol*>.
145 *
146 * Well-known symbols are never GC'd. The description() of each well-known
147 * symbol is a permanent atom.
148 */
149 struct WellKnownSymbols {
150 #define DECLARE_SYMBOL(name) ImmutableTenuredPtr<JS::Symbol*> name;
151 JS_FOR_EACH_WELL_KNOWN_SYMBOL(DECLARE_SYMBOL)
152 #undef DECLARE_SYMBOL
153
154 const ImmutableTenuredPtr<JS::Symbol*>& get(size_t u) const {
155 MOZ_ASSERT(u < JS::WellKnownSymbolLimit);
156 const ImmutableTenuredPtr<JS::Symbol*>* symbols =
157 reinterpret_cast<const ImmutableTenuredPtr<JS::Symbol*>*>(this);
158 return symbols[u];
159 }
160
161 const ImmutableTenuredPtr<JS::Symbol*>& get(JS::SymbolCode code) const {
162 return get(size_t(code));
163 }
164
165 WellKnownSymbols() = default;
166 WellKnownSymbols(const WellKnownSymbols&) = delete;
167 WellKnownSymbols& operator=(const WellKnownSymbols&) = delete;
168 };
169
170 // There are several coarse locks in the enum below. These may be either
171 // per-runtime or per-process. When acquiring more than one of these locks,
172 // the acquisition must be done in the order below to avoid deadlocks.
173 enum RuntimeLock { HelperThreadStateLock, GCLock };
174
175 inline bool CanUseExtraThreads() {
176 extern bool gCanUseExtraThreads;
177 return gCanUseExtraThreads;
178 }
179
180 void DisableExtraThreads();
181
182 using ScriptAndCountsVector = GCVector<ScriptAndCounts, 0, SystemAllocPolicy>;
183
184 class AutoLockScriptData;
185
186 // Self-hosted lazy functions do not maintain a BaseScript as we can clone from
187 // the copy in the self-hosting zone. To allow these functions to be called by
188 // the JITs, we need a minimal script object. There is one instance per runtime.
189 struct SelfHostedLazyScript {
190 SelfHostedLazyScript() = default;
191
192 // Pointer to interpreter trampoline. This field is stored at same location as
193 // in BaseScript::jitCodeRaw_.
194 uint8_t* jitCodeRaw_ = nullptr;
195
196 // Warm-up count of zero. This field is stored at the same offset as
197 // BaseScript::warmUpData_.
198 ScriptWarmUpData warmUpData_ = {};
199
200 static constexpr size_t offsetOfJitCodeRaw() {
201 return offsetof(SelfHostedLazyScript, jitCodeRaw_);
202 }
203 static constexpr size_t offsetOfWarmUpData() {
204 return offsetof(SelfHostedLazyScript, warmUpData_);
205 }
206 };
207
208 // An interface for reporting telemetry from within SpiderMonkey. Reporting data
209 // to this interface will forward it to the embedding if a telemetry callback
210 // was registered. It is the embedding's responsibility to store and/or combine
211 // repeated samples for each metric.
212 class Metrics {
213 private:
214 JSRuntime* rt_;
215
216 public:
217 explicit Metrics(JSRuntime* rt) : rt_(rt) {}
218
219 // Records a TimeDuration metric. These are converted to integers when being
220 // recorded so choose an appropriate scale. In the future these will be Glean
221 // Timing Distribution metrics.
222 struct TimeDuration_S {
223 using SourceType = mozilla::TimeDuration;
224 static uint32_t convert(SourceType td) { return uint32_t(td.ToSeconds()); }
225 };
226 struct TimeDuration_MS {
227 using SourceType = mozilla::TimeDuration;
228 static uint32_t convert(SourceType td) {
229 return uint32_t(td.ToMilliseconds());
230 }
231 };
232 struct TimeDuration_US {
233 using SourceType = mozilla::TimeDuration;
234 static uint32_t convert(SourceType td) {
235 return uint32_t(td.ToMicroseconds());
236 }
237 };
238
239 // Record a metric in bytes. In the future these will be Glean Memory
240 // Distribution metrics.
241 struct MemoryDistribution {
242 using SourceType = size_t;
243 static uint32_t convert(SourceType sz) {
244 return static_cast<uint32_t>(std::min(sz, size_t(UINT32_MAX)));
245 }
246 };
247
248 // Record a metric for a quanity of items. This doesn't currently have a Glean
249 // analogue and we avoid using MemoryDistribution directly to avoid confusion
250 // about units.
251 using QuantityDistribution = MemoryDistribution;
252
253 // Record the distribution of boolean values. In the future this will be a
254 // Glean Rate metric.
255 struct Boolean {
256 using SourceType = bool;
257 static uint32_t convert(SourceType sample) {
258 return static_cast<uint32_t>(sample);
259 }
260 };
261
262 // Record the distribution of an enumeration value. This records integer
263 // values so take care not to redefine the value of enum values. In the
264 // future, these should become Glean Labeled Counter metrics.
265 struct Enumeration {
266 using SourceType = unsigned int;
267 static uint32_t convert(SourceType sample) {
268 MOZ_ASSERT(sample <= 100);
269 return static_cast<uint32_t>(sample);
270 }
271 };
272
273 // Record a percentage distribution in the range 0 to 100. This takes a double
274 // and converts it to an integer. In the future, this will be a Glean Custom
275 // Distribution unless they add a better match.
276 struct Percentage {
277 using SourceType = double;
278 static uint32_t convert(SourceType sample) {
279 MOZ_ASSERT(sample >= 0.0 && sample <= 100.0);
280 return static_cast<uint32_t>(sample);
281 }
282 };
283
284 // Record an unsigned integer.
285 struct Integer {
286 using SourceType = uint32_t;
287 static uint32_t convert(SourceType sample) { return sample; }
288 };
289
290 inline void addTelemetry(JSMetric id, uint32_t sample);
291
292 #define DECLARE_METRIC_HELPER(NAME, TY) \
293 void NAME(TY::SourceType sample) { \
294 addTelemetry(JSMetric::NAME, TY::convert(sample)); \
295 }
296 FOR_EACH_JS_METRIC(DECLARE_METRIC_HELPER)
297 #undef DECLARE_METRIC_HELPER
298 };
299
300 class HasSeenObjectEmulateUndefinedFuse : public js::InvalidatingRuntimeFuse {
301 virtual const char* name() override {
302 return "HasSeenObjectEmulateUndefinedFuse";
303 }
304 virtual bool checkInvariant(JSContext* cx) override {
305 // Without traversing the GC heap I don't think it's possible to assert
306 // this invariant directly.
307 return true;
308 }
309
310 public:
311 virtual void popFuse(JSContext* cx) override;
312 };
313
314 class HasSeenArrayExceedsInt32LengthFuse : public js::InvalidatingRuntimeFuse {
315 virtual const char* name() override {
316 return "HasSeenArrayExceedsInt32LengthFuse";
317 }
318
319 virtual bool checkInvariant(JSContext* cx) override { return true; }
320
321 public:
322 virtual void popFuse(JSContext* cx) override;
323 };
324
325 } // namespace js
326
327 struct JSRuntime {
328 private:
329 friend class js::Activation;
330 friend class js::ActivationIterator;
331 friend class js::jit::JitActivation;
332 friend class js::jit::CompileRuntime;
333
334 /* Space for interpreter frames. */
335 js::MainThreadData<js::InterpreterStack> interpreterStack_;
336
337 #ifdef ENABLE_PORTABLE_BASELINE_INTERP
338 /* Space for portable baseline interpreter frames. */
339 js::MainThreadData<js::PortableBaselineStack> portableBaselineStack_;
340 #endif
341
342 public:
343 js::InterpreterStack& interpreterStack() { return interpreterStack_.ref(); }
344 #ifdef ENABLE_PORTABLE_BASELINE_INTERP
345 js::PortableBaselineStack& portableBaselineStack() {
346 return portableBaselineStack_.ref();
347 }
348 #endif
349
350 /*
351 * If non-null, another runtime guaranteed to outlive this one and whose
352 * permanent data may be used by this one where possible.
353 */
354 JSRuntime* const parentRuntime;
355
356 bool isMainRuntime() const { return !parentRuntime; }
357
358 #ifdef DEBUG
359 /* The number of child runtimes that have this runtime as their parent. */
360 mozilla::Atomic<size_t> childRuntimeCount;
361
362 class AutoUpdateChildRuntimeCount {
363 JSRuntime* parent_;
364
365 public:
366 explicit AutoUpdateChildRuntimeCount(JSRuntime* parent) : parent_(parent) {
367 if (parent_) {
368 parent_->childRuntimeCount++;
369 }
370 }
371
372 ~AutoUpdateChildRuntimeCount() {
373 if (parent_) {
374 parent_->childRuntimeCount--;
375 }
376 }
377 };
378
379 AutoUpdateChildRuntimeCount updateChildRuntimeCount;
380 #endif
381
382 private:
383 #ifdef DEBUG
384 js::WriteOnceData<bool> initialized_;
385 #endif
386
387 // The JSContext* for the runtime's main thread. Immutable after this is set
388 // in JSRuntime::init.
389 JSContext* mainContext_;
390
391 public:
392 JSContext* mainContextFromAnyThread() const { return mainContext_; }
393 const void* addressOfMainContext() { return &mainContext_; }
394 js::Fprinter parserWatcherFile;
395
396 inline JSContext* mainContextFromOwnThread();
397
398 js::Metrics metrics() { return js::Metrics(this); }
399
400 /*
401 * The start of the range stored in the profiler sample buffer, as measured
402 * after the most recent sample.
403 * All JitcodeGlobalTable entries referenced from a given sample are
404 * assigned the buffer position of the START of the sample. The buffer
405 * entries that reference the JitcodeGlobalTable entries will only ever be
406 * read from the buffer while the entire sample is still inside the buffer;
407 * if some buffer entries at the start of the sample have left the buffer,
408 * the entire sample will be considered inaccessible.
409 * This means that, once profilerSampleBufferRangeStart_ advances beyond
410 * the sample position that's stored on a JitcodeGlobalTable entry, the
411 * buffer entries that reference this JitcodeGlobalTable entry will be
412 * considered inaccessible, and those JitcodeGlobalTable entry can be
413 * disposed of.
414 */
415 mozilla::Atomic<uint64_t, mozilla::ReleaseAcquire>
416 profilerSampleBufferRangeStart_;
417
418 mozilla::Maybe<uint64_t> profilerSampleBufferRangeStart() {
419 if (beingDestroyed_ || !geckoProfiler().enabled()) {
420 return mozilla::Nothing();
421 }
422 uint64_t rangeStart = profilerSampleBufferRangeStart_;
423 return mozilla::Some(rangeStart);
424 }
425 void setProfilerSampleBufferRangeStart(uint64_t rangeStart) {
426 profilerSampleBufferRangeStart_ = rangeStart;
427 }
428
429 /* Call this to accumulate telemetry data. May be called from any thread; the
430 * embedder is responsible for locking. */
431 JSAccumulateTelemetryDataCallback telemetryCallback;
432
433 /* Call this to accumulate use counter data. */
434 js::MainThreadData<JSSetUseCounterCallback> useCounterCallback;
435
436 public:
437 // Accumulates data for Firefox telemetry.
438 void addTelemetry(JSMetric id, uint32_t sample);
439
440 void setTelemetryCallback(JSRuntime* rt,
441 JSAccumulateTelemetryDataCallback callback);
442
443 // Sets the use counter for a specific feature, measuring the presence or
444 // absence of usage of a feature on a specific web page and document which
445 // the passed JSObject belongs to.
446 void setUseCounter(JSObject* obj, JSUseCounter counter);
447
448 void setUseCounterCallback(JSRuntime* rt, JSSetUseCounterCallback callback);
449
450 public:
451 js::UnprotectedData<js::OffThreadPromiseRuntimeState> offThreadPromiseState;
452 js::UnprotectedData<JS::ConsumeStreamCallback> consumeStreamCallback;
453 js::UnprotectedData<JS::ReportStreamErrorCallback> reportStreamErrorCallback;
454
455 bool getHostDefinedData(JSContext* cx,
456 JS::MutableHandle<JSObject*> data) const;
457
458 bool enqueuePromiseJob(JSContext* cx, js::HandleFunction job,
459 js::HandleObject promise,
460 js::HandleObject hostDefinedData);
461 void addUnhandledRejectedPromise(JSContext* cx, js::HandleObject promise);
462 void removeUnhandledRejectedPromise(JSContext* cx, js::HandleObject promise);
463
464 /* Had an out-of-memory error which did not populate an exception. */
465 mozilla::Atomic<bool, mozilla::SequentiallyConsistent> hadOutOfMemory;
466
467 /*
468 * Allow relazifying functions in compartments that are active. This is
469 * only used by the relazifyFunctions() testing function.
470 */
471 js::MainThreadData<bool> allowRelazificationForTesting;
472
473 /* Zone destroy callback. */
474 js::MainThreadData<JSDestroyZoneCallback> destroyZoneCallback;
475
476 /* Compartment destroy callback. */
477 js::MainThreadData<JSDestroyCompartmentCallback> destroyCompartmentCallback;
478
479 /* Compartment memory reporting callback. */
480 js::MainThreadData<JSSizeOfIncludingThisCompartmentCallback>
481 sizeOfIncludingThisCompartmentCallback;
482
483 /* Callback for creating ubi::Nodes representing DOM node objects. Set by
484 * JS::ubi::SetConstructUbiNodeForDOMObjectCallback. Refer to
485 * js/public/UbiNode.h.
486 */
487 void (*constructUbiNodeForDOMObjectCallback)(void*, JSObject*) = nullptr;
488
489 /* Realm destroy callback. */
490 js::MainThreadData<JS::DestroyRealmCallback> destroyRealmCallback;
491
492 /* Call this to get the name of a realm. */
493 js::MainThreadData<JS::RealmNameCallback> realmNameCallback;
494
495 js::MainThreadData<mozilla::UniquePtr<js::SourceHook>> sourceHook;
496
497 js::MainThreadData<const JSSecurityCallbacks*> securityCallbacks;
498 js::MainThreadData<const js::DOMCallbacks*> DOMcallbacks;
499 js::MainThreadData<JSDestroyPrincipalsOp> destroyPrincipals;
500 js::MainThreadData<JSReadPrincipalsOp> readPrincipals;
501
502 js::MainThreadData<JS::EnsureCanAddPrivateElementOp> canAddPrivateElement;
503
504 /* Optional warning reporter. */
505 js::MainThreadData<JS::WarningReporter> warningReporter;
506
507 // Lazy self-hosted functions use a shared SelfHostedLazyScript instance
508 // instead instead of a BaseScript. This contains the minimal pointers to
509 // trampolines for the scripts to support direct jitCodeRaw calls.
510 js::UnprotectedData<js::SelfHostedLazyScript> selfHostedLazyScript;
511
512 private:
513 // The self-hosted JS code is compiled as a Stencil which is then attached to
514 // the Runtime. This is used to instantiate functions into realms on demand.
515 js::WriteOnceData<js::frontend::CompilationInput*> selfHostStencilInput_;
516 js::WriteOnceData<js::frontend::CompilationStencil*> selfHostStencil_;
517
518 public:
519 // The self-hosted stencil is immutable once attached to the runtime, so
520 // worker runtimes directly use the stencil on the parent runtime.
521 js::frontend::CompilationInput& selfHostStencilInput() {
522 MOZ_ASSERT(hasSelfHostStencil());
523 return *selfHostStencilInput_.ref();
524 }
525 js::frontend::CompilationStencil& selfHostStencil() {
526 MOZ_ASSERT(hasSelfHostStencil());
527 return *selfHostStencil_.ref();
528 }
529 bool hasSelfHostStencil() const { return bool(selfHostStencil_.ref()); }
530
531 // A mapping from the name of self-hosted function to a ScriptIndex range of
532 // the function and inner-functions within the self-hosted stencil.
533 js::MainThreadData<
534 JS::GCHashMap<js::PreBarriered<JSAtom*>, js::frontend::ScriptIndexRange,
535 js::DefaultHasher<JSAtom*>, js::SystemAllocPolicy>>
536 selfHostScriptMap;
537 // A cache for a self-hosted function's JitCode (managed through a
538 // BaselineScript) keyed by script index.
539 js::MainThreadData<
540 js::GCHashMap<js::PreBarriered<JSAtom*>, js::jit::BaselineScript*,
541 js::DefaultHasher<JSAtom*>, js::SystemAllocPolicy>>
542 selfHostJitCache;
543
544 void clearSelfHostedJitCache();
545
546 private:
547 /* Gecko profiling metadata */
548 js::UnprotectedData<js::GeckoProfilerRuntime> geckoProfiler_;
549
550 public:
551 js::GeckoProfilerRuntime& geckoProfiler() { return geckoProfiler_.ref(); }
552
553 // Heap GC roots for PersistentRooted pointers.
554 js::MainThreadData<mozilla::EnumeratedArray<
555 JS::RootKind, mozilla::LinkedList<js::PersistentRootedBase>,
556 size_t(JS::RootKind::Limit)>>
557 heapRoots;
558
559 void tracePersistentRoots(JSTracer* trc);
560 void finishPersistentRoots();
561
562 void finishRoots();
563
564 private:
565 js::UnprotectedData<const JSPrincipals*> trustedPrincipals_;
566
567 public:
568 void setTrustedPrincipals(const JSPrincipals* p) { trustedPrincipals_ = p; }
569 const JSPrincipals* trustedPrincipals() const { return trustedPrincipals_; }
570
571 js::MainThreadData<const JSWrapObjectCallbacks*> wrapObjectCallbacks;
572 js::MainThreadData<js::PreserveWrapperCallback> preserveWrapperCallback;
573 js::MainThreadData<js::HasReleasedWrapperCallback> hasReleasedWrapperCallback;
574
575 js::MainThreadData<js::ScriptEnvironmentPreparer*> scriptEnvironmentPreparer;
576
577 js::MainThreadData<JS::CTypesActivityCallback> ctypesActivityCallback;
578
579 private:
580 js::WriteOnceData<const JSClass*> windowProxyClass_;
581
582 public:
583 const JSClass* maybeWindowProxyClass() const { return windowProxyClass_; }
584 void setWindowProxyClass(const JSClass* clasp) { windowProxyClass_ = clasp; }
585
586 private:
587 // List of non-ephemeron weak containers to sweep during
588 // beginSweepingSweepGroup.
589 js::MainThreadData<mozilla::LinkedList<JS::detail::WeakCacheBase>>
590 weakCaches_;
591
592 public:
593 mozilla::LinkedList<JS::detail::WeakCacheBase>& weakCaches() {
594 return weakCaches_.ref();
595 }
596 void registerWeakCache(JS::detail::WeakCacheBase* cachep) {
597 weakCaches().insertBack(cachep);
598 }
599
600 template <typename T>
601 struct GlobalObjectWatchersLinkAccess {
602 static mozilla::DoublyLinkedListElement<T>& Get(T* aThis) {
603 return aThis->onNewGlobalObjectWatchersLink;
604 }
605 };
606
607 template <typename T>
608 struct GarbageCollectionWatchersLinkAccess {
609 static mozilla::DoublyLinkedListElement<T>& Get(T* aThis) {
610 return aThis->onGarbageCollectionWatchersLink;
611 }
612 };
613
614 using OnNewGlobalWatchersList =
615 mozilla::DoublyLinkedList<js::Debugger,
616 GlobalObjectWatchersLinkAccess<js::Debugger>>;
617 using OnGarbageCollectionWatchersList = mozilla::DoublyLinkedList<
618 js::Debugger, GarbageCollectionWatchersLinkAccess<js::Debugger>>;
619
620 private:
621 /*
622 * List of all enabled Debuggers that have onNewGlobalObject handler
623 * methods established.
624 */
625 js::MainThreadData<OnNewGlobalWatchersList> onNewGlobalObjectWatchers_;
626
627 /*
628 * List of all enabled Debuggers that have onGarbageCollection handler
629 * methods established.
630 */
631 js::MainThreadData<OnGarbageCollectionWatchersList>
632 onGarbageCollectionWatchers_;
633
634 public:
635 OnNewGlobalWatchersList& onNewGlobalObjectWatchers() {
636 return onNewGlobalObjectWatchers_.ref();
637 }
638
639 OnGarbageCollectionWatchersList& onGarbageCollectionWatchers() {
640 return onGarbageCollectionWatchers_.ref();
641 }
642
643 private:
644 /* Linked list of all Debugger objects in the runtime. */
645 js::MainThreadData<mozilla::LinkedList<js::Debugger>> debuggerList_;
646
647 public:
648 mozilla::LinkedList<js::Debugger>& debuggerList() {
649 return debuggerList_.ref();
650 }
651
652 public:
653 JS::HeapState heapState() const { return gc.heapState(); }
654
655 // How many realms there are across all zones. This number includes
656 // off-thread context realms, so it isn't necessarily equal to the
657 // number of realms visited by RealmsIter.
658 js::MainThreadData<size_t> numRealms;
659
660 // The Gecko Profiler may want to sample the allocations happening across the
661 // browser. This callback can be registered to record the allocation.
662 js::MainThreadData<JS::RecordAllocationsCallback> recordAllocationCallback;
663 js::MainThreadData<double> allocationSamplingProbability;
664
665 private:
666 // Number of debuggee realms in the runtime.
667 js::MainThreadData<size_t> numDebuggeeRealms_;
668
669 // Number of debuggee realms in the runtime observing code coverage.
670 js::MainThreadData<size_t> numDebuggeeRealmsObservingCoverage_;
671
672 public:
673 void incrementNumDebuggeeRealms();
674 void decrementNumDebuggeeRealms();
675
676 size_t numDebuggeeRealms() const { return numDebuggeeRealms_; }
677
678 void incrementNumDebuggeeRealmsObservingCoverage();
679 void decrementNumDebuggeeRealmsObservingCoverage();
680
681 void startRecordingAllocations(double probability,
682 JS::RecordAllocationsCallback callback);
683 void stopRecordingAllocations();
684 void ensureRealmIsRecordingAllocations(JS::Handle<js::GlobalObject*> global);
685
686 /* Locale-specific callbacks for string conversion. */
687 js::MainThreadData<const JSLocaleCallbacks*> localeCallbacks;
688
689 /* Default locale for Internationalization API */
690 js::MainThreadData<js::UniqueChars> defaultLocale;
691
692 /* If true, new scripts must be created with PC counter information. */
693 js::MainThreadOrIonCompileData<bool> profilingScripts;
694
695 /* Strong references on scripts held for PCCount profiling API. */
696 js::MainThreadData<JS::PersistentRooted<js::ScriptAndCountsVector>*>
697 scriptAndCountsVector;
698
699 using RootedPlainObjVec = JS::PersistentRooted<
700 JS::GCVector<js::PlainObject*, 0, js::SystemAllocPolicy>>;
701 js::MainThreadData<js::UniquePtr<RootedPlainObjVec>> watchtowerTestingLog;
702
703 private:
704 /* Code coverage output. */
705 js::UnprotectedData<js::coverage::LCovRuntime> lcovOutput_;
706
707 /* Functions to call, together with data, when the runtime is being torn down.
708 */
709 js::MainThreadData<mozilla::Vector<std::pair<void (*)(void*), void*>, 4>>
710 cleanupClosures;
711
712 public:
713 js::coverage::LCovRuntime& lcovOutput() { return lcovOutput_.ref(); }
714
715 /* Register a cleanup function to be called during runtime shutdown. Do not
716 * depend on the ordering of cleanup calls. */
717 bool atExit(void (*function)(void*), void* data) {
718 return cleanupClosures.ref().append(std::pair(function, data));
719 }
720
721 private:
722 js::UnprotectedData<js::jit::JitRuntime*> jitRuntime_;
723
724 public:
725 mozilla::Maybe<js::frontend::ScriptIndexRange> getSelfHostedScriptIndexRange(
726 js::PropertyName* name);
727
728 [[nodiscard]] bool createJitRuntime(JSContext* cx);
729 js::jit::JitRuntime* jitRuntime() const { return jitRuntime_.ref(); }
730 bool hasJitRuntime() const { return !!jitRuntime_; }
731
732 private:
733 // Used to generate random keys for hash tables.
734 mozilla::Maybe<mozilla::non_crypto::XorShift128PlusRNG> randomKeyGenerator_;
735 mozilla::non_crypto::XorShift128PlusRNG& randomKeyGenerator();
736
737 // Used to generate random hash codes for symbols.
738 mozilla::Maybe<mozilla::non_crypto::XorShift128PlusRNG>
739 randomHashCodeGenerator_;
740
741 public:
742 mozilla::HashCodeScrambler randomHashCodeScrambler();
743 mozilla::non_crypto::XorShift128PlusRNG forkRandomKeyGenerator();
744
745 js::HashNumber randomHashCode();
746
747 //-------------------------------------------------------------------------
748 // Self-hosting support
749 //-------------------------------------------------------------------------
750
751 bool hasInitializedSelfHosting() const { return hasSelfHostStencil(); }
752
753 bool initSelfHostingStencil(JSContext* cx, JS::SelfHostedCache xdrCache,
754 JS::SelfHostedWriter xdrWriter);
755 bool initSelfHostingFromStencil(JSContext* cx);
756 void finishSelfHosting();
757 void traceSelfHostingStencil(JSTracer* trc);
758 js::GeneratorKind getSelfHostedFunctionGeneratorKind(js::PropertyName* name);
759 bool delazifySelfHostedFunction(JSContext* cx,
760 js::Handle<js::PropertyName*> name,
761 js::Handle<JSFunction*> targetFun);
762 bool getSelfHostedValue(JSContext* cx, js::Handle<js::PropertyName*> name,
763 js::MutableHandleValue vp);
764 void assertSelfHostedFunctionHasCanonicalName(
765 JS::Handle<js::PropertyName*> name);
766
767 private:
768 void setSelfHostingStencil(
769 JS::MutableHandle<js::UniquePtr<js::frontend::CompilationInput>> input,
770 RefPtr<js::frontend::CompilationStencil>&& stencil);
771
772 //-------------------------------------------------------------------------
773 // Locale information
774 //-------------------------------------------------------------------------
775
776 public:
777 /*
778 * Set the default locale for the ECMAScript Internationalization API
779 * (Intl.Collator, Intl.NumberFormat, Intl.DateTimeFormat).
780 * Note that the Internationalization API encourages clients to
781 * specify their own locales.
782 * The locale string remains owned by the caller.
783 */
784 bool setDefaultLocale(const char* locale);
785
786 /* Reset the default locale to OS defaults. */
787 void resetDefaultLocale();
788
789 /* Gets current default locale. String remains owned by context. */
790 const char* getDefaultLocale();
791
792 /* Garbage collector state. */
793 js::gc::GCRuntime gc;
794
795 /* Garbage collector state has been successfully initialized. */
796
797 bool hasZealMode(js::gc::ZealMode mode) { return gc.hasZealMode(mode); }
798
799 void lockGC() { gc.lockGC(); }
800
801 void unlockGC() { gc.unlockGC(); }
802
803 js::WriteOnceData<js::PropertyName*> emptyString;
804
805 public:
806 JS::GCContext* gcContext() { return &gc.mainThreadContext.ref(); }
807
808 #if !JS_HAS_INTL_API
809 /* Number localization, used by jsnum.cpp. */
810 js::WriteOnceData<const char*> thousandsSeparator;
811 js::WriteOnceData<const char*> decimalSeparator;
812 js::WriteOnceData<const char*> numGrouping;
813 #endif
814
815 private:
816 js::WriteOnceData<bool> beingDestroyed_;
817
818 public:
819 bool isBeingDestroyed() const { return beingDestroyed_; }
820
821 private:
822 bool allowContentJS_;
823
824 public:
825 bool allowContentJS() const { return allowContentJS_; }
826
827 friend class js::AutoAssertNoContentJS;
828
829 private:
830 // Table of all atoms other than those in permanentAtoms and staticStrings.
831 js::WriteOnceData<js::AtomsTable*> atoms_;
832
833 // Set of all live symbols produced by Symbol.for(). All such symbols are
834 // allocated in the atoms zone. Reading or writing the symbol registry
835 // can only be done from the main thread.
836 js::MainThreadOrGCTaskData<js::SymbolRegistry> symbolRegistry_;
837
838 js::WriteOnceData<js::FrozenAtomSet*> permanentAtoms_;
839
840 public:
841 bool initializeAtoms(JSContext* cx);
842 void finishAtoms();
843 bool atomsAreFinished() const { return !atoms_; }
844
845 js::AtomsTable* atomsForSweeping() {
846 MOZ_ASSERT(JS::RuntimeHeapIsCollecting());
847 return atoms_;
848 }
849
850 js::AtomsTable& atoms() {
851 MOZ_ASSERT(atoms_);
852 return *atoms_;
853 }
854
855 JS::Zone* atomsZone() {
856 MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(this));
857 return unsafeAtomsZone();
858 }
859 JS::Zone* unsafeAtomsZone() { return gc.atomsZone(); }
860
861 #ifdef DEBUG
862 bool isAtomsZone(const JS::Zone* zone) const {
863 return JS::shadow::Zone::from(zone)->isAtomsZone();
864 }
865 #endif
866
867 bool activeGCInAtomsZone();
868
869 js::SymbolRegistry& symbolRegistry() { return symbolRegistry_.ref(); }
870
871 // Permanent atoms are fixed during initialization of the runtime and are
872 // not modified or collected until the runtime is destroyed. These may be
873 // shared with another, longer living runtime through |parentRuntime| and
874 // can be freely accessed with no locking necessary.
875
876 // Permanent atoms pre-allocated for general use.
877 js::WriteOnceData<js::StaticStrings*> staticStrings;
878
879 // Cached pointers to various permanent property names.
880 js::WriteOnceData<JSAtomState*> commonNames;
881
882 // All permanent atoms in the runtime, other than those in staticStrings.
883 // Access to this does not require a lock because it is frozen and thus
884 // read-only.
885 const js::FrozenAtomSet* permanentAtoms() const {
886 MOZ_ASSERT(permanentAtomsPopulated());
887 return permanentAtoms_.ref();
888 }
889
890 // The permanent atoms table is populated during initialization.
891 bool permanentAtomsPopulated() const { return permanentAtoms_; }
892
893 // Cached well-known symbols (ES6 rev 24 6.1.5.1). Like permanent atoms,
894 // these are shared with the parentRuntime, if any.
895 js::WriteOnceData<js::WellKnownSymbols*> wellKnownSymbols;
896
897 #ifdef JS_HAS_INTL_API
898 /* Shared Intl data for this runtime. */
899 js::MainThreadData<js::intl::SharedIntlData> sharedIntlData;
900
901 void traceSharedIntlData(JSTracer* trc);
902 #endif
903
904 private:
905 js::SharedScriptDataTableHolder scriptDataTableHolder_;
906
907 public:
908 // Returns the runtime's local script data table holder.
909 js::SharedScriptDataTableHolder& scriptDataTableHolder();
910
911 private:
912 static mozilla::Atomic<size_t> liveRuntimesCount;
913
914 public:
915 static bool hasLiveRuntimes() { return liveRuntimesCount > 0; }
916 static bool hasSingleLiveRuntime() { return liveRuntimesCount == 1; }
917
918 explicit JSRuntime(JSRuntime* parentRuntime);
919 ~JSRuntime();
920
921 // destroyRuntime is used instead of a destructor, to ensure the downcast
922 // to JSContext remains valid. The final GC triggered here depends on this.
923 void destroyRuntime();
924
925 bool init(JSContext* cx, uint32_t maxbytes);
926
927 JSRuntime* thisFromCtor() { return this; }
928
929 private:
930 // Number of live SharedArrayBuffer objects, including those in Wasm shared
931 // memories. uint64_t to avoid any risk of overflow.
932 js::MainThreadData<uint64_t> liveSABs;
933
934 public:
935 void incSABCount() {
936 MOZ_RELEASE_ASSERT(liveSABs != UINT64_MAX);
937 liveSABs++;
938 }
939
940 void decSABCount() {
941 MOZ_RELEASE_ASSERT(liveSABs > 0);
942 liveSABs--;
943 }
944
945 bool hasLiveSABs() const { return liveSABs > 0; }
946
947 public:
948 js::MainThreadData<JS::BeforeWaitCallback> beforeWaitCallback;
949 js::MainThreadData<JS::AfterWaitCallback> afterWaitCallback;
950
951 public:
952 void reportAllocationOverflow() {
953 js::ReportAllocationOverflow(static_cast<JSContext*>(nullptr));
954 }
955
956 /*
957 * This should be called after system malloc/calloc/realloc returns nullptr
958 * to try to recove some memory or to report an error. For realloc, the
959 * original pointer must be passed as reallocPtr.
960 *
961 * The function must be called outside the GC lock.
962 */
963 JS_PUBLIC_API void* onOutOfMemory(js::AllocFunction allocator,
964 arena_id_t arena, size_t nbytes,
965 void* reallocPtr = nullptr,
966 JSContext* maybecx = nullptr);
967
968 /* onOutOfMemory but can call OnLargeAllocationFailure. */
969 JS_PUBLIC_API void* onOutOfMemoryCanGC(js::AllocFunction allocator,
970 arena_id_t arena, size_t nbytes,
971 void* reallocPtr = nullptr);
972
973 static const unsigned LARGE_ALLOCATION = 25 * 1024 * 1024;
974
975 void addSizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf,
976 JS::RuntimeSizes* rtSizes);
977
978 private:
979 // Settings for how helper threads can be used.
980 mozilla::Atomic<bool, mozilla::SequentiallyConsistent>
981 offthreadBaselineCompilationEnabled_;
982 mozilla::Atomic<bool, mozilla::SequentiallyConsistent>
983 offthreadIonCompilationEnabled_;
984
985 js::MainThreadData<bool> autoWritableJitCodeActive_;
986
987 public:
988 // Note: these values may be toggled dynamically (in response to about:config
989 // prefs changing).
990 void setOffthreadBaselineCompilationEnabled(bool value) {
991 offthreadBaselineCompilationEnabled_ = value;
992 }
993 bool canUseOffthreadBaselineCompilation() const {
994 return offthreadBaselineCompilationEnabled_;
995 }
996 void setOffthreadIonCompilationEnabled(bool value) {
997 offthreadIonCompilationEnabled_ = value;
998 }
999 void setOffthreadCompilationEnabled(bool value) {
1000 setOffthreadBaselineCompilationEnabled(value);
1001 setOffthreadIonCompilationEnabled(value);
1002 }
1003 bool canUseOffthreadIonCompilation() const {
1004 return offthreadIonCompilationEnabled_;
1005 }
1006 void toggleAutoWritableJitCodeActive(bool b) {
1007 MOZ_ASSERT(autoWritableJitCodeActive_ != b,
1008 "AutoWritableJitCode should not be nested.");
1009 autoWritableJitCodeActive_ = b;
1010 }
1011
1012 /* See comment for JS::SetOutOfMemoryCallback in js/MemoryCallbacks.h. */
1013 js::MainThreadData<JS::OutOfMemoryCallback> oomCallback;
1014 js::MainThreadData<void*> oomCallbackData;
1015
1016 /*
1017 * Debugger.Memory functions like takeCensus use this embedding-provided
1018 * function to assess the size of malloc'd blocks of memory.
1019 */
1020 js::MainThreadData<mozilla::MallocSizeOf> debuggerMallocSizeOf;
1021
1022 /* Last time at which an animation was played for this runtime. */
1023 js::MainThreadData<mozilla::TimeStamp> lastAnimationTime;
1024
1025 private:
1026 /* The stack format for the current runtime. Only valid on non-child
1027 * runtimes. */
1028 mozilla::Atomic<js::StackFormat, mozilla::ReleaseAcquire> stackFormat_;
1029
1030 public:
1031 js::StackFormat stackFormat() const {
1032 const JSRuntime* rt = this;
1033 while (rt->parentRuntime) {
1034 MOZ_ASSERT(rt->stackFormat_ == js::StackFormat::Default);
1035 rt = rt->parentRuntime;
1036 }
1037 MOZ_ASSERT(rt->stackFormat_ != js::StackFormat::Default);
1038 return rt->stackFormat_;
1039 }
1040 void setStackFormat(js::StackFormat format) {
1041 MOZ_ASSERT(!parentRuntime);
1042 MOZ_ASSERT(format != js::StackFormat::Default);
1043 stackFormat_ = format;
1044 }
1045
1046 private:
1047 // Warning: no data should be accessed in these caches from another thread,
1048 // but Ion needs to be able to access addresses inside here, which should be
1049 // safe, as the actual cache lookups will be performed on the main thread
1050 // through jitted code.
1051 js::MainThreadOrIonCompileData<js::RuntimeCaches> caches_;
1052
1053 public:
1054 js::RuntimeCaches& caches() { return caches_.ref(); }
1055
1056 // List of all the live wasm::Instances in the runtime. Equal to the union
1057 // of all instances registered in all JS::Realms. Accessed from watchdog
1058 // threads for purposes of wasm::InterruptRunningCode().
1059 js::ExclusiveData<js::wasm::InstanceVector> wasmInstances;
1060
1061 // A counter used when recording the order in which modules had their
1062 // AsyncEvaluation field set to true. This is used to order queued
1063 // evaluations. This is reset when the last module that was async evaluating
1064 // is finished.
1065 //
1066 // See https://tc39.es/ecma262/#sec-async-module-execution-fulfilled step 10
1067 // for use.
1068 js::MainThreadData<uint32_t> moduleAsyncEvaluatingPostOrder;
1069
1070 // The implementation-defined abstract operation HostResolveImportedModule.
1071 js::MainThreadData<JS::ModuleResolveHook> moduleResolveHook;
1072
1073 // A hook that implements the abstract operations
1074 // HostGetImportMetaProperties and HostFinalizeImportMeta.
1075 js::MainThreadData<JS::ModuleMetadataHook> moduleMetadataHook;
1076
1077 // A hook that implements the abstract operation
1078 // HostImportModuleDynamically. This is also used to enable/disable dynamic
1079 // module import and can accessed by off-thread parsing.
1080 mozilla::Atomic<JS::ModuleDynamicImportHook> moduleDynamicImportHook;
1081
1082 // Hooks called when script private references are created and destroyed.
1083 js::MainThreadData<JS::ScriptPrivateReferenceHook> scriptPrivateAddRefHook;
1084 js::MainThreadData<JS::ScriptPrivateReferenceHook> scriptPrivateReleaseHook;
1085
1086 void addRefScriptPrivate(const JS::Value& value) {
1087 if (!value.isUndefined() && scriptPrivateAddRefHook) {
1088 scriptPrivateAddRefHook(value);
1089 }
1090 }
1091
1092 void releaseScriptPrivate(const JS::Value& value) {
1093 if (!value.isUndefined() && scriptPrivateReleaseHook) {
1094 scriptPrivateReleaseHook(value);
1095 }
1096 }
1097
1098 public:
1099 #if defined(NIGHTLY_BUILD)
1100 // Support for informing the embedding of any error thrown.
1101 // This mechanism is designed to let the embedding
1102 // log/report/fail in case certain errors are thrown
1103 // (e.g. SyntaxError, ReferenceError or TypeError
1104 // in critical code).
1105 struct ErrorInterceptionSupport {
1106 ErrorInterceptionSupport() : isExecuting(false), interceptor(nullptr) {}
1107
1108 // true if the error interceptor is currently executing,
1109 // false otherwise. Used to avoid infinite loops.
1110 bool isExecuting;
1111
1112 // if non-null, any call to `setPendingException`
1113 // in this runtime will trigger the call to `interceptor`
1114 JSErrorInterceptor* interceptor;
1115 };
1116 ErrorInterceptionSupport errorInterception;
1117 #endif // defined(NIGHTLY_BUILD)
1118
1119 public:
1120 JS::GlobalInitializeCallback getShadowRealmInitializeGlobalCallback() {
1121 return shadowRealmInitializeGlobalCallback;
1122 }
1123
1124 JS::GlobalCreationCallback getShadowRealmGlobalCreationCallback() {
1125 return shadowRealmGlobalCreationCallback;
1126 }
1127
1128 js::MainThreadData<JS::GlobalInitializeCallback>
1129 shadowRealmInitializeGlobalCallback;
1130
1131 js::MainThreadData<JS::GlobalCreationCallback>
1132 shadowRealmGlobalCreationCallback;
1133
1134 js::MainThreadData<js::HasSeenObjectEmulateUndefinedFuse>
1135 hasSeenObjectEmulateUndefinedFuse;
1136
1137 js::MainThreadData<js::HasSeenArrayExceedsInt32LengthFuse>
1138 hasSeenArrayExceedsInt32LengthFuse;
1139 };
1140
1141 namespace js {
1142
1143 void Metrics::addTelemetry(JSMetric id, uint32_t sample) {
1144 rt_->addTelemetry(id, sample);
1145 }
1146
1147 static MOZ_ALWAYS_INLINE void MakeRangeGCSafe(Value* vec, size_t len) {
1148 // Don't PodZero here because JS::Value is non-trivial.
1149 for (size_t i = 0; i < len; i++) {
1150 vec[i].setDouble(+0.0);
1151 }
1152 }
1153
1154 static MOZ_ALWAYS_INLINE void MakeRangeGCSafe(Value* beg, Value* end) {
1155 MakeRangeGCSafe(beg, end - beg);
1156 }
1157
1158 static MOZ_ALWAYS_INLINE void MakeRangeGCSafe(jsid* beg, jsid* end) {
1159 std::fill(beg, end, PropertyKey::Int(0));
1160 }
1161
1162 static MOZ_ALWAYS_INLINE void MakeRangeGCSafe(jsid* vec, size_t len) {
1163 MakeRangeGCSafe(vec, vec + len);
1164 }
1165
1166 static MOZ_ALWAYS_INLINE void MakeRangeGCSafe(Shape** beg, Shape** end) {
1167 std::fill(beg, end, nullptr);
1168 }
1169
1170 static MOZ_ALWAYS_INLINE void MakeRangeGCSafe(Shape** vec, size_t len) {
1171 MakeRangeGCSafe(vec, vec + len);
1172 }
1173
1174 static MOZ_ALWAYS_INLINE void SetValueRangeToUndefined(Value* beg, Value* end) {
1175 for (Value* v = beg; v != end; ++v) {
1176 v->setUndefined();
1177 }
1178 }
1179
1180 static MOZ_ALWAYS_INLINE void SetValueRangeToUndefined(Value* vec, size_t len) {
1181 SetValueRangeToUndefined(vec, vec + len);
1182 }
1183
1184 static MOZ_ALWAYS_INLINE void SetValueRangeToNull(Value* beg, Value* end) {
1185 for (Value* v = beg; v != end; ++v) {
1186 v->setNull();
1187 }
1188 }
1189
1190 static MOZ_ALWAYS_INLINE void SetValueRangeToNull(Value* vec, size_t len) {
1191 SetValueRangeToNull(vec, vec + len);
1192 }
1193
1194 extern const JSSecurityCallbacks NullSecurityCallbacks;
1195
1196 // This callback is set by JS::SetProcessLargeAllocationFailureCallback
1197 // and may be null. See comment in jsapi.h.
1198 extern mozilla::Atomic<JS::LargeAllocationFailureCallback>
1199 OnLargeAllocationFailure;
1200
1201 // This callback is set by JS::SetBuildIdOp and may be null. See comment in
1202 // jsapi.h.
1203 extern mozilla::Atomic<JS::BuildIdOp> GetBuildId;
1204
1205 extern JS::FilenameValidationCallback gFilenameValidationCallback;
1206
1207 } /* namespace js */
1208
1209 #endif /* vm_Runtime_h */