Backed out 15 changesets (bug 1852806) for causing mda failures on test_video_low_pow...
[gecko.git] / js / src / jsfriendapi.cpp
blob44ca17897c6192452ab8c349c592898bf4dfd1e1
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/. */
7 #include "jsfriendapi.h"
9 #include "mozilla/Maybe.h"
10 #include "mozilla/PodOperations.h"
11 #include "mozilla/TimeStamp.h"
13 #include <stdint.h>
15 #include "builtin/BigInt.h"
16 #include "builtin/MapObject.h"
17 #include "builtin/TestingFunctions.h"
18 #include "frontend/FrontendContext.h" // FrontendContext
19 #include "gc/PublicIterators.h"
20 #include "gc/WeakMap.h"
21 #include "js/ColumnNumber.h" // JS::LimitedColumnNumberZeroOrigin
22 #include "js/experimental/CodeCoverage.h"
23 #include "js/experimental/CTypes.h" // JS::AutoCTypesActivityCallback, JS::SetCTypesActivityCallback
24 #include "js/experimental/Intl.h" // JS::AddMoz{DateTimeFormat,DisplayNames}Constructor
25 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
26 #include "js/friend/StackLimits.h" // JS_STACK_GROWTH_DIRECTION
27 #include "js/friend/WindowProxy.h" // js::ToWindowIfWindowProxy
28 #include "js/HashTable.h"
29 #include "js/Object.h" // JS::GetClass
30 #include "js/PropertyAndElement.h" // JS_DefineProperty
31 #include "js/Proxy.h"
32 #include "js/Stack.h" // JS::NativeStackLimitMax
33 #include "js/String.h" // JS::detail::StringToLinearStringSlow
34 #include "js/Wrapper.h"
35 #include "proxy/DeadObjectProxy.h"
36 #include "util/Poison.h"
37 #include "vm/ArgumentsObject.h"
38 #include "vm/BooleanObject.h"
39 #include "vm/DateObject.h"
40 #include "vm/ErrorObject.h"
41 #include "vm/Interpreter.h"
42 #include "vm/JSContext.h"
43 #include "vm/JSObject.h"
44 #include "vm/NumberObject.h"
45 #include "vm/PlainObject.h" // js::PlainObject
46 #include "vm/PromiseObject.h" // js::PromiseObject
47 #include "vm/Realm.h"
48 #include "vm/StringObject.h"
49 #include "vm/WrapperObject.h"
50 #ifdef ENABLE_RECORD_TUPLE
51 # include "vm/RecordType.h"
52 # include "vm/TupleType.h"
53 #endif
55 #include "gc/Marking-inl.h"
56 #include "vm/Compartment-inl.h" // JS::Compartment::wrap
57 #include "vm/JSObject-inl.h"
58 #include "vm/JSScript-inl.h"
59 #include "vm/Realm-inl.h"
61 using namespace js;
63 using mozilla::PodArrayZero;
65 JS::RootingContext::RootingContext(js::Nursery* nursery)
66 : nursery_(nursery), zone_(nullptr), realm_(nullptr) {
67 for (auto& listHead : stackRoots_) {
68 listHead = nullptr;
70 for (auto& listHead : autoGCRooters_) {
71 listHead = nullptr;
74 #if JS_STACK_GROWTH_DIRECTION > 0
75 for (int i = 0; i < StackKindCount; i++) {
76 nativeStackLimit[i] = JS::NativeStackLimitMax;
78 #else
79 static_assert(JS::NativeStackLimitMax == 0);
80 PodArrayZero(nativeStackLimit);
81 #endif
84 JS_PUBLIC_API void JS_SetGrayGCRootsTracer(JSContext* cx,
85 JSGrayRootsTracer traceOp,
86 void* data) {
87 cx->runtime()->gc.setGrayRootsTracer(traceOp, data);
90 JS_PUBLIC_API JSObject* JS_FindCompilationScope(JSContext* cx,
91 HandleObject objArg) {
92 cx->check(objArg);
94 RootedObject obj(cx, objArg);
97 * We unwrap wrappers here. This is a little weird, but it's what's being
98 * asked of us.
100 if (obj->is<WrapperObject>()) {
101 obj = UncheckedUnwrap(obj);
105 * Get the Window if `obj` is a WindowProxy so that we compile in the
106 * correct (global) scope.
108 return ToWindowIfWindowProxy(obj);
111 JS_PUBLIC_API JSFunction* JS_GetObjectFunction(JSObject* obj) {
112 if (obj->is<JSFunction>()) {
113 return &obj->as<JSFunction>();
115 return nullptr;
118 JS_PUBLIC_API JSObject* JS_NewObjectWithoutMetadata(
119 JSContext* cx, const JSClass* clasp, JS::Handle<JSObject*> proto) {
120 cx->check(proto);
121 AutoSuppressAllocationMetadataBuilder suppressMetadata(cx);
122 return JS_NewObjectWithGivenProto(cx, clasp, proto);
125 JS_PUBLIC_API bool JS::GetIsSecureContext(JS::Realm* realm) {
126 return realm->creationOptions().secureContext();
129 JS_PUBLIC_API JSPrincipals* JS::GetRealmPrincipals(JS::Realm* realm) {
130 return realm->principals();
133 JS_PUBLIC_API bool JS::GetDebuggerObservesWasm(JS::Realm* realm) {
134 return realm->debuggerObservesAsmJS();
137 JS_PUBLIC_API void JS::SetRealmPrincipals(JS::Realm* realm,
138 JSPrincipals* principals) {
139 // Short circuit if there's no change.
140 if (principals == realm->principals()) {
141 return;
144 // We'd like to assert that our new principals is always same-origin
145 // with the old one, but JSPrincipals doesn't give us a way to do that.
146 // But we can at least assert that we're not switching between system
147 // and non-system.
148 const JSPrincipals* trusted =
149 realm->runtimeFromMainThread()->trustedPrincipals();
150 bool isSystem = principals && principals == trusted;
151 MOZ_RELEASE_ASSERT(realm->isSystem() == isSystem);
153 // Clear out the old principals, if any.
154 if (realm->principals()) {
155 JS_DropPrincipals(TlsContext.get(), realm->principals());
156 realm->setPrincipals(nullptr);
159 // Set up the new principals.
160 if (principals) {
161 JS_HoldPrincipals(principals);
162 realm->setPrincipals(principals);
166 JS_PUBLIC_API JSPrincipals* JS_GetScriptPrincipals(JSScript* script) {
167 return script->principals();
170 JS_PUBLIC_API bool JS_ScriptHasMutedErrors(JSScript* script) {
171 return script->mutedErrors();
174 JS_PUBLIC_API bool JS_WrapPropertyDescriptor(
175 JSContext* cx, JS::MutableHandle<JS::PropertyDescriptor> desc) {
176 return cx->compartment()->wrap(cx, desc);
179 JS_PUBLIC_API bool JS_WrapPropertyDescriptor(
180 JSContext* cx,
181 JS::MutableHandle<mozilla::Maybe<JS::PropertyDescriptor>> desc) {
182 return cx->compartment()->wrap(cx, desc);
185 JS_PUBLIC_API void JS_TraceShapeCycleCollectorChildren(JS::CallbackTracer* trc,
186 JS::GCCellPtr shape) {
187 MOZ_ASSERT(shape.is<Shape>());
188 TraceCycleCollectorChildren(trc, &shape.as<Shape>());
191 static bool DefineHelpProperty(JSContext* cx, HandleObject obj,
192 const char* prop, const char* value) {
193 Rooted<JSAtom*> atom(cx, Atomize(cx, value, strlen(value)));
194 if (!atom) {
195 return false;
197 return JS_DefineProperty(cx, obj, prop, atom,
198 JSPROP_READONLY | JSPROP_PERMANENT);
201 JS_PUBLIC_API bool JS_DefineFunctionsWithHelp(
202 JSContext* cx, HandleObject obj, const JSFunctionSpecWithHelp* fs) {
203 MOZ_ASSERT(!cx->zone()->isAtomsZone());
205 CHECK_THREAD(cx);
206 cx->check(obj);
207 for (; fs->name; fs++) {
208 JSAtom* atom = Atomize(cx, fs->name, strlen(fs->name));
209 if (!atom) {
210 return false;
213 Rooted<jsid> id(cx, AtomToId(atom));
214 RootedFunction fun(cx, DefineFunction(cx, obj, id, fs->call, fs->nargs,
215 fs->flags | JSPROP_RESOLVING));
216 if (!fun) {
217 return false;
220 if (fs->jitInfo) {
221 fun->setJitInfo(fs->jitInfo);
224 if (fs->usage) {
225 if (!DefineHelpProperty(cx, fun, "usage", fs->usage)) {
226 return false;
230 if (fs->help) {
231 if (!DefineHelpProperty(cx, fun, "help", fs->help)) {
232 return false;
237 return true;
240 JS_PUBLIC_API bool JS::GetBuiltinClass(JSContext* cx, HandleObject obj,
241 js::ESClass* cls) {
242 if (MOZ_UNLIKELY(obj->is<ProxyObject>())) {
243 return Proxy::getBuiltinClass(cx, obj, cls);
246 if (obj->is<PlainObject>()) {
247 *cls = ESClass::Object;
248 } else if (obj->is<ArrayObject>()) {
249 *cls = ESClass::Array;
250 } else if (obj->is<NumberObject>()) {
251 *cls = ESClass::Number;
252 } else if (obj->is<StringObject>()) {
253 *cls = ESClass::String;
254 } else if (obj->is<BooleanObject>()) {
255 *cls = ESClass::Boolean;
256 } else if (obj->is<RegExpObject>()) {
257 *cls = ESClass::RegExp;
258 } else if (obj->is<ArrayBufferObject>()) {
259 *cls = ESClass::ArrayBuffer;
260 } else if (obj->is<SharedArrayBufferObject>()) {
261 *cls = ESClass::SharedArrayBuffer;
262 } else if (obj->is<DateObject>()) {
263 *cls = ESClass::Date;
264 } else if (obj->is<SetObject>()) {
265 *cls = ESClass::Set;
266 } else if (obj->is<MapObject>()) {
267 *cls = ESClass::Map;
268 } else if (obj->is<PromiseObject>()) {
269 *cls = ESClass::Promise;
270 } else if (obj->is<MapIteratorObject>()) {
271 *cls = ESClass::MapIterator;
272 } else if (obj->is<SetIteratorObject>()) {
273 *cls = ESClass::SetIterator;
274 } else if (obj->is<ArgumentsObject>()) {
275 *cls = ESClass::Arguments;
276 } else if (obj->is<ErrorObject>()) {
277 *cls = ESClass::Error;
278 } else if (obj->is<BigIntObject>()) {
279 *cls = ESClass::BigInt;
280 #ifdef ENABLE_RECORD_TUPLE
281 } else if (obj->is<RecordType>()) {
282 *cls = ESClass::Record;
283 } else if (obj->is<TupleType>()) {
284 *cls = ESClass::Tuple;
285 #endif
286 } else if (obj->is<JSFunction>()) {
287 *cls = ESClass::Function;
288 } else {
289 *cls = ESClass::Other;
292 return true;
295 JS_PUBLIC_API bool js::IsArgumentsObject(HandleObject obj) {
296 return obj->is<ArgumentsObject>();
299 JS_PUBLIC_API JS::Zone* js::GetRealmZone(JS::Realm* realm) {
300 return realm->zone();
303 JS_PUBLIC_API bool js::IsSystemCompartment(JS::Compartment* comp) {
304 // Realms in the same compartment must either all be system realms or
305 // non-system realms. We assert this in NewRealm and SetRealmPrincipals,
306 // but do an extra sanity check here.
307 MOZ_ASSERT(comp->realms()[0]->isSystem() ==
308 comp->realms().back()->isSystem());
309 return comp->realms()[0]->isSystem();
312 JS_PUBLIC_API bool js::IsSystemRealm(JS::Realm* realm) {
313 return realm->isSystem();
316 JS_PUBLIC_API bool js::IsSystemZone(Zone* zone) { return zone->isSystemZone(); }
318 JS_PUBLIC_API bool js::IsFunctionObject(JSObject* obj) {
319 return obj->is<JSFunction>();
322 JS_PUBLIC_API bool js::IsSavedFrame(JSObject* obj) {
323 return obj->is<SavedFrame>();
326 JS_PUBLIC_API bool js::UninlinedIsCrossCompartmentWrapper(const JSObject* obj) {
327 return js::IsCrossCompartmentWrapper(obj);
330 JS_PUBLIC_API void js::AssertSameCompartment(JSContext* cx, JSObject* obj) {
331 cx->check(obj);
334 JS_PUBLIC_API void js::AssertSameCompartment(JSContext* cx, JS::HandleValue v) {
335 cx->check(v);
338 #ifdef DEBUG
339 JS_PUBLIC_API void js::AssertSameCompartment(JSObject* objA, JSObject* objB) {
340 MOZ_ASSERT(objA->compartment() == objB->compartment());
342 #endif
344 JS_PUBLIC_API void js::NotifyAnimationActivity(JSObject* obj) {
345 MOZ_ASSERT(obj->is<GlobalObject>());
347 auto timeNow = mozilla::TimeStamp::Now();
348 obj->as<GlobalObject>().realm()->lastAnimationTime = timeNow;
349 obj->runtimeFromMainThread()->lastAnimationTime = timeNow;
352 JS_PUBLIC_API bool js::IsObjectInContextCompartment(JSObject* obj,
353 const JSContext* cx) {
354 return obj->compartment() == cx->compartment();
357 JS_PUBLIC_API JS::StackKind
358 js::AutoCheckRecursionLimit::stackKindForCurrentPrincipal(JSContext* cx) const {
359 return cx->stackKindForCurrentPrincipal();
362 JS::NativeStackLimit AutoCheckRecursionLimit::getStackLimit(
363 FrontendContext* fc) const {
364 return fc->stackLimit();
367 JS_PUBLIC_API JSFunction* js::DefineFunctionWithReserved(
368 JSContext* cx, JSObject* objArg, const char* name, JSNative call,
369 unsigned nargs, unsigned attrs) {
370 RootedObject obj(cx, objArg);
371 MOZ_ASSERT(!cx->zone()->isAtomsZone());
372 CHECK_THREAD(cx);
373 cx->check(obj);
374 JSAtom* atom = Atomize(cx, name, strlen(name));
375 if (!atom) {
376 return nullptr;
378 Rooted<jsid> id(cx, AtomToId(atom));
379 return DefineFunction(cx, obj, id, call, nargs, attrs,
380 gc::AllocKind::FUNCTION_EXTENDED);
383 JS_PUBLIC_API JSFunction* js::NewFunctionWithReserved(JSContext* cx,
384 JSNative native,
385 unsigned nargs,
386 unsigned flags,
387 const char* name) {
388 MOZ_ASSERT(!cx->zone()->isAtomsZone());
390 CHECK_THREAD(cx);
392 Rooted<JSAtom*> atom(cx);
393 if (name) {
394 atom = Atomize(cx, name, strlen(name));
395 if (!atom) {
396 return nullptr;
400 return (flags & JSFUN_CONSTRUCTOR)
401 ? NewNativeConstructor(cx, native, nargs, atom,
402 gc::AllocKind::FUNCTION_EXTENDED)
403 : NewNativeFunction(cx, native, nargs, atom,
404 gc::AllocKind::FUNCTION_EXTENDED);
407 JS_PUBLIC_API JSFunction* js::NewFunctionByIdWithReserved(
408 JSContext* cx, JSNative native, unsigned nargs, unsigned flags, jsid id) {
409 MOZ_ASSERT(id.isAtom());
410 MOZ_ASSERT(!cx->zone()->isAtomsZone());
411 CHECK_THREAD(cx);
412 cx->check(id);
414 Rooted<JSAtom*> atom(cx, id.toAtom());
415 return (flags & JSFUN_CONSTRUCTOR)
416 ? NewNativeConstructor(cx, native, nargs, atom,
417 gc::AllocKind::FUNCTION_EXTENDED)
418 : NewNativeFunction(cx, native, nargs, atom,
419 gc::AllocKind::FUNCTION_EXTENDED);
422 JS_PUBLIC_API const Value& js::GetFunctionNativeReserved(JSObject* fun,
423 size_t which) {
424 MOZ_ASSERT(fun->as<JSFunction>().isNativeFun());
425 return fun->as<JSFunction>().getExtendedSlot(which);
428 JS_PUBLIC_API void js::SetFunctionNativeReserved(JSObject* fun, size_t which,
429 const Value& val) {
430 MOZ_ASSERT(fun->as<JSFunction>().isNativeFun());
431 MOZ_ASSERT_IF(val.isObject(),
432 val.toObject().compartment() == fun->compartment());
433 fun->as<JSFunction>().setExtendedSlot(which, val);
436 JS_PUBLIC_API bool js::FunctionHasNativeReserved(JSObject* fun) {
437 MOZ_ASSERT(fun->as<JSFunction>().isNativeFun());
438 return fun->as<JSFunction>().isExtended();
441 bool js::GetObjectProto(JSContext* cx, JS::Handle<JSObject*> obj,
442 JS::MutableHandle<JSObject*> proto) {
443 cx->check(obj);
445 if (obj->is<ProxyObject>()) {
446 return JS_GetPrototype(cx, obj, proto);
449 proto.set(obj->staticPrototype());
450 return true;
453 JS_PUBLIC_API JSObject* js::GetStaticPrototype(JSObject* obj) {
454 MOZ_ASSERT(obj->hasStaticPrototype());
455 return obj->staticPrototype();
458 JS_PUBLIC_API bool js::GetRealmOriginalEval(JSContext* cx,
459 MutableHandleObject eval) {
460 eval.set(&cx->global()->getEvalFunction());
461 return true;
464 void JS::detail::SetReservedSlotWithBarrier(JSObject* obj, size_t slot,
465 const Value& value) {
466 if (obj->is<ProxyObject>()) {
467 obj->as<ProxyObject>().setReservedSlot(slot, value);
468 } else {
469 // Note: we don't use setReservedSlot so that this also works on swappable
470 // DOM objects. See NativeObject::getReservedSlotRef comment.
471 obj->as<NativeObject>().setSlot(slot, value);
475 void js::SetPreserveWrapperCallbacks(
476 JSContext* cx, PreserveWrapperCallback preserveWrapper,
477 HasReleasedWrapperCallback hasReleasedWrapper) {
478 cx->runtime()->preserveWrapperCallback = preserveWrapper;
479 cx->runtime()->hasReleasedWrapperCallback = hasReleasedWrapper;
482 JS_PUBLIC_API unsigned JS_PCToLineNumber(
483 JSScript* script, jsbytecode* pc,
484 JS::LimitedColumnNumberZeroOrigin* columnp) {
485 return PCToLineNumber(script, pc, columnp);
488 JS_PUBLIC_API bool JS_IsDeadWrapper(JSObject* obj) {
489 return IsDeadProxyObject(obj);
492 JS_PUBLIC_API JSObject* JS_NewDeadWrapper(JSContext* cx, JSObject* origObj) {
493 return NewDeadProxyObject(cx, origObj);
496 void js::TraceWeakMaps(WeakMapTracer* trc) {
497 WeakMapBase::traceAllMappings(trc);
500 extern JS_PUBLIC_API bool js::AreGCGrayBitsValid(JSRuntime* rt) {
501 return rt->gc.areGrayBitsValid();
504 JS_PUBLIC_API bool js::ZoneGlobalsAreAllGray(JS::Zone* zone) {
505 for (RealmsInZoneIter realm(zone); !realm.done(); realm.next()) {
506 JSObject* obj = realm->unsafeUnbarrieredMaybeGlobal();
507 if (!obj || !JS::ObjectIsMarkedGray(obj)) {
508 return false;
511 return true;
514 JS_PUBLIC_API bool js::IsCompartmentZoneSweepingOrCompacting(
515 JS::Compartment* comp) {
516 MOZ_ASSERT(comp);
517 return comp->zone()->isGCSweepingOrCompacting();
520 JS_PUBLIC_API void js::TraceGrayWrapperTargets(JSTracer* trc, Zone* zone) {
521 JS::AutoSuppressGCAnalysis nogc;
523 for (CompartmentsInZoneIter comp(zone); !comp.done(); comp.next()) {
524 for (Compartment::ObjectWrapperEnum e(comp); !e.empty(); e.popFront()) {
525 JSObject* target = e.front().key();
526 if (target->isMarkedGray()) {
527 TraceManuallyBarrieredEdge(trc, &target, "gray CCW target");
528 MOZ_ASSERT(target == e.front().key());
534 JSLinearString* JS::detail::StringToLinearStringSlow(JSContext* cx,
535 JSString* str) {
536 return str->ensureLinear(cx);
539 static bool CopyProxyObject(JSContext* cx, Handle<ProxyObject*> from,
540 Handle<ProxyObject*> to) {
541 MOZ_ASSERT(from->getClass() == to->getClass());
543 if (from->is<WrapperObject>() &&
544 (Wrapper::wrapperHandler(from)->flags() & Wrapper::CROSS_COMPARTMENT)) {
545 to->setCrossCompartmentPrivate(GetProxyPrivate(from));
546 } else {
547 RootedValue v(cx, GetProxyPrivate(from));
548 if (!cx->compartment()->wrap(cx, &v)) {
549 return false;
551 to->setSameCompartmentPrivate(v);
554 MOZ_ASSERT(from->numReservedSlots() == to->numReservedSlots());
556 RootedValue v(cx);
557 for (size_t n = 0; n < from->numReservedSlots(); n++) {
558 v = GetProxyReservedSlot(from, n);
559 if (!cx->compartment()->wrap(cx, &v)) {
560 return false;
562 SetProxyReservedSlot(to, n, v);
565 return true;
568 JS_PUBLIC_API JSObject* JS_CloneObject(JSContext* cx, HandleObject obj,
569 HandleObject proto) {
570 // |obj| might be in a different compartment.
571 cx->check(proto);
573 if (!obj->is<NativeObject>() && !obj->is<ProxyObject>()) {
574 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
575 JSMSG_CANT_CLONE_OBJECT);
576 return nullptr;
579 RootedObject clone(cx);
580 if (obj->is<NativeObject>()) {
581 clone = NewObjectWithGivenProto(cx, obj->getClass(), proto);
582 if (!clone) {
583 return nullptr;
586 if (clone->is<JSFunction>() && obj->compartment() != clone->compartment()) {
587 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
588 JSMSG_CANT_CLONE_OBJECT);
589 return nullptr;
591 } else {
592 auto* handler = GetProxyHandler(obj);
593 clone = ProxyObject::New(cx, handler, JS::NullHandleValue,
594 AsTaggedProto(proto), obj->getClass());
595 if (!clone) {
596 return nullptr;
599 if (!CopyProxyObject(cx, obj.as<ProxyObject>(), clone.as<ProxyObject>())) {
600 return nullptr;
604 return clone;
607 extern JS_PUBLIC_API bool JS::ForceLexicalInitialization(JSContext* cx,
608 HandleObject obj) {
609 AssertHeapIsIdle();
610 CHECK_THREAD(cx);
611 cx->check(obj);
613 bool initializedAny = false;
614 NativeObject* nobj = &obj->as<NativeObject>();
616 for (ShapePropertyIter<NoGC> iter(nobj->shape()); !iter.done(); iter++) {
617 Value v = nobj->getSlot(iter->slot());
618 if (iter->isDataProperty() && v.isMagic() &&
619 v.whyMagic() == JS_UNINITIALIZED_LEXICAL) {
620 nobj->setSlot(iter->slot(), UndefinedValue());
621 initializedAny = true;
624 return initializedAny;
627 extern JS_PUBLIC_API int JS::IsGCPoisoning() {
628 #ifdef JS_GC_ALLOW_EXTRA_POISONING
629 return js::gExtraPoisoningEnabled;
630 #else
631 return false;
632 #endif
635 JS_PUBLIC_API void JS::NotifyGCRootsRemoved(JSContext* cx) {
636 cx->runtime()->gc.notifyRootsRemoved();
639 JS_PUBLIC_API JS::Realm* js::GetAnyRealmInZone(JS::Zone* zone) {
640 if (zone->isAtomsZone()) {
641 return nullptr;
644 RealmsInZoneIter realm(zone);
645 MOZ_ASSERT(!realm.done());
646 return realm.get();
649 JS_PUBLIC_API bool js::IsSharableCompartment(JS::Compartment* comp) {
650 // If this compartment has nuked outgoing wrappers (because all its globals
651 // got nuked), we won't be able to create any useful CCWs out of it in the
652 // future, and so we shouldn't use it for any new globals.
653 if (comp->nukedOutgoingWrappers) {
654 return false;
657 // If this compartment has no live globals, it might be in the middle of being
658 // GCed. Don't create any new Realms inside. There's no point to doing that
659 // anyway, since the idea would be to avoid CCWs from existing Realms in the
660 // compartment to the new Realm, and there are no existing Realms.
661 if (!CompartmentHasLiveGlobal(comp)) {
662 return false;
665 // Good to go.
666 return true;
669 JS_PUBLIC_API JSObject* js::GetTestingFunctions(JSContext* cx) {
670 RootedObject obj(cx, JS_NewPlainObject(cx));
671 if (!obj) {
672 return nullptr;
675 if (!DefineTestingFunctions(cx, obj, false, false)) {
676 return nullptr;
679 return obj;
682 JS_PUBLIC_API void js::SetDOMCallbacks(JSContext* cx,
683 const DOMCallbacks* callbacks) {
684 cx->runtime()->DOMcallbacks = callbacks;
687 JS_PUBLIC_API const DOMCallbacks* js::GetDOMCallbacks(JSContext* cx) {
688 return cx->runtime()->DOMcallbacks;
691 JS_PUBLIC_API void js::PrepareScriptEnvironmentAndInvoke(
692 JSContext* cx, HandleObject global,
693 ScriptEnvironmentPreparer::Closure& closure) {
694 MOZ_ASSERT(!cx->isExceptionPending());
695 MOZ_ASSERT(global->is<GlobalObject>());
697 MOZ_RELEASE_ASSERT(
698 cx->runtime()->scriptEnvironmentPreparer,
699 "Embedding needs to set a scriptEnvironmentPreparer callback");
701 cx->runtime()->scriptEnvironmentPreparer->invoke(global, closure);
704 JS_PUBLIC_API void js::SetScriptEnvironmentPreparer(
705 JSContext* cx, ScriptEnvironmentPreparer* preparer) {
706 cx->runtime()->scriptEnvironmentPreparer = preparer;
709 JS_PUBLIC_API void JS::SetCTypesActivityCallback(JSContext* cx,
710 CTypesActivityCallback cb) {
711 cx->runtime()->ctypesActivityCallback = cb;
714 JS::AutoCTypesActivityCallback::AutoCTypesActivityCallback(
715 JSContext* cx, CTypesActivityType beginType, CTypesActivityType endType)
716 : cx(cx),
717 callback(cx->runtime()->ctypesActivityCallback),
718 endType(endType) {
719 if (callback) {
720 callback(cx, beginType);
724 JS_PUBLIC_API void js::SetAllocationMetadataBuilder(
725 JSContext* cx, const AllocationMetadataBuilder* callback) {
726 cx->realm()->setAllocationMetadataBuilder(callback);
729 JS_PUBLIC_API JSObject* js::GetAllocationMetadata(JSObject* obj) {
730 ObjectWeakMap* map = ObjectRealm::get(obj).objectMetadataTable.get();
731 if (map) {
732 return map->lookup(obj);
734 return nullptr;
737 JS_PUBLIC_API bool js::ReportIsNotFunction(JSContext* cx, HandleValue v) {
738 cx->check(v);
739 return ReportIsNotFunction(cx, v, -1);
742 #ifdef DEBUG
743 bool js::HasObjectMovedOp(JSObject* obj) {
744 return !!JS::GetClass(obj)->extObjectMovedOp();
746 #endif
748 JS_PUBLIC_API bool js::ForwardToNative(JSContext* cx, JSNative native,
749 const CallArgs& args) {
750 return native(cx, args.length(), args.base());
753 AutoAssertNoContentJS::AutoAssertNoContentJS(JSContext* cx)
754 : context_(cx), prevAllowContentJS_(cx->runtime()->allowContentJS_) {
755 cx->runtime()->allowContentJS_ = false;
758 AutoAssertNoContentJS::~AutoAssertNoContentJS() {
759 context_->runtime()->allowContentJS_ = prevAllowContentJS_;
762 JS_PUBLIC_API void js::EnableCodeCoverage() { js::coverage::EnableLCov(); }
764 JS_PUBLIC_API JS::Value js::MaybeGetScriptPrivate(JSObject* object) {
765 if (!object->is<ScriptSourceObject>()) {
766 return UndefinedValue();
769 return object->as<ScriptSourceObject>().getPrivate();
772 JS_PUBLIC_API uint64_t js::GetMemoryUsageForZone(Zone* zone) {
773 // We do not include zone->sharedMemoryUseCounts since that's already included
774 // in zone->mallocHeapSize.
775 return zone->gcHeapSize.bytes() + zone->mallocHeapSize.bytes() +
776 zone->jitHeapSize.bytes();
779 JS_PUBLIC_API const gc::SharedMemoryMap& js::GetSharedMemoryUsageForZone(
780 Zone* zone) {
781 return zone->sharedMemoryUseCounts;
784 JS_PUBLIC_API uint64_t js::GetGCHeapUsage(JSContext* cx) {
785 mozilla::CheckedInt<uint64_t> sum = 0;
786 using SharedSet = js::HashSet<void*, PointerHasher<void*>, SystemAllocPolicy>;
787 SharedSet sharedVisited;
789 for (ZonesIter zone(cx->runtime(), WithAtoms); !zone.done(); zone.next()) {
790 sum += GetMemoryUsageForZone(zone);
792 const gc::SharedMemoryMap& shared = GetSharedMemoryUsageForZone(zone);
793 for (auto iter = shared.iter(); !iter.done(); iter.next()) {
794 void* sharedMem = iter.get().key();
795 SharedSet::AddPtr addShared = sharedVisited.lookupForAdd(sharedMem);
796 if (addShared) {
797 // We *have* seen this shared memory before.
799 // Because shared memory is already included in
800 // GetMemoryUsageForZone() above, and we've seen it for a
801 // previous zone, we subtract it here so it's not counted more
802 // than once.
803 sum -= iter.get().value().nbytes;
804 } else if (!sharedVisited.add(addShared, sharedMem)) {
805 // OOM, abort counting (usually causing an over-estimate).
806 break;
811 MOZ_ASSERT(sum.isValid(), "Memory calculation under/over flowed");
812 return sum.value();
815 #ifdef DEBUG
816 JS_PUBLIC_API bool js::RuntimeIsBeingDestroyed() {
817 JSRuntime* runtime = TlsContext.get()->runtime();
818 MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(runtime));
819 return runtime->isBeingDestroyed();
821 #endif
823 // No-op implementations of public API that would depend on --with-intl-api
825 #ifndef JS_HAS_INTL_API
827 static bool IntlNotEnabled(JSContext* cx) {
828 JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr,
829 JSMSG_SUPPORT_NOT_ENABLED, "Intl");
830 return false;
833 bool JS::AddMozDateTimeFormatConstructor(JSContext* cx, JS::HandleObject intl) {
834 return IntlNotEnabled(cx);
837 bool JS::AddMozDisplayNamesConstructor(JSContext* cx, JS::HandleObject intl) {
838 return IntlNotEnabled(cx);
841 #endif // !JS_HAS_INTL_API
843 JS_PUBLIC_API JS::Zone* js::GetObjectZoneFromAnyThread(const JSObject* obj) {
844 return MaybeForwarded(obj)->zoneFromAnyThread();