Debian Codegraph @

js/src/vm/Realm.cpp

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 #include "js/shadow/Realm.h" // JS::shadow::Realm
8 #include "vm/Realm-inl.h"
9
10 #include "mozilla/MemoryReporting.h"
11
12 #include <stddef.h>
13
14 #include "jsfriendapi.h"
15 #include "jsmath.h"
16
17 #include "builtin/WrappedFunctionObject.h"
18 #include "debugger/DebugAPI.h"
19 #include "debugger/Debugger.h"
20 #include "gc/GC.h"
21 #include "jit/JitRuntime.h"
22 #include "js/CallAndConstruct.h" // JS::IsCallable
23 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
24 #include "js/GCVariant.h"
25 #include "js/Proxy.h"
26 #include "js/RootingAPI.h"
27 #include "js/Wrapper.h"
28 #include "vm/Compartment.h"
29 #include "vm/DateTime.h"
30 #include "vm/Iteration.h"
31 #include "vm/JSContext.h"
32
33 #include "gc/Marking-inl.h"
34 #include "vm/JSObject-inl.h"
35
36 using namespace js;
37
38 Realm::DebuggerVectorEntry::DebuggerVectorEntry(js::Debugger* dbg_,
39 JSObject* link)
40 : dbg(dbg_), debuggerLink(link) {}
41
42 ObjectRealm::ObjectRealm(JS::Zone* zone)
43 : innerViews(zone, zone), iteratorCache(zone) {}
44
45 Realm::Realm(Compartment* comp, const JS::RealmOptions& options)
46 : JS::shadow::Realm(comp),
47 zone_(comp->zone()),
48 runtime_(comp->runtimeFromMainThread()),
49 creationOptions_(options.creationOptions()),
50 behaviors_(options.behaviors()),
51 objects_(zone_),
52 randomKeyGenerator_(runtime_->forkRandomKeyGenerator()),
53 debuggers_(zone_),
54 allocatedDuringIncrementalGC_(zone_->isGCMarkingOrSweeping() ||
55 zone_->isGCFinished()),
56 wasm(runtime_) {
57 runtime_->numRealms++;
58 }
59
60 Realm::~Realm() {
61 MOZ_ASSERT(!hasBeenEnteredIgnoringJit());
62 MOZ_ASSERT(!localAllocSite);
63 MOZ_ASSERT_IF(isDebuggee(), isTracingExecution_);
64
65 // Write the code coverage information in a file.
66 if (lcovRealm_) {
67 runtime_->lcovOutput().writeLCovResult(*lcovRealm_);
68 }
69
70 if (allocationMetadataBuilder_) {
71 forgetAllocationMetadataBuilder();
72 }
73
74 if (isTracingExecution_) {
75 disableExecutionTracing();
76 }
77
78 MOZ_ASSERT(runtime_->numRealms > 0);
79 runtime_->numRealms--;
80 }
81
82 void Realm::init(JSContext* cx, JSPrincipals* principals) {
83 /*
84 * As a hack, we clear our timezone cache every time we create a new realm.
85 * This ensures that the cache is always relatively fresh, but shouldn't
86 * interfere with benchmarks that create tons of date objects (unless they
87 * also create tons of iframes, which seems unlikely).
88 */
89 js::ResetTimeZoneInternal(ResetTimeZoneMode::DontResetIfOffsetUnchanged);
90
91 if (principals) {
92 // Any realm with the trusted principals -- and there can be
93 // multiple -- is a system realm.
94 isSystem_ = (principals == cx->runtime()->trustedPrincipals());
95 JS_HoldPrincipals(principals);
96 principals_ = principals;
97 }
98
99 if (!isSystem_ && cx->hasExecutionTracer()) {
100 enableExecutionTracing();
101 }
102 }
103
104 bool JSRuntime::createJitRuntime(JSContext* cx) {
105 using namespace js::jit;
106
107 MOZ_ASSERT(!jitRuntime_);
108
109 if (!CanLikelyAllocateMoreExecutableMemory()) {
110 // Try to release memory first instead of potentially reporting OOM below.
111 if (OnLargeAllocationFailure) {
112 OnLargeAllocationFailure();
113 }
114 }
115
116 jit::JitRuntime* jrt = cx->new_<jit::JitRuntime>();
117 if (!jrt) {
118 return false;
119 }
120
121 // Unfortunately, initialization depends on jitRuntime_ being non-null, so
122 // we can't just wait to assign jitRuntime_.
123 jitRuntime_ = jrt;
124
125 if (!jitRuntime_->initialize(cx)) {
126 js_delete(jitRuntime_.ref());
127 jitRuntime_ = nullptr;
128 return false;
129 }
130
131 return true;
132 }
133
134 #ifdef JSGC_HASH_TABLE_CHECKS
135
136 void js::DtoaCache::checkCacheAfterMovingGC() {
137 MOZ_ASSERT(!str || !IsForwarded(str));
138 }
139
140 #endif // JSGC_HASH_TABLE_CHECKS
141
142 NonSyntacticLexicalEnvironmentObject*
143 ObjectRealm::getOrCreateNonSyntacticLexicalEnvironment(JSContext* cx,
144 HandleObject enclosing,
145 HandleObject key,
146 HandleObject thisv) {
147 MOZ_ASSERT(&ObjectRealm::get(enclosing) == this);
148
149 if (!nonSyntacticLexicalEnvironments_) {
150 auto map = cx->make_unique<ObjectWeakMap>(cx);
151 if (!map) {
152 return nullptr;
153 }
154
155 nonSyntacticLexicalEnvironments_ = std::move(map);
156 }
157
158 JSObject* obj = nonSyntacticLexicalEnvironments_->get(key);
159 if (obj) {
160 return &obj->as<NonSyntacticLexicalEnvironmentObject>();
161 }
162
163 MOZ_ASSERT(key->is<NonSyntacticVariablesObject>() ||
164 !key->is<EnvironmentObject>());
165
166 Rooted<NonSyntacticLexicalEnvironmentObject*> lexicalEnv(
167 cx, NonSyntacticLexicalEnvironmentObject::create(cx, enclosing, thisv));
168 if (!lexicalEnv) {
169 return nullptr;
170 }
171
172 if (!nonSyntacticLexicalEnvironments_->put(key, lexicalEnv)) {
173 ReportOutOfMemory(cx);
174 return nullptr;
175 }
176
177 return lexicalEnv;
178 }
179
180 NonSyntacticLexicalEnvironmentObject*
181 ObjectRealm::getOrCreateNonSyntacticLexicalEnvironment(
182 JSContext* cx, Handle<NonSyntacticVariablesObject*> enclosing) {
183 HandleObject key = enclosing;
184
185 // NOTE: The default global |this| value is set to key for compatibility
186 // with existing users of the lexical environment cache.
187 // - When used by shared-global JSM loader, |this| must be the
188 // NonSyntacticVariablesObject passed as enclosing.
189 // See js::GetFunctionThis / js::GetNonSyntacticGlobalThis
190 return getOrCreateNonSyntacticLexicalEnvironment(cx, enclosing, key,
191 /*thisv = */ key);
192 }
193
194 NonSyntacticLexicalEnvironmentObject*
195 ObjectRealm::getOrCreateNonSyntacticLexicalEnvironment(
196 JSContext* cx, Handle<WithEnvironmentObject*> enclosing) {
197 MOZ_ASSERT(!enclosing->isSyntactic());
198
199 // If a wrapped WithEnvironmentObject was passed in, unwrap it, as we may
200 // be creating different WithEnvironmentObject wrappers each time.
201 RootedObject key(cx, &enclosing->as<WithEnvironmentObject>().object());
202
203 // NOTE: The default global |this| value is set to key for compatibility
204 // with existing users of the lexical environment cache.
205 // - When used by SubscriptLoader, |this| must be the target object of
206 // the WithEnvironmentObject wrapper.
207 // - When used by DOM Events, we execute directly as a function and do not
208 // access the |this| value.
209 // See js::GetFunctionThis / js::GetNonSyntacticGlobalThis
210 return getOrCreateNonSyntacticLexicalEnvironment(cx, enclosing, key,
211 /*thisv = */ key);
212 }
213
214 NonSyntacticLexicalEnvironmentObject*
215 ObjectRealm::getOrCreateNonSyntacticLexicalEnvironment(
216 JSContext* cx, Handle<WithEnvironmentObject*> enclosing,
217 Handle<NonSyntacticVariablesObject*> key) {
218 MOZ_ASSERT(!enclosing->isSyntactic());
219
220 RootedObject thisv(cx, &enclosing->object());
221 return getOrCreateNonSyntacticLexicalEnvironment(cx, enclosing, key, thisv);
222 }
223
224 NonSyntacticLexicalEnvironmentObject*
225 ObjectRealm::getNonSyntacticLexicalEnvironment(JSObject* key) const {
226 MOZ_ASSERT(&ObjectRealm::get(key) == this);
227
228 if (!nonSyntacticLexicalEnvironments_) {
229 return nullptr;
230 }
231 // If a wrapped WithEnvironmentObject was passed in, unwrap it as in
232 // getOrCreateNonSyntacticLexicalEnvironment.
233 if (key->is<WithEnvironmentObject>()) {
234 MOZ_ASSERT(!key->as<WithEnvironmentObject>().isSyntactic());
235 key = &key->as<WithEnvironmentObject>().object();
236 }
237 JSObject* lexicalEnv = nonSyntacticLexicalEnvironments_->get(key);
238 if (!lexicalEnv) {
239 return nullptr;
240 }
241 return &lexicalEnv->as<NonSyntacticLexicalEnvironmentObject>();
242 }
243
244 void Realm::traceGlobalData(JSTracer* trc) {
245 // Trace things reachable from the realm's global. Note that these edges
246 // must be swept too in case the realm is live but the global is not.
247
248 savedStacks_.trace(trc);
249
250 DebugAPI::traceFromRealm(trc, this);
251 }
252
253 void Realm::traceGlobalRoot(JSTracer* trc, const char* name) {
254 if (global_) {
255 TraceRoot(trc, global_.unbarrieredAddress(), name);
256 }
257 }
258
259 void ObjectRealm::trace(JSTracer* trc) {
260 if (objectMetadataTable) {
261 objectMetadataTable->trace(trc);
262 }
263
264 if (nonSyntacticLexicalEnvironments_) {
265 nonSyntacticLexicalEnvironments_->trace(trc);
266 }
267 }
268
269 void Realm::traceRoots(JSTracer* trc,
270 js::gc::GCRuntime::TraceOrMarkRuntime traceOrMark) {
271 // It's not possible to trigger a GC between allocating the pending object and
272 // setting its meta data in ~AutoSetNewObjectMetadata.
273 MOZ_RELEASE_ASSERT(!objectPendingMetadata_);
274
275 if (!JS::RuntimeHeapIsMinorCollecting()) {
276 // The global is never nursery allocated, so we don't need to
277 // trace it when doing a minor collection.
278 //
279 // If a realm is on-stack, we mark its global so that JSContext::global()
280 // remains valid.
281 if (shouldTraceGlobal()) {
282 traceGlobalRoot(trc, "on-stack realm global");
283 }
284
285 // If the realm is still being initialized we set a flag so that it doesn't
286 // get deleted, since there may be GC things that contain pointers to it.
287 if (shouldTraceGlobal() && initializingGlobal_) {
288 allocatedDuringIncrementalGC_ = true;
289 }
290 }
291
292 // Nothing below here needs to be treated as a root if we aren't marking
293 // this zone for a collection.
294 if (traceOrMark == js::gc::GCRuntime::MarkRuntime &&
295 !zone()->isCollectingFromAnyThread()) {
296 return;
297 }
298
299 /* Mark debug scopes, if present */
300 if (debugEnvs_) {
301 debugEnvs_->trace(trc);
302 }
303
304 objects_.trace(trc);
305 baselineCompileQueue_.trace(trc);
306 }
307
308 void ObjectRealm::finishRoots() {
309 if (objectMetadataTable) {
310 objectMetadataTable->clear();
311 }
312
313 if (nonSyntacticLexicalEnvironments_) {
314 nonSyntacticLexicalEnvironments_->clear();
315 }
316 }
317
318 void Realm::finishRoots() {
319 if (debugEnvs_) {
320 debugEnvs_->finish();
321 }
322
323 objects_.finishRoots();
324 }
325
326 void ObjectRealm::sweepAfterMinorGC(JSTracer* trc) {
327 InnerViewTable& table = innerViews.get();
328 if (table.needsSweepAfterMinorGC()) {
329 table.sweepAfterMinorGC(trc);
330 }
331 }
332
333 void Realm::sweepAfterMinorGC(JSTracer* trc) {
334 globalWriteBarriered = 0;
335 dtoaCache.purge();
336 objects_.sweepAfterMinorGC(trc);
337 }
338
339 void Realm::traceWeakSavedStacks(JSTracer* trc) { savedStacks_.traceWeak(trc); }
340
341 void Realm::traceWeakGlobalEdge(JSTracer* trc) {
342 // If the global is dead, free its GlobalObjectData.
343 auto result = TraceWeakEdge(trc, &global_, "Realm::global_");
344 if (result.isDead()) {
345 result.initialTarget()->releaseData(runtime_->gcContext());
346 }
347 }
348
349 void Realm::traceWeakDebugEnvironmentEdges(JSTracer* trc) {
350 if (debugEnvs_) {
351 debugEnvs_->traceWeak(trc);
352 }
353 }
354
355 void Realm::fixupAfterMovingGC(JSTracer* trc) {
356 purge();
357 traceWeakGlobalEdge(trc);
358 }
359
360 void Realm::purge() {
361 dtoaCache.purge();
362 newProxyCache.purge();
363 newPlainObjectWithPropsCache.purge();
364 plainObjectAssignCache.purge();
365 objects_.iteratorCache.clearAndCompact();
366 }
367
368 void Realm::removeFromCompileQueue(JSScript* script) {
369 baselineCompileQueue_.remove(script);
370 }
371
372 // Check to see if this individual realm is recording allocations. Debuggers or
373 // runtimes can try and record allocations, so this method can check to see if
374 // any initialization is needed.
375 bool Realm::isRecordingAllocations() { return !!allocationMetadataBuilder_; }
376
377 void Realm::setAllocationMetadataBuilder(
378 const js::AllocationMetadataBuilder* builder) {
379 // Clear any jitcode in the runtime, which behaves differently depending on
380 // whether there is a creation callback.
381 if (bool(allocationMetadataBuilder_) != bool(builder)) {
382 ReleaseAllJITCode(runtime_->gcContext());
383 if (builder) {
384 zone()->incNumRealmsWithAllocMetadataBuilder();
385 } else {
386 zone()->decNumRealmsWithAllocMetadataBuilder();
387 }
388 }
389
390 allocationMetadataBuilder_ = builder;
391 }
392
393 void Realm::forgetAllocationMetadataBuilder() {
394 if (!allocationMetadataBuilder_) {
395 return;
396 }
397
398 // Unlike setAllocationMetadataBuilder, we don't have to discard all JIT
399 // code here (code is still valid, just a bit slower because it doesn't do
400 // inline GC allocations when a metadata builder is present), but we do want
401 // to cancel off-thread Ion compilations to avoid races when Ion accesses
402 // numRealmsWithAllocMetadataBuilder_ off-thread.
403 CancelOffThreadIonCompile(zone());
404
405 zone()->decNumRealmsWithAllocMetadataBuilder();
406
407 allocationMetadataBuilder_ = nullptr;
408 }
409
410 void Realm::setNewObjectMetadata(JSContext* cx, HandleObject obj) {
411 MOZ_ASSERT(obj->maybeCCWRealm() == this);
412 cx->check(compartment(), obj);
413
414 AutoEnterOOMUnsafeRegion oomUnsafe;
415 if (JSObject* metadata =
416 allocationMetadataBuilder_->build(cx, obj, oomUnsafe)) {
417 MOZ_ASSERT(metadata->maybeCCWRealm() == obj->maybeCCWRealm());
418 cx->check(metadata);
419
420 if (!objects_.objectMetadataTable) {
421 auto table = cx->make_unique<ObjectWeakMap>(cx);
422 if (!table) {
423 oomUnsafe.crash("setNewObjectMetadata");
424 }
425
426 objects_.objectMetadataTable = std::move(table);
427 }
428
429 if (!objects_.objectMetadataTable->put(obj, metadata)) {
430 oomUnsafe.crash("setNewObjectMetadata");
431 }
432 }
433 }
434
435 void Realm::updateDebuggerObservesFlag(unsigned flag) {
436 MOZ_ASSERT(isDebuggee());
437 MOZ_ASSERT(flag == DebuggerObservesAllExecution ||
438 flag == DebuggerObservesCoverage ||
439 flag == DebuggerObservesAsmJS || flag == DebuggerObservesWasm ||
440 flag == DebuggerObservesNativeCall);
441
442 GlobalObject* global =
443 zone()->runtimeFromMainThread()->gc.isForegroundSweeping()
444 ? unsafeUnbarrieredMaybeGlobal()
445 : maybeGlobal();
446 bool observes = false;
447 if (flag == DebuggerObservesAllExecution) {
448 observes = (global && DebugAPI::debuggerObservesAllExecution(global)) ||
449 isTracingExecution_;
450 } else if (flag == DebuggerObservesCoverage) {
451 observes = DebugAPI::debuggerObservesCoverage(global);
452 } else if (flag == DebuggerObservesAsmJS) {
453 observes = DebugAPI::debuggerObservesAsmJS(global);
454 } else if (flag == DebuggerObservesWasm) {
455 observes = DebugAPI::debuggerObservesWasm(global);
456 } else if (flag == DebuggerObservesNativeCall) {
457 observes = DebugAPI::debuggerObservesNativeCall(global);
458 }
459
460 if (observes) {
461 debugModeBits_ |= flag;
462 } else {
463 debugModeBits_ &= ~flag;
464 }
465 }
466
467 void Realm::setIsDebuggee() {
468 if (!isDebuggee()) {
469 debugModeBits_ |= IsDebuggee;
470 runtimeFromMainThread()->incrementNumDebuggeeRealms();
471 }
472 }
473
474 void Realm::unsetIsDebuggee() {
475 if (isDebuggee()) {
476 if (debuggerObservesCoverage()) {
477 runtime_->decrementNumDebuggeeRealmsObservingCoverage();
478 }
479 debugModeBits_ = 0;
480 DebugEnvironments::onRealmUnsetIsDebuggee(this);
481 runtimeFromMainThread()->decrementNumDebuggeeRealms();
482 }
483 }
484
485 void Realm::updateDebuggerObservesCoverage() {
486 bool previousState = debuggerObservesCoverage();
487 updateDebuggerObservesFlag(DebuggerObservesCoverage);
488 if (previousState == debuggerObservesCoverage()) {
489 return;
490 }
491
492 if (debuggerObservesCoverage()) {
493 // Interrupt any running interpreter frame. The scriptCounts are
494 // allocated on demand when a script resumes its execution.
495 JSContext* cx = TlsContext.get();
496 for (ActivationIterator iter(cx); !iter.done(); ++iter) {
497 if (iter->isInterpreter()) {
498 iter->asInterpreter()->enableInterruptsUnconditionally();
499 }
500 }
501 runtime_->incrementNumDebuggeeRealmsObservingCoverage();
502 return;
503 }
504
505 runtime_->decrementNumDebuggeeRealmsObservingCoverage();
506
507 // If code coverage is enabled by any other means, keep it.
508 if (collectCoverageForDebug()) {
509 return;
510 }
511
512 clearScriptCounts();
513 clearScriptLCov();
514 }
515
516 coverage::LCovRealm* Realm::lcovRealm() {
517 if (!lcovRealm_) {
518 lcovRealm_ = js::MakeUnique<coverage::LCovRealm>(this);
519 }
520 return lcovRealm_.get();
521 }
522
523 bool Realm::collectCoverageForDebug() const {
524 return debuggerObservesCoverage() || coverage::IsLCovEnabled();
525 }
526
527 void Realm::clearScriptCounts() { zone()->clearScriptCounts(this); }
528
529 void Realm::clearScriptLCov() { zone()->clearScriptLCov(this); }
530
531 const char* Realm::getLocale() const {
532 if (RefPtr<LocaleString> locale = creationOptions_.locale()) {
533 return locale->chars();
534 }
535
536 return runtime_->getDefaultLocale();
537 }
538
539 void ObjectRealm::addSizeOfExcludingThis(
540 mozilla::MallocSizeOf mallocSizeOf, size_t* innerViewsArg,
541 size_t* objectMetadataTablesArg,
542 size_t* nonSyntacticLexicalEnvironmentsArg) {
543 *innerViewsArg += innerViews.sizeOfExcludingThis(mallocSizeOf);
544
545 if (objectMetadataTable) {
546 *objectMetadataTablesArg +=
547 objectMetadataTable->shallowSizeOfIncludingThis(mallocSizeOf);
548 }
549
550 if (auto& map = nonSyntacticLexicalEnvironments_) {
551 *nonSyntacticLexicalEnvironmentsArg +=
552 map->shallowSizeOfIncludingThis(mallocSizeOf);
553 }
554 }
555
556 void Realm::addSizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf,
557 size_t* realmObject, size_t* realmTables,
558 size_t* innerViewsArg,
559 size_t* objectMetadataTablesArg,
560 size_t* savedStacksSet,
561 size_t* nonSyntacticLexicalEnvironmentsArg) {
562 *realmObject += mallocSizeOf(this);
563 wasm.addSizeOfExcludingThis(mallocSizeOf, realmTables);
564
565 objects_.addSizeOfExcludingThis(mallocSizeOf, innerViewsArg,
566 objectMetadataTablesArg,
567 nonSyntacticLexicalEnvironmentsArg);
568
569 *savedStacksSet += savedStacks_.sizeOfExcludingThis(mallocSizeOf);
570 }
571
572 bool Realm::shouldCaptureStackForThrow() {
573 // Determine whether a stack trace should be captured for throw-statements (or
574 // similar) in JS code in this realm. We don't want to do this unconditionally
575 // because capturing stacks is slow and some scripts throw a lot of
576 // exceptions.
577 //
578 // Note: this is unrelated to Error.stack! That property is observable from
579 // JS code so we can't use these heuristics there. The code here is mostly
580 // relevant for uncaught exceptions that are not Error objects.
581
582 // To match other browsers, we always capture a stack trace if the realm is a
583 // debuggee (this includes the devtools console being open) or if unlimited
584 // stack traces have been enabled for this realm (used in automation).
585 if (isDebuggee() || isUnlimitedStacksCapturingEnabled) {
586 return true;
587 }
588
589 // Also always capture for chrome code. This is code we control and this helps
590 // debugging.
591 if (principals() &&
592 principals() == runtimeFromMainThread()->trustedPrincipals()) {
593 return true;
594 }
595
596 // Else, capture the stack only for the first N exceptions so that we can
597 // still show stack traces for scripts that don't throw a lot of exceptions
598 // (if the console is opened later).
599 static constexpr uint16_t MaxStacksCapturedForThrow = 50;
600 if (numStacksCapturedForThrow_ > MaxStacksCapturedForThrow) {
601 return false;
602 }
603 numStacksCapturedForThrow_++;
604 return true;
605 }
606
607 mozilla::HashCodeScrambler Realm::randomHashCodeScrambler() {
608 return mozilla::HashCodeScrambler(randomKeyGenerator_.next(),
609 randomKeyGenerator_.next());
610 }
611
612 void AutoSetNewObjectMetadata::setPendingMetadata() {
613 JSObject* obj = cx_->realm()->getAndClearObjectPendingMetadata();
614 if (!obj) {
615 return;
616 }
617
618 MOZ_ASSERT(obj->getClass()->shouldDelayMetadataBuilder());
619
620 if (cx_->isExceptionPending()) {
621 return;
622 }
623
624 // This function is called from a destructor that often runs upon exit from
625 // a function that is returning an unrooted pointer to a Cell. The
626 // allocation metadata callback often allocates; if it causes a GC, then the
627 // Cell pointer being returned won't be traced or relocated.
628 //
629 // The only extant callbacks are those internal to SpiderMonkey that
630 // capture the JS stack. In fact, we're considering removing general
631 // callbacks altogther in bug 1236748. Since it's not running arbitrary
632 // code, it's adequate to simply suppress GC while we run the callback.
633 gc::AutoSuppressGC autoSuppressGC(cx_);
634
635 (void)SetNewObjectMetadata(cx_, obj);
636 }
637
638 JS_PUBLIC_API void gc::TraceRealmRoot(JSTracer* trc, JS::Realm* realm,
639 const char* name) {
640 // Trace the realm's global object to keep the realm alive.
641 //
642 // Note: this is called for Rooted<Realm*>. If a realm has been entered with
643 // AutoRealm, the global object is traced in Realm::traceRoots.
644 MOZ_RELEASE_ASSERT(realm->hasLiveGlobal(),
645 "we need to have a global to keep the realm alive");
646 gc::AssertRootMarkingPhase(trc);
647 realm->traceGlobalRoot(trc, "rooted realm");
648 }
649
650 JS_PUBLIC_API JS::Realm* JS::GetCurrentRealmOrNull(JSContext* cx) {
651 return cx->realm();
652 }
653
654 JS_PUBLIC_API JS::Realm* JS::GetObjectRealmOrNull(JSObject* obj) {
655 return IsCrossCompartmentWrapper(obj) ? nullptr : obj->nonCCWRealm();
656 }
657
658 JS_PUBLIC_API void* JS::GetRealmPrivate(JS::Realm* realm) {
659 return realm->realmPrivate();
660 }
661
662 JS_PUBLIC_API void JS::SetRealmPrivate(JS::Realm* realm, void* data) {
663 realm->setRealmPrivate(data);
664 }
665
666 JS_PUBLIC_API void JS::SetDestroyRealmCallback(
667 JSContext* cx, JS::DestroyRealmCallback callback) {
668 cx->runtime()->destroyRealmCallback = callback;
669 }
670
671 JS_PUBLIC_API void JS::SetRealmNameCallback(JSContext* cx,
672 JS::RealmNameCallback callback) {
673 cx->runtime()->realmNameCallback = callback;
674 }
675
676 JS_PUBLIC_API JSObject* JS::GetRealmGlobalOrNull(JS::Realm* realm) {
677 return realm->maybeGlobal();
678 }
679
680 JS_PUBLIC_API bool JS::InitRealmStandardClasses(JSContext* cx) {
681 MOZ_ASSERT(!cx->zone()->isAtomsZone());
682 AssertHeapIsIdle();
683 CHECK_THREAD(cx);
684 return GlobalObject::initStandardClasses(cx, cx->global());
685 }
686
687 JS_PUBLIC_API bool JS::MaybeFreezeCtorAndPrototype(JSContext* cx,
688 HandleObject ctor,
689 HandleObject maybeProto) {
690 if (MOZ_LIKELY(!cx->realm()->creationOptions().freezeBuiltins())) {
691 return true;
692 }
693 if (!SetIntegrityLevel(cx, ctor, IntegrityLevel::Frozen)) {
694 return false;
695 }
696 if (maybeProto) {
697 if (!SetIntegrityLevel(cx, maybeProto, IntegrityLevel::Sealed)) {
698 return false;
699 }
700 }
701 return true;
702 }
703
704 JS_PUBLIC_API JSObject* JS::GetRealmObjectPrototype(JSContext* cx) {
705 CHECK_THREAD(cx);
706 return &cx->global()->getObjectPrototype();
707 }
708
709 JS_PUBLIC_API JS::Handle<JSObject*> JS::GetRealmObjectPrototypeHandle(
710 JSContext* cx) {
711 return cx->global()->getObjectPrototypeHandle();
712 }
713
714 JS_PUBLIC_API JSObject* JS::GetRealmFunctionPrototype(JSContext* cx) {
715 CHECK_THREAD(cx);
716 return &cx->global()->getFunctionPrototype();
717 }
718
719 JS_PUBLIC_API JS::Handle<JSObject*> JS::GetRealmFunctionPrototypeHandle(
720 JSContext* cx) {
721 CHECK_THREAD(cx);
722 return cx->global()->getFunctionPrototypeHandle();
723 }
724
725 JS_PUBLIC_API JSObject* JS::GetRealmArrayPrototype(JSContext* cx) {
726 CHECK_THREAD(cx);
727 return GlobalObject::getOrCreateArrayPrototype(cx, cx->global());
728 }
729
730 JS_PUBLIC_API JSObject* JS::GetRealmErrorPrototype(JSContext* cx) {
731 CHECK_THREAD(cx);
732 return GlobalObject::getOrCreateCustomErrorPrototype(cx, cx->global(),
733 JSEXN_ERR);
734 }
735
736 JS_PUBLIC_API JSObject* JS::GetRealmIteratorPrototype(JSContext* cx) {
737 CHECK_THREAD(cx);
738 return GlobalObject::getOrCreateIteratorPrototype(cx, cx->global());
739 }
740
741 JS_PUBLIC_API JSObject* JS::GetRealmAsyncIteratorPrototype(JSContext* cx) {
742 CHECK_THREAD(cx);
743 return GlobalObject::getOrCreateAsyncIteratorPrototype(cx, cx->global());
744 }
745
746 JS_PUBLIC_API JSObject* JS::GetRealmKeyObject(JSContext* cx) {
747 return GlobalObject::getOrCreateRealmKeyObject(cx, cx->global());
748 }
749
750 JS_PUBLIC_API Realm* JS::GetFunctionRealm(JSContext* cx, HandleObject objArg) {
751 // https://tc39.github.io/ecma262/#sec-getfunctionrealm
752 // 7.3.22 GetFunctionRealm ( obj )
753
754 CHECK_THREAD(cx);
755 cx->check(objArg);
756
757 RootedObject obj(cx, objArg);
758 while (true) {
759 obj = CheckedUnwrapStatic(obj);
760 if (!obj) {
761 ReportAccessDenied(cx);
762 return nullptr;
763 }
764
765 // Step 1.
766 MOZ_ASSERT(IsCallable(obj));
767
768 // Steps 2 and 3. We use a loop instead of recursion to unwrap bound
769 // functions.
770 if (obj->is<JSFunction>()) {
771 return obj->as<JSFunction>().realm();
772 }
773 if (obj->is<BoundFunctionObject>()) {
774 obj = obj->as<BoundFunctionObject>().getTarget();
775 continue;
776 }
777
778 // WrappedFunctionObjects also have a [[Realm]] internal slot,
779 // which is the nonCCWRealm by construction.
780 if (obj->is<WrappedFunctionObject>()) {
781 return obj->nonCCWRealm();
782 }
783
784 // Step 4.
785 if (IsScriptedProxy(obj)) {
786 // Steps 4.a-b.
787 JSObject* proxyTarget = GetProxyTargetObject(obj);
788 if (!proxyTarget) {
789 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
790 JSMSG_PROXY_REVOKED);
791 return nullptr;
792 }
793
794 // Step 4.c.
795 obj = proxyTarget;
796 continue;
797 }
798
799 // Step 5.
800 return cx->realm();
801 }
802 }
803
804 JS_PUBLIC_API void JS::ResetRealmMathRandomSeed(JSContext* cx) {
805 MOZ_ASSERT(cx->realm());
806 auto rng = cx->realm()->getOrCreateRandomNumberGenerator();
807 mozilla::Array<uint64_t, 2> seed;
808 GenerateXorShift128PlusSeed(seed);
809 rng.setState(seed[0], seed[1]);
810 }