Debian Codegraph @

js/src/vm/Realm.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_Realm_h
8 #define vm_Realm_h
9
10 #include "mozilla/Array.h"
11 #include "mozilla/Maybe.h"
12 #include "mozilla/MemoryReporting.h"
13 #include "mozilla/TimeStamp.h"
14 #include "mozilla/Variant.h"
15 #include "mozilla/XorShift128PlusRNG.h"
16
17 #include <stddef.h>
18
19 #include "builtin/Array.h"
20 #include "ds/IdValuePair.h"
21 #include "gc/Barrier.h"
22 #include "gc/WeakMap.h"
23 #include "jit/BaselineCompileQueue.h"
24 #include "js/GCVariant.h"
25 #include "js/RealmOptions.h"
26 #include "js/TelemetryTimers.h"
27 #include "js/UniquePtr.h"
28 #include "vm/ArrayBufferObject.h"
29 #include "vm/GuardFuse.h"
30 #include "vm/InvalidatingFuse.h"
31 #include "vm/JSContext.h"
32 #include "vm/RealmFuses.h"
33 #include "vm/SavedStacks.h"
34 #include "wasm/WasmRealm.h"
35
36 namespace js {
37
38 namespace coverage {
39 class LCovRealm;
40 } // namespace coverage
41
42 namespace jit {
43 class BaselineCompileQueue;
44 } // namespace jit
45
46 class AutoRestoreRealmDebugMode;
47 class Debugger;
48 class GlobalObject;
49 class GlobalObjectData;
50 class GlobalLexicalEnvironmentObject;
51 class NonSyntacticLexicalEnvironmentObject;
52 struct IdValuePair;
53 struct NativeIterator;
54
55 /*
56 * A single-entry cache for some base-10 double-to-string conversions. This
57 * helps date-format-xparb.js. It also avoids skewing the results for
58 * v8-splay.js when measured by the SunSpider harness, where the splay tree
59 * initialization (which includes many repeated double-to-string conversions)
60 * is erroneously included in the measurement; see bug 562553.
61 */
62 class DtoaCache {
63 double dbl;
64 int base;
65 JSLinearString* str; // if str==nullptr, dbl and base are not valid
66
67 public:
68 DtoaCache() : str(nullptr) {}
69 void purge() { str = nullptr; }
70
71 JSLinearString* lookup(int b, double d) {
72 return str && b == base && d == dbl ? str : nullptr;
73 }
74
75 void cache(int b, double d, JSLinearString* s) {
76 base = b;
77 dbl = d;
78 str = s;
79 }
80
81 #ifdef JSGC_HASH_TABLE_CHECKS
82 void checkCacheAfterMovingGC();
83 #endif
84 };
85
86 // Cache to speed up the group/shape lookup in ProxyObject::create. A proxy's
87 // shape is only determined by the Class + proto, so a small cache for this is
88 // very effective in practice.
89 class NewProxyCache {
90 struct Entry {
91 Shape* shape;
92 };
93 static const size_t NumEntries = 4;
94 mozilla::UniquePtr<Entry[], JS::FreePolicy> entries_;
95
96 public:
97 MOZ_ALWAYS_INLINE bool lookup(const JSClass* clasp, TaggedProto proto,
98 Shape** shape) const {
99 if (!entries_) {
100 return false;
101 }
102 for (size_t i = 0; i < NumEntries; i++) {
103 const Entry& entry = entries_[i];
104 if (entry.shape && entry.shape->getObjectClass() == clasp &&
105 entry.shape->proto() == proto) {
106 *shape = entry.shape;
107 return true;
108 }
109 }
110 return false;
111 }
112 void add(Shape* shape) {
113 MOZ_ASSERT(shape);
114 if (!entries_) {
115 entries_.reset(js_pod_calloc<Entry>(NumEntries));
116 if (!entries_) {
117 return;
118 }
119 } else {
120 for (size_t i = NumEntries - 1; i > 0; i--) {
121 entries_[i] = entries_[i - 1];
122 }
123 }
124 entries_[0].shape = shape;
125 }
126 void purge() { entries_.reset(); }
127 };
128
129 // Cache for NewPlainObjectWithProperties. When the list of properties matches
130 // a recently created object's shape, we can use this shape directly.
131 class NewPlainObjectWithPropsCache {
132 static const size_t NumEntries = 4;
133 mozilla::Array<SharedShape*, NumEntries> entries_;
134
135 public:
136 NewPlainObjectWithPropsCache() { purge(); }
137
138 SharedShape* lookup(Handle<IdValueVector> properties) const;
139 void add(SharedShape* shape);
140
141 void purge() {
142 for (size_t i = 0; i < NumEntries; i++) {
143 entries_[i] = nullptr;
144 }
145 }
146 };
147
148 // Cache for Object.assign's fast path for two plain objects. It's used to
149 // optimize:
150 //
151 // Object.assign(to, from)
152 //
153 // If the |to| object has shape |emptyToShape_| (shape with no properties) and
154 // the |from| object has shape |fromShape_|, we can use |newToShape_| for |to|
155 // and copy all (data)) properties from the |from| object.
156 //
157 // This is a one-entry cache for now. It has a hit rate of > 90% on both
158 // Speedometer 2 and Speedometer 3.
159 class MOZ_NON_TEMPORARY_CLASS PlainObjectAssignCache {
160 SharedShape* emptyToShape_ = nullptr;
161 SharedShape* fromShape_ = nullptr;
162 SharedShape* newToShape_ = nullptr;
163
164 #ifdef DEBUG
165 void assertValid() const;
166 #else
167 void assertValid() const {}
168 #endif
169
170 public:
171 PlainObjectAssignCache() = default;
172 PlainObjectAssignCache(const PlainObjectAssignCache&) = delete;
173 void operator=(const PlainObjectAssignCache&) = delete;
174
175 SharedShape* lookup(Shape* emptyToShape, Shape* fromShape) const {
176 if (emptyToShape_ == emptyToShape && fromShape_ == fromShape) {
177 assertValid();
178 return newToShape_;
179 }
180 return nullptr;
181 }
182 void fill(SharedShape* emptyToShape, SharedShape* fromShape,
183 SharedShape* newToShape) {
184 emptyToShape_ = emptyToShape;
185 fromShape_ = fromShape;
186 newToShape_ = newToShape;
187 assertValid();
188 }
189 void purge() {
190 emptyToShape_ = nullptr;
191 fromShape_ = nullptr;
192 newToShape_ = nullptr;
193 }
194 };
195
196 // [SMDOC] Object MetadataBuilder API
197 //
198 // We must ensure that all newly allocated JSObjects get their metadata
199 // set. However, metadata builders may require the new object be in a sane
200 // state (eg, have its reserved slots initialized so they can get the
201 // sizeOfExcludingThis of the object). Therefore, for objects of certain
202 // JSClasses (those marked with JSCLASS_DELAY_METADATA_BUILDER), it is not safe
203 // for the allocation paths to call the object metadata builder
204 // immediately. Instead, the JSClass-specific "constructor" C++ function up the
205 // stack makes a promise that it will ensure that the new object has its
206 // metadata set after the object is initialized.
207 //
208 // The js::AutoSetNewObjectMetadata RAII class provides an ergonomic way for
209 // constructor functions to do this.
210 //
211 // In the presence of internal errors, we do not set the new object's metadata
212 // (if it was even allocated).
213
214 class PropertyIteratorObject;
215
216 struct IteratorHashPolicy {
217 struct Lookup {
218 Shape** shapes;
219 size_t numShapes;
220 HashNumber shapesHash;
221
222 Lookup(Shape** shapes, size_t numShapes, HashNumber shapesHash)
223 : shapes(shapes), numShapes(numShapes), shapesHash(shapesHash) {
224 MOZ_ASSERT(numShapes > 0);
225 }
226 };
227 static HashNumber hash(const Lookup& lookup) { return lookup.shapesHash; }
228 static bool match(PropertyIteratorObject* obj, const Lookup& lookup);
229 };
230
231 class DebugEnvironments;
232 class NonSyntacticVariablesObject;
233 class WithEnvironmentObject;
234
235 // ObjectRealm stores various tables and other state associated with particular
236 // objects in a realm. To make sure the correct ObjectRealm is used for an
237 // object, use of the ObjectRealm::get(obj) static method is required.
238 class ObjectRealm {
239 // All non-syntactic lexical environments in the realm. These are kept in a
240 // map because when loading scripts into a non-syntactic environment, we
241 // need to use the same lexical environment to persist lexical bindings.
242 js::UniquePtr<js::ObjectWeakMap> nonSyntacticLexicalEnvironments_;
243
244 ObjectRealm(const ObjectRealm&) = delete;
245 void operator=(const ObjectRealm&) = delete;
246
247 public:
248 // Map from array buffers to views sharing that storage.
249 JS::WeakCache<js::InnerViewTable> innerViews;
250
251 // Keep track of the metadata objects which can be associated with each JS
252 // object. Both keys and values are in this realm.
253 js::UniquePtr<js::ObjectWeakMap> objectMetadataTable;
254
255 using IteratorCache =
256 js::HashSet<js::PropertyIteratorObject*, js::IteratorHashPolicy,
257 js::ZoneAllocPolicy>;
258 IteratorCache iteratorCache;
259
260 static inline ObjectRealm& get(const JSObject* obj);
261
262 explicit ObjectRealm(JS::Zone* zone);
263
264 void finishRoots();
265 void trace(JSTracer* trc);
266 void sweepAfterMinorGC(JSTracer* trc);
267
268 void addSizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf,
269 size_t* innerViewsArg,
270 size_t* objectMetadataTablesArg,
271 size_t* nonSyntacticLexicalEnvironmentsArg);
272
273 NonSyntacticLexicalEnvironmentObject*
274 getOrCreateNonSyntacticLexicalEnvironment(
275 JSContext* cx, Handle<NonSyntacticVariablesObject*> enclosing);
276
277 NonSyntacticLexicalEnvironmentObject*
278 getOrCreateNonSyntacticLexicalEnvironment(
279 JSContext* cx, Handle<WithEnvironmentObject*> enclosing);
280
281 NonSyntacticLexicalEnvironmentObject*
282 getOrCreateNonSyntacticLexicalEnvironment(
283 JSContext* cx, Handle<WithEnvironmentObject*> enclosing,
284 Handle<NonSyntacticVariablesObject*> key);
285
286 private:
287 NonSyntacticLexicalEnvironmentObject*
288 getOrCreateNonSyntacticLexicalEnvironment(JSContext* cx,
289 HandleObject enclosing,
290 HandleObject key,
291 HandleObject thisv);
292
293 public:
294 NonSyntacticLexicalEnvironmentObject* getNonSyntacticLexicalEnvironment(
295 JSObject* key) const;
296 };
297
298 } // namespace js
299
300 class JS::Realm : public JS::shadow::Realm {
301 JS::Zone* zone_;
302 JSRuntime* runtime_;
303
304 const JS::RealmCreationOptions creationOptions_;
305 JS::RealmBehaviors behaviors_;
306
307 friend struct ::JSContext;
308 js::WeakHeapPtr<js::GlobalObject*> global_;
309
310 // Note: this is private to enforce use of ObjectRealm::get(obj).
311 js::ObjectRealm objects_;
312 friend js::ObjectRealm& js::ObjectRealm::get(const JSObject*);
313
314 // See the "Object MetadataBuilder API" comment.
315 JSObject* objectPendingMetadata_ = nullptr;
316 #ifdef DEBUG
317 uint32_t numActiveAutoSetNewObjectMetadata_ = 0;
318 #endif
319
320 // Random number generator for Math.random().
321 mozilla::Maybe<mozilla::non_crypto::XorShift128PlusRNG>
322 randomNumberGenerator_;
323
324 // Random number generator for randomHashCodeScrambler().
325 mozilla::non_crypto::XorShift128PlusRNG randomKeyGenerator_;
326
327 JSPrincipals* principals_ = nullptr;
328
329 js::jit::BaselineCompileQueue baselineCompileQueue_;
330
331 // Bookkeeping information for debug scope objects.
332 js::UniquePtr<js::DebugEnvironments> debugEnvs_;
333
334 js::SavedStacks savedStacks_;
335
336 // Used by memory reporters and invalid otherwise.
337 JS::RealmStats* realmStats_ = nullptr;
338
339 const js::AllocationMetadataBuilder* allocationMetadataBuilder_ = nullptr;
340 void* realmPrivate_ = nullptr;
341
342 // There are two ways to enter a realm:
343 //
344 // (1) AutoRealm (and JSAutoRealm, JS::EnterRealm)
345 // (2) When calling a cross-realm (but same-compartment) function in JIT
346 // code.
347 //
348 // This field only accounts for (1), to keep the JIT code as simple as
349 // possible.
350 //
351 // An important invariant is that the JIT can only switch to a different
352 // realm within the same compartment, so whenever that happens there must
353 // always be a same-compartment realm with enterRealmDepthIgnoringJit_ > 0.
354 // This lets us set Compartment::hasEnteredRealm without walking the
355 // stack.
356 unsigned enterRealmDepthIgnoringJit_ = 0;
357
358 public:
359 // Various timers for collecting time spent delazifying, jit compiling,
360 // executing, etc
361 JS::JSTimers timers;
362
363 struct DebuggerVectorEntry {
364 // The debugger relies on iterating through the DebuggerVector to know what
365 // debuggers to notify about certain actions, which it does using this
366 // pointer. We need an explicit Debugger* because the JSObject* from
367 // the DebuggerDebuggeeLink to the Debugger is only set some of the time.
368 // This `Debugger*` pointer itself could also live on the
369 // DebuggerDebuggeeLink itself, but that would then require all of the
370 // places that iterate over the realm's DebuggerVector to also traverse
371 // the CCW which seems like it would be needlessly complicated.
372 js::WeakHeapPtr<js::Debugger*> dbg;
373
374 // This links to the debugger's DebuggerDebuggeeLink object, via a CCW.
375 // Tracing this link from the realm allows the debugger to define
376 // whether pieces of the debugger should be held live by a given realm.
377 js::HeapPtr<JSObject*> debuggerLink;
378
379 DebuggerVectorEntry(js::Debugger* dbg_, JSObject* link);
380 };
381 using DebuggerVector =
382 js::Vector<DebuggerVectorEntry, 0, js::ZoneAllocPolicy>;
383
384 private:
385 DebuggerVector debuggers_;
386
387 enum {
388 IsDebuggee = 1 << 0,
389 DebuggerObservesAllExecution = 1 << 1,
390 DebuggerObservesAsmJS = 1 << 2,
391 DebuggerObservesCoverage = 1 << 3,
392 DebuggerObservesWasm = 1 << 4,
393 DebuggerObservesNativeCall = 1 << 5,
394 };
395 unsigned debugModeBits_ = 0;
396 friend class js::AutoRestoreRealmDebugMode;
397
398 bool isSystem_ = false;
399 bool allocatedDuringIncrementalGC_;
400 bool initializingGlobal_ = true;
401
402 // Indicates that we are tracing all execution within this realm, i.e.,
403 // recording every entrance into exit from each function, among other
404 // things. See ExecutionTracer.h for where the bulk of this work
405 // happens.
406 bool isTracingExecution_ = false;
407
408 js::UniquePtr<js::coverage::LCovRealm> lcovRealm_ = nullptr;
409
410 public:
411 // WebAssembly state for the realm.
412 js::wasm::Realm wasm;
413
414 js::DtoaCache dtoaCache;
415 js::NewProxyCache newProxyCache;
416 js::NewPlainObjectWithPropsCache newPlainObjectWithPropsCache;
417 js::PlainObjectAssignCache plainObjectAssignCache;
418
419 // Last time at which an animation was played for this realm.
420 js::MainThreadData<mozilla::TimeStamp> lastAnimationTime;
421
422 /*
423 * For generational GC, record whether a write barrier has added this
424 * realm's global to the store buffer since the last minor GC.
425 *
426 * This is used to avoid calling into the VM every time a nursery object is
427 * written to a property of the global.
428 */
429 uint32_t globalWriteBarriered = 0;
430
431 // Counter for shouldCaptureStackForThrow.
432 uint16_t numStacksCapturedForThrow_ = 0;
433
434 // Count the number of allocation sites pretenured, for testing purposes.
435 uint16_t numAllocSitesPretenured = 0;
436
437 #ifdef DEBUG
438 bool firedOnNewGlobalObject = false;
439 #endif
440
441 // True if all incoming wrappers have been nuked. This happens when
442 // NukeCrossCompartmentWrappers is called with the NukeAllReferences option.
443 // This prevents us from creating new wrappers for the compartment.
444 bool nukedIncomingWrappers = false;
445
446 // Enable async stack capturing for this realm even if
447 // JS::ContextOptions::asyncStackCaptureDebuggeeOnly_ is true.
448 //
449 // No-op when JS::ContextOptions::asyncStack_ is false, or
450 // JS::ContextOptions::asyncStackCaptureDebuggeeOnly_ is false.
451 //
452 // This can be used as a lightweight alternative for making the global
453 // debuggee, if the async stack capturing is necessary but no other debugging
454 // features are used.
455 bool isAsyncStackCapturingEnabled = false;
456
457 // Allow to collect more than 50 stack traces for throw even if the global is
458 // not a debuggee.
459 //
460 // Similarly to isAsyncStackCapturingEnabled, this is a lightweight
461 // alternative for making the global a debuggee, when no actual debugging
462 // features are required.
463 bool isUnlimitedStacksCapturingEnabled = false;
464
465 private:
466 void updateDebuggerObservesFlag(unsigned flag);
467
468 Realm(const Realm&) = delete;
469 void operator=(const Realm&) = delete;
470
471 public:
472 Realm(JS::Compartment* comp, const JS::RealmOptions& options);
473 ~Realm();
474
475 void init(JSContext* cx, JSPrincipals* principals);
476 void destroy(JS::GCContext* gcx);
477
478 void addSizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf,
479 size_t* realmObject, size_t* realmTables,
480 size_t* innerViewsArg,
481 size_t* objectMetadataTablesArg,
482 size_t* savedStacksSet,
483 size_t* nonSyntacticLexicalEnvironmentsArg);
484
485 JS::Zone* zone() { return zone_; }
486 const JS::Zone* zone() const { return zone_; }
487
488 JSRuntime* runtimeFromMainThread() const {
489 MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(runtime_));
490 return runtime_;
491 }
492
493 // Note: Unrestricted access to the runtime from an arbitrary thread
494 // can easily lead to races. Use this method very carefully.
495 JSRuntime* runtimeFromAnyThread() const { return runtime_; }
496
497 const JS::RealmCreationOptions& creationOptions() const {
498 return creationOptions_;
499 }
500
501 // NOTE: Do not provide accessor for mutable reference.
502 // Modifying RealmBehaviors after creating a realm can result in
503 // inconsistency.
504 const JS::RealmBehaviors& behaviors() const { return behaviors_; }
505
506 void setNonLive() { behaviors_.setNonLive(); }
507 void setReduceTimerPrecisionCallerType(JS::RTPCallerTypeToken type) {
508 behaviors_.setReduceTimerPrecisionCallerType(type);
509 }
510
511 /* Whether to preserve JIT code on non-shrinking GCs. */
512 bool preserveJitCode() { return creationOptions_.preserveJitCode(); }
513
514 /* The global object for this realm.
515 *
516 * Note: the global_ field is null briefly during GC, after the global
517 * object is collected; but when that happens the Realm is destroyed during
518 * the same GC.)
519 *
520 * In contrast, JSObject::global() is infallible because marking a JSObject
521 * always marks its global as well.
522 */
523 inline js::GlobalObject* maybeGlobal() const;
524
525 /* An unbarriered getter for use while tracing. */
526 js::GlobalObject* unsafeUnbarrieredMaybeGlobal() const {
527 return global_.unbarrieredGet();
528 }
529
530 /* True if a global exists and it's not being collected. */
531 inline bool hasLiveGlobal() const;
532
533 /* True if a global exists and has been successfully initialized. */
534 inline bool hasInitializedGlobal() const;
535
536 inline void initGlobal(js::GlobalObject& global);
537 void clearInitializingGlobal() { initializingGlobal_ = false; }
538
539 /*
540 * This method traces data that is live iff we know that this realm's
541 * global is still live.
542 */
543 void traceGlobalData(JSTracer* trc);
544
545 void traceGlobalRoot(JSTracer* trc, const char* name);
546
547 void traceWeakGlobalEdge(JSTracer* trc);
548
549 /*
550 * This method traces Realm-owned GC roots that are considered live
551 * regardless of whether the realm's global is still live.
552 */
553 void traceRoots(JSTracer* trc,
554 js::gc::GCRuntime::TraceOrMarkRuntime traceOrMark);
555 /*
556 * This method clears out tables of roots in preparation for the final GC.
557 */
558 void finishRoots();
559
560 void sweepAfterMinorGC(JSTracer* trc);
561 void traceWeakDebugEnvironmentEdges(JSTracer* trc);
562
563 void clearScriptCounts();
564 void clearScriptLCov();
565
566 void purge();
567
568 void fixupAfterMovingGC(JSTracer* trc);
569
570 void enter() { enterRealmDepthIgnoringJit_++; }
571 void leave() {
572 MOZ_ASSERT(enterRealmDepthIgnoringJit_ > 0);
573 enterRealmDepthIgnoringJit_--;
574 }
575 bool hasBeenEnteredIgnoringJit() const {
576 return enterRealmDepthIgnoringJit_ > 0;
577 }
578 bool shouldTraceGlobal() const {
579 // If we entered this realm in JIT code, there must be a script and
580 // function on the stack for this realm, so the global will definitely
581 // be traced and it's safe to return false here.
582 return hasBeenEnteredIgnoringJit();
583 }
584
585 bool hasAllocationMetadataBuilder() const {
586 return allocationMetadataBuilder_;
587 }
588 const js::AllocationMetadataBuilder* getAllocationMetadataBuilder() const {
589 return allocationMetadataBuilder_;
590 }
591 const void* addressOfMetadataBuilder() const {
592 return &allocationMetadataBuilder_;
593 }
594 bool isRecordingAllocations();
595 void setAllocationMetadataBuilder(
596 const js::AllocationMetadataBuilder* builder);
597 void forgetAllocationMetadataBuilder();
598 void setNewObjectMetadata(JSContext* cx, JS::HandleObject obj);
599
600 bool hasObjectPendingMetadata() const {
601 MOZ_ASSERT_IF(objectPendingMetadata_, hasAllocationMetadataBuilder());
602 return objectPendingMetadata_ != nullptr;
603 }
604 void setObjectPendingMetadata(JSObject* obj) {
605 MOZ_ASSERT(numActiveAutoSetNewObjectMetadata_ > 0,
606 "Must not use JSCLASS_DELAY_METADATA_BUILDER without "
607 "AutoSetNewObjectMetadata");
608 MOZ_ASSERT(!objectPendingMetadata_);
609 MOZ_ASSERT(obj);
610 if (MOZ_UNLIKELY(hasAllocationMetadataBuilder())) {
611 objectPendingMetadata_ = obj;
612 }
613 }
614 JSObject* getAndClearObjectPendingMetadata() {
615 MOZ_ASSERT(hasAllocationMetadataBuilder());
616 JSObject* obj = objectPendingMetadata_;
617 objectPendingMetadata_ = nullptr;
618 return obj;
619 }
620
621 #ifdef DEBUG
622 bool hasActiveAutoSetNewObjectMetadata() const {
623 return numActiveAutoSetNewObjectMetadata_ > 0;
624 }
625 void incNumActiveAutoSetNewObjectMetadata() {
626 numActiveAutoSetNewObjectMetadata_++;
627 }
628 void decNumActiveAutoSetNewObjectMetadata() {
629 MOZ_ASSERT(numActiveAutoSetNewObjectMetadata_ > 0);
630 numActiveAutoSetNewObjectMetadata_--;
631 }
632 #endif
633
634 void* realmPrivate() const { return realmPrivate_; }
635 void setRealmPrivate(void* p) { realmPrivate_ = p; }
636
637 // This should only be called when it is non-null, i.e. during memory
638 // reporting.
639 JS::RealmStats& realmStats() {
640 // We use MOZ_RELEASE_ASSERT here because in bug 1132502 there was some
641 // (inconclusive) evidence that realmStats_ can be nullptr unexpectedly.
642 MOZ_RELEASE_ASSERT(realmStats_);
643 return *realmStats_;
644 }
645 void nullRealmStats() {
646 MOZ_ASSERT(realmStats_);
647 realmStats_ = nullptr;
648 }
649 void setRealmStats(JS::RealmStats* newStats) {
650 MOZ_ASSERT(!realmStats_ && newStats);
651 realmStats_ = newStats;
652 }
653
654 inline bool marked() const;
655 void clearAllocatedDuringGC() { allocatedDuringIncrementalGC_ = false; }
656
657 /*
658 * The principals associated with this realm. Note that the same several
659 * realms may share the same principals and that a realm may change
660 * principals during its lifetime (e.g. in case of lazy parsing).
661 */
662 JSPrincipals* principals() { return principals_; }
663 void setPrincipals(JSPrincipals* principals) { principals_ = principals; }
664
665 bool isSystem() const { return isSystem_; }
666 //
667 // The Debugger observes execution on a frame-by-frame basis. The
668 // invariants of Realm's debug mode bits, JSScript::isDebuggee,
669 // InterpreterFrame::isDebuggee, and BaselineFrame::isDebuggee are
670 // enumerated below.
671 //
672 // 1. When a realm's isDebuggee() == true, relazification and lazy
673 // parsing are disabled.
674 //
675 // Whether AOT wasm is disabled is togglable by the Debugger API. By
676 // default it is disabled. See debuggerObservesAsmJS below.
677 //
678 // 2. When a realm's debuggerObservesAllExecution() == true, all of
679 // the realm's scripts are considered debuggee scripts.
680 //
681 // 3. A script is considered a debuggee script either when, per above, its
682 // realm is observing all execution, or if it has breakpoints set.
683 //
684 // 4. A debuggee script always pushes a debuggee frame.
685 //
686 // 5. A debuggee frame calls all slow path Debugger hooks in the
687 // Interpreter and Baseline. A debuggee frame implies that its script's
688 // BaselineScript, if extant, has been compiled with debug hook calls.
689 //
690 // 6. A debuggee script or a debuggee frame (i.e., during OSR) ensures
691 // that the compiled BaselineScript is compiled with debug hook calls
692 // when attempting to enter Baseline.
693 //
694 // 7. A debuggee script or a debuggee frame (i.e., during OSR) does not
695 // attempt to enter Ion.
696 //
697 // Note that a debuggee frame may exist without its script being a
698 // debuggee script. e.g., Debugger.Frame.prototype.eval only marks the
699 // frame in which it is evaluating as a debuggee frame.
700 //
701
702 // True if this realm's global is a debuggee of some Debugger
703 // object.
704 bool isDebuggee() const { return !!(debugModeBits_ & IsDebuggee); }
705
706 void setIsDebuggee();
707 void unsetIsDebuggee();
708
709 bool isTracingExecution() { return isTracingExecution_; }
710
711 void enableExecutionTracing() {
712 MOZ_ASSERT(!debuggerObservesCoverage());
713
714 isTracingExecution_ = true;
715 setIsDebuggee();
716 updateDebuggerObservesAllExecution();
717 }
718
719 void disableExecutionTracing() {
720 if (!isTracingExecution_) {
721 return;
722 }
723
724 isTracingExecution_ = false;
725 // updateDebuggerObservesAllExecution always wants isDebuggee to be true,
726 // so we just have weird ordering here to play nicely with it
727 updateDebuggerObservesAllExecution();
728 if (!hasDebuggers()) {
729 unsetIsDebuggee();
730 }
731 }
732
733 DebuggerVector& getDebuggers(const JS::AutoRequireNoGC& nogc) {
734 return debuggers_;
735 };
736 bool hasDebuggers() const { return !debuggers_.empty(); }
737
738 // True if this compartment's global is a debuggee of some Debugger
739 // object with a live hook that observes all execution; e.g.,
740 // onEnterFrame.
741 bool debuggerObservesAllExecution() const {
742 static const unsigned Mask = IsDebuggee | DebuggerObservesAllExecution;
743 return (debugModeBits_ & Mask) == Mask;
744 }
745 void updateDebuggerObservesAllExecution() {
746 updateDebuggerObservesFlag(DebuggerObservesAllExecution);
747 }
748
749 // True if this realm's global is a debuggee of some Debugger object
750 // whose allowUnobservedAsmJS flag is false.
751 bool debuggerObservesAsmJS() const {
752 static const unsigned Mask = IsDebuggee | DebuggerObservesAsmJS;
753 return (debugModeBits_ & Mask) == Mask;
754 }
755 void updateDebuggerObservesAsmJS() {
756 updateDebuggerObservesFlag(DebuggerObservesAsmJS);
757 }
758
759 // True if this realm's global is a debuggee of some Debugger object
760 // whose allowUnobservedWasm flag is false.
761 //
762 // Note that since AOT wasm functions cannot bail out, this flag really
763 // means "observe wasm from this point forward". We cannot make
764 // already-compiled wasm code observable to Debugger.
765 bool debuggerObservesWasm() const {
766 static const unsigned Mask = IsDebuggee | DebuggerObservesWasm;
767 return (debugModeBits_ & Mask) == Mask;
768 }
769 void updateDebuggerObservesWasm() {
770 updateDebuggerObservesFlag(DebuggerObservesWasm);
771 }
772
773 // True if this compartment's global is a debuggee of some Debugger
774 // object with a live hook that observes native calls.
775 // (has a onNativeCall function registered)
776 bool debuggerObservesNativeCall() const {
777 static const unsigned Mask = IsDebuggee | DebuggerObservesNativeCall;
778 return (debugModeBits_ & Mask) == Mask;
779 }
780 void updateDebuggerObservesNativeCall() {
781 updateDebuggerObservesFlag(DebuggerObservesNativeCall);
782 }
783
784 // True if this realm's global is a debuggee of some Debugger object
785 // whose collectCoverageInfo flag is true.
786 bool debuggerObservesCoverage() const {
787 static const unsigned Mask = DebuggerObservesCoverage;
788 return (debugModeBits_ & Mask) == Mask;
789 }
790 void updateDebuggerObservesCoverage();
791
792 // Returns true if the Debugger API is collecting code coverage data for this
793 // realm or if the process-wide LCov option is enabled.
794 bool collectCoverageForDebug() const;
795
796 // Get or allocate the associated LCovRealm.
797 js::coverage::LCovRealm* lcovRealm();
798
799 bool shouldCaptureStackForThrow();
800
801 // Returns the locale for this realm. (Pointer must NOT be freed!)
802 const char* getLocale() const;
803
804 // Initializes randomNumberGenerator if needed.
805 mozilla::non_crypto::XorShift128PlusRNG& getOrCreateRandomNumberGenerator();
806
807 const mozilla::non_crypto::XorShift128PlusRNG*
808 addressOfRandomNumberGenerator() const {
809 return randomNumberGenerator_.ptr();
810 }
811
812 mozilla::HashCodeScrambler randomHashCodeScrambler();
813
814 js::jit::BaselineCompileQueue& baselineCompileQueue() {
815 return baselineCompileQueue_;
816 }
817 static constexpr size_t offsetOfBaselineCompileQueue() {
818 return offsetof(Realm, baselineCompileQueue_);
819 }
820 void removeFromCompileQueue(JSScript* script);
821
822 js::DebugEnvironments* debugEnvs() { return debugEnvs_.get(); }
823 js::UniquePtr<js::DebugEnvironments>& debugEnvsRef() { return debugEnvs_; }
824
825 js::SavedStacks& savedStacks() { return savedStacks_; }
826
827 // Recompute the probability with which this realm should record
828 // profiling data (stack traces, allocations log, etc.) about each
829 // allocation. We first consult the JS runtime to see if it is recording
830 // allocations, and if not then check the probabilities requested by the
831 // Debugger instances observing us, if any.
832 void chooseAllocationSamplingProbability() {
833 savedStacks_.chooseSamplingProbability(this);
834 }
835
836 void traceWeakSavedStacks(JSTracer* trc);
837
838 static constexpr size_t offsetOfCompartment() {
839 return offsetof(JS::Realm, compartment_);
840 }
841 static constexpr size_t offsetOfAllocationMetadataBuilder() {
842 return offsetof(JS::Realm, allocationMetadataBuilder_);
843 }
844 static constexpr size_t offsetOfDebugModeBits() {
845 return offsetof(JS::Realm, debugModeBits_);
846 }
847 static constexpr uint32_t debugModeIsDebuggeeBit() { return IsDebuggee; }
848
849 // Note: similar to cx->global(), JIT code can omit the read barrier for the
850 // context's active global.
851 static constexpr size_t offsetOfActiveGlobal() {
852 static_assert(sizeof(global_) == sizeof(uintptr_t),
853 "JIT code assumes field is pointer-sized");
854 return offsetof(JS::Realm, global_);
855 }
856
857 js::RealmFuses realmFuses;
858
859 // Allocation site used by binding code to provide feedback
860 // on allocation heap for DOM allocation functions.
861 //
862 // See CallIRGenerator::tryAttachCallNative
863 js::gc::AllocSite* localAllocSite = nullptr;
864
865 static size_t offsetOfLocalAllocSite() {
866 return offsetof(JS::Realm, localAllocSite);
867 }
868 };
869
870 inline js::Handle<js::GlobalObject*> JSContext::global() const {
871 /*
872 * It's safe to use |unbarrieredGet()| here because any realm that is on-stack
873 * will be marked automatically, so there's no need for a read barrier on
874 * it. Once the realm is popped, the handle is no longer safe to use.
875 */
876 MOZ_ASSERT(realm_, "Caller needs to enter a realm first");
877 return js::Handle<js::GlobalObject*>::fromMarkedLocation(
878 realm_->global_.unbarrieredAddress());
879 }
880
881 namespace js {
882
883 class MOZ_RAII AssertRealmUnchanged {
884 public:
885 explicit AssertRealmUnchanged(JSContext* cx)
886 : cx(cx), oldRealm(cx->realm()) {}
887
888 ~AssertRealmUnchanged() { MOZ_ASSERT(cx->realm() == oldRealm); }
889
890 protected:
891 JSContext* const cx;
892 JS::Realm* const oldRealm;
893 };
894
895 // AutoRealm can be used to enter the realm of a JSObject, JSScript or
896 // ObjectGroup. It must not be used with cross-compartment wrappers, because
897 // CCWs are not associated with a single realm.
898 class AutoRealm {
899 JSContext* const cx_;
900 JS::Realm* const origin_;
901
902 public:
903 template <typename T>
904 inline AutoRealm(JSContext* cx, const T& target);
905 inline ~AutoRealm();
906
907 JSContext* context() const { return cx_; }
908 JS::Realm* origin() const { return origin_; }
909
910 protected:
911 inline AutoRealm(JSContext* cx, JS::Realm* target);
912
913 private:
914 AutoRealm(const AutoRealm&) = delete;
915 AutoRealm& operator=(const AutoRealm&) = delete;
916 };
917
918 class MOZ_RAII AutoAllocInAtomsZone {
919 JSContext* const cx_;
920 JS::Realm* const origin_;
921 AutoAllocInAtomsZone(const AutoAllocInAtomsZone&) = delete;
922 AutoAllocInAtomsZone& operator=(const AutoAllocInAtomsZone&) = delete;
923
924 public:
925 inline explicit AutoAllocInAtomsZone(JSContext* cx);
926 inline ~AutoAllocInAtomsZone();
927 };
928
929 // During GC we sometimes need to enter a realm when we may have been allocating
930 // in the the atoms zone. This leaves the atoms zone temporarily. This happens
931 // in embedding callbacks and when we need to mark object groups as pretenured.
932 class MOZ_RAII AutoMaybeLeaveAtomsZone {
933 JSContext* const cx_;
934 bool wasInAtomsZone_;
935 AutoMaybeLeaveAtomsZone(const AutoMaybeLeaveAtomsZone&) = delete;
936 AutoMaybeLeaveAtomsZone& operator=(const AutoMaybeLeaveAtomsZone&) = delete;
937
938 public:
939 inline explicit AutoMaybeLeaveAtomsZone(JSContext* cx);
940 inline ~AutoMaybeLeaveAtomsZone();
941 };
942
943 // Enter a realm directly. Only use this where there's no target GC thing
944 // to pass to AutoRealm or where you need to avoid the assertions in
945 // JS::Compartment::enterCompartmentOf().
946 class AutoRealmUnchecked : protected AutoRealm {
947 public:
948 inline AutoRealmUnchecked(JSContext* cx, JS::Realm* target);
949 };
950
951 // Similar to AutoRealm, but this uses GetFunctionRealm in the spec, and
952 // handles both bound functions and proxies.
953 //
954 // If GetFunctionRealm fails for the following reasons, this does nothing:
955 // * `fun` is revoked proxy
956 // * unwrapping failed because of a security wrapper
957 class AutoFunctionOrCurrentRealm {
958 mozilla::Maybe<AutoRealmUnchecked> ar_;
959
960 public:
961 inline AutoFunctionOrCurrentRealm(JSContext* cx, js::HandleObject fun);
962 ~AutoFunctionOrCurrentRealm() = default;
963
964 private:
965 AutoFunctionOrCurrentRealm(const AutoFunctionOrCurrentRealm&) = delete;
966 AutoFunctionOrCurrentRealm& operator=(const AutoFunctionOrCurrentRealm&) =
967 delete;
968 };
969
970 /*
971 * Use this to change the behavior of an AutoRealm slightly on error. If
972 * the exception happens to be an Error object, copy it to the origin
973 * compartment instead of wrapping it.
974 */
975 class ErrorCopier {
976 mozilla::Maybe<AutoRealm>& ar;
977
978 public:
979 explicit ErrorCopier(mozilla::Maybe<AutoRealm>& ar) : ar(ar) {}
980 ~ErrorCopier();
981 };
982
983 // See the "Object MetadataBuilder API" comment.
984 class MOZ_RAII AutoSetNewObjectMetadata {
985 JSContext* cx_;
986
987 AutoSetNewObjectMetadata(const AutoSetNewObjectMetadata& aOther) = delete;
988 void operator=(const AutoSetNewObjectMetadata& aOther) = delete;
989
990 void setPendingMetadata();
991
992 public:
993 explicit inline AutoSetNewObjectMetadata(JSContext* cx) : cx_(cx) {
994 #ifdef DEBUG
995 MOZ_ASSERT(!cx->realm()->hasObjectPendingMetadata());
996 cx_->realm()->incNumActiveAutoSetNewObjectMetadata();
997 #endif
998 }
999 inline ~AutoSetNewObjectMetadata() {
1000 #ifdef DEBUG
1001 cx_->realm()->decNumActiveAutoSetNewObjectMetadata();
1002 #endif
1003 if (MOZ_UNLIKELY(cx_->realm()->hasAllocationMetadataBuilder())) {
1004 setPendingMetadata();
1005 }
1006 }
1007 };
1008
1009 } /* namespace js */
1010
1011 #endif /* vm_Realm_h */