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/. */
13 #include "mozilla/FloatingPoint.h"
14 #include "mozilla/Maybe.h"
15 #include "mozilla/PodOperations.h"
16 #include "mozilla/Sprintf.h"
28 #include "jsfriendapi.h"
32 #include "builtin/AtomicsObject.h"
33 #include "builtin/Eval.h"
34 #include "builtin/JSON.h"
35 #include "builtin/Promise.h"
36 #include "builtin/Symbol.h"
37 #include "frontend/BytecodeCompiler.h"
38 #include "frontend/FrontendContext.h" // AutoReportFrontendContext
40 #include "gc/GCContext.h"
41 #include "gc/Marking.h"
42 #include "gc/PublicIterators.h"
43 #include "jit/JitSpewer.h"
44 #include "js/CallAndConstruct.h" // JS::IsCallable
45 #include "js/CharacterEncoding.h"
46 #include "js/CompileOptions.h"
47 #include "js/ContextOptions.h" // JS::ContextOptions{,Ref}
48 #include "js/Conversions.h"
49 #include "js/ErrorInterceptor.h"
50 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
51 #include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit
52 #include "js/GlobalObject.h"
53 #include "js/Initialization.h"
54 #include "js/Interrupt.h"
56 #include "js/LocaleSensitive.h"
57 #include "js/MemoryCallbacks.h"
58 #include "js/MemoryFunctions.h"
59 #include "js/PropertySpec.h"
61 #include "js/ScriptPrivate.h"
62 #include "js/StableStringChars.h"
63 #include "js/Stack.h" // JS::NativeStackSize, JS::NativeStackLimitMax, JS::GetNativeStackLimit
64 #include "js/StreamConsumer.h"
65 #include "js/String.h" // JS::MaxStringLength
66 #include "js/Symbol.h"
67 #include "js/TelemetryTimers.h"
68 #include "js/Utility.h"
69 #include "js/WaitCallbacks.h"
70 #include "js/WasmModule.h"
71 #include "js/Wrapper.h"
72 #include "js/WrapperCallbacks.h"
73 #include "proxy/DOMProxy.h"
74 #include "util/StringBuffer.h"
75 #include "util/Text.h"
76 #include "vm/BoundFunctionObject.h"
77 #include "vm/EnvironmentObject.h"
78 #include "vm/ErrorObject.h"
79 #include "vm/ErrorReporting.h"
80 #include "vm/FunctionPrefixKind.h"
81 #include "vm/Interpreter.h"
82 #include "vm/JSAtom.h"
83 #include "vm/JSAtomState.h"
84 #include "vm/JSContext.h"
85 #include "vm/JSFunction.h"
86 #include "vm/JSObject.h"
87 #include "vm/JSScript.h"
88 #include "vm/PlainObject.h" // js::PlainObject
89 #include "vm/PromiseObject.h" // js::PromiseObject
90 #include "vm/Runtime.h"
91 #include "vm/SavedStacks.h"
92 #include "vm/StringType.h"
94 #include "vm/ToSource.h"
95 #include "vm/WrapperObject.h"
96 #include "wasm/WasmModule.h"
97 #include "wasm/WasmProcess.h"
99 #include "builtin/Promise-inl.h"
100 #include "debugger/DebugAPI-inl.h"
101 #include "vm/Compartment-inl.h"
102 #include "vm/Interpreter-inl.h"
103 #include "vm/IsGivenTypeObject-inl.h" // js::IsGivenTypeObject
104 #include "vm/JSAtom-inl.h"
105 #include "vm/JSFunction-inl.h"
106 #include "vm/JSScript-inl.h"
107 #include "vm/NativeObject-inl.h"
108 #include "vm/SavedStacks-inl.h"
109 #include "vm/StringType-inl.h"
113 using mozilla::Maybe
;
114 using mozilla::PodCopy
;
117 using JS::AutoStableStringChars
;
118 using JS::CompileOptions
;
119 using JS::ReadOnlyCompileOptions
;
120 using JS::SourceText
;
122 // See preprocessor definition of JS_BITS_PER_WORD in jstypes.h; make sure
123 // JS_64BIT (used internally) agrees with it
125 static_assert(JS_BITS_PER_WORD
== 64, "values must be in sync");
127 static_assert(JS_BITS_PER_WORD
== 32, "values must be in sync");
130 JS_PUBLIC_API
void JS::CallArgs::reportMoreArgsNeeded(JSContext
* cx
,
134 char requiredArgsStr
[40];
135 SprintfLiteral(requiredArgsStr
, "%u", required
);
136 char actualArgsStr
[40];
137 SprintfLiteral(actualArgsStr
, "%u", actual
);
138 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr,
139 JSMSG_MORE_ARGS_NEEDED
, fnname
, requiredArgsStr
,
140 required
== 1 ? "" : "s", actualArgsStr
);
143 static bool ErrorTakesArguments(unsigned msg
) {
144 MOZ_ASSERT(msg
< JSErr_Limit
);
145 unsigned argCount
= js_ErrorFormatString
[msg
].argCount
;
146 MOZ_ASSERT(argCount
<= 2);
147 return argCount
== 1 || argCount
== 2;
150 static bool ErrorTakesObjectArgument(unsigned msg
) {
151 MOZ_ASSERT(msg
< JSErr_Limit
);
152 unsigned argCount
= js_ErrorFormatString
[msg
].argCount
;
153 MOZ_ASSERT(argCount
<= 2);
154 return argCount
== 2;
157 bool JS::ObjectOpResult::reportError(JSContext
* cx
, HandleObject obj
,
159 static_assert(unsigned(OkCode
) == unsigned(JSMSG_NOT_AN_ERROR
),
160 "unsigned value of OkCode must not be an error code");
161 MOZ_ASSERT(code_
!= Uninitialized
);
165 if (code_
== JSMSG_OBJECT_NOT_EXTENSIBLE
) {
166 RootedValue
val(cx
, ObjectValue(*obj
));
167 return ReportValueError(cx
, code_
, JSDVG_IGNORE_STACK
, val
, nullptr);
170 if (ErrorTakesArguments(code_
)) {
171 UniqueChars propName
=
172 IdToPrintableUTF8(cx
, id
, IdToPrintableBehavior::IdIsPropertyKey
);
177 if (code_
== JSMSG_SET_NON_OBJECT_RECEIVER
) {
178 // We know that the original receiver was a primitive, so unbox it.
179 RootedValue
val(cx
, ObjectValue(*obj
));
180 if (!obj
->is
<ProxyObject
>()) {
181 if (!Unbox(cx
, obj
, &val
)) {
185 return ReportValueError(cx
, code_
, JSDVG_IGNORE_STACK
, val
, nullptr,
189 if (ErrorTakesObjectArgument(code_
)) {
190 JSObject
* unwrapped
= js::CheckedUnwrapStatic(obj
);
191 const char* name
= unwrapped
? unwrapped
->getClass()->name
: "Object";
192 JS_ReportErrorNumberUTF8(cx
, GetErrorMessage
, nullptr, code_
, name
,
197 JS_ReportErrorNumberUTF8(cx
, GetErrorMessage
, nullptr, code_
,
201 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr, code_
);
205 bool JS::ObjectOpResult::reportError(JSContext
* cx
, HandleObject obj
) {
206 MOZ_ASSERT(code_
!= Uninitialized
);
208 MOZ_ASSERT(!ErrorTakesArguments(code_
));
211 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr, code_
);
215 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantRedefineProp() {
216 return fail(JSMSG_CANT_REDEFINE_PROP
);
219 JS_PUBLIC_API
bool JS::ObjectOpResult::failReadOnly() {
220 return fail(JSMSG_READ_ONLY
);
223 JS_PUBLIC_API
bool JS::ObjectOpResult::failGetterOnly() {
224 return fail(JSMSG_GETTER_ONLY
);
227 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDelete() {
228 return fail(JSMSG_CANT_DELETE
);
231 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantSetInterposed() {
232 return fail(JSMSG_CANT_SET_INTERPOSED
);
235 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDefineWindowElement() {
236 return fail(JSMSG_CANT_DEFINE_WINDOW_ELEMENT
);
239 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDeleteWindowElement() {
240 return fail(JSMSG_CANT_DELETE_WINDOW_ELEMENT
);
243 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDefineWindowNamedProperty() {
244 return fail(JSMSG_CANT_DEFINE_WINDOW_NAMED_PROPERTY
);
247 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDeleteWindowNamedProperty() {
248 return fail(JSMSG_CANT_DELETE_WINDOW_NAMED_PROPERTY
);
251 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDefineWindowNonConfigurable() {
252 return fail(JSMSG_CANT_DEFINE_WINDOW_NC
);
255 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantPreventExtensions() {
256 return fail(JSMSG_CANT_PREVENT_EXTENSIONS
);
259 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantSetProto() {
260 return fail(JSMSG_CANT_SET_PROTO
);
263 JS_PUBLIC_API
bool JS::ObjectOpResult::failNoNamedSetter() {
264 return fail(JSMSG_NO_NAMED_SETTER
);
267 JS_PUBLIC_API
bool JS::ObjectOpResult::failNoIndexedSetter() {
268 return fail(JSMSG_NO_INDEXED_SETTER
);
271 JS_PUBLIC_API
bool JS::ObjectOpResult::failNotDataDescriptor() {
272 return fail(JSMSG_NOT_DATA_DESCRIPTOR
);
275 JS_PUBLIC_API
bool JS::ObjectOpResult::failInvalidDescriptor() {
276 return fail(JSMSG_INVALID_DESCRIPTOR
);
279 JS_PUBLIC_API
bool JS::ObjectOpResult::failBadArrayLength() {
280 return fail(JSMSG_BAD_ARRAY_LENGTH
);
283 JS_PUBLIC_API
bool JS::ObjectOpResult::failBadIndex() {
284 return fail(JSMSG_BAD_INDEX
);
287 JS_PUBLIC_API
int64_t JS_Now() { return PRMJ_Now(); }
289 JS_PUBLIC_API Value
JS_GetEmptyStringValue(JSContext
* cx
) {
290 return StringValue(cx
->runtime()->emptyString
);
293 JS_PUBLIC_API JSString
* JS_GetEmptyString(JSContext
* cx
) {
294 MOZ_ASSERT(cx
->emptyString());
295 return cx
->emptyString();
300 void AssertHeapIsIdle() { MOZ_ASSERT(!JS::RuntimeHeapIsBusy()); }
304 static void AssertHeapIsIdleOrIterating() {
305 MOZ_ASSERT(!JS::RuntimeHeapIsCollecting());
308 JS_PUBLIC_API
bool JS_ValueToObject(JSContext
* cx
, HandleValue value
,
309 MutableHandleObject objp
) {
313 if (value
.isNullOrUndefined()) {
317 JSObject
* obj
= ToObject(cx
, value
);
325 JS_PUBLIC_API JSFunction
* JS_ValueToFunction(JSContext
* cx
, HandleValue value
) {
329 return ReportIfNotFunction(cx
, value
);
332 JS_PUBLIC_API JSFunction
* JS_ValueToConstructor(JSContext
* cx
,
337 return ReportIfNotFunction(cx
, value
);
340 JS_PUBLIC_API JSString
* JS_ValueToSource(JSContext
* cx
, HandleValue value
) {
344 return ValueToSource(cx
, value
);
347 JS_PUBLIC_API
bool JS_DoubleIsInt32(double d
, int32_t* ip
) {
348 return mozilla::NumberIsInt32(d
, ip
);
351 JS_PUBLIC_API JSType
JS_TypeOfValue(JSContext
* cx
, HandleValue value
) {
355 return TypeOfValue(value
);
358 JS_PUBLIC_API
bool JS_IsBuiltinEvalFunction(JSFunction
* fun
) {
359 return IsAnyBuiltinEval(fun
);
362 JS_PUBLIC_API
bool JS_IsBuiltinFunctionConstructor(JSFunction
* fun
) {
363 return fun
->isBuiltinFunctionConstructor();
366 JS_PUBLIC_API
bool JS_ObjectIsBoundFunction(JSObject
* obj
) {
367 return obj
->is
<BoundFunctionObject
>();
370 JS_PUBLIC_API JSObject
* JS_GetBoundFunctionTarget(JSObject
* obj
) {
371 return obj
->is
<BoundFunctionObject
>()
372 ? obj
->as
<BoundFunctionObject
>().getTarget()
376 /************************************************************************/
378 // Prevent functions from being discarded by linker, so that they are callable
380 static void PreventDiscardingFunctions() {
381 if (reinterpret_cast<uintptr_t>(&PreventDiscardingFunctions
) == 1) {
383 memset((void*)&js::debug::GetMarkInfo
, 0, 1);
384 memset((void*)&js::debug::GetMarkWordAddress
, 0, 1);
385 memset((void*)&js::debug::GetMarkMask
, 0, 1);
389 JS_PUBLIC_API JSContext
* JS_NewContext(uint32_t maxbytes
,
390 JSRuntime
* parentRuntime
) {
391 MOZ_ASSERT(JS::detail::libraryInitState
== JS::detail::InitState::Running
,
392 "must call JS_Init prior to creating any JSContexts");
394 // Prevent linker from discarding unused debug functions.
395 PreventDiscardingFunctions();
397 // Make sure that all parent runtimes are the topmost parent.
398 while (parentRuntime
&& parentRuntime
->parentRuntime
) {
399 parentRuntime
= parentRuntime
->parentRuntime
;
402 return NewContext(maxbytes
, parentRuntime
);
405 JS_PUBLIC_API
void JS_DestroyContext(JSContext
* cx
) { DestroyContext(cx
); }
407 JS_PUBLIC_API
void* JS_GetContextPrivate(JSContext
* cx
) { return cx
->data
; }
409 JS_PUBLIC_API
void JS_SetContextPrivate(JSContext
* cx
, void* data
) {
413 JS_PUBLIC_API
void JS_SetFutexCanWait(JSContext
* cx
) {
414 cx
->fx
.setCanWait(true);
417 JS_PUBLIC_API JSRuntime
* JS_GetParentRuntime(JSContext
* cx
) {
418 return cx
->runtime()->parentRuntime
? cx
->runtime()->parentRuntime
422 JS_PUBLIC_API JSRuntime
* JS_GetRuntime(JSContext
* cx
) { return cx
->runtime(); }
424 JS_PUBLIC_API
JS::ContextOptions
& JS::ContextOptionsRef(JSContext
* cx
) {
425 return cx
->options();
428 JS::ContextOptions
& JS::ContextOptions::setFuzzing(bool flag
) {
435 JS_PUBLIC_API
const char* JS_GetImplementationVersion(void) {
436 return "JavaScript-C" MOZILLA_VERSION
;
439 JS_PUBLIC_API
void JS_SetDestroyZoneCallback(JSContext
* cx
,
440 JSDestroyZoneCallback callback
) {
441 cx
->runtime()->destroyZoneCallback
= callback
;
444 JS_PUBLIC_API
void JS_SetDestroyCompartmentCallback(
445 JSContext
* cx
, JSDestroyCompartmentCallback callback
) {
446 cx
->runtime()->destroyCompartmentCallback
= callback
;
449 JS_PUBLIC_API
void JS_SetSizeOfIncludingThisCompartmentCallback(
450 JSContext
* cx
, JSSizeOfIncludingThisCompartmentCallback callback
) {
451 cx
->runtime()->sizeOfIncludingThisCompartmentCallback
= callback
;
454 JS_PUBLIC_API
void JS_SetErrorInterceptorCallback(
455 JSRuntime
* rt
, JSErrorInterceptor
* callback
) {
456 #if defined(NIGHTLY_BUILD)
457 rt
->errorInterception
.interceptor
= callback
;
458 #endif // defined(NIGHTLY_BUILD)
461 JS_PUBLIC_API JSErrorInterceptor
* JS_GetErrorInterceptorCallback(
463 #if defined(NIGHTLY_BUILD)
464 return rt
->errorInterception
.interceptor
;
465 #else // !NIGHTLY_BUILD
467 #endif // defined(NIGHTLY_BUILD)
470 JS_PUBLIC_API Maybe
<JSExnType
> JS_GetErrorType(const JS::Value
& val
) {
471 // All errors are objects.
472 if (!val
.isObject()) {
473 return mozilla::Nothing();
476 const JSObject
& obj
= val
.toObject();
478 // All errors are `ErrorObject`.
479 if (!obj
.is
<js::ErrorObject
>()) {
480 // Not one of the primitive errors.
481 return mozilla::Nothing();
484 const js::ErrorObject
& err
= obj
.as
<js::ErrorObject
>();
485 return mozilla::Some(err
.type());
488 JS_PUBLIC_API
void JS_SetWrapObjectCallbacks(
489 JSContext
* cx
, const JSWrapObjectCallbacks
* callbacks
) {
490 cx
->runtime()->wrapObjectCallbacks
= callbacks
;
493 JS_PUBLIC_API Realm
* JS::EnterRealm(JSContext
* cx
, JSObject
* target
) {
497 MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(target
));
499 Realm
* oldRealm
= cx
->realm();
500 cx
->enterRealmOf(target
);
504 JS_PUBLIC_API
void JS::LeaveRealm(JSContext
* cx
, JS::Realm
* oldRealm
) {
507 cx
->leaveRealm(oldRealm
);
510 JSAutoRealm::JSAutoRealm(JSContext
* cx
, JSObject
* target
)
511 : cx_(cx
), oldRealm_(cx
->realm()) {
512 MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(target
));
513 AssertHeapIsIdleOrIterating();
514 cx_
->enterRealmOf(target
);
517 JSAutoRealm::JSAutoRealm(JSContext
* cx
, JSScript
* target
)
518 : cx_(cx
), oldRealm_(cx
->realm()) {
519 AssertHeapIsIdleOrIterating();
520 cx_
->enterRealmOf(target
);
523 JSAutoRealm::~JSAutoRealm() { cx_
->leaveRealm(oldRealm_
); }
525 JSAutoNullableRealm::JSAutoNullableRealm(JSContext
* cx
, JSObject
* targetOrNull
)
526 : cx_(cx
), oldRealm_(cx
->realm()) {
527 AssertHeapIsIdleOrIterating();
529 MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(targetOrNull
));
530 cx_
->enterRealmOf(targetOrNull
);
532 cx_
->enterNullRealm();
536 JSAutoNullableRealm::~JSAutoNullableRealm() { cx_
->leaveRealm(oldRealm_
); }
538 JS_PUBLIC_API
void JS_SetCompartmentPrivate(JS::Compartment
* compartment
,
540 compartment
->data
= data
;
543 JS_PUBLIC_API
void* JS_GetCompartmentPrivate(JS::Compartment
* compartment
) {
544 return compartment
->data
;
547 JS_PUBLIC_API
void JS_MarkCrossZoneId(JSContext
* cx
, jsid id
) {
551 JS_PUBLIC_API
void JS_MarkCrossZoneIdValue(JSContext
* cx
, const Value
& value
) {
552 cx
->markAtomValue(value
);
555 JS_PUBLIC_API
void JS_SetZoneUserData(JS::Zone
* zone
, void* data
) {
559 JS_PUBLIC_API
void* JS_GetZoneUserData(JS::Zone
* zone
) { return zone
->data
; }
561 JS_PUBLIC_API
bool JS_WrapObject(JSContext
* cx
, MutableHandleObject objp
) {
565 JS::ExposeObjectToActiveJS(objp
);
567 return cx
->compartment()->wrap(cx
, objp
);
570 JS_PUBLIC_API
bool JS_WrapValue(JSContext
* cx
, MutableHandleValue vp
) {
573 JS::ExposeValueToActiveJS(vp
);
574 return cx
->compartment()->wrap(cx
, vp
);
577 static void ReleaseAssertObjectHasNoWrappers(JSContext
* cx
,
578 HandleObject target
) {
579 for (CompartmentsIter
c(cx
->runtime()); !c
.done(); c
.next()) {
580 if (c
->lookupWrapper(target
)) {
581 MOZ_CRASH("wrapper found for target object");
587 * [SMDOC] Brain transplants.
589 * Not for beginners or the squeamish.
591 * Sometimes a web spec requires us to transplant an object from one
592 * compartment to another, like when a DOM node is inserted into a document in
593 * another window and thus gets "adopted". We cannot literally change the
594 * `.compartment()` of a `JSObject`; that would break the compartment
595 * invariants. However, as usual, we have a workaround using wrappers.
597 * Of all the wrapper-based workarounds we do, it's safe to say this is the
598 * most spectacular and questionable.
600 * `JS_TransplantObject(cx, origobj, target)` changes `origobj` into a
601 * simulacrum of `target`, using highly esoteric means. To JS code, the effect
602 * is as if `origobj` magically "became" `target`, but most often what actually
603 * happens is that `origobj` gets turned into a cross-compartment wrapper for
604 * `target`. The old behavior and contents of `origobj` are overwritten or
607 * Thus, to "transplant" an object from one compartment to another:
609 * 1. Let `origobj` be the object that you want to move. First, create a
610 * clone of it, `target`, in the destination compartment.
612 * In our DOM adoption example, `target` will be a Node of the same type as
613 * `origobj`, same content, but in the adopting document. We're not done
614 * yet: the spec for DOM adoption requires that `origobj.ownerDocument`
615 * actually change. All we've done so far is make a copy.
617 * 2. Call `JS_TransplantObject(cx, origobj, target)`. This typically turns
618 * `origobj` into a wrapper for `target`, so that any JS code that has a
619 * reference to `origobj` will observe it to have the behavior of `target`
620 * going forward. In addition, all existing wrappers for `origobj` are
621 * changed into wrappers for `target`, extending the illusion to those
622 * compartments as well.
624 * During navigation, we use the above technique to transplant the WindowProxy
625 * into the new Window's compartment.
629 * - `origobj` and `target` must be two distinct objects of the same
630 * `JSClass`. Some classes may not support transplantation; WindowProxy
631 * objects and DOM nodes are OK.
633 * - `target` should be created specifically to be passed to this function.
634 * There must be no existing cross-compartment wrappers for it; ideally
635 * there shouldn't be any pointers to it at all, except the one passed in.
637 * - `target` shouldn't be used afterwards. Instead, `JS_TransplantObject`
638 * returns a pointer to the transplanted object, which might be `target`
639 * but might be some other object in the same compartment. Use that.
641 * The reason for this last rule is that JS_TransplantObject does very strange
642 * things in some cases, like swapping `target`'s brain with that of another
643 * object. Leaving `target` behaving like its former self is not a goal.
645 * We don't have a good way to recover from failure in this function, so
646 * we intentionally crash instead.
649 static void CheckTransplantObject(JSObject
* obj
) {
651 MOZ_ASSERT(!obj
->is
<CrossCompartmentWrapperObject
>());
652 JS::AssertCellIsNotGray(obj
);
656 JS_PUBLIC_API JSObject
* JS_TransplantObject(JSContext
* cx
, HandleObject origobj
,
657 HandleObject target
) {
659 MOZ_ASSERT(origobj
!= target
);
660 CheckTransplantObject(origobj
);
661 CheckTransplantObject(target
);
662 ReleaseAssertObjectHasNoWrappers(cx
, target
);
664 RootedObject
newIdentity(cx
);
666 // Don't allow a compacting GC to observe any intermediate state.
667 AutoDisableCompactingGC
nocgc(cx
);
669 AutoDisableProxyCheck adpc
;
671 AutoEnterOOMUnsafeRegion oomUnsafe
;
673 JS::Compartment
* destination
= target
->compartment();
675 if (origobj
->compartment() == destination
) {
676 // If the original object is in the same compartment as the
677 // destination, then we know that we won't find a wrapper in the
678 // destination's cross compartment map and that the same
679 // object will continue to work.
680 AutoRealm
ar(cx
, origobj
);
681 JSObject::swap(cx
, origobj
, target
, oomUnsafe
);
682 newIdentity
= origobj
;
683 } else if (ObjectWrapperMap::Ptr p
= destination
->lookupWrapper(origobj
)) {
684 // There might already be a wrapper for the original object in
685 // the new compartment. If there is, we use its identity and swap
686 // in the contents of |target|.
687 newIdentity
= p
->value().get();
689 // When we remove origv from the wrapper map, its wrapper, newIdentity,
690 // must immediately cease to be a cross-compartment wrapper. Nuke it.
691 destination
->removeWrapper(p
);
692 NukeCrossCompartmentWrapper(cx
, newIdentity
);
694 AutoRealm
ar(cx
, newIdentity
);
695 JSObject::swap(cx
, newIdentity
, target
, oomUnsafe
);
697 // Otherwise, we use |target| for the new identity object.
698 newIdentity
= target
;
701 // Now, iterate through other scopes looking for references to the old
702 // object, and update the relevant cross-compartment wrappers. We do this
703 // even if origobj is in the same compartment as target and thus
704 // `newIdentity == origobj`, because this process also clears out any
705 // cached wrapper state.
706 if (!RemapAllWrappersForObject(cx
, origobj
, newIdentity
)) {
707 oomUnsafe
.crash("JS_TransplantObject");
710 // Lastly, update the original object to point to the new one.
711 if (origobj
->compartment() != destination
) {
712 RootedObject
newIdentityWrapper(cx
, newIdentity
);
713 AutoRealm
ar(cx
, origobj
);
714 if (!JS_WrapObject(cx
, &newIdentityWrapper
)) {
715 MOZ_RELEASE_ASSERT(cx
->isThrowingOutOfMemory() ||
716 cx
->isThrowingOverRecursed());
717 oomUnsafe
.crash("JS_TransplantObject");
719 MOZ_ASSERT(Wrapper::wrappedObject(newIdentityWrapper
) == newIdentity
);
720 JSObject::swap(cx
, origobj
, newIdentityWrapper
, oomUnsafe
);
721 if (origobj
->compartment()->lookupWrapper(newIdentity
)) {
722 MOZ_ASSERT(origobj
->is
<CrossCompartmentWrapperObject
>());
723 if (!origobj
->compartment()->putWrapper(cx
, newIdentity
, origobj
)) {
724 oomUnsafe
.crash("JS_TransplantObject");
729 // The new identity object might be one of several things. Return it to avoid
731 JS::AssertCellIsNotGray(newIdentity
);
735 JS_PUBLIC_API
void js::RemapRemoteWindowProxies(
736 JSContext
* cx
, CompartmentTransplantCallback
* callback
,
737 MutableHandleObject target
) {
739 CheckTransplantObject(target
);
740 ReleaseAssertObjectHasNoWrappers(cx
, target
);
742 // |target| can't be a remote proxy, because we expect it to get a CCW when
743 // wrapped across compartments.
744 MOZ_ASSERT(!js::IsDOMRemoteProxyObject(target
));
746 // Don't allow a compacting GC to observe any intermediate state.
747 AutoDisableCompactingGC
nocgc(cx
);
749 AutoDisableProxyCheck adpc
;
751 AutoEnterOOMUnsafeRegion oomUnsafe
;
753 AutoCheckRecursionLimit
recursion(cx
);
754 if (!recursion
.checkSystem(cx
)) {
755 oomUnsafe
.crash("js::RemapRemoteWindowProxies");
758 RootedObject
targetCompartmentProxy(cx
);
759 JS::RootedVector
<JSObject
*> otherProxies(cx
);
761 // Use the callback to find remote proxies in all compartments that match
762 // whatever criteria callback uses.
763 for (CompartmentsIter
c(cx
->runtime()); !c
.done(); c
.next()) {
764 RootedObject
remoteProxy(cx
, callback
->getObjectToTransplant(c
));
768 // The object the callback returns should be a DOM remote proxy object in
769 // the compartment c. We rely on it being a DOM remote proxy because that
770 // means that it won't have any cross-compartment wrappers.
771 MOZ_ASSERT(js::IsDOMRemoteProxyObject(remoteProxy
));
772 MOZ_ASSERT(remoteProxy
->compartment() == c
);
773 CheckTransplantObject(remoteProxy
);
775 // Immediately turn the DOM remote proxy object into a dead proxy object
776 // so we don't have to worry about anything weird going on with it.
777 js::NukeNonCCWProxy(cx
, remoteProxy
);
779 if (remoteProxy
->compartment() == target
->compartment()) {
780 targetCompartmentProxy
= remoteProxy
;
781 } else if (!otherProxies
.append(remoteProxy
)) {
782 oomUnsafe
.crash("js::RemapRemoteWindowProxies");
786 // If there was a remote proxy in |target|'s compartment, we need to use it
787 // instead of |target|, in case it had any references, so swap it. Do this
788 // before any other compartment so that the target object will be set up
789 // correctly before we start wrapping it into other compartments.
790 if (targetCompartmentProxy
) {
791 AutoRealm
ar(cx
, targetCompartmentProxy
);
792 JSObject::swap(cx
, targetCompartmentProxy
, target
, oomUnsafe
);
793 target
.set(targetCompartmentProxy
);
796 for (JSObject
*& obj
: otherProxies
) {
797 RootedObject
deadWrapper(cx
, obj
);
798 js::RemapDeadWrapper(cx
, deadWrapper
, target
);
803 * Recompute all cross-compartment wrappers for an object, resetting state.
804 * Gecko uses this to clear Xray wrappers when doing a navigation that reuses
805 * the inner window and global object.
807 JS_PUBLIC_API
bool JS_RefreshCrossCompartmentWrappers(JSContext
* cx
,
809 return RemapAllWrappersForObject(cx
, obj
, obj
);
812 typedef struct JSStdName
{
813 size_t atomOffset
; /* offset of atom pointer in JSAtomState */
815 bool isDummy() const { return key
== JSProto_Null
; }
816 bool isSentinel() const { return key
== JSProto_LIMIT
; }
819 static const JSStdName
* LookupStdName(const JSAtomState
& names
, JSAtom
* name
,
820 const JSStdName
* table
) {
821 for (unsigned i
= 0; !table
[i
].isSentinel(); i
++) {
822 if (table
[i
].isDummy()) {
825 JSAtom
* atom
= AtomStateOffsetToName(names
, table
[i
].atomOffset
);
836 * Table of standard classes, indexed by JSProtoKey. For entries where the
837 * JSProtoKey does not correspond to a class with a meaningful constructor, we
838 * insert a null entry into the table.
840 #define STD_NAME_ENTRY(name, clasp) {NAME_OFFSET(name), JSProto_##name},
841 #define STD_DUMMY_ENTRY(name, dummy) {0, JSProto_Null},
842 static const JSStdName standard_class_names
[] = {
843 JS_FOR_PROTOTYPES(STD_NAME_ENTRY
, STD_DUMMY_ENTRY
){0, JSProto_LIMIT
}};
846 * Table of top-level function and constant names and the JSProtoKey of the
847 * standard class that initializes them.
849 static const JSStdName builtin_property_names
[] = {
850 {NAME_OFFSET(eval
), JSProto_Object
},
852 /* Global properties and functions defined by the Number class. */
853 {NAME_OFFSET(NaN
), JSProto_Number
},
854 {NAME_OFFSET(Infinity
), JSProto_Number
},
855 {NAME_OFFSET(isNaN
), JSProto_Number
},
856 {NAME_OFFSET(isFinite
), JSProto_Number
},
857 {NAME_OFFSET(parseFloat
), JSProto_Number
},
858 {NAME_OFFSET(parseInt
), JSProto_Number
},
860 /* String global functions. */
861 {NAME_OFFSET(escape
), JSProto_String
},
862 {NAME_OFFSET(unescape
), JSProto_String
},
863 {NAME_OFFSET(decodeURI
), JSProto_String
},
864 {NAME_OFFSET(encodeURI
), JSProto_String
},
865 {NAME_OFFSET(decodeURIComponent
), JSProto_String
},
866 {NAME_OFFSET(encodeURIComponent
), JSProto_String
},
867 {NAME_OFFSET(uneval
), JSProto_String
},
871 static bool SkipUneval(jsid id
, JSContext
* cx
) {
872 return !cx
->realm()->creationOptions().getToSourceEnabled() &&
873 id
== NameToId(cx
->names().uneval
);
876 static bool SkipSharedArrayBufferConstructor(JSProtoKey key
,
877 GlobalObject
* global
) {
878 if (key
!= JSProto_SharedArrayBuffer
) {
882 const JS::RealmCreationOptions
& options
= global
->realm()->creationOptions();
883 MOZ_ASSERT(options
.getSharedMemoryAndAtomicsEnabled(),
884 "shouldn't contemplate defining SharedArrayBuffer if shared "
885 "memory is disabled");
887 // On the web, it isn't presently possible to expose the global
888 // "SharedArrayBuffer" property unless the page is cross-site-isolated. Only
889 // define this constructor if an option on the realm indicates that it should
891 return !options
.defineSharedArrayBufferConstructor();
894 JS_PUBLIC_API
bool JS_ResolveStandardClass(JSContext
* cx
, HandleObject obj
,
895 HandleId id
, bool* resolved
) {
900 Handle
<GlobalObject
*> global
= obj
.as
<GlobalObject
>();
907 /* Check whether we're resolving 'undefined', and define it if so. */
908 JSAtom
* idAtom
= id
.toAtom();
909 if (idAtom
== cx
->names().undefined
) {
911 return js::DefineDataProperty(
912 cx
, global
, id
, UndefinedHandleValue
,
913 JSPROP_PERMANENT
| JSPROP_READONLY
| JSPROP_RESOLVING
);
916 // Resolve a "globalThis" self-referential property if necessary.
917 if (idAtom
== cx
->names().globalThis
) {
918 return GlobalObject::maybeResolveGlobalThis(cx
, global
, resolved
);
921 // Try for class constructors/prototypes named by well-known atoms.
922 const JSStdName
* stdnm
=
923 LookupStdName(cx
->names(), idAtom
, standard_class_names
);
925 // Try less frequently used top-level functions and constants.
926 stdnm
= LookupStdName(cx
->names(), idAtom
, builtin_property_names
);
932 JSProtoKey key
= stdnm
->key
;
933 if (key
== JSProto_Null
|| GlobalObject::skipDeselectedConstructor(cx
, key
) ||
934 SkipUneval(id
, cx
)) {
938 // If this class is anonymous (or it's "SharedArrayBuffer" but that global
939 // constructor isn't supposed to be defined), then it doesn't exist as a
940 // global property, so we won't resolve anything.
941 const JSClass
* clasp
= ProtoKeyToClass(key
);
942 if (clasp
&& !clasp
->specShouldDefineConstructor()) {
945 if (SkipSharedArrayBufferConstructor(key
, global
)) {
949 if (!GlobalObject::ensureConstructor(cx
, global
, key
)) {
956 JS_PUBLIC_API
bool JS_MayResolveStandardClass(const JSAtomState
& names
, jsid id
,
957 JSObject
* maybeObj
) {
958 MOZ_ASSERT_IF(maybeObj
, maybeObj
->is
<GlobalObject
>());
960 // The global object's resolve hook is special: JS_ResolveStandardClass
961 // initializes the prototype chain lazily. Only attempt to optimize here
962 // if we know the prototype chain has been initialized.
963 if (!maybeObj
|| !maybeObj
->staticPrototype()) {
971 JSAtom
* atom
= id
.toAtom();
973 // This will return true even for deselected constructors. (To do
974 // better, we need a JSContext here; it's fine as it is.)
976 return atom
== names
.undefined
|| atom
== names
.globalThis
||
977 LookupStdName(names
, atom
, standard_class_names
) ||
978 LookupStdName(names
, atom
, builtin_property_names
);
981 JS_PUBLIC_API
bool JS_EnumerateStandardClasses(JSContext
* cx
,
986 Handle
<GlobalObject
*> global
= obj
.as
<GlobalObject
>();
987 return GlobalObject::initStandardClasses(cx
, global
);
990 static bool EnumerateStandardClassesInTable(JSContext
* cx
,
991 Handle
<GlobalObject
*> global
,
992 MutableHandleIdVector properties
,
993 const JSStdName
* table
,
994 bool includeResolved
) {
995 for (unsigned i
= 0; !table
[i
].isSentinel(); i
++) {
996 if (table
[i
].isDummy()) {
1000 JSProtoKey key
= table
[i
].key
;
1002 // If the standard class has been resolved, the properties have been
1003 // defined on the global so we don't need to add them here.
1004 if (!includeResolved
&& global
->isStandardClassResolved(key
)) {
1008 if (GlobalObject::skipDeselectedConstructor(cx
, key
)) {
1012 if (const JSClass
* clasp
= ProtoKeyToClass(key
)) {
1013 if (!clasp
->specShouldDefineConstructor() ||
1014 SkipSharedArrayBufferConstructor(key
, global
)) {
1019 jsid id
= NameToId(AtomStateOffsetToName(cx
->names(), table
[i
].atomOffset
));
1021 if (SkipUneval(id
, cx
)) {
1025 if (!properties
.append(id
)) {
1033 static bool EnumerateStandardClasses(JSContext
* cx
, JS::HandleObject obj
,
1034 JS::MutableHandleIdVector properties
,
1035 bool enumerableOnly
,
1036 bool includeResolved
) {
1037 if (enumerableOnly
) {
1038 // There are no enumerable standard classes and "undefined" is
1043 Handle
<GlobalObject
*> global
= obj
.as
<GlobalObject
>();
1045 // It's fine to always append |undefined| here, it's non-configurable and
1046 // the enumeration code filters duplicates.
1047 if (!properties
.append(NameToId(cx
->names().undefined
))) {
1051 bool resolved
= false;
1052 if (!GlobalObject::maybeResolveGlobalThis(cx
, global
, &resolved
)) {
1055 if (resolved
|| includeResolved
) {
1056 if (!properties
.append(NameToId(cx
->names().globalThis
))) {
1061 if (!EnumerateStandardClassesInTable(cx
, global
, properties
,
1062 standard_class_names
, includeResolved
)) {
1065 if (!EnumerateStandardClassesInTable(
1066 cx
, global
, properties
, builtin_property_names
, includeResolved
)) {
1073 JS_PUBLIC_API
bool JS_NewEnumerateStandardClasses(
1074 JSContext
* cx
, JS::HandleObject obj
, JS::MutableHandleIdVector properties
,
1075 bool enumerableOnly
) {
1076 return EnumerateStandardClasses(cx
, obj
, properties
, enumerableOnly
, false);
1079 JS_PUBLIC_API
bool JS_NewEnumerateStandardClassesIncludingResolved(
1080 JSContext
* cx
, JS::HandleObject obj
, JS::MutableHandleIdVector properties
,
1081 bool enumerableOnly
) {
1082 return EnumerateStandardClasses(cx
, obj
, properties
, enumerableOnly
, true);
1085 JS_PUBLIC_API
bool JS_GetClassObject(JSContext
* cx
, JSProtoKey key
,
1086 MutableHandleObject objp
) {
1089 JSObject
* obj
= GlobalObject::getOrCreateConstructor(cx
, key
);
1097 JS_PUBLIC_API
bool JS_GetClassPrototype(JSContext
* cx
, JSProtoKey key
,
1098 MutableHandleObject objp
) {
1102 // Bound functions don't have their own prototype object: they reuse the
1103 // prototype of the target object. This is typically Function.prototype so we
1105 if (key
== JSProto_BoundFunction
) {
1106 key
= JSProto_Function
;
1109 JSObject
* proto
= GlobalObject::getOrCreatePrototype(cx
, key
);
1119 JS_PUBLIC_API
void ProtoKeyToId(JSContext
* cx
, JSProtoKey key
,
1120 MutableHandleId idp
) {
1121 idp
.set(NameToId(ClassName(key
, cx
)));
1124 } /* namespace JS */
1126 JS_PUBLIC_API JSProtoKey
JS_IdToProtoKey(JSContext
* cx
, HandleId id
) {
1132 return JSProto_Null
;
1135 JSAtom
* atom
= id
.toAtom();
1136 const JSStdName
* stdnm
=
1137 LookupStdName(cx
->names(), atom
, standard_class_names
);
1139 return JSProto_Null
;
1142 if (GlobalObject::skipDeselectedConstructor(cx
, stdnm
->key
)) {
1143 return JSProto_Null
;
1146 if (SkipSharedArrayBufferConstructor(stdnm
->key
, cx
->global())) {
1147 MOZ_ASSERT(id
== NameToId(cx
->names().SharedArrayBuffer
));
1148 return JSProto_Null
;
1151 if (SkipUneval(id
, cx
)) {
1152 return JSProto_Null
;
1155 static_assert(std::size(standard_class_names
) == JSProto_LIMIT
+ 1);
1156 return static_cast<JSProtoKey
>(stdnm
- standard_class_names
);
1159 extern JS_PUBLIC_API
bool JS_IsGlobalObject(JSObject
* obj
) {
1160 return obj
->is
<GlobalObject
>();
1163 extern JS_PUBLIC_API JSObject
* JS_GlobalLexicalEnvironment(JSObject
* obj
) {
1164 return &obj
->as
<GlobalObject
>().lexicalEnvironment();
1167 extern JS_PUBLIC_API
bool JS_HasExtensibleLexicalEnvironment(JSObject
* obj
) {
1168 return obj
->is
<GlobalObject
>() ||
1169 ObjectRealm::get(obj
).getNonSyntacticLexicalEnvironment(obj
);
1172 extern JS_PUBLIC_API JSObject
* JS_ExtensibleLexicalEnvironment(JSObject
* obj
) {
1173 return ExtensibleLexicalEnvironmentObject::forVarEnvironment(obj
);
1176 JS_PUBLIC_API JSObject
* JS::CurrentGlobalOrNull(JSContext
* cx
) {
1177 AssertHeapIsIdleOrIterating();
1182 return cx
->global();
1185 JS_PUBLIC_API JSObject
* JS::GetNonCCWObjectGlobal(JSObject
* obj
) {
1186 AssertHeapIsIdleOrIterating();
1187 MOZ_DIAGNOSTIC_ASSERT(!IsCrossCompartmentWrapper(obj
));
1188 return &obj
->nonCCWGlobal();
1191 JS_PUBLIC_API
bool JS::detail::ComputeThis(JSContext
* cx
, Value
* vp
,
1192 MutableHandleObject thisObject
) {
1194 cx
->check(vp
[0], vp
[1]);
1196 MutableHandleValue thisv
= MutableHandleValue::fromMarkedLocation(&vp
[1]);
1197 JSObject
* obj
= BoxNonStrictThis(cx
, thisv
);
1202 thisObject
.set(obj
);
1206 static bool gProfileTimelineRecordingEnabled
= false;
1208 JS_PUBLIC_API
void JS::SetProfileTimelineRecordingEnabled(bool enabled
) {
1209 gProfileTimelineRecordingEnabled
= enabled
;
1212 JS_PUBLIC_API
bool JS::IsProfileTimelineRecordingEnabled() {
1213 return gProfileTimelineRecordingEnabled
;
1216 JS_PUBLIC_API
void* JS_malloc(JSContext
* cx
, size_t nbytes
) {
1219 return static_cast<void*>(cx
->maybe_pod_malloc
<uint8_t>(nbytes
));
1222 JS_PUBLIC_API
void* JS_realloc(JSContext
* cx
, void* p
, size_t oldBytes
,
1226 return static_cast<void*>(cx
->maybe_pod_realloc
<uint8_t>(
1227 static_cast<uint8_t*>(p
), oldBytes
, newBytes
));
1230 JS_PUBLIC_API
void JS_free(JSContext
* cx
, void* p
) { return js_free(p
); }
1232 JS_PUBLIC_API
void* JS_string_malloc(JSContext
* cx
, size_t nbytes
) {
1235 return static_cast<void*>(
1236 cx
->maybe_pod_arena_malloc
<uint8_t>(js::StringBufferArena
, nbytes
));
1239 JS_PUBLIC_API
void* JS_string_realloc(JSContext
* cx
, void* p
, size_t oldBytes
,
1243 return static_cast<void*>(cx
->maybe_pod_arena_realloc
<uint8_t>(
1244 js::StringBufferArena
, static_cast<uint8_t*>(p
), oldBytes
, newBytes
));
1247 JS_PUBLIC_API
void JS_string_free(JSContext
* cx
, void* p
) { return js_free(p
); }
1249 JS_PUBLIC_API
void JS::AddAssociatedMemory(JSObject
* obj
, size_t nbytes
,
1250 JS::MemoryUse use
) {
1256 Zone
* zone
= obj
->zone();
1257 MOZ_ASSERT(!IsInsideNursery(obj
));
1258 zone
->addCellMemory(obj
, nbytes
, js::MemoryUse(use
));
1259 zone
->maybeTriggerGCOnMalloc();
1262 JS_PUBLIC_API
void JS::RemoveAssociatedMemory(JSObject
* obj
, size_t nbytes
,
1263 JS::MemoryUse use
) {
1269 GCContext
* gcx
= obj
->runtimeFromMainThread()->gcContext();
1270 gcx
->removeCellMemory(obj
, nbytes
, js::MemoryUse(use
));
1275 JS_PUBLIC_API
bool JS_AddExtraGCRootsTracer(JSContext
* cx
,
1276 JSTraceDataOp traceOp
, void* data
) {
1277 return cx
->runtime()->gc
.addBlackRootsTracer(traceOp
, data
);
1280 JS_PUBLIC_API
void JS_RemoveExtraGCRootsTracer(JSContext
* cx
,
1281 JSTraceDataOp traceOp
,
1283 return cx
->runtime()->gc
.removeBlackRootsTracer(traceOp
, data
);
1286 JS_PUBLIC_API
JS::GCReason
JS::WantEagerMinorGC(JSRuntime
* rt
) {
1287 if (rt
->gc
.nursery().shouldCollect()) {
1288 return JS::GCReason::EAGER_NURSERY_COLLECTION
;
1290 return JS::GCReason::NO_REASON
;
1293 JS_PUBLIC_API
JS::GCReason
JS::WantEagerMajorGC(JSRuntime
* rt
) {
1294 return rt
->gc
.wantMajorGC(true);
1297 JS_PUBLIC_API
void JS::MaybeRunNurseryCollection(JSRuntime
* rt
,
1298 JS::GCReason reason
) {
1299 gc::GCRuntime
& gc
= rt
->gc
;
1300 if (gc
.nursery().shouldCollect()) {
1305 JS_PUBLIC_API
void JS_GC(JSContext
* cx
, JS::GCReason reason
) {
1307 JS::PrepareForFullGC(cx
);
1308 cx
->runtime()->gc
.gc(JS::GCOptions::Normal
, reason
);
1311 JS_PUBLIC_API
void JS_MaybeGC(JSContext
* cx
) {
1313 cx
->runtime()->gc
.maybeGC();
1316 JS_PUBLIC_API
void JS_SetGCCallback(JSContext
* cx
, JSGCCallback cb
,
1319 cx
->runtime()->gc
.setGCCallback(cb
, data
);
1322 JS_PUBLIC_API
void JS_SetObjectsTenuredCallback(JSContext
* cx
,
1323 JSObjectsTenuredCallback cb
,
1326 cx
->runtime()->gc
.setObjectsTenuredCallback(cb
, data
);
1329 JS_PUBLIC_API
bool JS_AddFinalizeCallback(JSContext
* cx
, JSFinalizeCallback cb
,
1332 return cx
->runtime()->gc
.addFinalizeCallback(cb
, data
);
1335 JS_PUBLIC_API
void JS_RemoveFinalizeCallback(JSContext
* cx
,
1336 JSFinalizeCallback cb
) {
1337 cx
->runtime()->gc
.removeFinalizeCallback(cb
);
1340 JS_PUBLIC_API
void JS::SetHostCleanupFinalizationRegistryCallback(
1341 JSContext
* cx
, JSHostCleanupFinalizationRegistryCallback cb
, void* data
) {
1343 cx
->runtime()->gc
.setHostCleanupFinalizationRegistryCallback(cb
, data
);
1346 JS_PUBLIC_API
void JS::ClearKeptObjects(JSContext
* cx
) {
1347 gc::GCRuntime
* gc
= &cx
->runtime()->gc
;
1349 for (ZonesIter
zone(gc
, ZoneSelector::WithAtoms
); !zone
.done(); zone
.next()) {
1350 zone
->clearKeptObjects();
1354 JS_PUBLIC_API
bool JS::AtomsZoneIsCollecting(JSRuntime
* runtime
) {
1355 return runtime
->activeGCInAtomsZone();
1358 JS_PUBLIC_API
bool JS::IsAtomsZone(JS::Zone
* zone
) {
1359 return zone
->isAtomsZone();
1362 JS_PUBLIC_API
bool JS_AddWeakPointerZonesCallback(JSContext
* cx
,
1363 JSWeakPointerZonesCallback cb
,
1366 return cx
->runtime()->gc
.addWeakPointerZonesCallback(cb
, data
);
1369 JS_PUBLIC_API
void JS_RemoveWeakPointerZonesCallback(
1370 JSContext
* cx
, JSWeakPointerZonesCallback cb
) {
1371 cx
->runtime()->gc
.removeWeakPointerZonesCallback(cb
);
1374 JS_PUBLIC_API
bool JS_AddWeakPointerCompartmentCallback(
1375 JSContext
* cx
, JSWeakPointerCompartmentCallback cb
, void* data
) {
1377 return cx
->runtime()->gc
.addWeakPointerCompartmentCallback(cb
, data
);
1380 JS_PUBLIC_API
void JS_RemoveWeakPointerCompartmentCallback(
1381 JSContext
* cx
, JSWeakPointerCompartmentCallback cb
) {
1382 cx
->runtime()->gc
.removeWeakPointerCompartmentCallback(cb
);
1385 JS_PUBLIC_API
bool JS_UpdateWeakPointerAfterGC(JSTracer
* trc
,
1386 JS::Heap
<JSObject
*>* objp
) {
1387 return TraceWeakEdge(trc
, objp
);
1390 JS_PUBLIC_API
bool JS_UpdateWeakPointerAfterGCUnbarriered(JSTracer
* trc
,
1392 return TraceManuallyBarrieredWeakEdge(trc
, objp
, "External weak pointer");
1395 JS_PUBLIC_API
void JS_SetGCParameter(JSContext
* cx
, JSGCParamKey key
,
1397 MOZ_ALWAYS_TRUE(cx
->runtime()->gc
.setParameter(cx
, key
, value
));
1400 JS_PUBLIC_API
void JS_ResetGCParameter(JSContext
* cx
, JSGCParamKey key
) {
1401 cx
->runtime()->gc
.resetParameter(cx
, key
);
1404 JS_PUBLIC_API
uint32_t JS_GetGCParameter(JSContext
* cx
, JSGCParamKey key
) {
1405 return cx
->runtime()->gc
.getParameter(key
);
1408 JS_PUBLIC_API
void JS_SetGCParametersBasedOnAvailableMemory(
1409 JSContext
* cx
, uint32_t availMemMB
) {
1415 static const JSGCConfig minimal
[] = {
1416 {JSGC_SLICE_TIME_BUDGET_MS
, 5},
1417 {JSGC_HIGH_FREQUENCY_TIME_LIMIT
, 1500},
1418 {JSGC_LARGE_HEAP_SIZE_MIN
, 250},
1419 {JSGC_SMALL_HEAP_SIZE_MAX
, 50},
1420 {JSGC_HIGH_FREQUENCY_SMALL_HEAP_GROWTH
, 300},
1421 {JSGC_HIGH_FREQUENCY_LARGE_HEAP_GROWTH
, 120},
1422 {JSGC_LOW_FREQUENCY_HEAP_GROWTH
, 120},
1423 {JSGC_ALLOCATION_THRESHOLD
, 15},
1424 {JSGC_MALLOC_THRESHOLD_BASE
, 20},
1425 {JSGC_SMALL_HEAP_INCREMENTAL_LIMIT
, 200},
1426 {JSGC_LARGE_HEAP_INCREMENTAL_LIMIT
, 110},
1427 {JSGC_URGENT_THRESHOLD_MB
, 8}};
1429 static const JSGCConfig nominal
[] = {
1430 {JSGC_SLICE_TIME_BUDGET_MS
, 5},
1431 {JSGC_HIGH_FREQUENCY_TIME_LIMIT
, 1000},
1432 {JSGC_LARGE_HEAP_SIZE_MIN
, 500},
1433 {JSGC_SMALL_HEAP_SIZE_MAX
, 100},
1434 {JSGC_HIGH_FREQUENCY_SMALL_HEAP_GROWTH
, 300},
1435 {JSGC_HIGH_FREQUENCY_LARGE_HEAP_GROWTH
, 150},
1436 {JSGC_LOW_FREQUENCY_HEAP_GROWTH
, 150},
1437 {JSGC_ALLOCATION_THRESHOLD
, 27},
1438 {JSGC_MALLOC_THRESHOLD_BASE
, 38},
1439 {JSGC_SMALL_HEAP_INCREMENTAL_LIMIT
, 150},
1440 {JSGC_LARGE_HEAP_INCREMENTAL_LIMIT
, 110},
1441 {JSGC_URGENT_THRESHOLD_MB
, 16}};
1443 const auto& configSet
= availMemMB
> 512 ? nominal
: minimal
;
1444 for (const auto& config
: configSet
) {
1445 JS_SetGCParameter(cx
, config
.key
, config
.value
);
1449 JS_PUBLIC_API JSString
* JS_NewExternalString(
1450 JSContext
* cx
, const char16_t
* chars
, size_t length
,
1451 const JSExternalStringCallbacks
* callbacks
) {
1454 return JSExternalString::new_(cx
, chars
, length
, callbacks
);
1457 JS_PUBLIC_API JSString
* JS_NewMaybeExternalString(
1458 JSContext
* cx
, const char16_t
* chars
, size_t length
,
1459 const JSExternalStringCallbacks
* callbacks
, bool* allocatedExternal
) {
1462 return NewMaybeExternalString(cx
, chars
, length
, callbacks
,
1466 extern JS_PUBLIC_API
const JSExternalStringCallbacks
*
1467 JS_GetExternalStringCallbacks(JSString
* str
) {
1468 return str
->asExternal().callbacks();
1471 static void SetNativeStackSize(JSContext
* cx
, JS::StackKind kind
,
1472 JS::NativeStackSize stackSize
) {
1474 cx
->nativeStackLimit
[kind
] = JS::WASINativeStackLimit
;
1476 if (stackSize
== 0) {
1477 cx
->nativeStackLimit
[kind
] = JS::NativeStackLimitMax
;
1479 cx
->nativeStackLimit
[kind
] =
1480 JS::GetNativeStackLimit(cx
->nativeStackBase(), stackSize
- 1);
1485 JS_PUBLIC_API
void JS_SetNativeStackQuota(
1486 JSContext
* cx
, JS::NativeStackSize systemCodeStackSize
,
1487 JS::NativeStackSize trustedScriptStackSize
,
1488 JS::NativeStackSize untrustedScriptStackSize
) {
1489 MOZ_ASSERT(!cx
->activation());
1490 MOZ_ASSERT(cx
->isMainThreadContext());
1492 if (!trustedScriptStackSize
) {
1493 trustedScriptStackSize
= systemCodeStackSize
;
1495 MOZ_ASSERT(trustedScriptStackSize
< systemCodeStackSize
);
1498 if (!untrustedScriptStackSize
) {
1499 untrustedScriptStackSize
= trustedScriptStackSize
;
1501 MOZ_ASSERT(untrustedScriptStackSize
< trustedScriptStackSize
);
1504 SetNativeStackSize(cx
, JS::StackForSystemCode
, systemCodeStackSize
);
1505 SetNativeStackSize(cx
, JS::StackForTrustedScript
, trustedScriptStackSize
);
1506 SetNativeStackSize(cx
, JS::StackForUntrustedScript
, untrustedScriptStackSize
);
1508 cx
->initJitStackLimit();
1511 /************************************************************************/
1513 JS_PUBLIC_API
bool JS_ValueToId(JSContext
* cx
, HandleValue value
,
1514 MutableHandleId idp
) {
1518 return ToPropertyKey(cx
, value
, idp
);
1521 JS_PUBLIC_API
bool JS_StringToId(JSContext
* cx
, HandleString string
,
1522 MutableHandleId idp
) {
1526 RootedValue
value(cx
, StringValue(string
));
1527 return PrimitiveValueToId
<CanGC
>(cx
, value
, idp
);
1530 JS_PUBLIC_API
bool JS_IdToValue(JSContext
* cx
, jsid id
, MutableHandleValue vp
) {
1534 vp
.set(IdToValue(id
));
1539 JS_PUBLIC_API
bool JS::ToPrimitive(JSContext
* cx
, HandleObject obj
, JSType hint
,
1540 MutableHandleValue vp
) {
1544 MOZ_ASSERT(obj
!= nullptr);
1545 MOZ_ASSERT(hint
== JSTYPE_UNDEFINED
|| hint
== JSTYPE_STRING
||
1546 hint
== JSTYPE_NUMBER
);
1548 return ToPrimitiveSlow(cx
, hint
, vp
);
1551 JS_PUBLIC_API
bool JS::GetFirstArgumentAsTypeHint(JSContext
* cx
, CallArgs args
,
1553 if (!args
.get(0).isString()) {
1554 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr,
1555 JSMSG_NOT_EXPECTED_TYPE
, "Symbol.toPrimitive",
1556 "\"string\", \"number\", or \"default\"",
1557 InformalValueTypeName(args
.get(0)));
1561 RootedString
str(cx
, args
.get(0).toString());
1564 if (!EqualStrings(cx
, str
, cx
->names().default_
, &match
)) {
1568 *result
= JSTYPE_UNDEFINED
;
1572 if (!EqualStrings(cx
, str
, cx
->names().string
, &match
)) {
1576 *result
= JSTYPE_STRING
;
1580 if (!EqualStrings(cx
, str
, cx
->names().number
, &match
)) {
1584 *result
= JSTYPE_NUMBER
;
1589 const char* source
= ValueToSourceForError(cx
, args
.get(0), bytes
);
1591 ReportOutOfMemory(cx
);
1595 JS_ReportErrorNumberUTF8(cx
, GetErrorMessage
, nullptr,
1596 JSMSG_NOT_EXPECTED_TYPE
, "Symbol.toPrimitive",
1597 "\"string\", \"number\", or \"default\"", source
);
1601 JS_PUBLIC_API JSObject
* JS_InitClass(
1602 JSContext
* cx
, HandleObject obj
, const JSClass
* protoClass
,
1603 HandleObject protoProto
, const char* name
, JSNative constructor
,
1604 unsigned nargs
, const JSPropertySpec
* ps
, const JSFunctionSpec
* fs
,
1605 const JSPropertySpec
* static_ps
, const JSFunctionSpec
* static_fs
) {
1608 cx
->check(obj
, protoProto
);
1609 return InitClass(cx
, obj
, protoClass
, protoProto
, name
, constructor
, nargs
,
1610 ps
, fs
, static_ps
, static_fs
);
1613 JS_PUBLIC_API
bool JS_LinkConstructorAndPrototype(JSContext
* cx
,
1615 HandleObject proto
) {
1616 return LinkConstructorAndPrototype(cx
, ctor
, proto
);
1619 JS_PUBLIC_API
bool JS_InstanceOf(JSContext
* cx
, HandleObject obj
,
1620 const JSClass
* clasp
, CallArgs
* args
) {
1626 cx
->check(args
->thisv(), args
->calleev());
1629 if (!obj
|| obj
->getClass() != clasp
) {
1631 ReportIncompatibleMethod(cx
, *args
, clasp
);
1638 JS_PUBLIC_API
bool JS_HasInstance(JSContext
* cx
, HandleObject obj
,
1639 HandleValue value
, bool* bp
) {
1641 cx
->check(obj
, value
);
1642 return InstanceofOperator(cx
, obj
, value
, bp
);
1645 JS_PUBLIC_API JSObject
* JS_GetConstructor(JSContext
* cx
, HandleObject proto
) {
1650 RootedValue
cval(cx
);
1651 if (!GetProperty(cx
, proto
, proto
, cx
->names().constructor
, &cval
)) {
1654 if (!IsFunctionObject(cval
)) {
1655 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr,
1656 JSMSG_NO_CONSTRUCTOR
, proto
->getClass()->name
);
1659 return &cval
.toObject();
1662 JS::RealmCreationOptions
&
1663 JS::RealmCreationOptions::setNewCompartmentInSystemZone() {
1664 compSpec_
= CompartmentSpecifier::NewCompartmentInSystemZone
;
1669 JS::RealmCreationOptions
&
1670 JS::RealmCreationOptions::setNewCompartmentInExistingZone(JSObject
* obj
) {
1671 compSpec_
= CompartmentSpecifier::NewCompartmentInExistingZone
;
1672 zone_
= obj
->zone();
1676 JS::RealmCreationOptions
& JS::RealmCreationOptions::setExistingCompartment(
1678 compSpec_
= CompartmentSpecifier::ExistingCompartment
;
1679 comp_
= obj
->compartment();
1683 JS::RealmCreationOptions
& JS::RealmCreationOptions::setExistingCompartment(
1684 JS::Compartment
* compartment
) {
1685 compSpec_
= CompartmentSpecifier::ExistingCompartment
;
1686 comp_
= compartment
;
1690 JS::RealmCreationOptions
& JS::RealmCreationOptions::setNewCompartmentAndZone() {
1691 compSpec_
= CompartmentSpecifier::NewCompartmentAndZone
;
1696 const JS::RealmCreationOptions
& JS::RealmCreationOptionsRef(Realm
* realm
) {
1697 return realm
->creationOptions();
1700 const JS::RealmCreationOptions
& JS::RealmCreationOptionsRef(JSContext
* cx
) {
1701 return cx
->realm()->creationOptions();
1704 bool JS::RealmCreationOptions::getSharedMemoryAndAtomicsEnabled() const {
1705 return sharedMemoryAndAtomics_
;
1708 JS::RealmCreationOptions
&
1709 JS::RealmCreationOptions::setSharedMemoryAndAtomicsEnabled(bool flag
) {
1710 sharedMemoryAndAtomics_
= flag
;
1714 bool JS::RealmCreationOptions::getCoopAndCoepEnabled() const {
1715 return coopAndCoep_
;
1718 JS::RealmCreationOptions
& JS::RealmCreationOptions::setCoopAndCoepEnabled(
1720 coopAndCoep_
= flag
;
1724 const JS::RealmBehaviors
& JS::RealmBehaviorsRef(JS::Realm
* realm
) {
1725 return realm
->behaviors();
1728 const JS::RealmBehaviors
& JS::RealmBehaviorsRef(JSContext
* cx
) {
1729 return cx
->realm()->behaviors();
1732 void JS::SetRealmNonLive(Realm
* realm
) { realm
->setNonLive(); }
1734 JS_PUBLIC_API JSObject
* JS_NewGlobalObject(JSContext
* cx
, const JSClass
* clasp
,
1735 JSPrincipals
* principals
,
1736 JS::OnNewGlobalHookOption hookOption
,
1737 const JS::RealmOptions
& options
) {
1739 cx
->runtime()->hasInitializedSelfHosting(),
1740 "Must call JS::InitSelfHostedCode() before creating a global");
1745 return GlobalObject::new_(cx
, clasp
, principals
, hookOption
, options
);
1748 JS_PUBLIC_API
void JS_GlobalObjectTraceHook(JSTracer
* trc
, JSObject
* global
) {
1749 GlobalObject
* globalObj
= &global
->as
<GlobalObject
>();
1750 Realm
* globalRealm
= globalObj
->realm();
1752 // If we GC when creating the global, we may not have set that global's
1753 // realm's global pointer yet. In this case, the realm will not yet contain
1754 // anything that needs to be traced.
1755 if (globalRealm
->unsafeUnbarrieredMaybeGlobal() != globalObj
) {
1759 // Trace the realm for any GC things that should only stick around if we
1760 // know the global is live.
1761 globalRealm
->traceGlobalData(trc
);
1763 globalObj
->traceData(trc
, globalObj
);
1765 if (JSTraceOp trace
= globalRealm
->creationOptions().getTrace()) {
1770 const JSClassOps
JS::DefaultGlobalClassOps
= {
1771 nullptr, // addProperty
1772 nullptr, // delProperty
1773 nullptr, // enumerate
1774 JS_NewEnumerateStandardClasses
, // newEnumerate
1775 JS_ResolveStandardClass
, // resolve
1776 JS_MayResolveStandardClass
, // mayResolve
1777 nullptr, // finalize
1779 nullptr, // construct
1780 JS_GlobalObjectTraceHook
, // trace
1783 JS_PUBLIC_API
void JS_FireOnNewGlobalObject(JSContext
* cx
,
1784 JS::HandleObject global
) {
1785 // This hook is infallible, because we don't really want arbitrary script
1786 // to be able to throw errors during delicate global creation routines.
1787 // This infallibility will eat OOM and slow script, but if that happens
1788 // we'll likely run up into them again soon in a fallible context.
1790 Rooted
<js::GlobalObject
*> globalObject(cx
, &global
->as
<GlobalObject
>());
1791 DebugAPI::onNewGlobalObject(cx
, globalObject
);
1792 cx
->runtime()->ensureRealmIsRecordingAllocations(globalObject
);
1795 JS_PUBLIC_API JSObject
* JS_NewObject(JSContext
* cx
, const JSClass
* clasp
) {
1796 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
1801 // Default class is Object.
1802 return NewPlainObject(cx
);
1805 MOZ_ASSERT(!clasp
->isJSFunction());
1806 MOZ_ASSERT(clasp
!= &PlainObject::class_
);
1807 MOZ_ASSERT(clasp
!= &ArrayObject::class_
);
1808 MOZ_ASSERT(!(clasp
->flags
& JSCLASS_IS_GLOBAL
));
1810 return NewBuiltinClassInstance(cx
, clasp
);
1813 JS_PUBLIC_API JSObject
* JS_NewObjectWithGivenProto(JSContext
* cx
,
1814 const JSClass
* clasp
,
1815 HandleObject proto
) {
1816 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
1822 // Default class is Object.
1823 return NewPlainObjectWithProto(cx
, proto
);
1826 MOZ_ASSERT(!clasp
->isJSFunction());
1827 MOZ_ASSERT(clasp
!= &PlainObject::class_
);
1828 MOZ_ASSERT(clasp
!= &ArrayObject::class_
);
1829 MOZ_ASSERT(!(clasp
->flags
& JSCLASS_IS_GLOBAL
));
1831 return NewObjectWithGivenProto(cx
, clasp
, proto
);
1834 JS_PUBLIC_API JSObject
* JS_NewPlainObject(JSContext
* cx
) {
1835 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
1839 return NewPlainObject(cx
);
1842 JS_PUBLIC_API JSObject
* JS_NewObjectForConstructor(JSContext
* cx
,
1843 const JSClass
* clasp
,
1844 const CallArgs
& args
) {
1848 MOZ_ASSERT(!clasp
->isJSFunction());
1849 MOZ_ASSERT(clasp
!= &PlainObject::class_
);
1850 MOZ_ASSERT(clasp
!= &ArrayObject::class_
);
1851 MOZ_ASSERT(!(clasp
->flags
& JSCLASS_IS_GLOBAL
));
1853 if (!ThrowIfNotConstructing(cx
, args
, clasp
->name
)) {
1857 RootedObject
newTarget(cx
, &args
.newTarget().toObject());
1858 cx
->check(newTarget
);
1860 RootedObject
proto(cx
);
1861 if (!GetPrototypeFromConstructor(cx
, newTarget
,
1862 JSCLASS_CACHED_PROTO_KEY(clasp
), &proto
)) {
1866 return NewObjectWithClassProto(cx
, clasp
, proto
);
1869 JS_PUBLIC_API
bool JS_IsNative(JSObject
* obj
) {
1870 return obj
->is
<NativeObject
>();
1873 JS_PUBLIC_API
void JS::AssertObjectBelongsToCurrentThread(JSObject
* obj
) {
1874 JSRuntime
* rt
= obj
->compartment()->runtimeFromAnyThread();
1875 MOZ_RELEASE_ASSERT(CurrentThreadCanAccessRuntime(rt
));
1878 JS_PUBLIC_API
void JS::SetFilenameValidationCallback(
1879 JS::FilenameValidationCallback cb
) {
1880 js::gFilenameValidationCallback
= cb
;
1883 JS_PUBLIC_API
void JS::SetHostEnsureCanAddPrivateElementHook(
1884 JSContext
* cx
, JS::EnsureCanAddPrivateElementOp op
) {
1885 cx
->runtime()->canAddPrivateElement
= op
;
1888 /*** Standard internal methods **********************************************/
1890 JS_PUBLIC_API
bool JS_GetPrototype(JSContext
* cx
, HandleObject obj
,
1891 MutableHandleObject result
) {
1893 return GetPrototype(cx
, obj
, result
);
1896 JS_PUBLIC_API
bool JS_SetPrototype(JSContext
* cx
, HandleObject obj
,
1897 HandleObject proto
) {
1900 cx
->check(obj
, proto
);
1902 return SetPrototype(cx
, obj
, proto
);
1905 JS_PUBLIC_API
bool JS_GetPrototypeIfOrdinary(JSContext
* cx
, HandleObject obj
,
1907 MutableHandleObject result
) {
1909 return GetPrototypeIfOrdinary(cx
, obj
, isOrdinary
, result
);
1912 JS_PUBLIC_API
bool JS_IsExtensible(JSContext
* cx
, HandleObject obj
,
1915 return IsExtensible(cx
, obj
, extensible
);
1918 JS_PUBLIC_API
bool JS_PreventExtensions(JSContext
* cx
, JS::HandleObject obj
,
1919 ObjectOpResult
& result
) {
1921 return PreventExtensions(cx
, obj
, result
);
1924 JS_PUBLIC_API
bool JS_SetImmutablePrototype(JSContext
* cx
, JS::HandleObject obj
,
1927 return SetImmutablePrototype(cx
, obj
, succeeded
);
1932 JS_PUBLIC_API
bool JS_FreezeObject(JSContext
* cx
, HandleObject obj
) {
1936 return FreezeObject(cx
, obj
);
1939 static bool DeepFreezeSlot(JSContext
* cx
, const Value
& v
) {
1940 if (v
.isPrimitive()) {
1943 RootedObject
obj(cx
, &v
.toObject());
1944 return JS_DeepFreezeObject(cx
, obj
);
1947 JS_PUBLIC_API
bool JS_DeepFreezeObject(JSContext
* cx
, HandleObject obj
) {
1952 // Assume that non-extensible objects are already deep-frozen, to avoid
1955 if (!IsExtensible(cx
, obj
, &extensible
)) {
1962 if (!FreezeObject(cx
, obj
)) {
1966 // Walk slots in obj and if any value is a non-null object, seal it.
1967 if (obj
->is
<NativeObject
>()) {
1968 Rooted
<NativeObject
*> nobj(cx
, &obj
->as
<NativeObject
>());
1969 for (uint32_t i
= 0, n
= nobj
->slotSpan(); i
< n
; ++i
) {
1970 if (!DeepFreezeSlot(cx
, nobj
->getSlot(i
))) {
1974 for (uint32_t i
= 0, n
= nobj
->getDenseInitializedLength(); i
< n
; ++i
) {
1975 if (!DeepFreezeSlot(cx
, nobj
->getDenseElement(i
))) {
1984 JS_PUBLIC_API
bool JSPropertySpec::getValue(JSContext
* cx
,
1985 MutableHandleValue vp
) const {
1986 MOZ_ASSERT(!isAccessor());
1988 switch (u
.value
.type
) {
1989 case ValueWrapper::Type::String
: {
1990 Rooted
<JSAtom
*> atom(cx
,
1991 Atomize(cx
, u
.value
.string
, strlen(u
.value
.string
)));
1999 case ValueWrapper::Type::Int32
:
2000 vp
.setInt32(u
.value
.int32
);
2003 case ValueWrapper::Type::Double
:
2004 vp
.setDouble(u
.value
.double_
);
2008 MOZ_CRASH("Unexpected type");
2011 bool PropertySpecNameToId(JSContext
* cx
, JSPropertySpec::Name name
,
2012 MutableHandleId id
) {
2013 if (name
.isSymbol()) {
2014 id
.set(PropertyKey::Symbol(cx
->wellKnownSymbols().get(name
.symbol())));
2016 JSAtom
* atom
= Atomize(cx
, name
.string(), strlen(name
.string()));
2020 id
.set(AtomToId(atom
));
2025 JS_PUBLIC_API
bool JS::PropertySpecNameToPermanentId(JSContext
* cx
,
2026 JSPropertySpec::Name name
,
2028 // We are calling fromMarkedLocation(idp) even though idp points to a
2029 // location that will never be marked. This is OK because the whole point
2030 // of this API is to populate *idp with a jsid that does not need to be
2032 MutableHandleId id
= MutableHandleId::fromMarkedLocation(idp
);
2033 if (!PropertySpecNameToId(cx
, name
, id
)) {
2037 if (id
.isString() && !PinAtom(cx
, &id
.toString()->asAtom())) {
2044 JS_PUBLIC_API
bool JS::ObjectToCompletePropertyDescriptor(
2045 JSContext
* cx
, HandleObject obj
, HandleValue descObj
,
2046 MutableHandle
<PropertyDescriptor
> desc
) {
2047 // |obj| can be in a different compartment here. The caller is responsible
2048 // for wrapping it (see JS_WrapPropertyDescriptor).
2050 if (!ToPropertyDescriptor(cx
, descObj
, true, desc
)) {
2053 CompletePropertyDescriptor(desc
);
2057 JS_PUBLIC_API
void JS_SetAllNonReservedSlotsToUndefined(JS::HandleObject obj
) {
2058 if (!obj
->is
<NativeObject
>()) {
2062 const JSClass
* clasp
= obj
->getClass();
2063 unsigned numReserved
= JSCLASS_RESERVED_SLOTS(clasp
);
2064 unsigned numSlots
= obj
->as
<NativeObject
>().slotSpan();
2065 for (unsigned i
= numReserved
; i
< numSlots
; i
++) {
2066 obj
->as
<NativeObject
>().setSlot(i
, UndefinedValue());
2070 JS_PUBLIC_API
void JS_SetReservedSlot(JSObject
* obj
, uint32_t index
,
2071 const Value
& value
) {
2072 // Note: we don't use setReservedSlot so that this also works on swappable DOM
2073 // objects. See NativeObject::getReservedSlotRef comment.
2074 MOZ_ASSERT(index
< JSCLASS_RESERVED_SLOTS(obj
->getClass()));
2075 obj
->as
<NativeObject
>().setSlot(index
, value
);
2078 JS_PUBLIC_API
void JS_InitReservedSlot(JSObject
* obj
, uint32_t index
, void* ptr
,
2079 size_t nbytes
, JS::MemoryUse use
) {
2080 // Note: we don't use InitReservedSlot so that this also works on swappable
2081 // DOM objects. See NativeObject::getReservedSlotRef comment.
2082 MOZ_ASSERT(index
< JSCLASS_RESERVED_SLOTS(obj
->getClass()));
2083 AddCellMemory(obj
, nbytes
, js::MemoryUse(use
));
2084 obj
->as
<NativeObject
>().initSlot(index
, PrivateValue(ptr
));
2087 JS_PUBLIC_API
bool JS::IsMapObject(JSContext
* cx
, JS::HandleObject obj
,
2089 return IsGivenTypeObject(cx
, obj
, ESClass::Map
, isMap
);
2092 JS_PUBLIC_API
bool JS::IsSetObject(JSContext
* cx
, JS::HandleObject obj
,
2094 return IsGivenTypeObject(cx
, obj
, ESClass::Set
, isSet
);
2097 JS_PUBLIC_API
void JS_HoldPrincipals(JSPrincipals
* principals
) {
2098 ++principals
->refcount
;
2101 JS_PUBLIC_API
void JS_DropPrincipals(JSContext
* cx
, JSPrincipals
* principals
) {
2102 int rc
= --principals
->refcount
;
2104 JS::AutoSuppressGCAnalysis nogc
;
2105 cx
->runtime()->destroyPrincipals(principals
);
2109 JS_PUBLIC_API
void JS_SetSecurityCallbacks(JSContext
* cx
,
2110 const JSSecurityCallbacks
* scb
) {
2111 MOZ_ASSERT(scb
!= &NullSecurityCallbacks
);
2112 cx
->runtime()->securityCallbacks
= scb
? scb
: &NullSecurityCallbacks
;
2115 JS_PUBLIC_API
const JSSecurityCallbacks
* JS_GetSecurityCallbacks(
2117 return (cx
->runtime()->securityCallbacks
!= &NullSecurityCallbacks
)
2118 ? cx
->runtime()->securityCallbacks
.ref()
2122 JS_PUBLIC_API
void JS_SetTrustedPrincipals(JSContext
* cx
, JSPrincipals
* prin
) {
2123 cx
->runtime()->setTrustedPrincipals(prin
);
2126 extern JS_PUBLIC_API
void JS_InitDestroyPrincipalsCallback(
2127 JSContext
* cx
, JSDestroyPrincipalsOp destroyPrincipals
) {
2128 MOZ_ASSERT(destroyPrincipals
);
2129 MOZ_ASSERT(!cx
->runtime()->destroyPrincipals
);
2130 cx
->runtime()->destroyPrincipals
= destroyPrincipals
;
2133 extern JS_PUBLIC_API
void JS_InitReadPrincipalsCallback(
2134 JSContext
* cx
, JSReadPrincipalsOp read
) {
2136 MOZ_ASSERT(!cx
->runtime()->readPrincipals
);
2137 cx
->runtime()->readPrincipals
= read
;
2140 JS_PUBLIC_API JSFunction
* JS_NewFunction(JSContext
* cx
, JSNative native
,
2141 unsigned nargs
, unsigned flags
,
2143 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
2148 Rooted
<JSAtom
*> atom(cx
);
2150 atom
= Atomize(cx
, name
, strlen(name
));
2156 return (flags
& JSFUN_CONSTRUCTOR
)
2157 ? NewNativeConstructor(cx
, native
, nargs
, atom
)
2158 : NewNativeFunction(cx
, native
, nargs
, atom
);
2161 JS_PUBLIC_API JSFunction
* JS::GetSelfHostedFunction(JSContext
* cx
,
2162 const char* selfHostedName
,
2165 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
2170 Rooted
<JSAtom
*> name(cx
, IdToFunctionName(cx
, id
));
2175 JSAtom
* shAtom
= Atomize(cx
, selfHostedName
, strlen(selfHostedName
));
2179 Rooted
<PropertyName
*> shName(cx
, shAtom
->asPropertyName());
2180 RootedValue
funVal(cx
);
2181 if (!GlobalObject::getSelfHostedFunction(cx
, cx
->global(), shName
, name
,
2185 return &funVal
.toObject().as
<JSFunction
>();
2188 JS_PUBLIC_API JSFunction
* JS::NewFunctionFromSpec(JSContext
* cx
,
2189 const JSFunctionSpec
* fs
,
2194 if (fs
->name
.isSymbol()) {
2195 JS::Symbol
* sym
= cx
->wellKnownSymbols().get(fs
->name
.symbol());
2196 MOZ_ASSERT(PropertyKey::Symbol(sym
) == id
);
2198 MOZ_ASSERT(id
.isString() &&
2199 StringEqualsAscii(id
.toLinearString(), fs
->name
.string()));
2203 // Delay cloning self-hosted functions until they are called. This is
2204 // achieved by passing DefineFunction a nullptr JSNative which produces an
2205 // interpreted JSFunction where !hasScript. Interpreted call paths then
2206 // call InitializeLazyFunctionScript if !hasScript.
2207 if (fs
->selfHostedName
) {
2208 MOZ_ASSERT(!fs
->call
.op
);
2209 MOZ_ASSERT(!fs
->call
.info
);
2212 Atomize(cx
, fs
->selfHostedName
, strlen(fs
->selfHostedName
));
2216 Rooted
<PropertyName
*> shName(cx
, shAtom
->asPropertyName());
2217 Rooted
<JSAtom
*> name(cx
, IdToFunctionName(cx
, id
));
2221 RootedValue
funVal(cx
);
2222 if (!GlobalObject::getSelfHostedFunction(cx
, cx
->global(), shName
, name
,
2223 fs
->nargs
, &funVal
)) {
2226 return &funVal
.toObject().as
<JSFunction
>();
2229 Rooted
<JSAtom
*> atom(cx
, IdToFunctionName(cx
, id
));
2234 MOZ_ASSERT(fs
->call
.op
);
2237 if (fs
->flags
& JSFUN_CONSTRUCTOR
) {
2238 fun
= NewNativeConstructor(cx
, fs
->call
.op
, fs
->nargs
, atom
);
2240 fun
= NewNativeFunction(cx
, fs
->call
.op
, fs
->nargs
, atom
);
2246 if (fs
->call
.info
) {
2247 fun
->setJitInfo(fs
->call
.info
);
2252 JS_PUBLIC_API JSFunction
* JS::NewFunctionFromSpec(JSContext
* cx
,
2253 const JSFunctionSpec
* fs
) {
2255 if (!PropertySpecNameToId(cx
, fs
->name
, &id
)) {
2259 return NewFunctionFromSpec(cx
, fs
, id
);
2262 JS_PUBLIC_API JSObject
* JS_GetFunctionObject(JSFunction
* fun
) { return fun
; }
2264 JS_PUBLIC_API JSString
* JS_GetFunctionId(JSFunction
* fun
) {
2265 return fun
->explicitName();
2268 JS_PUBLIC_API JSString
* JS_GetFunctionDisplayId(JSFunction
* fun
) {
2269 return fun
->displayAtom();
2272 JS_PUBLIC_API
uint16_t JS_GetFunctionArity(JSFunction
* fun
) {
2273 return fun
->nargs();
2276 JS_PUBLIC_API
bool JS_GetFunctionLength(JSContext
* cx
, HandleFunction fun
,
2279 return JSFunction::getLength(cx
, fun
, length
);
2282 JS_PUBLIC_API
bool JS_ObjectIsFunction(JSObject
* obj
) {
2283 return obj
->is
<JSFunction
>();
2286 JS_PUBLIC_API
bool JS_IsNativeFunction(JSObject
* funobj
, JSNative call
) {
2287 if (!funobj
->is
<JSFunction
>()) {
2290 JSFunction
* fun
= &funobj
->as
<JSFunction
>();
2291 return fun
->isNativeFun() && fun
->native() == call
;
2294 extern JS_PUBLIC_API
bool JS_IsConstructor(JSFunction
* fun
) {
2295 return fun
->isConstructor();
2298 void JS::TransitiveCompileOptions::copyPODTransitiveOptions(
2299 const TransitiveCompileOptions
& rhs
) {
2300 // filename_, introducerFilename_, sourceMapURL_ should be handled in caller.
2302 mutedErrors_
= rhs
.mutedErrors_
;
2303 forceStrictMode_
= rhs
.forceStrictMode_
;
2304 alwaysUseFdlibm_
= rhs
.alwaysUseFdlibm_
;
2305 sourcePragmas_
= rhs
.sourcePragmas_
;
2306 skipFilenameValidation_
= rhs
.skipFilenameValidation_
;
2307 hideScriptFromDebugger_
= rhs
.hideScriptFromDebugger_
;
2308 deferDebugMetadata_
= rhs
.deferDebugMetadata_
;
2309 eagerDelazificationStrategy_
= rhs
.eagerDelazificationStrategy_
;
2311 selfHostingMode
= rhs
.selfHostingMode
;
2312 asmJSOption
= rhs
.asmJSOption
;
2313 throwOnAsmJSValidationFailureOption
= rhs
.throwOnAsmJSValidationFailureOption
;
2314 forceAsync
= rhs
.forceAsync
;
2315 discardSource
= rhs
.discardSource
;
2316 sourceIsLazy
= rhs
.sourceIsLazy
;
2317 allowHTMLComments
= rhs
.allowHTMLComments
;
2318 nonSyntacticScope
= rhs
.nonSyntacticScope
;
2320 topLevelAwait
= rhs
.topLevelAwait
;
2321 importAssertions
= rhs
.importAssertions
;
2323 borrowBuffer
= rhs
.borrowBuffer
;
2324 usePinnedBytecode
= rhs
.usePinnedBytecode
;
2325 allocateInstantiationStorage
= rhs
.allocateInstantiationStorage
;
2326 deoptimizeModuleGlobalVars
= rhs
.deoptimizeModuleGlobalVars
;
2328 introductionType
= rhs
.introductionType
;
2329 introductionLineno
= rhs
.introductionLineno
;
2330 introductionOffset
= rhs
.introductionOffset
;
2331 hasIntroductionInfo
= rhs
.hasIntroductionInfo
;
2334 void JS::ReadOnlyCompileOptions::copyPODNonTransitiveOptions(
2335 const ReadOnlyCompileOptions
& rhs
) {
2336 lineno
= rhs
.lineno
;
2337 column
= rhs
.column
;
2338 scriptSourceOffset
= rhs
.scriptSourceOffset
;
2339 isRunOnce
= rhs
.isRunOnce
;
2340 noScriptRval
= rhs
.noScriptRval
;
2343 JS::OwningCompileOptions::OwningCompileOptions(JSContext
* cx
)
2344 : ReadOnlyCompileOptions() {}
2346 void JS::OwningCompileOptions::release() {
2347 // OwningCompileOptions always owns these, so these casts are okay.
2348 js_free(const_cast<char*>(filename_
.c_str()));
2349 js_free(const_cast<char16_t
*>(sourceMapURL_
));
2350 js_free(const_cast<char*>(introducerFilename_
.c_str()));
2352 filename_
= JS::ConstUTF8CharsZ();
2353 sourceMapURL_
= nullptr;
2354 introducerFilename_
= JS::ConstUTF8CharsZ();
2357 JS::OwningCompileOptions::~OwningCompileOptions() { release(); }
2359 size_t JS::OwningCompileOptions::sizeOfExcludingThis(
2360 mozilla::MallocSizeOf mallocSizeOf
) const {
2361 return mallocSizeOf(filename_
.c_str()) + mallocSizeOf(sourceMapURL_
) +
2362 mallocSizeOf(introducerFilename_
.c_str());
2365 template <typename ContextT
>
2366 bool JS::OwningCompileOptions::copyImpl(ContextT
* cx
,
2367 const ReadOnlyCompileOptions
& rhs
) {
2368 // Release existing string allocations.
2371 copyPODNonTransitiveOptions(rhs
);
2372 copyPODTransitiveOptions(rhs
);
2374 if (rhs
.filename()) {
2375 const char* str
= DuplicateString(cx
, rhs
.filename().c_str()).release();
2379 filename_
= JS::ConstUTF8CharsZ(str
);
2382 if (rhs
.sourceMapURL()) {
2383 sourceMapURL_
= DuplicateString(cx
, rhs
.sourceMapURL()).release();
2384 if (!sourceMapURL_
) {
2389 if (rhs
.introducerFilename()) {
2391 DuplicateString(cx
, rhs
.introducerFilename().c_str()).release();
2395 introducerFilename_
= JS::ConstUTF8CharsZ(str
);
2401 bool JS::OwningCompileOptions::copy(JSContext
* cx
,
2402 const ReadOnlyCompileOptions
& rhs
) {
2403 return copyImpl(cx
, rhs
);
2406 bool JS::OwningCompileOptions::copy(JS::FrontendContext
* fc
,
2407 const ReadOnlyCompileOptions
& rhs
) {
2408 return copyImpl(fc
, rhs
);
2411 JS::CompileOptions::CompileOptions(JSContext
* cx
) : ReadOnlyCompileOptions() {
2412 if (!js::IsAsmJSCompilationAvailable(cx
)) {
2413 // Distinguishing the cases is just for error reporting.
2414 asmJSOption
= !cx
->options().asmJS()
2415 ? AsmJSOption::DisabledByAsmJSPref
2416 : AsmJSOption::DisabledByNoWasmCompiler
;
2417 } else if (cx
->realm() && (cx
->realm()->debuggerObservesWasm() ||
2418 cx
->realm()->debuggerObservesAsmJS())) {
2419 asmJSOption
= AsmJSOption::DisabledByDebugger
;
2421 asmJSOption
= AsmJSOption::Enabled
;
2423 throwOnAsmJSValidationFailureOption
=
2424 cx
->options().throwOnAsmJSValidationFailure();
2426 importAssertions
= cx
->options().importAssertions();
2428 sourcePragmas_
= cx
->options().sourcePragmas();
2430 // Certain modes of operation force strict-mode in general.
2431 forceStrictMode_
= cx
->options().strictMode();
2433 // Certain modes of operation disallow syntax parsing in general.
2434 if (coverage::IsLCovEnabled()) {
2435 eagerDelazificationStrategy_
= DelazificationOption::ParseEverythingEagerly
;
2438 // Note: If we parse outside of a specific realm, we do not inherit any realm
2439 // behaviours. These can still be set manually on the options though.
2440 if (Realm
* realm
= cx
->realm()) {
2441 alwaysUseFdlibm_
= realm
->creationOptions().alwaysUseFdlibm();
2442 discardSource
= realm
->behaviors().discardSource();
2446 CompileOptions
& CompileOptions::setIntroductionInfoToCaller(
2447 JSContext
* cx
, const char* introductionType
,
2448 MutableHandle
<JSScript
*> introductionScript
) {
2449 RootedScript
maybeScript(cx
);
2450 const char* filename
;
2454 DescribeScriptedCallerForCompilation(cx
, &maybeScript
, &filename
, &lineno
,
2455 &pcOffset
, &mutedErrors
);
2457 introductionScript
.set(maybeScript
);
2458 return setIntroductionInfo(filename
, introductionType
, lineno
, pcOffset
);
2460 return setIntroductionType(introductionType
);
2463 JS_PUBLIC_API JSObject
* JS_GetGlobalFromScript(JSScript
* script
) {
2464 return &script
->global();
2467 JS_PUBLIC_API
const char* JS_GetScriptFilename(JSScript
* script
) {
2468 // This is called from ThreadStackHelper which can be called from another
2469 // thread or inside a signal hander, so we need to be careful in case a
2470 // copmacting GC is currently moving things around.
2471 return script
->maybeForwardedFilename();
2474 JS_PUBLIC_API
unsigned JS_GetScriptBaseLineNumber(JSContext
* cx
,
2476 return script
->lineno();
2479 JS_PUBLIC_API JSScript
* JS_GetFunctionScript(JSContext
* cx
,
2480 HandleFunction fun
) {
2481 if (fun
->isNativeFun()) {
2485 if (fun
->hasBytecode()) {
2486 return fun
->nonLazyScript();
2489 AutoRealm
ar(cx
, fun
);
2490 JSScript
* script
= JSFunction::getOrCreateScript(cx
, fun
);
2497 JS_PUBLIC_API JSString
* JS_DecompileScript(JSContext
* cx
, HandleScript script
) {
2498 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
2502 RootedFunction
fun(cx
, script
->function());
2504 return JS_DecompileFunction(cx
, fun
);
2507 if (!ScriptSource::loadSource(cx
, script
->scriptSource(), &haveSource
)) {
2510 return haveSource
? JSScript::sourceData(cx
, script
)
2511 : NewStringCopyZ
<CanGC
>(cx
, "[no source]");
2514 JS_PUBLIC_API JSString
* JS_DecompileFunction(JSContext
* cx
,
2515 HandleFunction fun
) {
2516 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
2520 return FunctionToString(cx
, fun
, /* isToSource = */ false);
2523 JS_PUBLIC_API
void JS::SetScriptPrivate(JSScript
* script
,
2524 const JS::Value
& value
) {
2525 JSRuntime
* rt
= script
->zone()->runtimeFromMainThread();
2526 script
->sourceObject()->setPrivate(rt
, value
);
2529 JS_PUBLIC_API
JS::Value
JS::GetScriptPrivate(JSScript
* script
) {
2530 return script
->sourceObject()->getPrivate();
2533 JS_PUBLIC_API
JS::Value
JS::GetScriptedCallerPrivate(JSContext
* cx
) {
2537 NonBuiltinFrameIter
iter(cx
, cx
->realm()->principals());
2538 if (iter
.done() || !iter
.hasScript()) {
2539 return UndefinedValue();
2542 return iter
.script()->sourceObject()->getPrivate();
2545 JS_PUBLIC_API
void JS::SetScriptPrivateReferenceHooks(
2546 JSRuntime
* rt
, JS::ScriptPrivateReferenceHook addRefHook
,
2547 JS::ScriptPrivateReferenceHook releaseHook
) {
2549 rt
->scriptPrivateAddRefHook
= addRefHook
;
2550 rt
->scriptPrivateReleaseHook
= releaseHook
;
2553 JS_PUBLIC_API
void JS::SetWaitCallback(JSRuntime
* rt
,
2554 BeforeWaitCallback beforeWait
,
2555 AfterWaitCallback afterWait
,
2556 size_t requiredMemory
) {
2557 MOZ_RELEASE_ASSERT(requiredMemory
<= WAIT_CALLBACK_CLIENT_MAXMEM
);
2558 MOZ_RELEASE_ASSERT((beforeWait
== nullptr) == (afterWait
== nullptr));
2559 rt
->beforeWaitCallback
= beforeWait
;
2560 rt
->afterWaitCallback
= afterWait
;
2563 JS_PUBLIC_API
bool JS_CheckForInterrupt(JSContext
* cx
) {
2564 return js::CheckForInterrupt(cx
);
2567 JS_PUBLIC_API
bool JS_AddInterruptCallback(JSContext
* cx
,
2568 JSInterruptCallback callback
) {
2569 return cx
->interruptCallbacks().append(callback
);
2572 JS_PUBLIC_API
bool JS_DisableInterruptCallback(JSContext
* cx
) {
2573 bool result
= cx
->interruptCallbackDisabled
;
2574 cx
->interruptCallbackDisabled
= true;
2578 JS_PUBLIC_API
void JS_ResetInterruptCallback(JSContext
* cx
, bool enable
) {
2579 cx
->interruptCallbackDisabled
= enable
;
2582 /************************************************************************/
2587 JS_PUBLIC_API
void JS::SetJobQueue(JSContext
* cx
, JobQueue
* queue
) {
2588 cx
->jobQueue
= queue
;
2591 extern JS_PUBLIC_API
void JS::SetPromiseRejectionTrackerCallback(
2592 JSContext
* cx
, PromiseRejectionTrackerCallback callback
,
2593 void* data
/* = nullptr */) {
2594 cx
->promiseRejectionTrackerCallback
= callback
;
2595 cx
->promiseRejectionTrackerCallbackData
= data
;
2598 extern JS_PUBLIC_API
void JS::JobQueueIsEmpty(JSContext
* cx
) {
2599 cx
->canSkipEnqueuingJobs
= true;
2602 extern JS_PUBLIC_API
void JS::JobQueueMayNotBeEmpty(JSContext
* cx
) {
2603 cx
->canSkipEnqueuingJobs
= false;
2606 JS_PUBLIC_API JSObject
* JS::NewPromiseObject(JSContext
* cx
,
2607 HandleObject executor
) {
2608 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
2611 cx
->check(executor
);
2614 return PromiseObject::createSkippingExecutor(cx
);
2617 MOZ_ASSERT(IsCallable(executor
));
2618 return PromiseObject::create(cx
, executor
);
2621 JS_PUBLIC_API
bool JS::IsPromiseObject(JS::HandleObject obj
) {
2622 return obj
->is
<PromiseObject
>();
2625 JS_PUBLIC_API JSObject
* JS::GetPromiseConstructor(JSContext
* cx
) {
2627 Rooted
<GlobalObject
*> global(cx
, cx
->global());
2628 return GlobalObject::getOrCreatePromiseConstructor(cx
, global
);
2631 JS_PUBLIC_API JSObject
* JS::GetPromisePrototype(JSContext
* cx
) {
2633 Rooted
<GlobalObject
*> global(cx
, cx
->global());
2634 return GlobalObject::getOrCreatePromisePrototype(cx
, global
);
2637 JS_PUBLIC_API
JS::PromiseState
JS::GetPromiseState(JS::HandleObject promise
) {
2638 PromiseObject
* promiseObj
= promise
->maybeUnwrapIf
<PromiseObject
>();
2640 return JS::PromiseState::Pending
;
2643 return promiseObj
->state();
2646 JS_PUBLIC_API
uint64_t JS::GetPromiseID(JS::HandleObject promise
) {
2647 return promise
->as
<PromiseObject
>().getID();
2650 JS_PUBLIC_API
JS::Value
JS::GetPromiseResult(JS::HandleObject promiseObj
) {
2651 PromiseObject
* promise
= &promiseObj
->as
<PromiseObject
>();
2652 MOZ_ASSERT(promise
->state() != JS::PromiseState::Pending
);
2653 return promise
->state() == JS::PromiseState::Fulfilled
? promise
->value()
2654 : promise
->reason();
2657 JS_PUBLIC_API
bool JS::GetPromiseIsHandled(JS::HandleObject promise
) {
2658 PromiseObject
* promiseObj
= &promise
->as
<PromiseObject
>();
2659 return !promiseObj
->isUnhandled();
2662 static PromiseObject
* UnwrapPromise(JSContext
* cx
, JS::HandleObject promise
,
2663 mozilla::Maybe
<AutoRealm
>& ar
) {
2668 PromiseObject
* promiseObj
;
2669 if (IsWrapper(promise
)) {
2670 promiseObj
= promise
->maybeUnwrapAs
<PromiseObject
>();
2672 ReportAccessDenied(cx
);
2675 ar
.emplace(cx
, promiseObj
);
2677 promiseObj
= promise
.as
<PromiseObject
>();
2682 JS_PUBLIC_API
bool JS::SetSettledPromiseIsHandled(JSContext
* cx
,
2683 JS::HandleObject promise
) {
2684 mozilla::Maybe
<AutoRealm
> ar
;
2685 Rooted
<PromiseObject
*> promiseObj(cx
, UnwrapPromise(cx
, promise
, ar
));
2689 js::SetSettledPromiseIsHandled(cx
, promiseObj
);
2693 JS_PUBLIC_API
bool JS::SetAnyPromiseIsHandled(JSContext
* cx
,
2694 JS::HandleObject promise
) {
2695 mozilla::Maybe
<AutoRealm
> ar
;
2696 Rooted
<PromiseObject
*> promiseObj(cx
, UnwrapPromise(cx
, promise
, ar
));
2700 js::SetAnyPromiseIsHandled(cx
, promiseObj
);
2704 JS_PUBLIC_API JSObject
* JS::GetPromiseAllocationSite(JS::HandleObject promise
) {
2705 return promise
->as
<PromiseObject
>().allocationSite();
2708 JS_PUBLIC_API JSObject
* JS::GetPromiseResolutionSite(JS::HandleObject promise
) {
2709 return promise
->as
<PromiseObject
>().resolutionSite();
2713 JS_PUBLIC_API
void JS::DumpPromiseAllocationSite(JSContext
* cx
,
2714 JS::HandleObject promise
) {
2715 RootedObject
stack(cx
, promise
->as
<PromiseObject
>().allocationSite());
2716 JSPrincipals
* principals
= cx
->realm()->principals();
2717 UniqueChars stackStr
= BuildUTF8StackString(cx
, principals
, stack
);
2719 fputs(stackStr
.get(), stderr
);
2723 JS_PUBLIC_API
void JS::DumpPromiseResolutionSite(JSContext
* cx
,
2724 JS::HandleObject promise
) {
2725 RootedObject
stack(cx
, promise
->as
<PromiseObject
>().resolutionSite());
2726 JSPrincipals
* principals
= cx
->realm()->principals();
2727 UniqueChars stackStr
= BuildUTF8StackString(cx
, principals
, stack
);
2729 fputs(stackStr
.get(), stderr
);
2734 JS_PUBLIC_API JSObject
* JS::CallOriginalPromiseResolve(
2735 JSContext
* cx
, JS::HandleValue resolutionValue
) {
2738 cx
->check(resolutionValue
);
2740 RootedObject
promise(cx
,
2741 PromiseObject::unforgeableResolve(cx
, resolutionValue
));
2742 MOZ_ASSERT_IF(promise
, promise
->canUnwrapAs
<PromiseObject
>());
2746 JS_PUBLIC_API JSObject
* JS::CallOriginalPromiseReject(
2747 JSContext
* cx
, JS::HandleValue rejectionValue
) {
2750 cx
->check(rejectionValue
);
2752 RootedObject
promise(cx
,
2753 PromiseObject::unforgeableReject(cx
, rejectionValue
));
2754 MOZ_ASSERT_IF(promise
, promise
->canUnwrapAs
<PromiseObject
>());
2758 static bool ResolveOrRejectPromise(JSContext
* cx
, JS::HandleObject promiseObj
,
2759 JS::HandleValue resultOrReason_
,
2763 cx
->check(promiseObj
, resultOrReason_
);
2765 mozilla::Maybe
<AutoRealm
> ar
;
2766 Rooted
<PromiseObject
*> promise(cx
);
2767 RootedValue
resultOrReason(cx
, resultOrReason_
);
2768 if (IsWrapper(promiseObj
)) {
2769 promise
= promiseObj
->maybeUnwrapAs
<PromiseObject
>();
2771 ReportAccessDenied(cx
);
2774 ar
.emplace(cx
, promise
);
2775 if (!cx
->compartment()->wrap(cx
, &resultOrReason
)) {
2779 promise
= promiseObj
.as
<PromiseObject
>();
2782 return reject
? PromiseObject::reject(cx
, promise
, resultOrReason
)
2783 : PromiseObject::resolve(cx
, promise
, resultOrReason
);
2786 JS_PUBLIC_API
bool JS::ResolvePromise(JSContext
* cx
,
2787 JS::HandleObject promiseObj
,
2788 JS::HandleValue resolutionValue
) {
2789 return ResolveOrRejectPromise(cx
, promiseObj
, resolutionValue
, false);
2792 JS_PUBLIC_API
bool JS::RejectPromise(JSContext
* cx
, JS::HandleObject promiseObj
,
2793 JS::HandleValue rejectionValue
) {
2794 return ResolveOrRejectPromise(cx
, promiseObj
, rejectionValue
, true);
2797 JS_PUBLIC_API JSObject
* JS::CallOriginalPromiseThen(
2798 JSContext
* cx
, JS::HandleObject promiseObj
, JS::HandleObject onFulfilled
,
2799 JS::HandleObject onRejected
) {
2802 cx
->check(promiseObj
, onFulfilled
, onRejected
);
2804 MOZ_ASSERT_IF(onFulfilled
, IsCallable(onFulfilled
));
2805 MOZ_ASSERT_IF(onRejected
, IsCallable(onRejected
));
2807 return OriginalPromiseThen(cx
, promiseObj
, onFulfilled
, onRejected
);
2810 [[nodiscard
]] static bool ReactToPromise(JSContext
* cx
,
2811 JS::Handle
<JSObject
*> promiseObj
,
2812 JS::Handle
<JSObject
*> onFulfilled
,
2813 JS::Handle
<JSObject
*> onRejected
,
2814 UnhandledRejectionBehavior behavior
) {
2817 cx
->check(promiseObj
, onFulfilled
, onRejected
);
2819 MOZ_ASSERT_IF(onFulfilled
, IsCallable(onFulfilled
));
2820 MOZ_ASSERT_IF(onRejected
, IsCallable(onRejected
));
2822 Rooted
<PromiseObject
*> unwrappedPromise(cx
);
2824 RootedValue
promiseVal(cx
, ObjectValue(*promiseObj
));
2825 unwrappedPromise
= UnwrapAndTypeCheckValue
<PromiseObject
>(
2826 cx
, promiseVal
, [cx
, promiseObj
] {
2827 JS_ReportErrorNumberLatin1(cx
, GetErrorMessage
, nullptr,
2828 JSMSG_INCOMPATIBLE_PROTO
, "Promise",
2829 "then", promiseObj
->getClass()->name
);
2831 if (!unwrappedPromise
) {
2836 return ReactToUnwrappedPromise(cx
, unwrappedPromise
, onFulfilled
, onRejected
,
2840 JS_PUBLIC_API
bool JS::AddPromiseReactions(JSContext
* cx
,
2841 JS::HandleObject promiseObj
,
2842 JS::HandleObject onFulfilled
,
2843 JS::HandleObject onRejected
) {
2844 return ReactToPromise(cx
, promiseObj
, onFulfilled
, onRejected
,
2845 UnhandledRejectionBehavior::Report
);
2848 JS_PUBLIC_API
bool JS::AddPromiseReactionsIgnoringUnhandledRejection(
2849 JSContext
* cx
, JS::HandleObject promiseObj
, JS::HandleObject onFulfilled
,
2850 JS::HandleObject onRejected
) {
2851 return ReactToPromise(cx
, promiseObj
, onFulfilled
, onRejected
,
2852 UnhandledRejectionBehavior::Ignore
);
2855 JS_PUBLIC_API
JS::PromiseUserInputEventHandlingState
2856 JS::GetPromiseUserInputEventHandlingState(JS::HandleObject promiseObj_
) {
2857 PromiseObject
* promise
= promiseObj_
->maybeUnwrapIf
<PromiseObject
>();
2859 return JS::PromiseUserInputEventHandlingState::DontCare
;
2862 if (!promise
->requiresUserInteractionHandling()) {
2863 return JS::PromiseUserInputEventHandlingState::DontCare
;
2865 if (promise
->hadUserInteractionUponCreation()) {
2866 return JS::PromiseUserInputEventHandlingState::HadUserInteractionAtCreation
;
2868 return JS::PromiseUserInputEventHandlingState::
2869 DidntHaveUserInteractionAtCreation
;
2872 JS_PUBLIC_API
bool JS::SetPromiseUserInputEventHandlingState(
2873 JS::HandleObject promiseObj_
,
2874 JS::PromiseUserInputEventHandlingState state
) {
2875 PromiseObject
* promise
= promiseObj_
->maybeUnwrapIf
<PromiseObject
>();
2881 case JS::PromiseUserInputEventHandlingState::DontCare
:
2882 promise
->setRequiresUserInteractionHandling(false);
2884 case JS::PromiseUserInputEventHandlingState::HadUserInteractionAtCreation
:
2885 promise
->setRequiresUserInteractionHandling(true);
2886 promise
->setHadUserInteractionUponCreation(true);
2888 case JS::PromiseUserInputEventHandlingState::
2889 DidntHaveUserInteractionAtCreation
:
2890 promise
->setRequiresUserInteractionHandling(true);
2891 promise
->setHadUserInteractionUponCreation(false);
2894 MOZ_ASSERT_UNREACHABLE(
2895 "Invalid PromiseUserInputEventHandlingState enum value");
2902 * Unforgeable version of Promise.all for internal use.
2904 * Takes a dense array of Promise objects and returns a promise that's
2905 * resolved with an array of resolution values when all those promises ahve
2906 * been resolved, or rejected with the rejection value of the first rejected
2909 * Asserts that the array is dense and all entries are Promise objects.
2911 JS_PUBLIC_API JSObject
* JS::GetWaitForAllPromise(
2912 JSContext
* cx
, JS::HandleObjectVector promises
) {
2916 return js::GetWaitForAllPromise(cx
, promises
);
2919 JS_PUBLIC_API
void JS::InitDispatchToEventLoop(
2920 JSContext
* cx
, JS::DispatchToEventLoopCallback callback
, void* closure
) {
2921 cx
->runtime()->offThreadPromiseState
.ref().init(callback
, closure
);
2924 JS_PUBLIC_API
void JS::ShutdownAsyncTasks(JSContext
* cx
) {
2925 cx
->runtime()->offThreadPromiseState
.ref().shutdown(cx
);
2928 JS_PUBLIC_API
void JS::InitConsumeStreamCallback(
2929 JSContext
* cx
, ConsumeStreamCallback consume
,
2930 ReportStreamErrorCallback report
) {
2931 cx
->runtime()->consumeStreamCallback
= consume
;
2932 cx
->runtime()->reportStreamErrorCallback
= report
;
2935 JS_PUBLIC_API
void JS_RequestInterruptCallback(JSContext
* cx
) {
2936 cx
->requestInterrupt(InterruptReason::CallbackUrgent
);
2939 JS_PUBLIC_API
void JS_RequestInterruptCallbackCanWait(JSContext
* cx
) {
2940 cx
->requestInterrupt(InterruptReason::CallbackCanWait
);
2943 JS::AutoSetAsyncStackForNewCalls::AutoSetAsyncStackForNewCalls(
2944 JSContext
* cx
, HandleObject stack
, const char* asyncCause
,
2945 JS::AutoSetAsyncStackForNewCalls::AsyncCallKind kind
)
2947 oldAsyncStack(cx
, cx
->asyncStackForNewActivations()),
2948 oldAsyncCause(cx
->asyncCauseForNewActivations
),
2949 oldAsyncCallIsExplicit(cx
->asyncCallIsExplicit
) {
2952 // The option determines whether we actually use the new values at this
2953 // point. It will not affect restoring the previous values when the object
2954 // is destroyed, so if the option changes it won't cause consistency issues.
2955 if (!cx
->options().asyncStack()) {
2959 SavedFrame
* asyncStack
= &stack
->as
<SavedFrame
>();
2961 cx
->asyncStackForNewActivations() = asyncStack
;
2962 cx
->asyncCauseForNewActivations
= asyncCause
;
2963 cx
->asyncCallIsExplicit
= kind
== AsyncCallKind::EXPLICIT
;
2966 JS::AutoSetAsyncStackForNewCalls::~AutoSetAsyncStackForNewCalls() {
2967 cx
->asyncCauseForNewActivations
= oldAsyncCause
;
2968 cx
->asyncStackForNewActivations() =
2969 oldAsyncStack
? &oldAsyncStack
->as
<SavedFrame
>() : nullptr;
2970 cx
->asyncCallIsExplicit
= oldAsyncCallIsExplicit
;
2973 /************************************************************************/
2974 JS_PUBLIC_API JSString
* JS_NewStringCopyN(JSContext
* cx
, const char* s
,
2978 return NewStringCopyN
<CanGC
>(cx
, s
, n
);
2981 JS_PUBLIC_API JSString
* JS_NewStringCopyZ(JSContext
* cx
, const char* s
) {
2985 return cx
->runtime()->emptyString
;
2987 return NewStringCopyZ
<CanGC
>(cx
, s
);
2990 JS_PUBLIC_API JSString
* JS_NewStringCopyUTF8Z(JSContext
* cx
,
2991 const JS::ConstUTF8CharsZ s
) {
2994 return NewStringCopyUTF8Z(cx
, s
);
2997 JS_PUBLIC_API JSString
* JS_NewStringCopyUTF8N(JSContext
* cx
,
2998 const JS::UTF8Chars s
) {
3001 return NewStringCopyUTF8N(cx
, s
);
3004 JS_PUBLIC_API
bool JS_StringHasBeenPinned(JSContext
* cx
, JSString
* str
) {
3008 if (!str
->isAtom()) {
3012 return AtomIsPinned(cx
, &str
->asAtom());
3015 JS_PUBLIC_API JSString
* JS_AtomizeString(JSContext
* cx
, const char* s
) {
3016 return JS_AtomizeStringN(cx
, s
, strlen(s
));
3019 JS_PUBLIC_API JSString
* JS_AtomizeStringN(JSContext
* cx
, const char* s
,
3023 return Atomize(cx
, s
, length
);
3026 JS_PUBLIC_API JSString
* JS_AtomizeAndPinString(JSContext
* cx
, const char* s
) {
3027 return JS_AtomizeAndPinStringN(cx
, s
, strlen(s
));
3030 JS_PUBLIC_API JSString
* JS_AtomizeAndPinStringN(JSContext
* cx
, const char* s
,
3035 JSAtom
* atom
= cx
->zone() ? Atomize(cx
, s
, length
)
3036 : AtomizeWithoutActiveZone(cx
, s
, length
);
3037 if (!atom
|| !PinAtom(cx
, atom
)) {
3041 MOZ_ASSERT(JS_StringHasBeenPinned(cx
, atom
));
3045 JS_PUBLIC_API JSString
* JS_NewLatin1String(
3046 JSContext
* cx
, js::UniquePtr
<JS::Latin1Char
[], JS::FreePolicy
> chars
,
3050 return NewString
<CanGC
>(cx
, std::move(chars
), length
);
3053 JS_PUBLIC_API JSString
* JS_NewUCString(JSContext
* cx
,
3054 JS::UniqueTwoByteChars chars
,
3058 return NewString
<CanGC
>(cx
, std::move(chars
), length
);
3061 JS_PUBLIC_API JSString
* JS_NewUCStringDontDeflate(JSContext
* cx
,
3062 JS::UniqueTwoByteChars chars
,
3066 return NewStringDontDeflate
<CanGC
>(cx
, std::move(chars
), length
);
3069 JS_PUBLIC_API JSString
* JS_NewUCStringCopyN(JSContext
* cx
, const char16_t
* s
,
3074 return cx
->names().empty
;
3076 return NewStringCopyN
<CanGC
>(cx
, s
, n
);
3079 JS_PUBLIC_API JSString
* JS_NewUCStringCopyZ(JSContext
* cx
, const char16_t
* s
) {
3083 return cx
->runtime()->emptyString
;
3085 return NewStringCopyZ
<CanGC
>(cx
, s
);
3088 JS_PUBLIC_API JSString
* JS_AtomizeUCString(JSContext
* cx
, const char16_t
* s
) {
3089 return JS_AtomizeUCStringN(cx
, s
, js_strlen(s
));
3092 JS_PUBLIC_API JSString
* JS_AtomizeUCStringN(JSContext
* cx
, const char16_t
* s
,
3096 return AtomizeChars(cx
, s
, length
);
3099 JS_PUBLIC_API
size_t JS_GetStringLength(JSString
* str
) { return str
->length(); }
3101 JS_PUBLIC_API
bool JS_StringIsLinear(JSString
* str
) { return str
->isLinear(); }
3103 JS_PUBLIC_API
bool JS_DeprecatedStringHasLatin1Chars(JSString
* str
) {
3104 return str
->hasLatin1Chars();
3107 JS_PUBLIC_API
const JS::Latin1Char
* JS_GetLatin1StringCharsAndLength(
3108 JSContext
* cx
, const JS::AutoRequireNoGC
& nogc
, JSString
* str
,
3110 MOZ_ASSERT(plength
);
3114 JSLinearString
* linear
= str
->ensureLinear(cx
);
3118 *plength
= linear
->length();
3119 return linear
->latin1Chars(nogc
);
3122 JS_PUBLIC_API
const char16_t
* JS_GetTwoByteStringCharsAndLength(
3123 JSContext
* cx
, const JS::AutoRequireNoGC
& nogc
, JSString
* str
,
3125 MOZ_ASSERT(plength
);
3129 JSLinearString
* linear
= str
->ensureLinear(cx
);
3133 *plength
= linear
->length();
3134 return linear
->twoByteChars(nogc
);
3137 JS_PUBLIC_API
const char16_t
* JS_GetTwoByteExternalStringChars(JSString
* str
) {
3138 return str
->asExternal().twoByteChars();
3141 JS_PUBLIC_API
bool JS_GetStringCharAt(JSContext
* cx
, JSString
* str
,
3142 size_t index
, char16_t
* res
) {
3147 JSLinearString
* linear
= str
->ensureLinear(cx
);
3152 *res
= linear
->latin1OrTwoByteChar(index
);
3156 JS_PUBLIC_API
bool JS_CopyStringChars(JSContext
* cx
,
3157 mozilla::Range
<char16_t
> dest
,
3163 JSLinearString
* linear
= str
->ensureLinear(cx
);
3168 MOZ_ASSERT(linear
->length() <= dest
.length());
3169 CopyChars(dest
.begin().get(), *linear
);
3173 extern JS_PUBLIC_API
JS::UniqueTwoByteChars
JS_CopyStringCharsZ(JSContext
* cx
,
3178 JSLinearString
* linear
= str
->ensureLinear(cx
);
3183 size_t len
= linear
->length();
3185 static_assert(JS::MaxStringLength
< UINT32_MAX
,
3186 "len + 1 must not overflow on 32-bit platforms");
3188 UniqueTwoByteChars
chars(cx
->pod_malloc
<char16_t
>(len
+ 1));
3193 CopyChars(chars
.get(), *linear
);
3199 extern JS_PUBLIC_API JSLinearString
* JS_EnsureLinearString(JSContext
* cx
,
3204 return str
->ensureLinear(cx
);
3207 JS_PUBLIC_API
bool JS_CompareStrings(JSContext
* cx
, JSString
* str1
,
3208 JSString
* str2
, int32_t* result
) {
3212 return CompareStrings(cx
, str1
, str2
, result
);
3215 JS_PUBLIC_API
bool JS_StringEqualsAscii(JSContext
* cx
, JSString
* str
,
3216 const char* asciiBytes
, bool* match
) {
3220 JSLinearString
* linearStr
= str
->ensureLinear(cx
);
3224 *match
= StringEqualsAscii(linearStr
, asciiBytes
);
3228 JS_PUBLIC_API
bool JS_StringEqualsAscii(JSContext
* cx
, JSString
* str
,
3229 const char* asciiBytes
, size_t length
,
3234 JSLinearString
* linearStr
= str
->ensureLinear(cx
);
3238 *match
= StringEqualsAscii(linearStr
, asciiBytes
, length
);
3242 JS_PUBLIC_API
bool JS_LinearStringEqualsAscii(JSLinearString
* str
,
3243 const char* asciiBytes
) {
3244 return StringEqualsAscii(str
, asciiBytes
);
3247 JS_PUBLIC_API
bool JS_LinearStringEqualsAscii(JSLinearString
* str
,
3248 const char* asciiBytes
,
3250 return StringEqualsAscii(str
, asciiBytes
, length
);
3253 JS_PUBLIC_API
size_t JS_PutEscapedLinearString(char* buffer
, size_t size
,
3254 JSLinearString
* str
,
3256 return PutEscapedString(buffer
, size
, str
, quote
);
3259 JS_PUBLIC_API
size_t JS_PutEscapedString(JSContext
* cx
, char* buffer
,
3260 size_t size
, JSString
* str
,
3263 JSLinearString
* linearStr
= str
->ensureLinear(cx
);
3267 return PutEscapedString(buffer
, size
, linearStr
, quote
);
3270 JS_PUBLIC_API JSString
* JS_NewDependentString(JSContext
* cx
, HandleString str
,
3271 size_t start
, size_t length
) {
3274 return NewDependentString(cx
, str
, start
, length
);
3277 JS_PUBLIC_API JSString
* JS_ConcatStrings(JSContext
* cx
, HandleString left
,
3278 HandleString right
) {
3281 return ConcatStrings
<CanGC
>(cx
, left
, right
);
3284 JS_PUBLIC_API
bool JS_DecodeBytes(JSContext
* cx
, const char* src
, size_t srclen
,
3285 char16_t
* dst
, size_t* dstlenp
) {
3294 size_t dstlen
= *dstlenp
;
3296 if (srclen
> dstlen
) {
3297 CopyAndInflateChars(dst
, src
, dstlen
);
3299 gc::AutoSuppressGC
suppress(cx
);
3300 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr,
3301 JSMSG_BUFFER_TOO_SMALL
);
3305 CopyAndInflateChars(dst
, src
, srclen
);
3310 JS_PUBLIC_API
JS::UniqueChars
JS_EncodeStringToASCII(JSContext
* cx
,
3315 return js::EncodeAscii(cx
, str
);
3318 JS_PUBLIC_API
JS::UniqueChars
JS_EncodeStringToLatin1(JSContext
* cx
,
3323 return js::EncodeLatin1(cx
, str
);
3326 JS_PUBLIC_API
JS::UniqueChars
JS_EncodeStringToUTF8(JSContext
* cx
,
3331 return StringToNewUTF8CharsZ(cx
, *str
);
3334 JS_PUBLIC_API
size_t JS_GetStringEncodingLength(JSContext
* cx
, JSString
* str
) {
3338 if (!str
->ensureLinear(cx
)) {
3341 return str
->length();
3344 JS_PUBLIC_API
bool JS_EncodeStringToBuffer(JSContext
* cx
, JSString
* str
,
3345 char* buffer
, size_t length
) {
3349 JSLinearString
* linear
= str
->ensureLinear(cx
);
3354 JS::AutoCheckCannotGC nogc
;
3355 size_t writeLength
= std::min(linear
->length(), length
);
3356 if (linear
->hasLatin1Chars()) {
3357 mozilla::PodCopy(reinterpret_cast<Latin1Char
*>(buffer
),
3358 linear
->latin1Chars(nogc
), writeLength
);
3360 const char16_t
* src
= linear
->twoByteChars(nogc
);
3361 for (size_t i
= 0; i
< writeLength
; i
++) {
3362 buffer
[i
] = char(src
[i
]);
3368 JS_PUBLIC_API
mozilla::Maybe
<std::tuple
<size_t, size_t>>
3369 JS_EncodeStringToUTF8BufferPartial(JSContext
* cx
, JSString
* str
,
3370 mozilla::Span
<char> buffer
) {
3373 JS::AutoCheckCannotGC nogc
;
3374 return str
->encodeUTF8Partial(nogc
, buffer
);
3377 JS_PUBLIC_API
JS::Symbol
* JS::NewSymbol(JSContext
* cx
,
3378 HandleString description
) {
3382 cx
->check(description
);
3385 return Symbol::new_(cx
, SymbolCode::UniqueSymbol
, description
);
3388 JS_PUBLIC_API
JS::Symbol
* JS::GetSymbolFor(JSContext
* cx
, HandleString key
) {
3393 return Symbol::for_(cx
, key
);
3396 JS_PUBLIC_API JSString
* JS::GetSymbolDescription(HandleSymbol symbol
) {
3397 return symbol
->description();
3400 JS_PUBLIC_API
JS::SymbolCode
JS::GetSymbolCode(Handle
<Symbol
*> symbol
) {
3401 return symbol
->code();
3404 JS_PUBLIC_API
JS::Symbol
* JS::GetWellKnownSymbol(JSContext
* cx
,
3405 JS::SymbolCode which
) {
3406 return cx
->wellKnownSymbols().get(which
);
3409 JS_PUBLIC_API
JS::PropertyKey
JS::GetWellKnownSymbolKey(JSContext
* cx
,
3410 JS::SymbolCode which
) {
3411 return PropertyKey::Symbol(cx
->wellKnownSymbols().get(which
));
3414 static bool AddPrefix(JSContext
* cx
, JS::Handle
<JS::PropertyKey
> id
,
3415 FunctionPrefixKind prefixKind
,
3416 JS::MutableHandle
<JS::PropertyKey
> out
) {
3417 JS::Rooted
<JSAtom
*> atom(cx
, js::IdToFunctionName(cx
, id
, prefixKind
));
3422 out
.set(JS::PropertyKey::NonIntAtom(atom
));
3426 JS_PUBLIC_API
bool JS::ToGetterId(JSContext
* cx
, JS::Handle
<JS::PropertyKey
> id
,
3427 JS::MutableHandle
<JS::PropertyKey
> getterId
) {
3428 return AddPrefix(cx
, id
, FunctionPrefixKind::Get
, getterId
);
3431 JS_PUBLIC_API
bool JS::ToSetterId(JSContext
* cx
, JS::Handle
<JS::PropertyKey
> id
,
3432 JS::MutableHandle
<JS::PropertyKey
> setterId
) {
3433 return AddPrefix(cx
, id
, FunctionPrefixKind::Set
, setterId
);
3437 static bool PropertySpecNameIsDigits(JSPropertySpec::Name name
) {
3438 if (name
.isSymbol()) {
3441 const char* s
= name
.string();
3446 if (*s
< '0' || *s
> '9') {
3454 JS_PUBLIC_API
bool JS::PropertySpecNameEqualsId(JSPropertySpec::Name name
,
3456 if (name
.isSymbol()) {
3457 return id
.isWellKnownSymbol(name
.symbol());
3460 MOZ_ASSERT(!PropertySpecNameIsDigits(name
));
3461 return id
.isAtom() && JS_LinearStringEqualsAscii(id
.toAtom(), name
.string());
3464 JS_PUBLIC_API
bool JS_Stringify(JSContext
* cx
, MutableHandleValue vp
,
3465 HandleObject replacer
, HandleValue space
,
3466 JSONWriteCallback callback
, void* data
) {
3469 cx
->check(replacer
, space
);
3470 StringBuffer
sb(cx
);
3471 if (!sb
.ensureTwoByteChars()) {
3474 if (!Stringify(cx
, vp
, replacer
, space
, sb
, StringifyBehavior::Normal
)) {
3477 if (sb
.empty() && !sb
.append(cx
->names().null
)) {
3480 return callback(sb
.rawTwoByteBegin(), sb
.length(), data
);
3483 JS_PUBLIC_API
bool JS::ToJSON(JSContext
* cx
, HandleValue value
,
3484 HandleObject replacer
, HandleValue space
,
3485 JSONWriteCallback callback
, void* data
) {
3488 cx
->check(replacer
, space
);
3489 StringBuffer
sb(cx
);
3490 if (!sb
.ensureTwoByteChars()) {
3493 RootedValue
v(cx
, value
);
3494 if (!Stringify(cx
, &v
, replacer
, space
, sb
, StringifyBehavior::Normal
)) {
3500 return callback(sb
.rawTwoByteBegin(), sb
.length(), data
);
3503 JS_PUBLIC_API
bool JS::ToJSONMaybeSafely(JSContext
* cx
, JS::HandleObject input
,
3504 JSONWriteCallback callback
,
3510 StringBuffer
sb(cx
);
3511 if (!sb
.ensureTwoByteChars()) {
3515 RootedValue
inputValue(cx
, ObjectValue(*input
));
3516 if (!Stringify(cx
, &inputValue
, nullptr, NullHandleValue
, sb
,
3517 StringifyBehavior::RestrictedSafe
))
3520 if (sb
.empty() && !sb
.append(cx
->names().null
)) {
3524 return callback(sb
.rawTwoByteBegin(), sb
.length(), data
);
3527 JS_PUBLIC_API
bool JS_ParseJSON(JSContext
* cx
, const char16_t
* chars
,
3528 uint32_t len
, MutableHandleValue vp
) {
3531 return ParseJSONWithReviver(cx
, mozilla::Range
<const char16_t
>(chars
, len
),
3532 NullHandleValue
, vp
);
3535 JS_PUBLIC_API
bool JS_ParseJSON(JSContext
* cx
, HandleString str
,
3536 MutableHandleValue vp
) {
3537 return JS_ParseJSONWithReviver(cx
, str
, NullHandleValue
, vp
);
3540 JS_PUBLIC_API
bool JS_ParseJSON(JSContext
* cx
, const Latin1Char
* chars
,
3541 uint32_t len
, MutableHandleValue vp
) {
3544 return ParseJSONWithReviver(cx
, mozilla::Range
<const Latin1Char
>(chars
, len
),
3545 NullHandleValue
, vp
);
3548 JS_PUBLIC_API
bool JS_ParseJSONWithReviver(JSContext
* cx
, const char16_t
* chars
,
3549 uint32_t len
, HandleValue reviver
,
3550 MutableHandleValue vp
) {
3553 return ParseJSONWithReviver(cx
, mozilla::Range
<const char16_t
>(chars
, len
),
3557 JS_PUBLIC_API
bool JS_ParseJSONWithReviver(JSContext
* cx
, HandleString str
,
3558 HandleValue reviver
,
3559 MutableHandleValue vp
) {
3564 AutoStableStringChars
stableChars(cx
);
3565 if (!stableChars
.init(cx
, str
)) {
3569 return stableChars
.isLatin1()
3570 ? ParseJSONWithReviver(cx
, stableChars
.latin1Range(), reviver
, vp
)
3571 : ParseJSONWithReviver(cx
, stableChars
.twoByteRange(), reviver
,
3575 /************************************************************************/
3577 JS_PUBLIC_API
void JS_ReportErrorASCII(JSContext
* cx
, const char* format
, ...) {
3581 va_start(ap
, format
);
3582 ReportErrorVA(cx
, IsWarning::No
, format
, ArgumentsAreASCII
, ap
);
3586 JS_PUBLIC_API
void JS_ReportErrorLatin1(JSContext
* cx
, const char* format
,
3591 va_start(ap
, format
);
3592 ReportErrorVA(cx
, IsWarning::No
, format
, ArgumentsAreLatin1
, ap
);
3596 JS_PUBLIC_API
void JS_ReportErrorUTF8(JSContext
* cx
, const char* format
, ...) {
3600 va_start(ap
, format
);
3601 ReportErrorVA(cx
, IsWarning::No
, format
, ArgumentsAreUTF8
, ap
);
3605 JS_PUBLIC_API
void JS_ReportErrorNumberASCII(JSContext
* cx
,
3606 JSErrorCallback errorCallback
,
3608 const unsigned errorNumber
, ...) {
3610 va_start(ap
, errorNumber
);
3611 JS_ReportErrorNumberASCIIVA(cx
, errorCallback
, userRef
, errorNumber
, ap
);
3615 JS_PUBLIC_API
void JS_ReportErrorNumberASCIIVA(JSContext
* cx
,
3616 JSErrorCallback errorCallback
,
3618 const unsigned errorNumber
,
3621 ReportErrorNumberVA(cx
, IsWarning::No
, errorCallback
, userRef
, errorNumber
,
3622 ArgumentsAreASCII
, ap
);
3625 JS_PUBLIC_API
void JS_ReportErrorNumberLatin1(JSContext
* cx
,
3626 JSErrorCallback errorCallback
,
3628 const unsigned errorNumber
, ...) {
3630 va_start(ap
, errorNumber
);
3631 JS_ReportErrorNumberLatin1VA(cx
, errorCallback
, userRef
, errorNumber
, ap
);
3635 JS_PUBLIC_API
void JS_ReportErrorNumberLatin1VA(JSContext
* cx
,
3636 JSErrorCallback errorCallback
,
3638 const unsigned errorNumber
,
3641 ReportErrorNumberVA(cx
, IsWarning::No
, errorCallback
, userRef
, errorNumber
,
3642 ArgumentsAreLatin1
, ap
);
3645 JS_PUBLIC_API
void JS_ReportErrorNumberUTF8(JSContext
* cx
,
3646 JSErrorCallback errorCallback
,
3648 const unsigned errorNumber
, ...) {
3650 va_start(ap
, errorNumber
);
3651 JS_ReportErrorNumberUTF8VA(cx
, errorCallback
, userRef
, errorNumber
, ap
);
3655 JS_PUBLIC_API
void JS_ReportErrorNumberUTF8VA(JSContext
* cx
,
3656 JSErrorCallback errorCallback
,
3658 const unsigned errorNumber
,
3661 ReportErrorNumberVA(cx
, IsWarning::No
, errorCallback
, userRef
, errorNumber
,
3662 ArgumentsAreUTF8
, ap
);
3665 JS_PUBLIC_API
void JS_ReportErrorNumberUTF8Array(JSContext
* cx
,
3666 JSErrorCallback errorCallback
,
3668 const unsigned errorNumber
,
3669 const char** args
) {
3671 ReportErrorNumberUTF8Array(cx
, IsWarning::No
, errorCallback
, userRef
,
3675 JS_PUBLIC_API
void JS_ReportErrorNumberUC(JSContext
* cx
,
3676 JSErrorCallback errorCallback
,
3678 const unsigned errorNumber
, ...) {
3682 va_start(ap
, errorNumber
);
3683 ReportErrorNumberVA(cx
, IsWarning::No
, errorCallback
, userRef
, errorNumber
,
3684 ArgumentsAreUnicode
, ap
);
3688 JS_PUBLIC_API
void JS_ReportErrorNumberUCArray(JSContext
* cx
,
3689 JSErrorCallback errorCallback
,
3691 const unsigned errorNumber
,
3692 const char16_t
** args
) {
3694 ReportErrorNumberUCArray(cx
, IsWarning::No
, errorCallback
, userRef
,
3698 JS_PUBLIC_API
void JS_ReportOutOfMemory(JSContext
* cx
) {
3699 ReportOutOfMemory(cx
);
3702 JS_PUBLIC_API
void JS_ReportAllocationOverflow(JSContext
* cx
) {
3703 ReportAllocationOverflow(cx
);
3706 JS_PUBLIC_API
bool JS_ExpandErrorArgumentsASCII(JSContext
* cx
,
3707 JSErrorCallback errorCallback
,
3708 const unsigned errorNumber
,
3709 JSErrorReport
* reportp
, ...) {
3714 va_start(ap
, reportp
);
3715 AutoReportFrontendContext
fc(cx
);
3716 ok
= ExpandErrorArgumentsVA(&fc
, errorCallback
, nullptr, errorNumber
,
3717 ArgumentsAreASCII
, reportp
, ap
);
3721 /************************************************************************/
3723 JS_PUBLIC_API
bool JS_SetDefaultLocale(JSRuntime
* rt
, const char* locale
) {
3725 return rt
->setDefaultLocale(locale
);
3728 JS_PUBLIC_API UniqueChars
JS_GetDefaultLocale(JSContext
* cx
) {
3730 if (const char* locale
= cx
->runtime()->getDefaultLocale()) {
3731 return DuplicateString(cx
, locale
);
3737 JS_PUBLIC_API
void JS_ResetDefaultLocale(JSRuntime
* rt
) {
3739 rt
->resetDefaultLocale();
3742 JS_PUBLIC_API
void JS_SetLocaleCallbacks(JSRuntime
* rt
,
3743 const JSLocaleCallbacks
* callbacks
) {
3745 rt
->localeCallbacks
= callbacks
;
3748 JS_PUBLIC_API
const JSLocaleCallbacks
* JS_GetLocaleCallbacks(JSRuntime
* rt
) {
3749 /* This function can be called by a finalizer. */
3750 return rt
->localeCallbacks
;
3753 /************************************************************************/
3755 JS_PUBLIC_API
bool JS_IsExceptionPending(JSContext
* cx
) {
3756 /* This function can be called by a finalizer. */
3757 return (bool)cx
->isExceptionPending();
3760 JS_PUBLIC_API
bool JS_IsThrowingOutOfMemory(JSContext
* cx
) {
3761 return cx
->isThrowingOutOfMemory();
3764 JS_PUBLIC_API
bool JS_GetPendingException(JSContext
* cx
,
3765 MutableHandleValue vp
) {
3768 if (!cx
->isExceptionPending()) {
3771 return cx
->getPendingException(vp
);
3774 JS_PUBLIC_API
void JS_SetPendingException(JSContext
* cx
, HandleValue value
,
3775 JS::ExceptionStackBehavior behavior
) {
3778 // We don't check the compartment of `value` here, because we're not
3779 // doing anything with it other than storing it, and stored
3780 // exception values can be in an abitrary compartment.
3782 if (behavior
== JS::ExceptionStackBehavior::Capture
) {
3783 cx
->setPendingException(value
, ShouldCaptureStack::Always
);
3785 cx
->setPendingException(value
, nullptr);
3789 JS_PUBLIC_API
void JS_ClearPendingException(JSContext
* cx
) {
3791 cx
->clearPendingException();
3794 JS::AutoSaveExceptionState::AutoSaveExceptionState(JSContext
* cx
)
3795 : context(cx
), status(cx
->status
), exceptionValue(cx
), exceptionStack(cx
) {
3798 if (IsCatchableExceptionStatus(status
)) {
3799 exceptionValue
= cx
->unwrappedException();
3800 exceptionStack
= cx
->unwrappedExceptionStack();
3802 cx
->clearPendingException();
3805 void JS::AutoSaveExceptionState::drop() {
3806 status
= JS::ExceptionStatus::None
;
3807 exceptionValue
.setUndefined();
3808 exceptionStack
= nullptr;
3811 void JS::AutoSaveExceptionState::restore() {
3812 context
->status
= status
;
3813 context
->unwrappedException() = exceptionValue
;
3814 if (exceptionStack
) {
3815 context
->unwrappedExceptionStack() = &exceptionStack
->as
<SavedFrame
>();
3820 JS::AutoSaveExceptionState::~AutoSaveExceptionState() {
3821 // NOTE: An interrupt/uncatchable exception or a debugger-forced-return may be
3822 // clobbered here by the saved exception. If that is not desired, this
3823 // state should be dropped before the destructor fires.
3824 if (!context
->isExceptionPending()) {
3825 if (status
!= JS::ExceptionStatus::None
) {
3826 context
->status
= status
;
3828 if (IsCatchableExceptionStatus(status
)) {
3829 context
->unwrappedException() = exceptionValue
;
3830 if (exceptionStack
) {
3831 context
->unwrappedExceptionStack() = &exceptionStack
->as
<SavedFrame
>();
3837 JS_PUBLIC_API JSErrorReport
* JS_ErrorFromException(JSContext
* cx
,
3842 return ErrorFromException(cx
, obj
);
3845 void JSErrorReport::initBorrowedLinebuf(const char16_t
* linebufArg
,
3846 size_t linebufLengthArg
,
3847 size_t tokenOffsetArg
) {
3848 MOZ_ASSERT(linebufArg
);
3849 MOZ_ASSERT(tokenOffsetArg
<= linebufLengthArg
);
3850 MOZ_ASSERT(linebufArg
[linebufLengthArg
] == '\0');
3852 linebuf_
= linebufArg
;
3853 linebufLength_
= linebufLengthArg
;
3854 tokenOffset_
= tokenOffsetArg
;
3857 void JSErrorReport::freeLinebuf() {
3858 if (ownsLinebuf_
&& linebuf_
) {
3859 js_free((void*)linebuf_
);
3860 ownsLinebuf_
= false;
3865 JSString
* JSErrorBase::newMessageString(JSContext
* cx
) {
3867 return cx
->runtime()->emptyString
;
3870 return JS_NewStringCopyUTF8Z(cx
, message_
);
3873 void JSErrorBase::freeMessage() {
3875 js_free((void*)message_
.get());
3876 ownsMessage_
= false;
3878 message_
= JS::ConstUTF8CharsZ();
3881 JSErrorNotes::JSErrorNotes() : notes_() {}
3883 JSErrorNotes::~JSErrorNotes() = default;
3885 static UniquePtr
<JSErrorNotes::Note
> CreateErrorNoteVA(
3886 FrontendContext
* fc
, const char* filename
, unsigned sourceId
,
3887 unsigned lineno
, unsigned column
, JSErrorCallback errorCallback
,
3888 void* userRef
, const unsigned errorNumber
, ErrorArgumentsType argumentsType
,
3890 auto note
= MakeUnique
<JSErrorNotes::Note
>();
3892 ReportOutOfMemory(fc
);
3896 note
->errorNumber
= errorNumber
;
3897 note
->filename
= JS::ConstUTF8CharsZ(filename
);
3898 note
->sourceId
= sourceId
;
3899 note
->lineno
= lineno
;
3900 note
->column
= column
;
3902 if (!ExpandErrorArgumentsVA(fc
, errorCallback
, userRef
, errorNumber
, nullptr,
3903 argumentsType
, note
.get(), ap
)) {
3910 bool JSErrorNotes::addNoteVA(FrontendContext
* fc
, const char* filename
,
3911 unsigned sourceId
, unsigned lineno
,
3912 unsigned column
, JSErrorCallback errorCallback
,
3913 void* userRef
, const unsigned errorNumber
,
3914 ErrorArgumentsType argumentsType
, va_list ap
) {
3916 CreateErrorNoteVA(fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
3917 userRef
, errorNumber
, argumentsType
, ap
);
3922 if (!notes_
.append(std::move(note
))) {
3923 ReportOutOfMemory(fc
);
3929 bool JSErrorNotes::addNoteASCII(JSContext
* cx
, const char* filename
,
3930 unsigned sourceId
, unsigned lineno
,
3931 unsigned column
, JSErrorCallback errorCallback
,
3932 void* userRef
, const unsigned errorNumber
,
3934 AutoReportFrontendContext
fc(cx
);
3936 va_start(ap
, errorNumber
);
3937 bool ok
= addNoteVA(&fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
3938 userRef
, errorNumber
, ArgumentsAreASCII
, ap
);
3943 bool JSErrorNotes::addNoteASCII(FrontendContext
* fc
, const char* filename
,
3944 unsigned sourceId
, unsigned lineno
,
3945 unsigned column
, JSErrorCallback errorCallback
,
3946 void* userRef
, const unsigned errorNumber
,
3949 va_start(ap
, errorNumber
);
3950 bool ok
= addNoteVA(fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
3951 userRef
, errorNumber
, ArgumentsAreASCII
, ap
);
3956 bool JSErrorNotes::addNoteLatin1(JSContext
* cx
, const char* filename
,
3957 unsigned sourceId
, unsigned lineno
,
3958 unsigned column
, JSErrorCallback errorCallback
,
3959 void* userRef
, const unsigned errorNumber
,
3961 AutoReportFrontendContext
fc(cx
);
3963 va_start(ap
, errorNumber
);
3964 bool ok
= addNoteVA(&fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
3965 userRef
, errorNumber
, ArgumentsAreLatin1
, ap
);
3970 bool JSErrorNotes::addNoteLatin1(FrontendContext
* fc
, const char* filename
,
3971 unsigned sourceId
, unsigned lineno
,
3972 unsigned column
, JSErrorCallback errorCallback
,
3973 void* userRef
, const unsigned errorNumber
,
3976 va_start(ap
, errorNumber
);
3977 bool ok
= addNoteVA(fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
3978 userRef
, errorNumber
, ArgumentsAreLatin1
, ap
);
3983 bool JSErrorNotes::addNoteUTF8(JSContext
* cx
, const char* filename
,
3984 unsigned sourceId
, unsigned lineno
,
3985 unsigned column
, JSErrorCallback errorCallback
,
3986 void* userRef
, const unsigned errorNumber
, ...) {
3987 AutoReportFrontendContext
fc(cx
);
3989 va_start(ap
, errorNumber
);
3990 bool ok
= addNoteVA(&fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
3991 userRef
, errorNumber
, ArgumentsAreUTF8
, ap
);
3996 bool JSErrorNotes::addNoteUTF8(FrontendContext
* fc
, const char* filename
,
3997 unsigned sourceId
, unsigned lineno
,
3998 unsigned column
, JSErrorCallback errorCallback
,
3999 void* userRef
, const unsigned errorNumber
, ...) {
4001 va_start(ap
, errorNumber
);
4002 bool ok
= addNoteVA(fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
4003 userRef
, errorNumber
, ArgumentsAreUTF8
, ap
);
4008 JS_PUBLIC_API
size_t JSErrorNotes::length() { return notes_
.length(); }
4010 UniquePtr
<JSErrorNotes
> JSErrorNotes::copy(JSContext
* cx
) {
4011 auto copiedNotes
= MakeUnique
<JSErrorNotes
>();
4013 ReportOutOfMemory(cx
);
4017 for (auto&& note
: *this) {
4018 UniquePtr
<JSErrorNotes::Note
> copied
= CopyErrorNote(cx
, note
.get());
4023 if (!copiedNotes
->notes_
.append(std::move(copied
))) {
4031 JS_PUBLIC_API
JSErrorNotes::iterator
JSErrorNotes::begin() {
4032 return iterator(notes_
.begin());
4035 JS_PUBLIC_API
JSErrorNotes::iterator
JSErrorNotes::end() {
4036 return iterator(notes_
.end());
4039 extern MOZ_NEVER_INLINE JS_PUBLIC_API
void JS_AbortIfWrongThread(
4041 if (!CurrentThreadCanAccessRuntime(cx
->runtime())) {
4044 if (TlsContext
.get() != cx
) {
4050 JS_PUBLIC_API
void JS_GetGCZealBits(JSContext
* cx
, uint32_t* zealBits
,
4051 uint32_t* frequency
,
4052 uint32_t* nextScheduled
) {
4053 cx
->runtime()->gc
.getZealBits(zealBits
, frequency
, nextScheduled
);
4056 JS_PUBLIC_API
void JS_SetGCZeal(JSContext
* cx
, uint8_t zeal
,
4057 uint32_t frequency
) {
4058 cx
->runtime()->gc
.setZeal(zeal
, frequency
);
4061 JS_PUBLIC_API
void JS_UnsetGCZeal(JSContext
* cx
, uint8_t zeal
) {
4062 cx
->runtime()->gc
.unsetZeal(zeal
);
4065 JS_PUBLIC_API
void JS_ScheduleGC(JSContext
* cx
, uint32_t count
) {
4066 cx
->runtime()->gc
.setNextScheduled(count
);
4070 JS_PUBLIC_API
void JS_SetParallelParsingEnabled(JSContext
* cx
, bool enabled
) {
4071 cx
->runtime()->setParallelParsingEnabled(enabled
);
4074 JS_PUBLIC_API
void JS_SetOffthreadIonCompilationEnabled(JSContext
* cx
,
4076 cx
->runtime()->setOffthreadIonCompilationEnabled(enabled
);
4079 JS_PUBLIC_API
void JS_SetGlobalJitCompilerOption(JSContext
* cx
,
4080 JSJitCompilerOption opt
,
4082 JSRuntime
* rt
= cx
->runtime();
4084 case JSJITCOMPILER_BASELINE_INTERPRETER_WARMUP_TRIGGER
:
4085 if (value
== uint32_t(-1)) {
4086 jit::DefaultJitOptions defaultValues
;
4087 value
= defaultValues
.baselineInterpreterWarmUpThreshold
;
4089 jit::JitOptions
.baselineInterpreterWarmUpThreshold
= value
;
4091 case JSJITCOMPILER_BASELINE_WARMUP_TRIGGER
:
4092 if (value
== uint32_t(-1)) {
4093 jit::DefaultJitOptions defaultValues
;
4094 value
= defaultValues
.baselineJitWarmUpThreshold
;
4096 jit::JitOptions
.baselineJitWarmUpThreshold
= value
;
4098 case JSJITCOMPILER_IC_FORCE_MEGAMORPHIC
:
4099 jit::JitOptions
.forceMegamorphicICs
= !!value
;
4101 case JSJITCOMPILER_ION_NORMAL_WARMUP_TRIGGER
:
4102 if (value
== uint32_t(-1)) {
4103 jit::JitOptions
.resetNormalIonWarmUpThreshold();
4106 jit::JitOptions
.setNormalIonWarmUpThreshold(value
);
4108 case JSJITCOMPILER_ION_GVN_ENABLE
:
4110 jit::JitOptions
.enableGvn(false);
4111 JitSpew(js::jit::JitSpew_IonScripts
, "Disable ion's GVN");
4113 jit::JitOptions
.enableGvn(true);
4114 JitSpew(js::jit::JitSpew_IonScripts
, "Enable ion's GVN");
4117 case JSJITCOMPILER_ION_FORCE_IC
:
4119 jit::JitOptions
.forceInlineCaches
= false;
4120 JitSpew(js::jit::JitSpew_IonScripts
,
4121 "Ion: Enable non-IC optimizations.");
4123 jit::JitOptions
.forceInlineCaches
= true;
4124 JitSpew(js::jit::JitSpew_IonScripts
,
4125 "Ion: Disable non-IC optimizations.");
4128 case JSJITCOMPILER_ION_CHECK_RANGE_ANALYSIS
:
4130 jit::JitOptions
.checkRangeAnalysis
= false;
4131 JitSpew(js::jit::JitSpew_IonScripts
,
4132 "Ion: Enable range analysis checks.");
4134 jit::JitOptions
.checkRangeAnalysis
= true;
4135 JitSpew(js::jit::JitSpew_IonScripts
,
4136 "Ion: Disable range analysis checks.");
4139 case JSJITCOMPILER_ION_ENABLE
:
4141 jit::JitOptions
.ion
= true;
4142 JitSpew(js::jit::JitSpew_IonScripts
, "Enable ion");
4143 } else if (value
== 0) {
4144 jit::JitOptions
.ion
= false;
4145 JitSpew(js::jit::JitSpew_IonScripts
, "Disable ion");
4148 case JSJITCOMPILER_JIT_TRUSTEDPRINCIPALS_ENABLE
:
4150 jit::JitOptions
.jitForTrustedPrincipals
= true;
4151 JitSpew(js::jit::JitSpew_IonScripts
,
4152 "Enable ion and baselinejit for trusted principals");
4153 } else if (value
== 0) {
4154 jit::JitOptions
.jitForTrustedPrincipals
= false;
4155 JitSpew(js::jit::JitSpew_IonScripts
,
4156 "Disable ion and baselinejit for trusted principals");
4159 case JSJITCOMPILER_ION_FREQUENT_BAILOUT_THRESHOLD
:
4160 if (value
== uint32_t(-1)) {
4161 jit::DefaultJitOptions defaultValues
;
4162 value
= defaultValues
.frequentBailoutThreshold
;
4164 jit::JitOptions
.frequentBailoutThreshold
= value
;
4166 case JSJITCOMPILER_BASE_REG_FOR_LOCALS
:
4168 jit::JitOptions
.baseRegForLocals
= jit::BaseRegForAddress::SP
;
4169 } else if (value
== 1) {
4170 jit::JitOptions
.baseRegForLocals
= jit::BaseRegForAddress::FP
;
4172 jit::DefaultJitOptions defaultValues
;
4173 jit::JitOptions
.baseRegForLocals
= defaultValues
.baseRegForLocals
;
4176 case JSJITCOMPILER_BASELINE_INTERPRETER_ENABLE
:
4178 jit::JitOptions
.baselineInterpreter
= true;
4179 } else if (value
== 0) {
4180 ReleaseAllJITCode(rt
->gcContext());
4181 jit::JitOptions
.baselineInterpreter
= false;
4184 case JSJITCOMPILER_BASELINE_ENABLE
:
4186 jit::JitOptions
.baselineJit
= true;
4187 ReleaseAllJITCode(rt
->gcContext());
4188 JitSpew(js::jit::JitSpew_BaselineScripts
, "Enable baseline");
4189 } else if (value
== 0) {
4190 jit::JitOptions
.baselineJit
= false;
4191 ReleaseAllJITCode(rt
->gcContext());
4192 JitSpew(js::jit::JitSpew_BaselineScripts
, "Disable baseline");
4195 case JSJITCOMPILER_NATIVE_REGEXP_ENABLE
:
4196 jit::JitOptions
.nativeRegExp
= !!value
;
4198 case JSJITCOMPILER_JIT_HINTS_ENABLE
:
4199 jit::JitOptions
.disableJitHints
= !value
;
4201 case JSJITCOMPILER_OFFTHREAD_COMPILATION_ENABLE
:
4203 rt
->setOffthreadIonCompilationEnabled(true);
4204 JitSpew(js::jit::JitSpew_IonScripts
, "Enable offthread compilation");
4205 } else if (value
== 0) {
4206 rt
->setOffthreadIonCompilationEnabled(false);
4207 JitSpew(js::jit::JitSpew_IonScripts
, "Disable offthread compilation");
4210 case JSJITCOMPILER_INLINING_BYTECODE_MAX_LENGTH
:
4211 if (value
== uint32_t(-1)) {
4212 jit::DefaultJitOptions defaultValues
;
4213 value
= defaultValues
.smallFunctionMaxBytecodeLength
;
4215 jit::JitOptions
.smallFunctionMaxBytecodeLength
= value
;
4217 case JSJITCOMPILER_JUMP_THRESHOLD
:
4218 if (value
== uint32_t(-1)) {
4219 jit::DefaultJitOptions defaultValues
;
4220 value
= defaultValues
.jumpThreshold
;
4222 jit::JitOptions
.jumpThreshold
= value
;
4224 case JSJITCOMPILER_SPECTRE_INDEX_MASKING
:
4225 jit::JitOptions
.spectreIndexMasking
= !!value
;
4227 case JSJITCOMPILER_SPECTRE_OBJECT_MITIGATIONS
:
4228 jit::JitOptions
.spectreObjectMitigations
= !!value
;
4230 case JSJITCOMPILER_SPECTRE_STRING_MITIGATIONS
:
4231 jit::JitOptions
.spectreStringMitigations
= !!value
;
4233 case JSJITCOMPILER_SPECTRE_VALUE_MASKING
:
4234 jit::JitOptions
.spectreValueMasking
= !!value
;
4236 case JSJITCOMPILER_SPECTRE_JIT_TO_CXX_CALLS
:
4237 jit::JitOptions
.spectreJitToCxxCalls
= !!value
;
4239 case JSJITCOMPILER_WRITE_PROTECT_CODE
:
4240 jit::JitOptions
.maybeSetWriteProtectCode(!!value
);
4242 case JSJITCOMPILER_WATCHTOWER_MEGAMORPHIC
:
4243 jit::JitOptions
.enableWatchtowerMegamorphic
= !!value
;
4245 case JSJITCOMPILER_WASM_FOLD_OFFSETS
:
4246 jit::JitOptions
.wasmFoldOffsets
= !!value
;
4248 case JSJITCOMPILER_WASM_DELAY_TIER2
:
4249 jit::JitOptions
.wasmDelayTier2
= !!value
;
4251 case JSJITCOMPILER_WASM_JIT_BASELINE
:
4252 JS::ContextOptionsRef(cx
).setWasmBaseline(!!value
);
4254 case JSJITCOMPILER_WASM_JIT_OPTIMIZING
:
4255 JS::ContextOptionsRef(cx
).setWasmIon(!!value
);
4258 case JSJITCOMPILER_FULL_DEBUG_CHECKS
:
4259 jit::JitOptions
.fullDebugChecks
= !!value
;
4267 JS_PUBLIC_API
bool JS_GetGlobalJitCompilerOption(JSContext
* cx
,
4268 JSJitCompilerOption opt
,
4269 uint32_t* valueOut
) {
4270 MOZ_ASSERT(valueOut
);
4271 #ifndef JS_CODEGEN_NONE
4272 JSRuntime
* rt
= cx
->runtime();
4274 case JSJITCOMPILER_BASELINE_INTERPRETER_WARMUP_TRIGGER
:
4275 *valueOut
= jit::JitOptions
.baselineInterpreterWarmUpThreshold
;
4277 case JSJITCOMPILER_BASELINE_WARMUP_TRIGGER
:
4278 *valueOut
= jit::JitOptions
.baselineJitWarmUpThreshold
;
4280 case JSJITCOMPILER_IC_FORCE_MEGAMORPHIC
:
4281 *valueOut
= jit::JitOptions
.forceMegamorphicICs
;
4283 case JSJITCOMPILER_ION_NORMAL_WARMUP_TRIGGER
:
4284 *valueOut
= jit::JitOptions
.normalIonWarmUpThreshold
;
4286 case JSJITCOMPILER_ION_FORCE_IC
:
4287 *valueOut
= jit::JitOptions
.forceInlineCaches
;
4289 case JSJITCOMPILER_ION_CHECK_RANGE_ANALYSIS
:
4290 *valueOut
= jit::JitOptions
.checkRangeAnalysis
;
4292 case JSJITCOMPILER_ION_ENABLE
:
4293 *valueOut
= jit::JitOptions
.ion
;
4295 case JSJITCOMPILER_ION_FREQUENT_BAILOUT_THRESHOLD
:
4296 *valueOut
= jit::JitOptions
.frequentBailoutThreshold
;
4298 case JSJITCOMPILER_BASE_REG_FOR_LOCALS
:
4299 *valueOut
= uint32_t(jit::JitOptions
.baseRegForLocals
);
4301 case JSJITCOMPILER_INLINING_BYTECODE_MAX_LENGTH
:
4302 *valueOut
= jit::JitOptions
.smallFunctionMaxBytecodeLength
;
4304 case JSJITCOMPILER_BASELINE_INTERPRETER_ENABLE
:
4305 *valueOut
= jit::JitOptions
.baselineInterpreter
;
4307 case JSJITCOMPILER_BASELINE_ENABLE
:
4308 *valueOut
= jit::JitOptions
.baselineJit
;
4310 case JSJITCOMPILER_NATIVE_REGEXP_ENABLE
:
4311 *valueOut
= jit::JitOptions
.nativeRegExp
;
4313 case JSJITCOMPILER_OFFTHREAD_COMPILATION_ENABLE
:
4314 *valueOut
= rt
->canUseOffthreadIonCompilation();
4316 case JSJITCOMPILER_SPECTRE_INDEX_MASKING
:
4317 *valueOut
= jit::JitOptions
.spectreIndexMasking
? 1 : 0;
4319 case JSJITCOMPILER_SPECTRE_OBJECT_MITIGATIONS
:
4320 *valueOut
= jit::JitOptions
.spectreObjectMitigations
? 1 : 0;
4322 case JSJITCOMPILER_SPECTRE_STRING_MITIGATIONS
:
4323 *valueOut
= jit::JitOptions
.spectreStringMitigations
? 1 : 0;
4325 case JSJITCOMPILER_SPECTRE_VALUE_MASKING
:
4326 *valueOut
= jit::JitOptions
.spectreValueMasking
? 1 : 0;
4328 case JSJITCOMPILER_SPECTRE_JIT_TO_CXX_CALLS
:
4329 *valueOut
= jit::JitOptions
.spectreJitToCxxCalls
? 1 : 0;
4331 case JSJITCOMPILER_WRITE_PROTECT_CODE
:
4332 *valueOut
= jit::JitOptions
.writeProtectCode
? 1 : 0;
4334 case JSJITCOMPILER_WATCHTOWER_MEGAMORPHIC
:
4335 *valueOut
= jit::JitOptions
.enableWatchtowerMegamorphic
? 1 : 0;
4337 case JSJITCOMPILER_WASM_FOLD_OFFSETS
:
4338 *valueOut
= jit::JitOptions
.wasmFoldOffsets
? 1 : 0;
4340 case JSJITCOMPILER_WASM_JIT_BASELINE
:
4341 *valueOut
= JS::ContextOptionsRef(cx
).wasmBaseline() ? 1 : 0;
4343 case JSJITCOMPILER_WASM_JIT_OPTIMIZING
:
4344 *valueOut
= JS::ContextOptionsRef(cx
).wasmIon() ? 1 : 0;
4347 case JSJITCOMPILER_FULL_DEBUG_CHECKS
:
4348 *valueOut
= jit::JitOptions
.fullDebugChecks
? 1 : 0;
4360 JS_PUBLIC_API
void JS::DisableSpectreMitigationsAfterInit() {
4361 // This is used to turn off Spectre mitigations in pre-allocated child
4362 // processes used for isolated web content. Assert there's a single runtime
4363 // and cancel off-thread compilations, to ensure we're not racing with any
4365 JSContext
* cx
= TlsContext
.get();
4366 MOZ_RELEASE_ASSERT(cx
);
4367 MOZ_RELEASE_ASSERT(JSRuntime::hasSingleLiveRuntime());
4368 MOZ_RELEASE_ASSERT(cx
->runtime()->wasmInstances
.lock()->empty());
4370 CancelOffThreadIonCompile(cx
->runtime());
4372 jit::JitOptions
.spectreIndexMasking
= false;
4373 jit::JitOptions
.spectreObjectMitigations
= false;
4374 jit::JitOptions
.spectreStringMitigations
= false;
4375 jit::JitOptions
.spectreValueMasking
= false;
4376 jit::JitOptions
.spectreJitToCxxCalls
= false;
4379 /************************************************************************/
4381 #if !defined(STATIC_EXPORTABLE_JS_API) && !defined(STATIC_JS_API) && \
4382 defined(XP_WIN) && (defined(MOZ_MEMORY) || !defined(JS_STANDALONE))
4384 # include "util/WindowsWrapper.h"
4387 * Initialization routine for the JS DLL.
4389 BOOL WINAPI
DllMain(HINSTANCE hDLL
, DWORD dwReason
, LPVOID lpReserved
) {
4395 JS_PUBLIC_API
bool JS_IndexToId(JSContext
* cx
, uint32_t index
,
4396 MutableHandleId id
) {
4397 return IndexToId(cx
, index
, id
);
4400 JS_PUBLIC_API
bool JS_CharsToId(JSContext
* cx
, JS::TwoByteChars chars
,
4401 MutableHandleId idp
) {
4402 Rooted
<JSAtom
*> atom(cx
,
4403 AtomizeChars(cx
, chars
.begin().get(), chars
.length()));
4408 MOZ_ASSERT(!atom
->isIndex(), "API misuse: |chars| must not encode an index");
4410 idp
.set(AtomToId(atom
));
4414 JS_PUBLIC_API
bool JS_IsIdentifier(JSContext
* cx
, HandleString str
,
4415 bool* isIdentifier
) {
4418 JSLinearString
* linearStr
= str
->ensureLinear(cx
);
4423 *isIdentifier
= js::frontend::IsIdentifier(linearStr
);
4427 JS_PUBLIC_API
bool JS_IsIdentifier(const char16_t
* chars
, size_t length
) {
4428 return js::frontend::IsIdentifier(chars
, length
);
4433 void AutoFilename::reset() {
4438 if (filename_
.is
<const char*>()) {
4439 filename_
.as
<const char*>() = nullptr;
4441 filename_
.as
<UniqueChars
>().reset();
4445 void AutoFilename::setScriptSource(js::ScriptSource
* p
) {
4451 setUnowned(p
->filename());
4455 void AutoFilename::setUnowned(const char* filename
) {
4457 filename_
.as
<const char*>() = filename
? filename
: "";
4460 void AutoFilename::setOwned(UniqueChars
&& filename
) {
4462 filename_
= AsVariant(std::move(filename
));
4465 const char* AutoFilename::get() const {
4466 if (filename_
.is
<const char*>()) {
4467 return filename_
.as
<const char*>();
4469 return filename_
.as
<UniqueChars
>().get();
4472 JS_PUBLIC_API
bool DescribeScriptedCaller(JSContext
* cx
, AutoFilename
* filename
,
4473 unsigned* lineno
, unsigned* column
) {
4484 if (!cx
->compartment()) {
4488 NonBuiltinFrameIter
i(cx
, cx
->realm()->principals());
4493 // If the caller is hidden, the embedding wants us to return false here so
4494 // that it can check its own stack (see HideScriptedCaller).
4495 if (i
.activation()->scriptedCallerIsHidden()) {
4501 // For Wasm, copy out the filename, there is no script source.
4502 UniqueChars copy
= DuplicateString(i
.filename() ? i
.filename() : "");
4504 filename
->setUnowned("out of memory");
4506 filename
->setOwned(std::move(copy
));
4509 // All other frames have a script source to read the filename from.
4510 filename
->setScriptSource(i
.scriptSource());
4515 *lineno
= i
.computeLine(column
);
4516 } else if (column
) {
4517 i
.computeLine(column
);
4523 // Fast path to get the activation and realm to use for GetScriptedCallerGlobal.
4524 // If this returns false, the fast path didn't work out and the caller has to
4525 // use the (much slower) NonBuiltinFrameIter path.
4527 // The optimization here is that we skip Ion-inlined frames and only look at
4528 // 'outer' frames. That's fine because Ion doesn't inline cross-realm calls.
4529 // However, GetScriptedCallerGlobal has to skip self-hosted frames and Ion
4530 // can inline self-hosted scripts, so we have to be careful:
4532 // * When we see a non-self-hosted outer script, it's possible we inlined
4533 // self-hosted scripts into it but that doesn't matter because these scripts
4534 // all have the same realm/global anyway.
4536 // * When we see a self-hosted outer script, it's possible we inlined
4537 // non-self-hosted scripts into it, so we have to give up because in this
4538 // case, whether or not to skip the self-hosted frame (to the possibly
4539 // different-realm caller) requires the slow path to handle inlining. Baseline
4540 // and the interpreter don't inline so this only affects Ion.
4541 static bool GetScriptedCallerActivationRealmFast(JSContext
* cx
,
4542 Activation
** activation
,
4544 ActivationIterator
activationIter(cx
);
4546 if (activationIter
.done()) {
4547 *activation
= nullptr;
4552 if (activationIter
->isJit()) {
4553 jit::JitActivation
* act
= activationIter
->asJit();
4554 JitFrameIter
iter(act
);
4556 iter
.skipNonScriptedJSFrames();
4561 if (!iter
.isSelfHostedIgnoringInlining()) {
4563 *realm
= iter
.realm();
4567 if (iter
.isJSJit() && iter
.asJSJit().isIonScripted()) {
4568 // Ion might have inlined non-self-hosted scripts in this
4569 // self-hosted script.
4575 } else if (activationIter
->isInterpreter()) {
4576 InterpreterActivation
* act
= activationIter
->asInterpreter();
4577 for (InterpreterFrameIterator
iter(act
); !iter
.done(); ++iter
) {
4578 if (!iter
.frame()->script()->selfHosted()) {
4580 *realm
= iter
.frame()->script()->realm();
4589 JS_PUBLIC_API JSObject
* GetScriptedCallerGlobal(JSContext
* cx
) {
4590 Activation
* activation
;
4592 if (GetScriptedCallerActivationRealmFast(cx
, &activation
, &realm
)) {
4597 NonBuiltinFrameIter
i(cx
);
4601 activation
= i
.activation();
4605 MOZ_ASSERT(realm
->compartment() == activation
->compartment());
4607 // If the caller is hidden, the embedding wants us to return null here so
4608 // that it can check its own stack (see HideScriptedCaller).
4609 if (activation
->scriptedCallerIsHidden()) {
4613 GlobalObject
* global
= realm
->maybeGlobal();
4615 // No one should be running code in a realm without any live objects, so
4616 // there should definitely be a live global.
4622 JS_PUBLIC_API
void HideScriptedCaller(JSContext
* cx
) {
4625 // If there's no accessible activation on the stack, we'll return null from
4626 // DescribeScriptedCaller anyway, so there's no need to annotate anything.
4627 Activation
* act
= cx
->activation();
4631 act
->hideScriptedCaller();
4634 JS_PUBLIC_API
void UnhideScriptedCaller(JSContext
* cx
) {
4635 Activation
* act
= cx
->activation();
4639 act
->unhideScriptedCaller();
4642 } /* namespace JS */
4645 JS_PUBLIC_API
void JS::detail::AssertArgumentsAreSane(JSContext
* cx
,
4646 HandleValue value
) {
4651 #endif /* JS_DEBUG */
4653 JS_PUBLIC_API
bool JS::FinishIncrementalEncoding(JSContext
* cx
,
4654 JS::HandleScript script
,
4655 TranscodeBuffer
& buffer
) {
4659 if (!script
->scriptSource()->xdrFinalizeEncoder(cx
, buffer
)) {
4665 JS_PUBLIC_API
bool JS::FinishIncrementalEncoding(JSContext
* cx
,
4666 JS::Handle
<JSObject
*> module
,
4667 TranscodeBuffer
& buffer
) {
4668 if (!module
->as
<ModuleObject
>()
4669 .scriptSourceObject()
4671 ->xdrFinalizeEncoder(cx
, buffer
)) {
4677 JS_PUBLIC_API
void JS::AbortIncrementalEncoding(JS::HandleScript script
) {
4681 script
->scriptSource()->xdrAbortEncoder();
4684 JS_PUBLIC_API
void JS::AbortIncrementalEncoding(JS::Handle
<JSObject
*> module
) {
4685 module
->as
<ModuleObject
>().scriptSourceObject()->source()->xdrAbortEncoder();
4688 bool JS::IsWasmModuleObject(HandleObject obj
) {
4689 return obj
->canUnwrapAs
<WasmModuleObject
>();
4692 JS_PUBLIC_API RefPtr
<JS::WasmModule
> JS::GetWasmModule(HandleObject obj
) {
4693 MOZ_ASSERT(JS::IsWasmModuleObject(obj
));
4694 WasmModuleObject
& mobj
= obj
->unwrapAs
<WasmModuleObject
>();
4695 return const_cast<wasm::Module
*>(&mobj
.module());
4698 bool JS::DisableWasmHugeMemory() { return wasm::DisableHugeMemory(); }
4700 JS_PUBLIC_API
void JS::SetProcessLargeAllocationFailureCallback(
4701 JS::LargeAllocationFailureCallback lafc
) {
4702 MOZ_ASSERT(!OnLargeAllocationFailure
);
4703 OnLargeAllocationFailure
= lafc
;
4706 JS_PUBLIC_API
void JS::SetOutOfMemoryCallback(JSContext
* cx
,
4707 OutOfMemoryCallback cb
,
4709 cx
->runtime()->oomCallback
= cb
;
4710 cx
->runtime()->oomCallbackData
= data
;
4713 JS_PUBLIC_API
void JS::SetShadowRealmInitializeGlobalCallback(
4714 JSContext
* cx
, JS::GlobalInitializeCallback callback
) {
4715 cx
->runtime()->shadowRealmInitializeGlobalCallback
= callback
;
4718 JS_PUBLIC_API
void JS::SetShadowRealmGlobalCreationCallback(
4719 JSContext
* cx
, JS::GlobalCreationCallback callback
) {
4720 cx
->runtime()->shadowRealmGlobalCreationCallback
= callback
;
4723 JS::FirstSubsumedFrame::FirstSubsumedFrame(
4724 JSContext
* cx
, bool ignoreSelfHostedFrames
/* = true */)
4725 : JS::FirstSubsumedFrame(cx
, cx
->realm()->principals(),
4726 ignoreSelfHostedFrames
) {}
4728 JS_PUBLIC_API
bool JS::CaptureCurrentStack(
4729 JSContext
* cx
, JS::MutableHandleObject stackp
,
4730 JS::StackCapture
&& capture
/* = JS::StackCapture(JS::AllFrames()) */) {
4733 MOZ_RELEASE_ASSERT(cx
->realm());
4735 Realm
* realm
= cx
->realm();
4736 Rooted
<SavedFrame
*> frame(cx
);
4737 if (!realm
->savedStacks().saveCurrentStack(cx
, &frame
, std::move(capture
))) {
4740 stackp
.set(frame
.get());
4744 JS_PUBLIC_API
bool JS::IsAsyncStackCaptureEnabledForRealm(JSContext
* cx
) {
4745 if (!cx
->options().asyncStack()) {
4749 if (!cx
->options().asyncStackCaptureDebuggeeOnly() ||
4750 cx
->realm()->isDebuggee()) {
4754 return cx
->realm()->isAsyncStackCapturingEnabled
;
4757 JS_PUBLIC_API
bool JS::CopyAsyncStack(JSContext
* cx
,
4758 JS::HandleObject asyncStack
,
4759 JS::HandleString asyncCause
,
4760 JS::MutableHandleObject stackp
,
4761 const Maybe
<size_t>& maxFrameCount
) {
4764 MOZ_RELEASE_ASSERT(cx
->realm());
4766 js::AssertObjectIsSavedFrameOrWrapper(cx
, asyncStack
);
4767 Realm
* realm
= cx
->realm();
4768 Rooted
<SavedFrame
*> frame(cx
);
4769 if (!realm
->savedStacks().copyAsyncStack(cx
, asyncStack
, asyncCause
, &frame
,
4773 stackp
.set(frame
.get());
4777 JS_PUBLIC_API Zone
* JS::GetObjectZone(JSObject
* obj
) { return obj
->zone(); }
4779 JS_PUBLIC_API Zone
* JS::GetNurseryCellZone(gc::Cell
* cell
) {
4780 return cell
->nurseryZone();
4783 JS_PUBLIC_API
JS::TraceKind
JS::GCThingTraceKind(void* thing
) {
4785 return static_cast<js::gc::Cell
*>(thing
)->getTraceKind();
4788 JS_PUBLIC_API
void js::SetStackFormat(JSContext
* cx
, js::StackFormat format
) {
4789 cx
->runtime()->setStackFormat(format
);
4792 JS_PUBLIC_API
js::StackFormat
js::GetStackFormat(JSContext
* cx
) {
4793 return cx
->runtime()->stackFormat();
4796 JS_PUBLIC_API
JS::JSTimers
JS::GetJSTimers(JSContext
* cx
) {
4797 return cx
->realm()->timers
;
4802 JS_PUBLIC_API
void NoteIntentionalCrash() {
4805 reinterpret_cast<bool*>(dlsym(RTLD_DEFAULT
, "gBreakpadInjectorEnabled"));
4813 bool gSupportDifferentialTesting
= false;
4820 JS_PUBLIC_API
void JS::SetSupportDifferentialTesting(bool value
) {
4821 js::gSupportDifferentialTesting
= value
;