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/FrontendContext.h" // AutoReportFrontendContext
39 #include "gc/GCContext.h"
40 #include "gc/Marking.h"
41 #include "gc/PublicIterators.h"
42 #include "jit/JitSpewer.h"
43 #include "js/CallAndConstruct.h" // JS::IsCallable
44 #include "js/CharacterEncoding.h"
45 #include "js/ColumnNumber.h" // JS::TaggedColumnNumberOneOrigin, JS::ColumnNumberOneOrigin
46 #include "js/CompileOptions.h"
47 #include "js/ContextOptions.h" // JS::ContextOptions{,Ref}
48 #include "js/Conversions.h"
49 #include "js/Date.h" // JS::GetReduceMicrosecondTimePrecisionCallback
50 #include "js/ErrorInterceptor.h"
51 #include "js/ErrorReport.h" // JSErrorBase
52 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
53 #include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit
54 #include "js/GlobalObject.h"
55 #include "js/Initialization.h"
56 #include "js/Interrupt.h"
58 #include "js/LocaleSensitive.h"
59 #include "js/MemoryCallbacks.h"
60 #include "js/MemoryFunctions.h"
61 #include "js/PropertySpec.h"
63 #include "js/ScriptPrivate.h"
64 #include "js/StableStringChars.h"
65 #include "js/Stack.h" // JS::NativeStackSize, JS::NativeStackLimitMax, JS::GetNativeStackLimit
66 #include "js/StreamConsumer.h"
67 #include "js/String.h" // JS::MaxStringLength
68 #include "js/Symbol.h"
69 #include "js/TelemetryTimers.h"
70 #include "js/Utility.h"
71 #include "js/WaitCallbacks.h"
72 #include "js/WasmModule.h"
73 #include "js/Wrapper.h"
74 #include "js/WrapperCallbacks.h"
75 #include "proxy/DOMProxy.h"
76 #include "util/Identifier.h" // IsIdentifier
77 #include "util/StringBuffer.h"
78 #include "util/Text.h"
79 #include "vm/BoundFunctionObject.h"
80 #include "vm/EnvironmentObject.h"
81 #include "vm/ErrorObject.h"
82 #include "vm/ErrorReporting.h"
83 #include "vm/FunctionPrefixKind.h"
84 #include "vm/Interpreter.h"
85 #include "vm/JSAtomState.h"
86 #include "vm/JSAtomUtils.h" // Atomize, AtomizeWithoutActiveZone, AtomizeChars, PinAtom, ClassName
87 #include "vm/JSContext.h"
88 #include "vm/JSFunction.h"
89 #include "vm/JSObject.h"
90 #include "vm/JSScript.h"
91 #include "vm/PlainObject.h" // js::PlainObject
92 #include "vm/PromiseObject.h" // js::PromiseObject
93 #include "vm/Runtime.h"
94 #include "vm/SavedStacks.h"
95 #include "vm/StringType.h"
97 #include "vm/ToSource.h"
98 #include "vm/WrapperObject.h"
99 #include "wasm/WasmModule.h"
100 #include "wasm/WasmProcess.h"
102 #include "builtin/Promise-inl.h"
103 #include "debugger/DebugAPI-inl.h"
104 #include "vm/Compartment-inl.h"
105 #include "vm/Interpreter-inl.h"
106 #include "vm/IsGivenTypeObject-inl.h" // js::IsGivenTypeObject
107 #include "vm/JSAtomUtils-inl.h" // AtomToId, PrimitiveValueToId, IndexToId, ClassName
108 #include "vm/JSFunction-inl.h"
109 #include "vm/JSScript-inl.h"
110 #include "vm/NativeObject-inl.h"
111 #include "vm/SavedStacks-inl.h"
112 #include "vm/StringType-inl.h"
116 using mozilla::Maybe
;
117 using mozilla::PodCopy
;
120 using JS::AutoStableStringChars
;
121 using JS::CompileOptions
;
122 using JS::ReadOnlyCompileOptions
;
123 using JS::SourceText
;
125 // See preprocessor definition of JS_BITS_PER_WORD in jstypes.h; make sure
126 // JS_64BIT (used internally) agrees with it
128 static_assert(JS_BITS_PER_WORD
== 64, "values must be in sync");
130 static_assert(JS_BITS_PER_WORD
== 32, "values must be in sync");
133 JS_PUBLIC_API
void JS::CallArgs::reportMoreArgsNeeded(JSContext
* cx
,
137 char requiredArgsStr
[40];
138 SprintfLiteral(requiredArgsStr
, "%u", required
);
139 char actualArgsStr
[40];
140 SprintfLiteral(actualArgsStr
, "%u", actual
);
141 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr,
142 JSMSG_MORE_ARGS_NEEDED
, fnname
, requiredArgsStr
,
143 required
== 1 ? "" : "s", actualArgsStr
);
146 static bool ErrorTakesArguments(unsigned msg
) {
147 MOZ_ASSERT(msg
< JSErr_Limit
);
148 unsigned argCount
= js_ErrorFormatString
[msg
].argCount
;
149 MOZ_ASSERT(argCount
<= 2);
150 return argCount
== 1 || argCount
== 2;
153 static bool ErrorTakesObjectArgument(unsigned msg
) {
154 MOZ_ASSERT(msg
< JSErr_Limit
);
155 unsigned argCount
= js_ErrorFormatString
[msg
].argCount
;
156 MOZ_ASSERT(argCount
<= 2);
157 return argCount
== 2;
160 bool JS::ObjectOpResult::reportError(JSContext
* cx
, HandleObject obj
,
162 static_assert(unsigned(OkCode
) == unsigned(JSMSG_NOT_AN_ERROR
),
163 "unsigned value of OkCode must not be an error code");
164 MOZ_ASSERT(code_
!= Uninitialized
);
168 if (code_
== JSMSG_OBJECT_NOT_EXTENSIBLE
) {
169 RootedValue
val(cx
, ObjectValue(*obj
));
170 return ReportValueError(cx
, code_
, JSDVG_IGNORE_STACK
, val
, nullptr);
173 if (ErrorTakesArguments(code_
)) {
174 UniqueChars propName
=
175 IdToPrintableUTF8(cx
, id
, IdToPrintableBehavior::IdIsPropertyKey
);
180 if (code_
== JSMSG_SET_NON_OBJECT_RECEIVER
) {
181 // We know that the original receiver was a primitive, so unbox it.
182 RootedValue
val(cx
, ObjectValue(*obj
));
183 if (!obj
->is
<ProxyObject
>()) {
184 if (!Unbox(cx
, obj
, &val
)) {
188 return ReportValueError(cx
, code_
, JSDVG_IGNORE_STACK
, val
, nullptr,
192 if (ErrorTakesObjectArgument(code_
)) {
193 JSObject
* unwrapped
= js::CheckedUnwrapStatic(obj
);
194 const char* name
= unwrapped
? unwrapped
->getClass()->name
: "Object";
195 JS_ReportErrorNumberUTF8(cx
, GetErrorMessage
, nullptr, code_
, name
,
200 JS_ReportErrorNumberUTF8(cx
, GetErrorMessage
, nullptr, code_
,
204 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr, code_
);
208 bool JS::ObjectOpResult::reportError(JSContext
* cx
, HandleObject obj
) {
209 MOZ_ASSERT(code_
!= Uninitialized
);
211 MOZ_ASSERT(!ErrorTakesArguments(code_
));
214 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr, code_
);
218 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantRedefineProp() {
219 return fail(JSMSG_CANT_REDEFINE_PROP
);
222 JS_PUBLIC_API
bool JS::ObjectOpResult::failReadOnly() {
223 return fail(JSMSG_READ_ONLY
);
226 JS_PUBLIC_API
bool JS::ObjectOpResult::failGetterOnly() {
227 return fail(JSMSG_GETTER_ONLY
);
230 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDelete() {
231 return fail(JSMSG_CANT_DELETE
);
234 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantSetInterposed() {
235 return fail(JSMSG_CANT_SET_INTERPOSED
);
238 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDefineWindowElement() {
239 return fail(JSMSG_CANT_DEFINE_WINDOW_ELEMENT
);
242 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDeleteWindowElement() {
243 return fail(JSMSG_CANT_DELETE_WINDOW_ELEMENT
);
246 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDefineWindowNamedProperty() {
247 return fail(JSMSG_CANT_DEFINE_WINDOW_NAMED_PROPERTY
);
250 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDeleteWindowNamedProperty() {
251 return fail(JSMSG_CANT_DELETE_WINDOW_NAMED_PROPERTY
);
254 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDefineWindowNonConfigurable() {
255 return fail(JSMSG_CANT_DEFINE_WINDOW_NC
);
258 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantPreventExtensions() {
259 return fail(JSMSG_CANT_PREVENT_EXTENSIONS
);
262 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantSetProto() {
263 return fail(JSMSG_CANT_SET_PROTO
);
266 JS_PUBLIC_API
bool JS::ObjectOpResult::failNoNamedSetter() {
267 return fail(JSMSG_NO_NAMED_SETTER
);
270 JS_PUBLIC_API
bool JS::ObjectOpResult::failNoIndexedSetter() {
271 return fail(JSMSG_NO_INDEXED_SETTER
);
274 JS_PUBLIC_API
bool JS::ObjectOpResult::failNotDataDescriptor() {
275 return fail(JSMSG_NOT_DATA_DESCRIPTOR
);
278 JS_PUBLIC_API
bool JS::ObjectOpResult::failInvalidDescriptor() {
279 return fail(JSMSG_INVALID_DESCRIPTOR
);
282 JS_PUBLIC_API
bool JS::ObjectOpResult::failBadArrayLength() {
283 return fail(JSMSG_BAD_ARRAY_LENGTH
);
286 JS_PUBLIC_API
bool JS::ObjectOpResult::failBadIndex() {
287 return fail(JSMSG_BAD_INDEX
);
290 JS_PUBLIC_API
int64_t JS_Now() { return PRMJ_Now(); }
292 JS_PUBLIC_API Value
JS_GetEmptyStringValue(JSContext
* cx
) {
293 return StringValue(cx
->runtime()->emptyString
);
296 JS_PUBLIC_API JSString
* JS_GetEmptyString(JSContext
* cx
) {
297 MOZ_ASSERT(cx
->emptyString());
298 return cx
->emptyString();
303 void AssertHeapIsIdle() { MOZ_ASSERT(!JS::RuntimeHeapIsBusy()); }
307 static void AssertHeapIsIdleOrIterating() {
308 MOZ_ASSERT(!JS::RuntimeHeapIsCollecting());
311 JS_PUBLIC_API
bool JS_ValueToObject(JSContext
* cx
, HandleValue value
,
312 MutableHandleObject objp
) {
316 if (value
.isNullOrUndefined()) {
320 JSObject
* obj
= ToObject(cx
, value
);
328 JS_PUBLIC_API JSFunction
* JS_ValueToFunction(JSContext
* cx
, HandleValue value
) {
332 return ReportIfNotFunction(cx
, value
);
335 JS_PUBLIC_API JSFunction
* JS_ValueToConstructor(JSContext
* cx
,
340 return ReportIfNotFunction(cx
, value
);
343 JS_PUBLIC_API JSString
* JS_ValueToSource(JSContext
* cx
, HandleValue value
) {
347 return ValueToSource(cx
, value
);
350 JS_PUBLIC_API
bool JS_DoubleIsInt32(double d
, int32_t* ip
) {
351 return mozilla::NumberIsInt32(d
, ip
);
354 JS_PUBLIC_API JSType
JS_TypeOfValue(JSContext
* cx
, HandleValue value
) {
358 return TypeOfValue(value
);
361 JS_PUBLIC_API
bool JS_IsBuiltinEvalFunction(JSFunction
* fun
) {
362 return IsAnyBuiltinEval(fun
);
365 JS_PUBLIC_API
bool JS_IsBuiltinFunctionConstructor(JSFunction
* fun
) {
366 return fun
->isBuiltinFunctionConstructor();
369 JS_PUBLIC_API
bool JS_ObjectIsBoundFunction(JSObject
* obj
) {
370 return obj
->is
<BoundFunctionObject
>();
373 JS_PUBLIC_API JSObject
* JS_GetBoundFunctionTarget(JSObject
* obj
) {
374 return obj
->is
<BoundFunctionObject
>()
375 ? obj
->as
<BoundFunctionObject
>().getTarget()
379 /************************************************************************/
381 // Prevent functions from being discarded by linker, so that they are callable
383 static void PreventDiscardingFunctions() {
384 if (reinterpret_cast<uintptr_t>(&PreventDiscardingFunctions
) == 1) {
386 memset((void*)&js::debug::GetMarkInfo
, 0, 1);
387 memset((void*)&js::debug::GetMarkWordAddress
, 0, 1);
388 memset((void*)&js::debug::GetMarkMask
, 0, 1);
392 JS_PUBLIC_API JSContext
* JS_NewContext(uint32_t maxbytes
,
393 JSRuntime
* parentRuntime
) {
394 MOZ_ASSERT(JS::detail::libraryInitState
== JS::detail::InitState::Running
,
395 "must call JS_Init prior to creating any JSContexts");
397 // Prevent linker from discarding unused debug functions.
398 PreventDiscardingFunctions();
400 // Make sure that all parent runtimes are the topmost parent.
401 while (parentRuntime
&& parentRuntime
->parentRuntime
) {
402 parentRuntime
= parentRuntime
->parentRuntime
;
405 return NewContext(maxbytes
, parentRuntime
);
408 JS_PUBLIC_API
void JS_DestroyContext(JSContext
* cx
) { DestroyContext(cx
); }
410 JS_PUBLIC_API
void* JS_GetContextPrivate(JSContext
* cx
) { return cx
->data
; }
412 JS_PUBLIC_API
void JS_SetContextPrivate(JSContext
* cx
, void* data
) {
416 JS_PUBLIC_API
void JS_SetFutexCanWait(JSContext
* cx
) {
417 cx
->fx
.setCanWait(true);
420 JS_PUBLIC_API JSRuntime
* JS_GetParentRuntime(JSContext
* cx
) {
421 return cx
->runtime()->parentRuntime
? cx
->runtime()->parentRuntime
425 JS_PUBLIC_API JSRuntime
* JS_GetRuntime(JSContext
* cx
) { return cx
->runtime(); }
427 JS_PUBLIC_API
JS::ContextOptions
& JS::ContextOptionsRef(JSContext
* cx
) {
428 return cx
->options();
431 JS::ContextOptions
& JS::ContextOptions::setFuzzing(bool flag
) {
438 JS_PUBLIC_API
const char* JS_GetImplementationVersion(void) {
439 return "JavaScript-C" MOZILLA_VERSION
;
442 JS_PUBLIC_API
void JS_SetDestroyZoneCallback(JSContext
* cx
,
443 JSDestroyZoneCallback callback
) {
444 cx
->runtime()->destroyZoneCallback
= callback
;
447 JS_PUBLIC_API
void JS_SetDestroyCompartmentCallback(
448 JSContext
* cx
, JSDestroyCompartmentCallback callback
) {
449 cx
->runtime()->destroyCompartmentCallback
= callback
;
452 JS_PUBLIC_API
void JS_SetSizeOfIncludingThisCompartmentCallback(
453 JSContext
* cx
, JSSizeOfIncludingThisCompartmentCallback callback
) {
454 cx
->runtime()->sizeOfIncludingThisCompartmentCallback
= callback
;
457 JS_PUBLIC_API
void JS_SetErrorInterceptorCallback(
458 JSRuntime
* rt
, JSErrorInterceptor
* callback
) {
459 #if defined(NIGHTLY_BUILD)
460 rt
->errorInterception
.interceptor
= callback
;
461 #endif // defined(NIGHTLY_BUILD)
464 JS_PUBLIC_API JSErrorInterceptor
* JS_GetErrorInterceptorCallback(
466 #if defined(NIGHTLY_BUILD)
467 return rt
->errorInterception
.interceptor
;
468 #else // !NIGHTLY_BUILD
470 #endif // defined(NIGHTLY_BUILD)
473 JS_PUBLIC_API Maybe
<JSExnType
> JS_GetErrorType(const JS::Value
& val
) {
474 // All errors are objects.
475 if (!val
.isObject()) {
476 return mozilla::Nothing();
479 const JSObject
& obj
= val
.toObject();
481 // All errors are `ErrorObject`.
482 if (!obj
.is
<js::ErrorObject
>()) {
483 // Not one of the primitive errors.
484 return mozilla::Nothing();
487 const js::ErrorObject
& err
= obj
.as
<js::ErrorObject
>();
488 return mozilla::Some(err
.type());
491 JS_PUBLIC_API
void JS_SetWrapObjectCallbacks(
492 JSContext
* cx
, const JSWrapObjectCallbacks
* callbacks
) {
493 cx
->runtime()->wrapObjectCallbacks
= callbacks
;
496 JS_PUBLIC_API Realm
* JS::EnterRealm(JSContext
* cx
, JSObject
* target
) {
500 MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(target
));
502 Realm
* oldRealm
= cx
->realm();
503 cx
->enterRealmOf(target
);
507 JS_PUBLIC_API
void JS::LeaveRealm(JSContext
* cx
, JS::Realm
* oldRealm
) {
510 cx
->leaveRealm(oldRealm
);
513 JSAutoRealm::JSAutoRealm(JSContext
* cx
, JSObject
* target
)
514 : cx_(cx
), oldRealm_(cx
->realm()) {
515 MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(target
));
516 AssertHeapIsIdleOrIterating();
517 cx_
->enterRealmOf(target
);
520 JSAutoRealm::JSAutoRealm(JSContext
* cx
, JSScript
* target
)
521 : cx_(cx
), oldRealm_(cx
->realm()) {
522 AssertHeapIsIdleOrIterating();
523 cx_
->enterRealmOf(target
);
526 JSAutoRealm::~JSAutoRealm() { cx_
->leaveRealm(oldRealm_
); }
528 JSAutoNullableRealm::JSAutoNullableRealm(JSContext
* cx
, JSObject
* targetOrNull
)
529 : cx_(cx
), oldRealm_(cx
->realm()) {
530 AssertHeapIsIdleOrIterating();
532 MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(targetOrNull
));
533 cx_
->enterRealmOf(targetOrNull
);
535 cx_
->enterNullRealm();
539 JSAutoNullableRealm::~JSAutoNullableRealm() { cx_
->leaveRealm(oldRealm_
); }
541 JS_PUBLIC_API
void JS_SetCompartmentPrivate(JS::Compartment
* compartment
,
543 compartment
->data
= data
;
546 JS_PUBLIC_API
void* JS_GetCompartmentPrivate(JS::Compartment
* compartment
) {
547 return compartment
->data
;
550 JS_PUBLIC_API
void JS_MarkCrossZoneId(JSContext
* cx
, jsid id
) {
554 JS_PUBLIC_API
void JS_MarkCrossZoneIdValue(JSContext
* cx
, const Value
& value
) {
555 cx
->markAtomValue(value
);
558 JS_PUBLIC_API
void JS_SetZoneUserData(JS::Zone
* zone
, void* data
) {
562 JS_PUBLIC_API
void* JS_GetZoneUserData(JS::Zone
* zone
) { return zone
->data
; }
564 JS_PUBLIC_API
bool JS_WrapObject(JSContext
* cx
, MutableHandleObject objp
) {
568 JS::ExposeObjectToActiveJS(objp
);
570 return cx
->compartment()->wrap(cx
, objp
);
573 JS_PUBLIC_API
bool JS_WrapValue(JSContext
* cx
, MutableHandleValue vp
) {
576 JS::ExposeValueToActiveJS(vp
);
577 return cx
->compartment()->wrap(cx
, vp
);
580 static void ReleaseAssertObjectHasNoWrappers(JSContext
* cx
,
581 HandleObject target
) {
582 for (CompartmentsIter
c(cx
->runtime()); !c
.done(); c
.next()) {
583 if (c
->lookupWrapper(target
)) {
584 MOZ_CRASH("wrapper found for target object");
590 * [SMDOC] Brain transplants.
592 * Not for beginners or the squeamish.
594 * Sometimes a web spec requires us to transplant an object from one
595 * compartment to another, like when a DOM node is inserted into a document in
596 * another window and thus gets "adopted". We cannot literally change the
597 * `.compartment()` of a `JSObject`; that would break the compartment
598 * invariants. However, as usual, we have a workaround using wrappers.
600 * Of all the wrapper-based workarounds we do, it's safe to say this is the
601 * most spectacular and questionable.
603 * `JS_TransplantObject(cx, origobj, target)` changes `origobj` into a
604 * simulacrum of `target`, using highly esoteric means. To JS code, the effect
605 * is as if `origobj` magically "became" `target`, but most often what actually
606 * happens is that `origobj` gets turned into a cross-compartment wrapper for
607 * `target`. The old behavior and contents of `origobj` are overwritten or
610 * Thus, to "transplant" an object from one compartment to another:
612 * 1. Let `origobj` be the object that you want to move. First, create a
613 * clone of it, `target`, in the destination compartment.
615 * In our DOM adoption example, `target` will be a Node of the same type as
616 * `origobj`, same content, but in the adopting document. We're not done
617 * yet: the spec for DOM adoption requires that `origobj.ownerDocument`
618 * actually change. All we've done so far is make a copy.
620 * 2. Call `JS_TransplantObject(cx, origobj, target)`. This typically turns
621 * `origobj` into a wrapper for `target`, so that any JS code that has a
622 * reference to `origobj` will observe it to have the behavior of `target`
623 * going forward. In addition, all existing wrappers for `origobj` are
624 * changed into wrappers for `target`, extending the illusion to those
625 * compartments as well.
627 * During navigation, we use the above technique to transplant the WindowProxy
628 * into the new Window's compartment.
632 * - `origobj` and `target` must be two distinct objects of the same
633 * `JSClass`. Some classes may not support transplantation; WindowProxy
634 * objects and DOM nodes are OK.
636 * - `target` should be created specifically to be passed to this function.
637 * There must be no existing cross-compartment wrappers for it; ideally
638 * there shouldn't be any pointers to it at all, except the one passed in.
640 * - `target` shouldn't be used afterwards. Instead, `JS_TransplantObject`
641 * returns a pointer to the transplanted object, which might be `target`
642 * but might be some other object in the same compartment. Use that.
644 * The reason for this last rule is that JS_TransplantObject does very strange
645 * things in some cases, like swapping `target`'s brain with that of another
646 * object. Leaving `target` behaving like its former self is not a goal.
648 * We don't have a good way to recover from failure in this function, so
649 * we intentionally crash instead.
652 static void CheckTransplantObject(JSObject
* obj
) {
654 MOZ_ASSERT(!obj
->is
<CrossCompartmentWrapperObject
>());
655 JS::AssertCellIsNotGray(obj
);
659 JS_PUBLIC_API JSObject
* JS_TransplantObject(JSContext
* cx
, HandleObject origobj
,
660 HandleObject target
) {
662 MOZ_ASSERT(origobj
!= target
);
663 CheckTransplantObject(origobj
);
664 CheckTransplantObject(target
);
665 ReleaseAssertObjectHasNoWrappers(cx
, target
);
667 RootedObject
newIdentity(cx
);
669 // Don't allow a compacting GC to observe any intermediate state.
670 AutoDisableCompactingGC
nocgc(cx
);
672 AutoDisableProxyCheck adpc
;
674 AutoEnterOOMUnsafeRegion oomUnsafe
;
676 JS::Compartment
* destination
= target
->compartment();
678 if (origobj
->compartment() == destination
) {
679 // If the original object is in the same compartment as the
680 // destination, then we know that we won't find a wrapper in the
681 // destination's cross compartment map and that the same
682 // object will continue to work.
683 AutoRealm
ar(cx
, origobj
);
684 JSObject::swap(cx
, origobj
, target
, oomUnsafe
);
685 newIdentity
= origobj
;
686 } else if (ObjectWrapperMap::Ptr p
= destination
->lookupWrapper(origobj
)) {
687 // There might already be a wrapper for the original object in
688 // the new compartment. If there is, we use its identity and swap
689 // in the contents of |target|.
690 newIdentity
= p
->value().get();
692 // When we remove origv from the wrapper map, its wrapper, newIdentity,
693 // must immediately cease to be a cross-compartment wrapper. Nuke it.
694 destination
->removeWrapper(p
);
695 NukeCrossCompartmentWrapper(cx
, newIdentity
);
697 AutoRealm
ar(cx
, newIdentity
);
698 JSObject::swap(cx
, newIdentity
, target
, oomUnsafe
);
700 // Otherwise, we use |target| for the new identity object.
701 newIdentity
= target
;
704 // Now, iterate through other scopes looking for references to the old
705 // object, and update the relevant cross-compartment wrappers. We do this
706 // even if origobj is in the same compartment as target and thus
707 // `newIdentity == origobj`, because this process also clears out any
708 // cached wrapper state.
709 if (!RemapAllWrappersForObject(cx
, origobj
, newIdentity
)) {
710 oomUnsafe
.crash("JS_TransplantObject");
713 // Lastly, update the original object to point to the new one.
714 if (origobj
->compartment() != destination
) {
715 RootedObject
newIdentityWrapper(cx
, newIdentity
);
716 AutoRealm
ar(cx
, origobj
);
717 if (!JS_WrapObject(cx
, &newIdentityWrapper
)) {
718 MOZ_RELEASE_ASSERT(cx
->isThrowingOutOfMemory() ||
719 cx
->isThrowingOverRecursed());
720 oomUnsafe
.crash("JS_TransplantObject");
722 MOZ_ASSERT(Wrapper::wrappedObject(newIdentityWrapper
) == newIdentity
);
723 JSObject::swap(cx
, origobj
, newIdentityWrapper
, oomUnsafe
);
724 if (origobj
->compartment()->lookupWrapper(newIdentity
)) {
725 MOZ_ASSERT(origobj
->is
<CrossCompartmentWrapperObject
>());
726 if (!origobj
->compartment()->putWrapper(cx
, newIdentity
, origobj
)) {
727 oomUnsafe
.crash("JS_TransplantObject");
732 // The new identity object might be one of several things. Return it to avoid
734 JS::AssertCellIsNotGray(newIdentity
);
738 JS_PUBLIC_API
void js::RemapRemoteWindowProxies(
739 JSContext
* cx
, CompartmentTransplantCallback
* callback
,
740 MutableHandleObject target
) {
742 CheckTransplantObject(target
);
743 ReleaseAssertObjectHasNoWrappers(cx
, target
);
745 // |target| can't be a remote proxy, because we expect it to get a CCW when
746 // wrapped across compartments.
747 MOZ_ASSERT(!js::IsDOMRemoteProxyObject(target
));
749 // Don't allow a compacting GC to observe any intermediate state.
750 AutoDisableCompactingGC
nocgc(cx
);
752 AutoDisableProxyCheck adpc
;
754 AutoEnterOOMUnsafeRegion oomUnsafe
;
756 AutoCheckRecursionLimit
recursion(cx
);
757 if (!recursion
.checkSystem(cx
)) {
758 oomUnsafe
.crash("js::RemapRemoteWindowProxies");
761 RootedObject
targetCompartmentProxy(cx
);
762 JS::RootedVector
<JSObject
*> otherProxies(cx
);
764 // Use the callback to find remote proxies in all compartments that match
765 // whatever criteria callback uses.
766 for (CompartmentsIter
c(cx
->runtime()); !c
.done(); c
.next()) {
767 RootedObject
remoteProxy(cx
, callback
->getObjectToTransplant(c
));
771 // The object the callback returns should be a DOM remote proxy object in
772 // the compartment c. We rely on it being a DOM remote proxy because that
773 // means that it won't have any cross-compartment wrappers.
774 MOZ_ASSERT(js::IsDOMRemoteProxyObject(remoteProxy
));
775 MOZ_ASSERT(remoteProxy
->compartment() == c
);
776 CheckTransplantObject(remoteProxy
);
778 // Immediately turn the DOM remote proxy object into a dead proxy object
779 // so we don't have to worry about anything weird going on with it.
780 js::NukeNonCCWProxy(cx
, remoteProxy
);
782 if (remoteProxy
->compartment() == target
->compartment()) {
783 targetCompartmentProxy
= remoteProxy
;
784 } else if (!otherProxies
.append(remoteProxy
)) {
785 oomUnsafe
.crash("js::RemapRemoteWindowProxies");
789 // If there was a remote proxy in |target|'s compartment, we need to use it
790 // instead of |target|, in case it had any references, so swap it. Do this
791 // before any other compartment so that the target object will be set up
792 // correctly before we start wrapping it into other compartments.
793 if (targetCompartmentProxy
) {
794 AutoRealm
ar(cx
, targetCompartmentProxy
);
795 JSObject::swap(cx
, targetCompartmentProxy
, target
, oomUnsafe
);
796 target
.set(targetCompartmentProxy
);
799 for (JSObject
*& obj
: otherProxies
) {
800 RootedObject
deadWrapper(cx
, obj
);
801 js::RemapDeadWrapper(cx
, deadWrapper
, target
);
806 * Recompute all cross-compartment wrappers for an object, resetting state.
807 * Gecko uses this to clear Xray wrappers when doing a navigation that reuses
808 * the inner window and global object.
810 JS_PUBLIC_API
bool JS_RefreshCrossCompartmentWrappers(JSContext
* cx
,
812 return RemapAllWrappersForObject(cx
, obj
, obj
);
815 typedef struct JSStdName
{
816 size_t atomOffset
; /* offset of atom pointer in JSAtomState */
818 bool isDummy() const { return key
== JSProto_Null
; }
819 bool isSentinel() const { return key
== JSProto_LIMIT
; }
822 static const JSStdName
* LookupStdName(const JSAtomState
& names
, JSAtom
* name
,
823 const JSStdName
* table
) {
824 for (unsigned i
= 0; !table
[i
].isSentinel(); i
++) {
825 if (table
[i
].isDummy()) {
828 JSAtom
* atom
= AtomStateOffsetToName(names
, table
[i
].atomOffset
);
839 * Table of standard classes, indexed by JSProtoKey. For entries where the
840 * JSProtoKey does not correspond to a class with a meaningful constructor, we
841 * insert a null entry into the table.
843 #define STD_NAME_ENTRY(name, clasp) {NAME_OFFSET(name), JSProto_##name},
844 #define STD_DUMMY_ENTRY(name, dummy) {0, JSProto_Null},
845 static const JSStdName standard_class_names
[] = {
846 JS_FOR_PROTOTYPES(STD_NAME_ENTRY
, STD_DUMMY_ENTRY
){0, JSProto_LIMIT
}};
849 * Table of top-level function and constant names and the JSProtoKey of the
850 * standard class that initializes them.
852 static const JSStdName builtin_property_names
[] = {
853 {NAME_OFFSET(eval
), JSProto_Object
},
855 /* Global properties and functions defined by the Number class. */
856 {NAME_OFFSET(NaN
), JSProto_Number
},
857 {NAME_OFFSET(Infinity
), JSProto_Number
},
858 {NAME_OFFSET(isNaN
), JSProto_Number
},
859 {NAME_OFFSET(isFinite
), JSProto_Number
},
860 {NAME_OFFSET(parseFloat
), JSProto_Number
},
861 {NAME_OFFSET(parseInt
), JSProto_Number
},
863 /* String global functions. */
864 {NAME_OFFSET(escape
), JSProto_String
},
865 {NAME_OFFSET(unescape
), JSProto_String
},
866 {NAME_OFFSET(decodeURI
), JSProto_String
},
867 {NAME_OFFSET(encodeURI
), JSProto_String
},
868 {NAME_OFFSET(decodeURIComponent
), JSProto_String
},
869 {NAME_OFFSET(encodeURIComponent
), JSProto_String
},
870 {NAME_OFFSET(uneval
), JSProto_String
},
874 static bool SkipUneval(jsid id
, JSContext
* cx
) {
875 return !cx
->realm()->creationOptions().getToSourceEnabled() &&
876 id
== NameToId(cx
->names().uneval
);
879 static bool SkipSharedArrayBufferConstructor(JSProtoKey key
,
880 GlobalObject
* global
) {
881 if (key
!= JSProto_SharedArrayBuffer
) {
885 const JS::RealmCreationOptions
& options
= global
->realm()->creationOptions();
886 MOZ_ASSERT(options
.getSharedMemoryAndAtomicsEnabled(),
887 "shouldn't contemplate defining SharedArrayBuffer if shared "
888 "memory is disabled");
890 // On the web, it isn't presently possible to expose the global
891 // "SharedArrayBuffer" property unless the page is cross-site-isolated. Only
892 // define this constructor if an option on the realm indicates that it should
894 return !options
.defineSharedArrayBufferConstructor();
897 JS_PUBLIC_API
bool JS_ResolveStandardClass(JSContext
* cx
, HandleObject obj
,
898 HandleId id
, bool* resolved
) {
903 Handle
<GlobalObject
*> global
= obj
.as
<GlobalObject
>();
910 /* Check whether we're resolving 'undefined', and define it if so. */
911 JSAtom
* idAtom
= id
.toAtom();
912 if (idAtom
== cx
->names().undefined
) {
914 return js::DefineDataProperty(
915 cx
, global
, id
, UndefinedHandleValue
,
916 JSPROP_PERMANENT
| JSPROP_READONLY
| JSPROP_RESOLVING
);
919 // Resolve a "globalThis" self-referential property if necessary.
920 if (idAtom
== cx
->names().globalThis
) {
921 return GlobalObject::maybeResolveGlobalThis(cx
, global
, resolved
);
924 // Try for class constructors/prototypes named by well-known atoms.
925 const JSStdName
* stdnm
=
926 LookupStdName(cx
->names(), idAtom
, standard_class_names
);
928 // Try less frequently used top-level functions and constants.
929 stdnm
= LookupStdName(cx
->names(), idAtom
, builtin_property_names
);
935 JSProtoKey key
= stdnm
->key
;
936 if (key
== JSProto_Null
|| GlobalObject::skipDeselectedConstructor(cx
, key
) ||
937 SkipUneval(id
, cx
)) {
941 // If this class is anonymous (or it's "SharedArrayBuffer" but that global
942 // constructor isn't supposed to be defined), then it doesn't exist as a
943 // global property, so we won't resolve anything.
944 const JSClass
* clasp
= ProtoKeyToClass(key
);
945 if (clasp
&& !clasp
->specShouldDefineConstructor()) {
948 if (SkipSharedArrayBufferConstructor(key
, global
)) {
952 if (!GlobalObject::ensureConstructor(cx
, global
, key
)) {
959 JS_PUBLIC_API
bool JS_MayResolveStandardClass(const JSAtomState
& names
, jsid id
,
960 JSObject
* maybeObj
) {
961 MOZ_ASSERT_IF(maybeObj
, maybeObj
->is
<GlobalObject
>());
963 // The global object's resolve hook is special: JS_ResolveStandardClass
964 // initializes the prototype chain lazily. Only attempt to optimize here
965 // if we know the prototype chain has been initialized.
966 if (!maybeObj
|| !maybeObj
->staticPrototype()) {
974 JSAtom
* atom
= id
.toAtom();
976 // This will return true even for deselected constructors. (To do
977 // better, we need a JSContext here; it's fine as it is.)
979 return atom
== names
.undefined
|| atom
== names
.globalThis
||
980 LookupStdName(names
, atom
, standard_class_names
) ||
981 LookupStdName(names
, atom
, builtin_property_names
);
984 JS_PUBLIC_API
bool JS_EnumerateStandardClasses(JSContext
* cx
,
989 Handle
<GlobalObject
*> global
= obj
.as
<GlobalObject
>();
990 return GlobalObject::initStandardClasses(cx
, global
);
993 static bool EnumerateStandardClassesInTable(JSContext
* cx
,
994 Handle
<GlobalObject
*> global
,
995 MutableHandleIdVector properties
,
996 const JSStdName
* table
,
997 bool includeResolved
) {
998 for (unsigned i
= 0; !table
[i
].isSentinel(); i
++) {
999 if (table
[i
].isDummy()) {
1003 JSProtoKey key
= table
[i
].key
;
1005 // If the standard class has been resolved, the properties have been
1006 // defined on the global so we don't need to add them here.
1007 if (!includeResolved
&& global
->isStandardClassResolved(key
)) {
1011 if (GlobalObject::skipDeselectedConstructor(cx
, key
)) {
1015 if (const JSClass
* clasp
= ProtoKeyToClass(key
)) {
1016 if (!clasp
->specShouldDefineConstructor() ||
1017 SkipSharedArrayBufferConstructor(key
, global
)) {
1022 jsid id
= NameToId(AtomStateOffsetToName(cx
->names(), table
[i
].atomOffset
));
1024 if (SkipUneval(id
, cx
)) {
1028 if (!properties
.append(id
)) {
1036 static bool EnumerateStandardClasses(JSContext
* cx
, JS::HandleObject obj
,
1037 JS::MutableHandleIdVector properties
,
1038 bool enumerableOnly
,
1039 bool includeResolved
) {
1040 if (enumerableOnly
) {
1041 // There are no enumerable standard classes and "undefined" is
1046 Handle
<GlobalObject
*> global
= obj
.as
<GlobalObject
>();
1048 // It's fine to always append |undefined| here, it's non-configurable and
1049 // the enumeration code filters duplicates.
1050 if (!properties
.append(NameToId(cx
->names().undefined
))) {
1054 bool resolved
= false;
1055 if (!GlobalObject::maybeResolveGlobalThis(cx
, global
, &resolved
)) {
1058 if (resolved
|| includeResolved
) {
1059 if (!properties
.append(NameToId(cx
->names().globalThis
))) {
1064 if (!EnumerateStandardClassesInTable(cx
, global
, properties
,
1065 standard_class_names
, includeResolved
)) {
1068 if (!EnumerateStandardClassesInTable(
1069 cx
, global
, properties
, builtin_property_names
, includeResolved
)) {
1076 JS_PUBLIC_API
bool JS_NewEnumerateStandardClasses(
1077 JSContext
* cx
, JS::HandleObject obj
, JS::MutableHandleIdVector properties
,
1078 bool enumerableOnly
) {
1079 return EnumerateStandardClasses(cx
, obj
, properties
, enumerableOnly
, false);
1082 JS_PUBLIC_API
bool JS_NewEnumerateStandardClassesIncludingResolved(
1083 JSContext
* cx
, JS::HandleObject obj
, JS::MutableHandleIdVector properties
,
1084 bool enumerableOnly
) {
1085 return EnumerateStandardClasses(cx
, obj
, properties
, enumerableOnly
, true);
1088 JS_PUBLIC_API
bool JS_GetClassObject(JSContext
* cx
, JSProtoKey key
,
1089 MutableHandleObject objp
) {
1092 JSObject
* obj
= GlobalObject::getOrCreateConstructor(cx
, key
);
1100 JS_PUBLIC_API
bool JS_GetClassPrototype(JSContext
* cx
, JSProtoKey key
,
1101 MutableHandleObject objp
) {
1105 // Bound functions don't have their own prototype object: they reuse the
1106 // prototype of the target object. This is typically Function.prototype so we
1108 if (key
== JSProto_BoundFunction
) {
1109 key
= JSProto_Function
;
1112 JSObject
* proto
= GlobalObject::getOrCreatePrototype(cx
, key
);
1122 JS_PUBLIC_API
void ProtoKeyToId(JSContext
* cx
, JSProtoKey key
,
1123 MutableHandleId idp
) {
1124 idp
.set(NameToId(ClassName(key
, cx
)));
1127 } /* namespace JS */
1129 JS_PUBLIC_API JSProtoKey
JS_IdToProtoKey(JSContext
* cx
, HandleId id
) {
1135 return JSProto_Null
;
1138 JSAtom
* atom
= id
.toAtom();
1139 const JSStdName
* stdnm
=
1140 LookupStdName(cx
->names(), atom
, standard_class_names
);
1142 return JSProto_Null
;
1145 if (GlobalObject::skipDeselectedConstructor(cx
, stdnm
->key
)) {
1146 return JSProto_Null
;
1149 if (SkipSharedArrayBufferConstructor(stdnm
->key
, cx
->global())) {
1150 MOZ_ASSERT(id
== NameToId(cx
->names().SharedArrayBuffer
));
1151 return JSProto_Null
;
1154 if (SkipUneval(id
, cx
)) {
1155 return JSProto_Null
;
1158 static_assert(std::size(standard_class_names
) == JSProto_LIMIT
+ 1);
1159 return static_cast<JSProtoKey
>(stdnm
- standard_class_names
);
1162 extern JS_PUBLIC_API
bool JS_IsGlobalObject(JSObject
* obj
) {
1163 return obj
->is
<GlobalObject
>();
1166 extern JS_PUBLIC_API JSObject
* JS_GlobalLexicalEnvironment(JSObject
* obj
) {
1167 return &obj
->as
<GlobalObject
>().lexicalEnvironment();
1170 extern JS_PUBLIC_API
bool JS_HasExtensibleLexicalEnvironment(JSObject
* obj
) {
1171 return obj
->is
<GlobalObject
>() ||
1172 ObjectRealm::get(obj
).getNonSyntacticLexicalEnvironment(obj
);
1175 extern JS_PUBLIC_API JSObject
* JS_ExtensibleLexicalEnvironment(JSObject
* obj
) {
1176 return ExtensibleLexicalEnvironmentObject::forVarEnvironment(obj
);
1179 JS_PUBLIC_API JSObject
* JS::CurrentGlobalOrNull(JSContext
* cx
) {
1180 AssertHeapIsIdleOrIterating();
1185 return cx
->global();
1188 JS_PUBLIC_API JSObject
* JS::GetNonCCWObjectGlobal(JSObject
* obj
) {
1189 AssertHeapIsIdleOrIterating();
1190 MOZ_DIAGNOSTIC_ASSERT(!IsCrossCompartmentWrapper(obj
));
1191 return &obj
->nonCCWGlobal();
1194 JS_PUBLIC_API
bool JS::detail::ComputeThis(JSContext
* cx
, Value
* vp
,
1195 MutableHandleObject thisObject
) {
1197 cx
->check(vp
[0], vp
[1]);
1199 MutableHandleValue thisv
= MutableHandleValue::fromMarkedLocation(&vp
[1]);
1200 JSObject
* obj
= BoxNonStrictThis(cx
, thisv
);
1205 thisObject
.set(obj
);
1209 static bool gProfileTimelineRecordingEnabled
= false;
1211 JS_PUBLIC_API
void JS::SetProfileTimelineRecordingEnabled(bool enabled
) {
1212 gProfileTimelineRecordingEnabled
= enabled
;
1215 JS_PUBLIC_API
bool JS::IsProfileTimelineRecordingEnabled() {
1216 return gProfileTimelineRecordingEnabled
;
1219 JS_PUBLIC_API
void* JS_malloc(JSContext
* cx
, size_t nbytes
) {
1222 return static_cast<void*>(cx
->maybe_pod_malloc
<uint8_t>(nbytes
));
1225 JS_PUBLIC_API
void* JS_realloc(JSContext
* cx
, void* p
, size_t oldBytes
,
1229 return static_cast<void*>(cx
->maybe_pod_realloc
<uint8_t>(
1230 static_cast<uint8_t*>(p
), oldBytes
, newBytes
));
1233 JS_PUBLIC_API
void JS_free(JSContext
* cx
, void* p
) { return js_free(p
); }
1235 JS_PUBLIC_API
void* JS_string_malloc(JSContext
* cx
, size_t nbytes
) {
1238 return static_cast<void*>(
1239 cx
->maybe_pod_arena_malloc
<uint8_t>(js::StringBufferArena
, nbytes
));
1242 JS_PUBLIC_API
void* JS_string_realloc(JSContext
* cx
, void* p
, size_t oldBytes
,
1246 return static_cast<void*>(cx
->maybe_pod_arena_realloc
<uint8_t>(
1247 js::StringBufferArena
, static_cast<uint8_t*>(p
), oldBytes
, newBytes
));
1250 JS_PUBLIC_API
void JS_string_free(JSContext
* cx
, void* p
) { return js_free(p
); }
1252 JS_PUBLIC_API
void JS::AddAssociatedMemory(JSObject
* obj
, size_t nbytes
,
1253 JS::MemoryUse use
) {
1259 Zone
* zone
= obj
->zone();
1260 MOZ_ASSERT(!IsInsideNursery(obj
));
1261 zone
->addCellMemory(obj
, nbytes
, js::MemoryUse(use
));
1262 zone
->maybeTriggerGCOnMalloc();
1265 JS_PUBLIC_API
void JS::RemoveAssociatedMemory(JSObject
* obj
, size_t nbytes
,
1266 JS::MemoryUse use
) {
1272 GCContext
* gcx
= obj
->runtimeFromMainThread()->gcContext();
1273 gcx
->removeCellMemory(obj
, nbytes
, js::MemoryUse(use
));
1278 JS_PUBLIC_API
bool JS_AddExtraGCRootsTracer(JSContext
* cx
,
1279 JSTraceDataOp traceOp
, void* data
) {
1280 return cx
->runtime()->gc
.addBlackRootsTracer(traceOp
, data
);
1283 JS_PUBLIC_API
void JS_RemoveExtraGCRootsTracer(JSContext
* cx
,
1284 JSTraceDataOp traceOp
,
1286 return cx
->runtime()->gc
.removeBlackRootsTracer(traceOp
, data
);
1289 JS_PUBLIC_API
JS::GCReason
JS::WantEagerMinorGC(JSRuntime
* rt
) {
1290 if (rt
->gc
.nursery().shouldCollect()) {
1291 return JS::GCReason::EAGER_NURSERY_COLLECTION
;
1293 return JS::GCReason::NO_REASON
;
1296 JS_PUBLIC_API
JS::GCReason
JS::WantEagerMajorGC(JSRuntime
* rt
) {
1297 return rt
->gc
.wantMajorGC(true);
1300 JS_PUBLIC_API
void JS::MaybeRunNurseryCollection(JSRuntime
* rt
,
1301 JS::GCReason reason
) {
1302 gc::GCRuntime
& gc
= rt
->gc
;
1303 if (gc
.nursery().shouldCollect()) {
1308 JS_PUBLIC_API
void JS::RunNurseryCollection(
1309 JSRuntime
* rt
, JS::GCReason reason
,
1310 mozilla::TimeDuration aSinceLastMinorGC
) {
1311 gc::GCRuntime
& gc
= rt
->gc
;
1312 if (!gc
.nursery().lastCollectionEndTime() ||
1313 (mozilla::TimeStamp::Now() - gc
.nursery().lastCollectionEndTime() >
1314 aSinceLastMinorGC
)) {
1319 JS_PUBLIC_API
void JS_GC(JSContext
* cx
, JS::GCReason reason
) {
1321 JS::PrepareForFullGC(cx
);
1322 cx
->runtime()->gc
.gc(JS::GCOptions::Normal
, reason
);
1325 JS_PUBLIC_API
void JS_MaybeGC(JSContext
* cx
) {
1327 cx
->runtime()->gc
.maybeGC();
1330 JS_PUBLIC_API
void JS_SetGCCallback(JSContext
* cx
, JSGCCallback cb
,
1333 cx
->runtime()->gc
.setGCCallback(cb
, data
);
1336 JS_PUBLIC_API
void JS_SetObjectsTenuredCallback(JSContext
* cx
,
1337 JSObjectsTenuredCallback cb
,
1340 cx
->runtime()->gc
.setObjectsTenuredCallback(cb
, data
);
1343 JS_PUBLIC_API
bool JS_AddFinalizeCallback(JSContext
* cx
, JSFinalizeCallback cb
,
1346 return cx
->runtime()->gc
.addFinalizeCallback(cb
, data
);
1349 JS_PUBLIC_API
void JS_RemoveFinalizeCallback(JSContext
* cx
,
1350 JSFinalizeCallback cb
) {
1351 cx
->runtime()->gc
.removeFinalizeCallback(cb
);
1354 JS_PUBLIC_API
void JS::SetHostCleanupFinalizationRegistryCallback(
1355 JSContext
* cx
, JSHostCleanupFinalizationRegistryCallback cb
, void* data
) {
1357 cx
->runtime()->gc
.setHostCleanupFinalizationRegistryCallback(cb
, data
);
1360 JS_PUBLIC_API
void JS::ClearKeptObjects(JSContext
* cx
) {
1361 gc::GCRuntime
* gc
= &cx
->runtime()->gc
;
1363 for (ZonesIter
zone(gc
, ZoneSelector::WithAtoms
); !zone
.done(); zone
.next()) {
1364 zone
->clearKeptObjects();
1368 JS_PUBLIC_API
bool JS::AtomsZoneIsCollecting(JSRuntime
* runtime
) {
1369 return runtime
->activeGCInAtomsZone();
1372 JS_PUBLIC_API
bool JS::IsAtomsZone(JS::Zone
* zone
) {
1373 return zone
->isAtomsZone();
1376 JS_PUBLIC_API
bool JS_AddWeakPointerZonesCallback(JSContext
* cx
,
1377 JSWeakPointerZonesCallback cb
,
1380 return cx
->runtime()->gc
.addWeakPointerZonesCallback(cb
, data
);
1383 JS_PUBLIC_API
void JS_RemoveWeakPointerZonesCallback(
1384 JSContext
* cx
, JSWeakPointerZonesCallback cb
) {
1385 cx
->runtime()->gc
.removeWeakPointerZonesCallback(cb
);
1388 JS_PUBLIC_API
bool JS_AddWeakPointerCompartmentCallback(
1389 JSContext
* cx
, JSWeakPointerCompartmentCallback cb
, void* data
) {
1391 return cx
->runtime()->gc
.addWeakPointerCompartmentCallback(cb
, data
);
1394 JS_PUBLIC_API
void JS_RemoveWeakPointerCompartmentCallback(
1395 JSContext
* cx
, JSWeakPointerCompartmentCallback cb
) {
1396 cx
->runtime()->gc
.removeWeakPointerCompartmentCallback(cb
);
1399 JS_PUBLIC_API
bool JS_UpdateWeakPointerAfterGC(JSTracer
* trc
,
1400 JS::Heap
<JSObject
*>* objp
) {
1401 return TraceWeakEdge(trc
, objp
);
1404 JS_PUBLIC_API
bool JS_UpdateWeakPointerAfterGCUnbarriered(JSTracer
* trc
,
1406 return TraceManuallyBarrieredWeakEdge(trc
, objp
, "External weak pointer");
1409 JS_PUBLIC_API
void JS_SetGCParameter(JSContext
* cx
, JSGCParamKey key
,
1411 MOZ_ALWAYS_TRUE(cx
->runtime()->gc
.setParameter(cx
, key
, value
));
1414 JS_PUBLIC_API
void JS_ResetGCParameter(JSContext
* cx
, JSGCParamKey key
) {
1415 cx
->runtime()->gc
.resetParameter(cx
, key
);
1418 JS_PUBLIC_API
uint32_t JS_GetGCParameter(JSContext
* cx
, JSGCParamKey key
) {
1419 return cx
->runtime()->gc
.getParameter(key
);
1422 JS_PUBLIC_API
void JS_SetGCParametersBasedOnAvailableMemory(
1423 JSContext
* cx
, uint32_t availMemMB
) {
1429 static const JSGCConfig minimal
[] = {
1430 {JSGC_SLICE_TIME_BUDGET_MS
, 5},
1431 {JSGC_HIGH_FREQUENCY_TIME_LIMIT
, 1500},
1432 {JSGC_LARGE_HEAP_SIZE_MIN
, 250},
1433 {JSGC_SMALL_HEAP_SIZE_MAX
, 50},
1434 {JSGC_HIGH_FREQUENCY_SMALL_HEAP_GROWTH
, 300},
1435 {JSGC_HIGH_FREQUENCY_LARGE_HEAP_GROWTH
, 120},
1436 {JSGC_LOW_FREQUENCY_HEAP_GROWTH
, 120},
1437 {JSGC_ALLOCATION_THRESHOLD
, 15},
1438 {JSGC_MALLOC_THRESHOLD_BASE
, 20},
1439 {JSGC_SMALL_HEAP_INCREMENTAL_LIMIT
, 200},
1440 {JSGC_LARGE_HEAP_INCREMENTAL_LIMIT
, 110},
1441 {JSGC_URGENT_THRESHOLD_MB
, 8}};
1443 static const JSGCConfig nominal
[] = {
1444 {JSGC_SLICE_TIME_BUDGET_MS
, 5},
1445 {JSGC_HIGH_FREQUENCY_TIME_LIMIT
, 1000},
1446 {JSGC_LARGE_HEAP_SIZE_MIN
, 500},
1447 {JSGC_SMALL_HEAP_SIZE_MAX
, 100},
1448 {JSGC_HIGH_FREQUENCY_SMALL_HEAP_GROWTH
, 300},
1449 {JSGC_HIGH_FREQUENCY_LARGE_HEAP_GROWTH
, 150},
1450 {JSGC_LOW_FREQUENCY_HEAP_GROWTH
, 150},
1451 {JSGC_ALLOCATION_THRESHOLD
, 27},
1452 {JSGC_MALLOC_THRESHOLD_BASE
, 38},
1453 {JSGC_SMALL_HEAP_INCREMENTAL_LIMIT
, 150},
1454 {JSGC_LARGE_HEAP_INCREMENTAL_LIMIT
, 110},
1455 {JSGC_URGENT_THRESHOLD_MB
, 16}};
1457 const auto& configSet
= availMemMB
> 512 ? nominal
: minimal
;
1458 for (const auto& config
: configSet
) {
1459 JS_SetGCParameter(cx
, config
.key
, config
.value
);
1463 JS_PUBLIC_API JSString
* JS_NewExternalString(
1464 JSContext
* cx
, const char16_t
* chars
, size_t length
,
1465 const JSExternalStringCallbacks
* callbacks
) {
1468 return JSExternalString::new_(cx
, chars
, length
, callbacks
);
1471 JS_PUBLIC_API JSString
* JS_NewMaybeExternalString(
1472 JSContext
* cx
, const char16_t
* chars
, size_t length
,
1473 const JSExternalStringCallbacks
* callbacks
, bool* allocatedExternal
) {
1476 return NewMaybeExternalString(cx
, chars
, length
, callbacks
,
1480 extern JS_PUBLIC_API
const JSExternalStringCallbacks
*
1481 JS_GetExternalStringCallbacks(JSString
* str
) {
1482 return str
->asExternal().callbacks();
1485 static void SetNativeStackSize(JSContext
* cx
, JS::StackKind kind
,
1486 JS::NativeStackSize stackSize
) {
1488 cx
->nativeStackLimit
[kind
] = JS::WASINativeStackLimit
;
1490 if (stackSize
== 0) {
1491 cx
->nativeStackLimit
[kind
] = JS::NativeStackLimitMax
;
1493 cx
->nativeStackLimit
[kind
] =
1494 JS::GetNativeStackLimit(cx
->nativeStackBase(), stackSize
- 1);
1499 JS_PUBLIC_API
void JS_SetNativeStackQuota(
1500 JSContext
* cx
, JS::NativeStackSize systemCodeStackSize
,
1501 JS::NativeStackSize trustedScriptStackSize
,
1502 JS::NativeStackSize untrustedScriptStackSize
) {
1503 MOZ_ASSERT(!cx
->activation());
1505 if (!trustedScriptStackSize
) {
1506 trustedScriptStackSize
= systemCodeStackSize
;
1508 MOZ_ASSERT(trustedScriptStackSize
< systemCodeStackSize
);
1511 if (!untrustedScriptStackSize
) {
1512 untrustedScriptStackSize
= trustedScriptStackSize
;
1514 MOZ_ASSERT(untrustedScriptStackSize
< trustedScriptStackSize
);
1517 SetNativeStackSize(cx
, JS::StackForSystemCode
, systemCodeStackSize
);
1518 SetNativeStackSize(cx
, JS::StackForTrustedScript
, trustedScriptStackSize
);
1519 SetNativeStackSize(cx
, JS::StackForUntrustedScript
, untrustedScriptStackSize
);
1521 cx
->initJitStackLimit();
1524 /************************************************************************/
1526 JS_PUBLIC_API
bool JS_ValueToId(JSContext
* cx
, HandleValue value
,
1527 MutableHandleId idp
) {
1531 return ToPropertyKey(cx
, value
, idp
);
1534 JS_PUBLIC_API
bool JS_StringToId(JSContext
* cx
, HandleString string
,
1535 MutableHandleId idp
) {
1539 RootedValue
value(cx
, StringValue(string
));
1540 return PrimitiveValueToId
<CanGC
>(cx
, value
, idp
);
1543 JS_PUBLIC_API
bool JS_IdToValue(JSContext
* cx
, jsid id
, MutableHandleValue vp
) {
1547 vp
.set(IdToValue(id
));
1552 JS_PUBLIC_API
bool JS::ToPrimitive(JSContext
* cx
, HandleObject obj
, JSType hint
,
1553 MutableHandleValue vp
) {
1557 MOZ_ASSERT(obj
!= nullptr);
1558 MOZ_ASSERT(hint
== JSTYPE_UNDEFINED
|| hint
== JSTYPE_STRING
||
1559 hint
== JSTYPE_NUMBER
);
1561 return ToPrimitiveSlow(cx
, hint
, vp
);
1564 JS_PUBLIC_API
bool JS::GetFirstArgumentAsTypeHint(JSContext
* cx
, CallArgs args
,
1566 if (!args
.get(0).isString()) {
1567 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr,
1568 JSMSG_NOT_EXPECTED_TYPE
, "Symbol.toPrimitive",
1569 "\"string\", \"number\", or \"default\"",
1570 InformalValueTypeName(args
.get(0)));
1574 RootedString
str(cx
, args
.get(0).toString());
1577 if (!EqualStrings(cx
, str
, cx
->names().default_
, &match
)) {
1581 *result
= JSTYPE_UNDEFINED
;
1585 if (!EqualStrings(cx
, str
, cx
->names().string
, &match
)) {
1589 *result
= JSTYPE_STRING
;
1593 if (!EqualStrings(cx
, str
, cx
->names().number
, &match
)) {
1597 *result
= JSTYPE_NUMBER
;
1602 const char* source
= ValueToSourceForError(cx
, args
.get(0), bytes
);
1604 ReportOutOfMemory(cx
);
1608 JS_ReportErrorNumberUTF8(cx
, GetErrorMessage
, nullptr,
1609 JSMSG_NOT_EXPECTED_TYPE
, "Symbol.toPrimitive",
1610 "\"string\", \"number\", or \"default\"", source
);
1614 JS_PUBLIC_API JSObject
* JS_InitClass(
1615 JSContext
* cx
, HandleObject obj
, const JSClass
* protoClass
,
1616 HandleObject protoProto
, const char* name
, JSNative constructor
,
1617 unsigned nargs
, const JSPropertySpec
* ps
, const JSFunctionSpec
* fs
,
1618 const JSPropertySpec
* static_ps
, const JSFunctionSpec
* static_fs
) {
1621 cx
->check(obj
, protoProto
);
1622 return InitClass(cx
, obj
, protoClass
, protoProto
, name
, constructor
, nargs
,
1623 ps
, fs
, static_ps
, static_fs
);
1626 JS_PUBLIC_API
bool JS_LinkConstructorAndPrototype(JSContext
* cx
,
1628 HandleObject proto
) {
1629 return LinkConstructorAndPrototype(cx
, ctor
, proto
);
1632 JS_PUBLIC_API
bool JS_InstanceOf(JSContext
* cx
, HandleObject obj
,
1633 const JSClass
* clasp
, CallArgs
* args
) {
1639 cx
->check(args
->thisv(), args
->calleev());
1642 if (!obj
|| obj
->getClass() != clasp
) {
1644 ReportIncompatibleMethod(cx
, *args
, clasp
);
1651 JS_PUBLIC_API
bool JS_HasInstance(JSContext
* cx
, HandleObject obj
,
1652 HandleValue value
, bool* bp
) {
1654 cx
->check(obj
, value
);
1655 return InstanceofOperator(cx
, obj
, value
, bp
);
1658 JS_PUBLIC_API JSObject
* JS_GetConstructor(JSContext
* cx
, HandleObject proto
) {
1663 RootedValue
cval(cx
);
1664 if (!GetProperty(cx
, proto
, proto
, cx
->names().constructor
, &cval
)) {
1667 if (!IsFunctionObject(cval
)) {
1668 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr,
1669 JSMSG_NO_CONSTRUCTOR
, proto
->getClass()->name
);
1672 return &cval
.toObject();
1675 JS::RealmCreationOptions
&
1676 JS::RealmCreationOptions::setNewCompartmentInSystemZone() {
1677 compSpec_
= CompartmentSpecifier::NewCompartmentInSystemZone
;
1682 JS::RealmCreationOptions
&
1683 JS::RealmCreationOptions::setNewCompartmentInExistingZone(JSObject
* obj
) {
1684 compSpec_
= CompartmentSpecifier::NewCompartmentInExistingZone
;
1685 zone_
= obj
->zone();
1689 JS::RealmCreationOptions
& JS::RealmCreationOptions::setExistingCompartment(
1691 compSpec_
= CompartmentSpecifier::ExistingCompartment
;
1692 comp_
= obj
->compartment();
1696 JS::RealmCreationOptions
& JS::RealmCreationOptions::setExistingCompartment(
1697 JS::Compartment
* compartment
) {
1698 compSpec_
= CompartmentSpecifier::ExistingCompartment
;
1699 comp_
= compartment
;
1703 JS::RealmCreationOptions
& JS::RealmCreationOptions::setNewCompartmentAndZone() {
1704 compSpec_
= CompartmentSpecifier::NewCompartmentAndZone
;
1709 const JS::RealmCreationOptions
& JS::RealmCreationOptionsRef(Realm
* realm
) {
1710 return realm
->creationOptions();
1713 const JS::RealmCreationOptions
& JS::RealmCreationOptionsRef(JSContext
* cx
) {
1714 return cx
->realm()->creationOptions();
1717 bool JS::RealmCreationOptions::getSharedMemoryAndAtomicsEnabled() const {
1718 return sharedMemoryAndAtomics_
;
1721 JS::RealmCreationOptions
&
1722 JS::RealmCreationOptions::setSharedMemoryAndAtomicsEnabled(bool flag
) {
1723 sharedMemoryAndAtomics_
= flag
;
1727 bool JS::RealmCreationOptions::getCoopAndCoepEnabled() const {
1728 return coopAndCoep_
;
1731 JS::RealmCreationOptions
& JS::RealmCreationOptions::setCoopAndCoepEnabled(
1733 coopAndCoep_
= flag
;
1737 JS::RealmCreationOptions
& JS::RealmCreationOptions::setLocaleCopyZ(
1738 const char* locale
) {
1739 const size_t size
= strlen(locale
) + 1;
1741 AutoEnterOOMUnsafeRegion oomUnsafe
;
1742 char* memoryPtr
= js_pod_malloc
<char>(sizeof(LocaleString
) + size
);
1744 oomUnsafe
.crash("RealmCreationOptions::setLocaleCopyZ");
1747 char* localePtr
= memoryPtr
+ sizeof(LocaleString
);
1748 memcpy(localePtr
, locale
, size
);
1750 locale_
= new (memoryPtr
) LocaleString(localePtr
);
1755 const JS::RealmBehaviors
& JS::RealmBehaviorsRef(JS::Realm
* realm
) {
1756 return realm
->behaviors();
1759 const JS::RealmBehaviors
& JS::RealmBehaviorsRef(JSContext
* cx
) {
1760 return cx
->realm()->behaviors();
1763 void JS::SetRealmNonLive(Realm
* realm
) { realm
->setNonLive(); }
1765 void JS::SetRealmReduceTimerPrecisionCallerType(Realm
* realm
,
1766 JS::RTPCallerTypeToken type
) {
1767 realm
->setReduceTimerPrecisionCallerType(type
);
1770 JS_PUBLIC_API JSObject
* JS_NewGlobalObject(JSContext
* cx
, const JSClass
* clasp
,
1771 JSPrincipals
* principals
,
1772 JS::OnNewGlobalHookOption hookOption
,
1773 const JS::RealmOptions
& options
) {
1775 cx
->runtime()->hasInitializedSelfHosting(),
1776 "Must call JS::InitSelfHostedCode() before creating a global");
1781 return GlobalObject::new_(cx
, clasp
, principals
, hookOption
, options
);
1784 JS_PUBLIC_API
void JS_GlobalObjectTraceHook(JSTracer
* trc
, JSObject
* global
) {
1785 GlobalObject
* globalObj
= &global
->as
<GlobalObject
>();
1786 Realm
* globalRealm
= globalObj
->realm();
1788 // If we GC when creating the global, we may not have set that global's
1789 // realm's global pointer yet. In this case, the realm will not yet contain
1790 // anything that needs to be traced.
1791 if (globalRealm
->unsafeUnbarrieredMaybeGlobal() != globalObj
) {
1795 // Trace the realm for any GC things that should only stick around if we
1796 // know the global is live.
1797 globalRealm
->traceGlobalData(trc
);
1799 globalObj
->traceData(trc
, globalObj
);
1801 if (JSTraceOp trace
= globalRealm
->creationOptions().getTrace()) {
1806 const JSClassOps
JS::DefaultGlobalClassOps
= {
1807 nullptr, // addProperty
1808 nullptr, // delProperty
1809 nullptr, // enumerate
1810 JS_NewEnumerateStandardClasses
, // newEnumerate
1811 JS_ResolveStandardClass
, // resolve
1812 JS_MayResolveStandardClass
, // mayResolve
1813 nullptr, // finalize
1815 nullptr, // construct
1816 JS_GlobalObjectTraceHook
, // trace
1819 JS_PUBLIC_API
void JS_FireOnNewGlobalObject(JSContext
* cx
,
1820 JS::HandleObject global
) {
1821 // This hook is infallible, because we don't really want arbitrary script
1822 // to be able to throw errors during delicate global creation routines.
1823 // This infallibility will eat OOM and slow script, but if that happens
1824 // we'll likely run up into them again soon in a fallible context.
1827 Rooted
<js::GlobalObject
*> globalObject(cx
, &global
->as
<GlobalObject
>());
1828 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
1829 if (JS::GetReduceMicrosecondTimePrecisionCallback()) {
1830 MOZ_DIAGNOSTIC_ASSERT(globalObject
->realm()
1832 .reduceTimerPrecisionCallerType()
1834 "Trying to create a global without setting an "
1835 "explicit RTPCallerType!");
1838 DebugAPI::onNewGlobalObject(cx
, globalObject
);
1839 cx
->runtime()->ensureRealmIsRecordingAllocations(globalObject
);
1842 JS_PUBLIC_API JSObject
* JS_NewObject(JSContext
* cx
, const JSClass
* clasp
) {
1843 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
1848 // Default class is Object.
1849 return NewPlainObject(cx
);
1852 MOZ_ASSERT(!clasp
->isJSFunction());
1853 MOZ_ASSERT(clasp
!= &PlainObject::class_
);
1854 MOZ_ASSERT(clasp
!= &ArrayObject::class_
);
1855 MOZ_ASSERT(!(clasp
->flags
& JSCLASS_IS_GLOBAL
));
1857 return NewBuiltinClassInstance(cx
, clasp
);
1860 JS_PUBLIC_API JSObject
* JS_NewObjectWithGivenProto(JSContext
* cx
,
1861 const JSClass
* clasp
,
1862 HandleObject proto
) {
1863 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
1869 // Default class is Object.
1870 return NewPlainObjectWithProto(cx
, proto
);
1873 MOZ_ASSERT(!clasp
->isJSFunction());
1874 MOZ_ASSERT(clasp
!= &PlainObject::class_
);
1875 MOZ_ASSERT(clasp
!= &ArrayObject::class_
);
1876 MOZ_ASSERT(!(clasp
->flags
& JSCLASS_IS_GLOBAL
));
1878 return NewObjectWithGivenProto(cx
, clasp
, proto
);
1881 JS_PUBLIC_API JSObject
* JS_NewPlainObject(JSContext
* cx
) {
1882 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
1886 return NewPlainObject(cx
);
1889 JS_PUBLIC_API JSObject
* JS_NewObjectForConstructor(JSContext
* cx
,
1890 const JSClass
* clasp
,
1891 const CallArgs
& args
) {
1895 MOZ_ASSERT(!clasp
->isJSFunction());
1896 MOZ_ASSERT(clasp
!= &PlainObject::class_
);
1897 MOZ_ASSERT(clasp
!= &ArrayObject::class_
);
1898 MOZ_ASSERT(!(clasp
->flags
& JSCLASS_IS_GLOBAL
));
1900 if (!ThrowIfNotConstructing(cx
, args
, clasp
->name
)) {
1904 RootedObject
newTarget(cx
, &args
.newTarget().toObject());
1905 cx
->check(newTarget
);
1907 RootedObject
proto(cx
);
1908 if (!GetPrototypeFromConstructor(cx
, newTarget
,
1909 JSCLASS_CACHED_PROTO_KEY(clasp
), &proto
)) {
1913 return NewObjectWithClassProto(cx
, clasp
, proto
);
1916 JS_PUBLIC_API
bool JS_IsNative(JSObject
* obj
) {
1917 return obj
->is
<NativeObject
>();
1920 JS_PUBLIC_API
void JS::AssertObjectBelongsToCurrentThread(JSObject
* obj
) {
1921 JSRuntime
* rt
= obj
->compartment()->runtimeFromAnyThread();
1922 MOZ_RELEASE_ASSERT(CurrentThreadCanAccessRuntime(rt
));
1925 JS_PUBLIC_API
void JS::SetFilenameValidationCallback(
1926 JS::FilenameValidationCallback cb
) {
1927 js::gFilenameValidationCallback
= cb
;
1930 JS_PUBLIC_API
void JS::SetHostEnsureCanAddPrivateElementHook(
1931 JSContext
* cx
, JS::EnsureCanAddPrivateElementOp op
) {
1932 cx
->runtime()->canAddPrivateElement
= op
;
1935 /*** Standard internal methods **********************************************/
1937 JS_PUBLIC_API
bool JS_GetPrototype(JSContext
* cx
, HandleObject obj
,
1938 MutableHandleObject result
) {
1940 return GetPrototype(cx
, obj
, result
);
1943 JS_PUBLIC_API
bool JS_SetPrototype(JSContext
* cx
, HandleObject obj
,
1944 HandleObject proto
) {
1947 cx
->check(obj
, proto
);
1949 return SetPrototype(cx
, obj
, proto
);
1952 JS_PUBLIC_API
bool JS_GetPrototypeIfOrdinary(JSContext
* cx
, HandleObject obj
,
1954 MutableHandleObject result
) {
1956 return GetPrototypeIfOrdinary(cx
, obj
, isOrdinary
, result
);
1959 JS_PUBLIC_API
bool JS_IsExtensible(JSContext
* cx
, HandleObject obj
,
1962 return IsExtensible(cx
, obj
, extensible
);
1965 JS_PUBLIC_API
bool JS_PreventExtensions(JSContext
* cx
, JS::HandleObject obj
,
1966 ObjectOpResult
& result
) {
1968 return PreventExtensions(cx
, obj
, result
);
1971 JS_PUBLIC_API
bool JS_SetImmutablePrototype(JSContext
* cx
, JS::HandleObject obj
,
1974 return SetImmutablePrototype(cx
, obj
, succeeded
);
1979 JS_PUBLIC_API
bool JS_FreezeObject(JSContext
* cx
, HandleObject obj
) {
1983 return FreezeObject(cx
, obj
);
1986 static bool DeepFreezeSlot(JSContext
* cx
, const Value
& v
) {
1987 if (v
.isPrimitive()) {
1990 RootedObject
obj(cx
, &v
.toObject());
1991 return JS_DeepFreezeObject(cx
, obj
);
1994 JS_PUBLIC_API
bool JS_DeepFreezeObject(JSContext
* cx
, HandleObject obj
) {
1999 // Assume that non-extensible objects are already deep-frozen, to avoid
2002 if (!IsExtensible(cx
, obj
, &extensible
)) {
2009 if (!FreezeObject(cx
, obj
)) {
2013 // Walk slots in obj and if any value is a non-null object, seal it.
2014 if (obj
->is
<NativeObject
>()) {
2015 Rooted
<NativeObject
*> nobj(cx
, &obj
->as
<NativeObject
>());
2016 for (uint32_t i
= 0, n
= nobj
->slotSpan(); i
< n
; ++i
) {
2017 if (!DeepFreezeSlot(cx
, nobj
->getSlot(i
))) {
2021 for (uint32_t i
= 0, n
= nobj
->getDenseInitializedLength(); i
< n
; ++i
) {
2022 if (!DeepFreezeSlot(cx
, nobj
->getDenseElement(i
))) {
2031 JS_PUBLIC_API
bool JSPropertySpec::getValue(JSContext
* cx
,
2032 MutableHandleValue vp
) const {
2033 MOZ_ASSERT(!isAccessor());
2035 switch (u
.value
.type
) {
2036 case ValueWrapper::Type::String
: {
2037 Rooted
<JSAtom
*> atom(cx
,
2038 Atomize(cx
, u
.value
.string
, strlen(u
.value
.string
)));
2046 case ValueWrapper::Type::Int32
:
2047 vp
.setInt32(u
.value
.int32
);
2050 case ValueWrapper::Type::Double
:
2051 vp
.setDouble(u
.value
.double_
);
2055 MOZ_CRASH("Unexpected type");
2058 bool PropertySpecNameToId(JSContext
* cx
, JSPropertySpec::Name name
,
2059 MutableHandleId id
) {
2060 if (name
.isSymbol()) {
2061 id
.set(PropertyKey::Symbol(cx
->wellKnownSymbols().get(name
.symbol())));
2063 JSAtom
* atom
= Atomize(cx
, name
.string(), strlen(name
.string()));
2067 id
.set(AtomToId(atom
));
2072 JS_PUBLIC_API
bool JS::PropertySpecNameToPermanentId(JSContext
* cx
,
2073 JSPropertySpec::Name name
,
2075 // We are calling fromMarkedLocation(idp) even though idp points to a
2076 // location that will never be marked. This is OK because the whole point
2077 // of this API is to populate *idp with a jsid that does not need to be
2079 MutableHandleId id
= MutableHandleId::fromMarkedLocation(idp
);
2080 if (!PropertySpecNameToId(cx
, name
, id
)) {
2084 if (id
.isString() && !PinAtom(cx
, &id
.toString()->asAtom())) {
2091 JS_PUBLIC_API
bool JS::ToCompletePropertyDescriptor(
2092 JSContext
* cx
, HandleValue descriptor
,
2093 MutableHandle
<PropertyDescriptor
> desc
) {
2096 cx
->check(descriptor
);
2097 if (!ToPropertyDescriptor(cx
, descriptor
, /* checkAccessors */ true, desc
)) {
2100 CompletePropertyDescriptor(desc
);
2104 JS_PUBLIC_API
void JS_SetAllNonReservedSlotsToUndefined(JS::HandleObject obj
) {
2105 if (!obj
->is
<NativeObject
>()) {
2109 const JSClass
* clasp
= obj
->getClass();
2110 unsigned numReserved
= JSCLASS_RESERVED_SLOTS(clasp
);
2111 unsigned numSlots
= obj
->as
<NativeObject
>().slotSpan();
2112 for (unsigned i
= numReserved
; i
< numSlots
; i
++) {
2113 obj
->as
<NativeObject
>().setSlot(i
, UndefinedValue());
2117 JS_PUBLIC_API
void JS_SetReservedSlot(JSObject
* obj
, uint32_t index
,
2118 const Value
& value
) {
2119 // Note: we don't use setReservedSlot so that this also works on swappable DOM
2120 // objects. See NativeObject::getReservedSlotRef comment.
2121 MOZ_ASSERT(index
< JSCLASS_RESERVED_SLOTS(obj
->getClass()));
2122 obj
->as
<NativeObject
>().setSlot(index
, value
);
2125 JS_PUBLIC_API
void JS_InitReservedSlot(JSObject
* obj
, uint32_t index
, void* ptr
,
2126 size_t nbytes
, JS::MemoryUse use
) {
2127 // Note: we don't use InitReservedSlot so that this also works on swappable
2128 // DOM objects. See NativeObject::getReservedSlotRef comment.
2129 MOZ_ASSERT(index
< JSCLASS_RESERVED_SLOTS(obj
->getClass()));
2130 AddCellMemory(obj
, nbytes
, js::MemoryUse(use
));
2131 obj
->as
<NativeObject
>().initSlot(index
, PrivateValue(ptr
));
2134 JS_PUBLIC_API
bool JS::IsMapObject(JSContext
* cx
, JS::HandleObject obj
,
2136 return IsGivenTypeObject(cx
, obj
, ESClass::Map
, isMap
);
2139 JS_PUBLIC_API
bool JS::IsSetObject(JSContext
* cx
, JS::HandleObject obj
,
2141 return IsGivenTypeObject(cx
, obj
, ESClass::Set
, isSet
);
2144 JS_PUBLIC_API
void JS_HoldPrincipals(JSPrincipals
* principals
) {
2145 ++principals
->refcount
;
2148 JS_PUBLIC_API
void JS_DropPrincipals(JSContext
* cx
, JSPrincipals
* principals
) {
2149 int rc
= --principals
->refcount
;
2151 JS::AutoSuppressGCAnalysis nogc
;
2152 cx
->runtime()->destroyPrincipals(principals
);
2156 JS_PUBLIC_API
void JS_SetSecurityCallbacks(JSContext
* cx
,
2157 const JSSecurityCallbacks
* scb
) {
2158 MOZ_ASSERT(scb
!= &NullSecurityCallbacks
);
2159 cx
->runtime()->securityCallbacks
= scb
? scb
: &NullSecurityCallbacks
;
2162 JS_PUBLIC_API
const JSSecurityCallbacks
* JS_GetSecurityCallbacks(
2164 return (cx
->runtime()->securityCallbacks
!= &NullSecurityCallbacks
)
2165 ? cx
->runtime()->securityCallbacks
.ref()
2169 JS_PUBLIC_API
void JS_SetTrustedPrincipals(JSContext
* cx
, JSPrincipals
* prin
) {
2170 cx
->runtime()->setTrustedPrincipals(prin
);
2173 extern JS_PUBLIC_API
void JS_InitDestroyPrincipalsCallback(
2174 JSContext
* cx
, JSDestroyPrincipalsOp destroyPrincipals
) {
2175 MOZ_ASSERT(destroyPrincipals
);
2176 MOZ_ASSERT(!cx
->runtime()->destroyPrincipals
);
2177 cx
->runtime()->destroyPrincipals
= destroyPrincipals
;
2180 extern JS_PUBLIC_API
void JS_InitReadPrincipalsCallback(
2181 JSContext
* cx
, JSReadPrincipalsOp read
) {
2183 MOZ_ASSERT(!cx
->runtime()->readPrincipals
);
2184 cx
->runtime()->readPrincipals
= read
;
2187 JS_PUBLIC_API JSFunction
* JS_NewFunction(JSContext
* cx
, JSNative native
,
2188 unsigned nargs
, unsigned flags
,
2190 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
2195 Rooted
<JSAtom
*> atom(cx
);
2197 atom
= Atomize(cx
, name
, strlen(name
));
2203 return (flags
& JSFUN_CONSTRUCTOR
)
2204 ? NewNativeConstructor(cx
, native
, nargs
, atom
)
2205 : NewNativeFunction(cx
, native
, nargs
, atom
);
2208 JS_PUBLIC_API JSFunction
* JS::GetSelfHostedFunction(JSContext
* cx
,
2209 const char* selfHostedName
,
2212 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
2217 Rooted
<JSAtom
*> name(cx
, IdToFunctionName(cx
, id
));
2222 JSAtom
* shAtom
= Atomize(cx
, selfHostedName
, strlen(selfHostedName
));
2226 Rooted
<PropertyName
*> shName(cx
, shAtom
->asPropertyName());
2227 RootedValue
funVal(cx
);
2228 if (!GlobalObject::getSelfHostedFunction(cx
, cx
->global(), shName
, name
,
2232 return &funVal
.toObject().as
<JSFunction
>();
2235 JS_PUBLIC_API JSFunction
* JS::NewFunctionFromSpec(JSContext
* cx
,
2236 const JSFunctionSpec
* fs
,
2241 if (fs
->name
.isSymbol()) {
2242 JS::Symbol
* sym
= cx
->wellKnownSymbols().get(fs
->name
.symbol());
2243 MOZ_ASSERT(PropertyKey::Symbol(sym
) == id
);
2245 MOZ_ASSERT(id
.isString() &&
2246 StringEqualsAscii(id
.toLinearString(), fs
->name
.string()));
2250 // Delay cloning self-hosted functions until they are called. This is
2251 // achieved by passing DefineFunction a nullptr JSNative which produces an
2252 // interpreted JSFunction where !hasScript. Interpreted call paths then
2253 // call InitializeLazyFunctionScript if !hasScript.
2254 if (fs
->selfHostedName
) {
2255 MOZ_ASSERT(!fs
->call
.op
);
2256 MOZ_ASSERT(!fs
->call
.info
);
2259 Atomize(cx
, fs
->selfHostedName
, strlen(fs
->selfHostedName
));
2263 Rooted
<PropertyName
*> shName(cx
, shAtom
->asPropertyName());
2264 Rooted
<JSAtom
*> name(cx
, IdToFunctionName(cx
, id
));
2268 RootedValue
funVal(cx
);
2269 if (!GlobalObject::getSelfHostedFunction(cx
, cx
->global(), shName
, name
,
2270 fs
->nargs
, &funVal
)) {
2273 return &funVal
.toObject().as
<JSFunction
>();
2276 Rooted
<JSAtom
*> atom(cx
, IdToFunctionName(cx
, id
));
2281 MOZ_ASSERT(fs
->call
.op
);
2284 if (fs
->flags
& JSFUN_CONSTRUCTOR
) {
2285 fun
= NewNativeConstructor(cx
, fs
->call
.op
, fs
->nargs
, atom
);
2287 fun
= NewNativeFunction(cx
, fs
->call
.op
, fs
->nargs
, atom
);
2293 if (fs
->call
.info
) {
2294 fun
->setJitInfo(fs
->call
.info
);
2299 JS_PUBLIC_API JSFunction
* JS::NewFunctionFromSpec(JSContext
* cx
,
2300 const JSFunctionSpec
* fs
) {
2302 if (!PropertySpecNameToId(cx
, fs
->name
, &id
)) {
2306 return NewFunctionFromSpec(cx
, fs
, id
);
2309 JS_PUBLIC_API JSObject
* JS_GetFunctionObject(JSFunction
* fun
) { return fun
; }
2311 JS_PUBLIC_API
bool JS_GetFunctionId(JSContext
* cx
, JS::Handle
<JSFunction
*> fun
,
2312 JS::MutableHandle
<JSString
*> name
) {
2313 JS::Rooted
<JSAtom
*> atom(cx
);
2314 if (!fun
->getExplicitName(cx
, &atom
)) {
2321 JS_PUBLIC_API JSString
* JS_GetMaybePartialFunctionId(JSFunction
* fun
) {
2322 return fun
->maybePartialExplicitName();
2325 JS_PUBLIC_API
bool JS_GetFunctionDisplayId(JSContext
* cx
,
2326 JS::Handle
<JSFunction
*> fun
,
2327 JS::MutableHandle
<JSString
*> name
) {
2328 JS::Rooted
<JSAtom
*> atom(cx
);
2329 if (!fun
->getDisplayAtom(cx
, &atom
)) {
2336 JS_PUBLIC_API JSString
* JS_GetMaybePartialFunctionDisplayId(JSFunction
* fun
) {
2337 return fun
->maybePartialDisplayAtom();
2340 JS_PUBLIC_API
uint16_t JS_GetFunctionArity(JSFunction
* fun
) {
2341 return fun
->nargs();
2344 JS_PUBLIC_API
bool JS_GetFunctionLength(JSContext
* cx
, HandleFunction fun
,
2347 return JSFunction::getLength(cx
, fun
, length
);
2350 JS_PUBLIC_API
bool JS_ObjectIsFunction(JSObject
* obj
) {
2351 return obj
->is
<JSFunction
>();
2354 JS_PUBLIC_API
bool JS_IsNativeFunction(JSObject
* funobj
, JSNative call
) {
2355 if (!funobj
->is
<JSFunction
>()) {
2358 JSFunction
* fun
= &funobj
->as
<JSFunction
>();
2359 return fun
->isNativeFun() && fun
->native() == call
;
2362 extern JS_PUBLIC_API
bool JS_IsConstructor(JSFunction
* fun
) {
2363 return fun
->isConstructor();
2366 void JS::TransitiveCompileOptions::copyPODTransitiveOptions(
2367 const TransitiveCompileOptions
& rhs
) {
2368 // filename_, introducerFilename_, sourceMapURL_ should be handled in caller.
2370 mutedErrors_
= rhs
.mutedErrors_
;
2371 forceStrictMode_
= rhs
.forceStrictMode_
;
2372 alwaysUseFdlibm_
= rhs
.alwaysUseFdlibm_
;
2373 skipFilenameValidation_
= rhs
.skipFilenameValidation_
;
2374 hideScriptFromDebugger_
= rhs
.hideScriptFromDebugger_
;
2375 deferDebugMetadata_
= rhs
.deferDebugMetadata_
;
2376 eagerDelazificationStrategy_
= rhs
.eagerDelazificationStrategy_
;
2378 selfHostingMode
= rhs
.selfHostingMode
;
2379 discardSource
= rhs
.discardSource
;
2380 sourceIsLazy
= rhs
.sourceIsLazy
;
2381 allowHTMLComments
= rhs
.allowHTMLComments
;
2382 nonSyntacticScope
= rhs
.nonSyntacticScope
;
2384 topLevelAwait
= rhs
.topLevelAwait
;
2386 borrowBuffer
= rhs
.borrowBuffer
;
2387 usePinnedBytecode
= rhs
.usePinnedBytecode
;
2388 deoptimizeModuleGlobalVars
= rhs
.deoptimizeModuleGlobalVars
;
2390 prefableOptions_
= rhs
.prefableOptions_
;
2392 introductionType
= rhs
.introductionType
;
2393 introductionLineno
= rhs
.introductionLineno
;
2394 introductionOffset
= rhs
.introductionOffset
;
2395 hasIntroductionInfo
= rhs
.hasIntroductionInfo
;
2398 void JS::ReadOnlyCompileOptions::copyPODNonTransitiveOptions(
2399 const ReadOnlyCompileOptions
& rhs
) {
2400 lineno
= rhs
.lineno
;
2401 column
= rhs
.column
;
2402 scriptSourceOffset
= rhs
.scriptSourceOffset
;
2403 isRunOnce
= rhs
.isRunOnce
;
2404 noScriptRval
= rhs
.noScriptRval
;
2407 JS::OwningCompileOptions::OwningCompileOptions(JSContext
* cx
) {}
2409 void JS::OwningCompileOptions::release() {
2410 // OwningCompileOptions always owns these, so these casts are okay.
2411 js_free(const_cast<char*>(filename_
.c_str()));
2412 js_free(const_cast<char16_t
*>(sourceMapURL_
));
2413 js_free(const_cast<char*>(introducerFilename_
.c_str()));
2415 filename_
= JS::ConstUTF8CharsZ();
2416 sourceMapURL_
= nullptr;
2417 introducerFilename_
= JS::ConstUTF8CharsZ();
2420 JS::OwningCompileOptions::~OwningCompileOptions() { release(); }
2422 size_t JS::OwningCompileOptions::sizeOfExcludingThis(
2423 mozilla::MallocSizeOf mallocSizeOf
) const {
2424 return mallocSizeOf(filename_
.c_str()) + mallocSizeOf(sourceMapURL_
) +
2425 mallocSizeOf(introducerFilename_
.c_str());
2428 void JS::OwningCompileOptions::steal(JS::OwningCompileOptions
&& rhs
) {
2429 // Release existing string allocations.
2432 copyPODNonTransitiveOptions(rhs
);
2433 copyPODTransitiveOptions(rhs
);
2435 filename_
= rhs
.filename_
;
2436 rhs
.filename_
= JS::ConstUTF8CharsZ();
2437 introducerFilename_
= rhs
.introducerFilename_
;
2438 rhs
.introducerFilename_
= JS::ConstUTF8CharsZ();
2439 sourceMapURL_
= rhs
.sourceMapURL_
;
2440 rhs
.sourceMapURL_
= nullptr;
2443 void JS::OwningCompileOptions::steal(JS::OwningDecodeOptions
&& rhs
) {
2444 // Release existing string allocations.
2447 rhs
.copyPODOptionsTo(*this);
2449 introducerFilename_
= rhs
.introducerFilename_
;
2450 rhs
.introducerFilename_
= JS::ConstUTF8CharsZ();
2453 template <typename ContextT
>
2454 bool JS::OwningCompileOptions::copyImpl(ContextT
* cx
,
2455 const ReadOnlyCompileOptions
& rhs
) {
2456 // Release existing string allocations.
2459 copyPODNonTransitiveOptions(rhs
);
2460 copyPODTransitiveOptions(rhs
);
2462 if (rhs
.filename()) {
2463 const char* str
= DuplicateString(cx
, rhs
.filename().c_str()).release();
2467 filename_
= JS::ConstUTF8CharsZ(str
);
2470 if (rhs
.sourceMapURL()) {
2471 sourceMapURL_
= DuplicateString(cx
, rhs
.sourceMapURL()).release();
2472 if (!sourceMapURL_
) {
2477 if (rhs
.introducerFilename()) {
2479 DuplicateString(cx
, rhs
.introducerFilename().c_str()).release();
2483 introducerFilename_
= JS::ConstUTF8CharsZ(str
);
2489 bool JS::OwningCompileOptions::copy(JSContext
* cx
,
2490 const ReadOnlyCompileOptions
& rhs
) {
2491 return copyImpl(cx
, rhs
);
2494 bool JS::OwningCompileOptions::copy(JS::FrontendContext
* fc
,
2495 const ReadOnlyCompileOptions
& rhs
) {
2496 return copyImpl(fc
, rhs
);
2499 JS::CompileOptions::CompileOptions(JSContext
* cx
) {
2500 prefableOptions_
= cx
->options().compileOptions();
2502 if (cx
->options().asmJSOption() == AsmJSOption::Enabled
) {
2503 if (!js::IsAsmJSCompilationAvailable(cx
)) {
2504 prefableOptions_
.setAsmJSOption(AsmJSOption::DisabledByNoWasmCompiler
);
2505 } else if (cx
->realm() && (cx
->realm()->debuggerObservesWasm() ||
2506 cx
->realm()->debuggerObservesAsmJS())) {
2507 prefableOptions_
.setAsmJSOption(AsmJSOption::DisabledByDebugger
);
2511 // Certain modes of operation disallow syntax parsing in general.
2512 if (coverage::IsLCovEnabled()) {
2513 eagerDelazificationStrategy_
= DelazificationOption::ParseEverythingEagerly
;
2516 // Note: If we parse outside of a specific realm, we do not inherit any realm
2517 // behaviours. These can still be set manually on the options though.
2518 if (Realm
* realm
= cx
->realm()) {
2519 alwaysUseFdlibm_
= realm
->creationOptions().alwaysUseFdlibm();
2520 discardSource
= realm
->behaviors().discardSource();
2524 CompileOptions
& CompileOptions::setIntroductionInfoToCaller(
2525 JSContext
* cx
, const char* introductionType
,
2526 MutableHandle
<JSScript
*> introductionScript
) {
2527 RootedScript
maybeScript(cx
);
2528 const char* filename
;
2532 DescribeScriptedCallerForCompilation(cx
, &maybeScript
, &filename
, &lineno
,
2533 &pcOffset
, &mutedErrors
);
2535 introductionScript
.set(maybeScript
);
2536 return setIntroductionInfo(filename
, introductionType
, lineno
, pcOffset
);
2538 return setIntroductionType(introductionType
);
2541 JS::OwningDecodeOptions::~OwningDecodeOptions() { release(); }
2543 void JS::OwningDecodeOptions::release() {
2544 js_free(const_cast<char*>(introducerFilename_
.c_str()));
2546 introducerFilename_
= JS::ConstUTF8CharsZ();
2549 bool JS::OwningDecodeOptions::copy(JS::FrontendContext
* maybeFc
,
2550 const JS::ReadOnlyDecodeOptions
& rhs
) {
2551 copyPODOptionsFrom(rhs
);
2553 if (rhs
.introducerFilename()) {
2554 MOZ_ASSERT(maybeFc
);
2556 DuplicateString(maybeFc
, rhs
.introducerFilename().c_str()).release();
2560 introducerFilename_
= JS::ConstUTF8CharsZ(str
);
2566 void JS::OwningDecodeOptions::infallibleCopy(
2567 const JS::ReadOnlyDecodeOptions
& rhs
) {
2568 copyPODOptionsFrom(rhs
);
2570 MOZ_ASSERT(!rhs
.introducerFilename());
2573 size_t JS::OwningDecodeOptions::sizeOfExcludingThis(
2574 mozilla::MallocSizeOf mallocSizeOf
) const {
2575 return mallocSizeOf(introducerFilename_
.c_str());
2578 JS_PUBLIC_API JSObject
* JS_GetGlobalFromScript(JSScript
* script
) {
2579 return &script
->global();
2582 JS_PUBLIC_API
const char* JS_GetScriptFilename(JSScript
* script
) {
2583 // This is called from ThreadStackHelper which can be called from another
2584 // thread or inside a signal hander, so we need to be careful in case a
2585 // copmacting GC is currently moving things around.
2586 return script
->maybeForwardedFilename();
2589 JS_PUBLIC_API
unsigned JS_GetScriptBaseLineNumber(JSContext
* cx
,
2591 return script
->lineno();
2594 JS_PUBLIC_API JSScript
* JS_GetFunctionScript(JSContext
* cx
,
2595 HandleFunction fun
) {
2596 if (fun
->isNativeFun()) {
2600 if (fun
->hasBytecode()) {
2601 return fun
->nonLazyScript();
2604 AutoRealm
ar(cx
, fun
);
2605 JSScript
* script
= JSFunction::getOrCreateScript(cx
, fun
);
2612 JS_PUBLIC_API JSString
* JS_DecompileScript(JSContext
* cx
, HandleScript script
) {
2613 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
2617 RootedFunction
fun(cx
, script
->function());
2619 return JS_DecompileFunction(cx
, fun
);
2622 if (!ScriptSource::loadSource(cx
, script
->scriptSource(), &haveSource
)) {
2625 return haveSource
? JSScript::sourceData(cx
, script
)
2626 : NewStringCopyZ
<CanGC
>(cx
, "[no source]");
2629 JS_PUBLIC_API JSString
* JS_DecompileFunction(JSContext
* cx
,
2630 HandleFunction fun
) {
2631 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
2635 return FunctionToString(cx
, fun
, /* isToSource = */ false);
2638 JS_PUBLIC_API
void JS::SetScriptPrivate(JSScript
* script
,
2639 const JS::Value
& value
) {
2640 JSRuntime
* rt
= script
->zone()->runtimeFromMainThread();
2641 script
->sourceObject()->setPrivate(rt
, value
);
2644 JS_PUBLIC_API
JS::Value
JS::GetScriptPrivate(JSScript
* script
) {
2645 return script
->sourceObject()->getPrivate();
2648 JS_PUBLIC_API
JS::Value
JS::GetScriptedCallerPrivate(JSContext
* cx
) {
2652 NonBuiltinFrameIter
iter(cx
, cx
->realm()->principals());
2653 if (iter
.done() || !iter
.hasScript()) {
2654 return UndefinedValue();
2657 return iter
.script()->sourceObject()->getPrivate();
2660 JS_PUBLIC_API
void JS::SetScriptPrivateReferenceHooks(
2661 JSRuntime
* rt
, JS::ScriptPrivateReferenceHook addRefHook
,
2662 JS::ScriptPrivateReferenceHook releaseHook
) {
2664 rt
->scriptPrivateAddRefHook
= addRefHook
;
2665 rt
->scriptPrivateReleaseHook
= releaseHook
;
2668 JS_PUBLIC_API
void JS::SetWaitCallback(JSRuntime
* rt
,
2669 BeforeWaitCallback beforeWait
,
2670 AfterWaitCallback afterWait
,
2671 size_t requiredMemory
) {
2672 MOZ_RELEASE_ASSERT(requiredMemory
<= WAIT_CALLBACK_CLIENT_MAXMEM
);
2673 MOZ_RELEASE_ASSERT((beforeWait
== nullptr) == (afterWait
== nullptr));
2674 rt
->beforeWaitCallback
= beforeWait
;
2675 rt
->afterWaitCallback
= afterWait
;
2678 JS_PUBLIC_API
bool JS_CheckForInterrupt(JSContext
* cx
) {
2679 return js::CheckForInterrupt(cx
);
2682 JS_PUBLIC_API
bool JS_AddInterruptCallback(JSContext
* cx
,
2683 JSInterruptCallback callback
) {
2684 return cx
->interruptCallbacks().append(callback
);
2687 JS_PUBLIC_API
bool JS_DisableInterruptCallback(JSContext
* cx
) {
2688 bool result
= cx
->interruptCallbackDisabled
;
2689 cx
->interruptCallbackDisabled
= true;
2693 JS_PUBLIC_API
void JS_ResetInterruptCallback(JSContext
* cx
, bool enable
) {
2694 cx
->interruptCallbackDisabled
= enable
;
2697 /************************************************************************/
2702 JS_PUBLIC_API
void JS::SetJobQueue(JSContext
* cx
, JobQueue
* queue
) {
2703 cx
->jobQueue
= queue
;
2706 extern JS_PUBLIC_API
void JS::SetPromiseRejectionTrackerCallback(
2707 JSContext
* cx
, PromiseRejectionTrackerCallback callback
,
2708 void* data
/* = nullptr */) {
2709 cx
->promiseRejectionTrackerCallback
= callback
;
2710 cx
->promiseRejectionTrackerCallbackData
= data
;
2713 extern JS_PUBLIC_API
void JS::JobQueueIsEmpty(JSContext
* cx
) {
2714 cx
->canSkipEnqueuingJobs
= true;
2717 extern JS_PUBLIC_API
void JS::JobQueueMayNotBeEmpty(JSContext
* cx
) {
2718 cx
->canSkipEnqueuingJobs
= false;
2721 JS_PUBLIC_API JSObject
* JS::NewPromiseObject(JSContext
* cx
,
2722 HandleObject executor
) {
2723 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
2726 cx
->check(executor
);
2729 return PromiseObject::createSkippingExecutor(cx
);
2732 MOZ_ASSERT(IsCallable(executor
));
2733 return PromiseObject::create(cx
, executor
);
2736 JS_PUBLIC_API
bool JS::IsPromiseObject(JS::HandleObject obj
) {
2737 return obj
->is
<PromiseObject
>();
2740 JS_PUBLIC_API JSObject
* JS::GetPromiseConstructor(JSContext
* cx
) {
2742 Rooted
<GlobalObject
*> global(cx
, cx
->global());
2743 return GlobalObject::getOrCreatePromiseConstructor(cx
, global
);
2746 JS_PUBLIC_API JSObject
* JS::GetPromisePrototype(JSContext
* cx
) {
2748 Rooted
<GlobalObject
*> global(cx
, cx
->global());
2749 return GlobalObject::getOrCreatePromisePrototype(cx
, global
);
2752 JS_PUBLIC_API
JS::PromiseState
JS::GetPromiseState(JS::HandleObject promise
) {
2753 PromiseObject
* promiseObj
= promise
->maybeUnwrapIf
<PromiseObject
>();
2755 return JS::PromiseState::Pending
;
2758 return promiseObj
->state();
2761 JS_PUBLIC_API
uint64_t JS::GetPromiseID(JS::HandleObject promise
) {
2762 return promise
->as
<PromiseObject
>().getID();
2765 JS_PUBLIC_API
JS::Value
JS::GetPromiseResult(JS::HandleObject promiseObj
) {
2766 PromiseObject
* promise
= &promiseObj
->as
<PromiseObject
>();
2767 MOZ_ASSERT(promise
->state() != JS::PromiseState::Pending
);
2768 return promise
->state() == JS::PromiseState::Fulfilled
? promise
->value()
2769 : promise
->reason();
2772 JS_PUBLIC_API
bool JS::GetPromiseIsHandled(JS::HandleObject promise
) {
2773 PromiseObject
* promiseObj
= &promise
->as
<PromiseObject
>();
2774 return !promiseObj
->isUnhandled();
2777 static PromiseObject
* UnwrapPromise(JSContext
* cx
, JS::HandleObject promise
,
2778 mozilla::Maybe
<AutoRealm
>& ar
) {
2783 PromiseObject
* promiseObj
;
2784 if (IsWrapper(promise
)) {
2785 promiseObj
= promise
->maybeUnwrapAs
<PromiseObject
>();
2787 ReportAccessDenied(cx
);
2790 ar
.emplace(cx
, promiseObj
);
2792 promiseObj
= promise
.as
<PromiseObject
>();
2797 JS_PUBLIC_API
bool JS::SetSettledPromiseIsHandled(JSContext
* cx
,
2798 JS::HandleObject promise
) {
2799 mozilla::Maybe
<AutoRealm
> ar
;
2800 Rooted
<PromiseObject
*> promiseObj(cx
, UnwrapPromise(cx
, promise
, ar
));
2804 js::SetSettledPromiseIsHandled(cx
, promiseObj
);
2808 JS_PUBLIC_API
bool JS::SetAnyPromiseIsHandled(JSContext
* cx
,
2809 JS::HandleObject promise
) {
2810 mozilla::Maybe
<AutoRealm
> ar
;
2811 Rooted
<PromiseObject
*> promiseObj(cx
, UnwrapPromise(cx
, promise
, ar
));
2815 js::SetAnyPromiseIsHandled(cx
, promiseObj
);
2819 JS_PUBLIC_API JSObject
* JS::GetPromiseAllocationSite(JS::HandleObject promise
) {
2820 return promise
->as
<PromiseObject
>().allocationSite();
2823 JS_PUBLIC_API JSObject
* JS::GetPromiseResolutionSite(JS::HandleObject promise
) {
2824 return promise
->as
<PromiseObject
>().resolutionSite();
2828 JS_PUBLIC_API
void JS::DumpPromiseAllocationSite(JSContext
* cx
,
2829 JS::HandleObject promise
) {
2830 RootedObject
stack(cx
, promise
->as
<PromiseObject
>().allocationSite());
2831 JSPrincipals
* principals
= cx
->realm()->principals();
2832 UniqueChars stackStr
= BuildUTF8StackString(cx
, principals
, stack
);
2834 fputs(stackStr
.get(), stderr
);
2838 JS_PUBLIC_API
void JS::DumpPromiseResolutionSite(JSContext
* cx
,
2839 JS::HandleObject promise
) {
2840 RootedObject
stack(cx
, promise
->as
<PromiseObject
>().resolutionSite());
2841 JSPrincipals
* principals
= cx
->realm()->principals();
2842 UniqueChars stackStr
= BuildUTF8StackString(cx
, principals
, stack
);
2844 fputs(stackStr
.get(), stderr
);
2849 JS_PUBLIC_API JSObject
* JS::CallOriginalPromiseResolve(
2850 JSContext
* cx
, JS::HandleValue resolutionValue
) {
2853 cx
->check(resolutionValue
);
2855 RootedObject
promise(cx
,
2856 PromiseObject::unforgeableResolve(cx
, resolutionValue
));
2857 MOZ_ASSERT_IF(promise
, promise
->canUnwrapAs
<PromiseObject
>());
2861 JS_PUBLIC_API JSObject
* JS::CallOriginalPromiseReject(
2862 JSContext
* cx
, JS::HandleValue rejectionValue
) {
2865 cx
->check(rejectionValue
);
2867 RootedObject
promise(cx
,
2868 PromiseObject::unforgeableReject(cx
, rejectionValue
));
2869 MOZ_ASSERT_IF(promise
, promise
->canUnwrapAs
<PromiseObject
>());
2873 static bool ResolveOrRejectPromise(JSContext
* cx
, JS::HandleObject promiseObj
,
2874 JS::HandleValue resultOrReason_
,
2878 cx
->check(promiseObj
, resultOrReason_
);
2880 mozilla::Maybe
<AutoRealm
> ar
;
2881 Rooted
<PromiseObject
*> promise(cx
);
2882 RootedValue
resultOrReason(cx
, resultOrReason_
);
2883 if (IsWrapper(promiseObj
)) {
2884 promise
= promiseObj
->maybeUnwrapAs
<PromiseObject
>();
2886 ReportAccessDenied(cx
);
2889 ar
.emplace(cx
, promise
);
2890 if (!cx
->compartment()->wrap(cx
, &resultOrReason
)) {
2894 promise
= promiseObj
.as
<PromiseObject
>();
2897 return reject
? PromiseObject::reject(cx
, promise
, resultOrReason
)
2898 : PromiseObject::resolve(cx
, promise
, resultOrReason
);
2901 JS_PUBLIC_API
bool JS::ResolvePromise(JSContext
* cx
,
2902 JS::HandleObject promiseObj
,
2903 JS::HandleValue resolutionValue
) {
2904 return ResolveOrRejectPromise(cx
, promiseObj
, resolutionValue
, false);
2907 JS_PUBLIC_API
bool JS::RejectPromise(JSContext
* cx
, JS::HandleObject promiseObj
,
2908 JS::HandleValue rejectionValue
) {
2909 return ResolveOrRejectPromise(cx
, promiseObj
, rejectionValue
, true);
2912 JS_PUBLIC_API JSObject
* JS::CallOriginalPromiseThen(
2913 JSContext
* cx
, JS::HandleObject promiseObj
, JS::HandleObject onFulfilled
,
2914 JS::HandleObject onRejected
) {
2917 cx
->check(promiseObj
, onFulfilled
, onRejected
);
2919 MOZ_ASSERT_IF(onFulfilled
, IsCallable(onFulfilled
));
2920 MOZ_ASSERT_IF(onRejected
, IsCallable(onRejected
));
2922 return OriginalPromiseThen(cx
, promiseObj
, onFulfilled
, onRejected
);
2925 [[nodiscard
]] static bool ReactToPromise(JSContext
* cx
,
2926 JS::Handle
<JSObject
*> promiseObj
,
2927 JS::Handle
<JSObject
*> onFulfilled
,
2928 JS::Handle
<JSObject
*> onRejected
,
2929 UnhandledRejectionBehavior behavior
) {
2932 cx
->check(promiseObj
, onFulfilled
, onRejected
);
2934 MOZ_ASSERT_IF(onFulfilled
, IsCallable(onFulfilled
));
2935 MOZ_ASSERT_IF(onRejected
, IsCallable(onRejected
));
2937 Rooted
<PromiseObject
*> unwrappedPromise(cx
);
2939 RootedValue
promiseVal(cx
, ObjectValue(*promiseObj
));
2940 unwrappedPromise
= UnwrapAndTypeCheckValue
<PromiseObject
>(
2941 cx
, promiseVal
, [cx
, promiseObj
] {
2942 JS_ReportErrorNumberLatin1(cx
, GetErrorMessage
, nullptr,
2943 JSMSG_INCOMPATIBLE_PROTO
, "Promise",
2944 "then", promiseObj
->getClass()->name
);
2946 if (!unwrappedPromise
) {
2951 return ReactToUnwrappedPromise(cx
, unwrappedPromise
, onFulfilled
, onRejected
,
2955 JS_PUBLIC_API
bool JS::AddPromiseReactions(JSContext
* cx
,
2956 JS::HandleObject promiseObj
,
2957 JS::HandleObject onFulfilled
,
2958 JS::HandleObject onRejected
) {
2959 return ReactToPromise(cx
, promiseObj
, onFulfilled
, onRejected
,
2960 UnhandledRejectionBehavior::Report
);
2963 JS_PUBLIC_API
bool JS::AddPromiseReactionsIgnoringUnhandledRejection(
2964 JSContext
* cx
, JS::HandleObject promiseObj
, JS::HandleObject onFulfilled
,
2965 JS::HandleObject onRejected
) {
2966 return ReactToPromise(cx
, promiseObj
, onFulfilled
, onRejected
,
2967 UnhandledRejectionBehavior::Ignore
);
2970 JS_PUBLIC_API
JS::PromiseUserInputEventHandlingState
2971 JS::GetPromiseUserInputEventHandlingState(JS::HandleObject promiseObj_
) {
2972 PromiseObject
* promise
= promiseObj_
->maybeUnwrapIf
<PromiseObject
>();
2974 return JS::PromiseUserInputEventHandlingState::DontCare
;
2977 if (!promise
->requiresUserInteractionHandling()) {
2978 return JS::PromiseUserInputEventHandlingState::DontCare
;
2980 if (promise
->hadUserInteractionUponCreation()) {
2981 return JS::PromiseUserInputEventHandlingState::HadUserInteractionAtCreation
;
2983 return JS::PromiseUserInputEventHandlingState::
2984 DidntHaveUserInteractionAtCreation
;
2987 JS_PUBLIC_API
bool JS::SetPromiseUserInputEventHandlingState(
2988 JS::HandleObject promiseObj_
,
2989 JS::PromiseUserInputEventHandlingState state
) {
2990 PromiseObject
* promise
= promiseObj_
->maybeUnwrapIf
<PromiseObject
>();
2996 case JS::PromiseUserInputEventHandlingState::DontCare
:
2997 promise
->setRequiresUserInteractionHandling(false);
2999 case JS::PromiseUserInputEventHandlingState::HadUserInteractionAtCreation
:
3000 promise
->setRequiresUserInteractionHandling(true);
3001 promise
->setHadUserInteractionUponCreation(true);
3003 case JS::PromiseUserInputEventHandlingState::
3004 DidntHaveUserInteractionAtCreation
:
3005 promise
->setRequiresUserInteractionHandling(true);
3006 promise
->setHadUserInteractionUponCreation(false);
3009 MOZ_ASSERT_UNREACHABLE(
3010 "Invalid PromiseUserInputEventHandlingState enum value");
3017 * Unforgeable version of Promise.all for internal use.
3019 * Takes a dense array of Promise objects and returns a promise that's
3020 * resolved with an array of resolution values when all those promises ahve
3021 * been resolved, or rejected with the rejection value of the first rejected
3024 * Asserts that the array is dense and all entries are Promise objects.
3026 JS_PUBLIC_API JSObject
* JS::GetWaitForAllPromise(
3027 JSContext
* cx
, JS::HandleObjectVector promises
) {
3031 return js::GetWaitForAllPromise(cx
, promises
);
3034 JS_PUBLIC_API
void JS::InitDispatchToEventLoop(
3035 JSContext
* cx
, JS::DispatchToEventLoopCallback callback
, void* closure
) {
3036 cx
->runtime()->offThreadPromiseState
.ref().init(callback
, closure
);
3039 JS_PUBLIC_API
void JS::ShutdownAsyncTasks(JSContext
* cx
) {
3040 cx
->runtime()->offThreadPromiseState
.ref().shutdown(cx
);
3043 JS_PUBLIC_API
void JS::InitConsumeStreamCallback(
3044 JSContext
* cx
, ConsumeStreamCallback consume
,
3045 ReportStreamErrorCallback report
) {
3046 cx
->runtime()->consumeStreamCallback
= consume
;
3047 cx
->runtime()->reportStreamErrorCallback
= report
;
3050 JS_PUBLIC_API
void JS_RequestInterruptCallback(JSContext
* cx
) {
3051 cx
->requestInterrupt(InterruptReason::CallbackUrgent
);
3054 JS_PUBLIC_API
void JS_RequestInterruptCallbackCanWait(JSContext
* cx
) {
3055 cx
->requestInterrupt(InterruptReason::CallbackCanWait
);
3058 JS::AutoSetAsyncStackForNewCalls::AutoSetAsyncStackForNewCalls(
3059 JSContext
* cx
, HandleObject stack
, const char* asyncCause
,
3060 JS::AutoSetAsyncStackForNewCalls::AsyncCallKind kind
)
3062 oldAsyncStack(cx
, cx
->asyncStackForNewActivations()),
3063 oldAsyncCause(cx
->asyncCauseForNewActivations
),
3064 oldAsyncCallIsExplicit(cx
->asyncCallIsExplicit
) {
3067 // The option determines whether we actually use the new values at this
3068 // point. It will not affect restoring the previous values when the object
3069 // is destroyed, so if the option changes it won't cause consistency issues.
3070 if (!cx
->options().asyncStack()) {
3074 SavedFrame
* asyncStack
= &stack
->as
<SavedFrame
>();
3076 cx
->asyncStackForNewActivations() = asyncStack
;
3077 cx
->asyncCauseForNewActivations
= asyncCause
;
3078 cx
->asyncCallIsExplicit
= kind
== AsyncCallKind::EXPLICIT
;
3081 JS::AutoSetAsyncStackForNewCalls::~AutoSetAsyncStackForNewCalls() {
3082 cx
->asyncCauseForNewActivations
= oldAsyncCause
;
3083 cx
->asyncStackForNewActivations() =
3084 oldAsyncStack
? &oldAsyncStack
->as
<SavedFrame
>() : nullptr;
3085 cx
->asyncCallIsExplicit
= oldAsyncCallIsExplicit
;
3088 /************************************************************************/
3089 JS_PUBLIC_API JSString
* JS_NewStringCopyN(JSContext
* cx
, const char* s
,
3093 return NewStringCopyN
<CanGC
>(cx
, s
, n
);
3096 JS_PUBLIC_API JSString
* JS_NewStringCopyZ(JSContext
* cx
, const char* s
) {
3100 return cx
->runtime()->emptyString
;
3102 return NewStringCopyZ
<CanGC
>(cx
, s
);
3105 JS_PUBLIC_API JSString
* JS_NewStringCopyUTF8Z(JSContext
* cx
,
3106 const JS::ConstUTF8CharsZ s
) {
3109 return NewStringCopyUTF8Z(cx
, s
);
3112 JS_PUBLIC_API JSString
* JS_NewStringCopyUTF8N(JSContext
* cx
,
3113 const JS::UTF8Chars s
) {
3116 return NewStringCopyUTF8N(cx
, s
);
3119 JS_PUBLIC_API
bool JS_StringHasBeenPinned(JSContext
* cx
, JSString
* str
) {
3123 if (!str
->isAtom()) {
3127 return AtomIsPinned(cx
, &str
->asAtom());
3130 JS_PUBLIC_API JSString
* JS_AtomizeString(JSContext
* cx
, const char* s
) {
3131 return JS_AtomizeStringN(cx
, s
, strlen(s
));
3134 JS_PUBLIC_API JSString
* JS_AtomizeStringN(JSContext
* cx
, const char* s
,
3138 return Atomize(cx
, s
, length
);
3141 JS_PUBLIC_API JSString
* JS_AtomizeAndPinString(JSContext
* cx
, const char* s
) {
3142 return JS_AtomizeAndPinStringN(cx
, s
, strlen(s
));
3145 JS_PUBLIC_API JSString
* JS_AtomizeAndPinStringN(JSContext
* cx
, const char* s
,
3150 JSAtom
* atom
= cx
->zone() ? Atomize(cx
, s
, length
)
3151 : AtomizeWithoutActiveZone(cx
, s
, length
);
3152 if (!atom
|| !PinAtom(cx
, atom
)) {
3156 MOZ_ASSERT(JS_StringHasBeenPinned(cx
, atom
));
3160 JS_PUBLIC_API JSString
* JS_NewLatin1String(
3161 JSContext
* cx
, js::UniquePtr
<JS::Latin1Char
[], JS::FreePolicy
> chars
,
3165 return NewString
<CanGC
>(cx
, std::move(chars
), length
);
3168 JS_PUBLIC_API JSString
* JS_NewUCString(JSContext
* cx
,
3169 JS::UniqueTwoByteChars chars
,
3173 return NewString
<CanGC
>(cx
, std::move(chars
), length
);
3176 JS_PUBLIC_API JSString
* JS_NewUCStringDontDeflate(JSContext
* cx
,
3177 JS::UniqueTwoByteChars chars
,
3181 return NewStringDontDeflate
<CanGC
>(cx
, std::move(chars
), length
);
3184 JS_PUBLIC_API JSString
* JS_NewUCStringCopyN(JSContext
* cx
, const char16_t
* s
,
3189 return cx
->names().empty_
;
3191 return NewStringCopyN
<CanGC
>(cx
, s
, n
);
3194 JS_PUBLIC_API JSString
* JS_NewUCStringCopyZ(JSContext
* cx
, const char16_t
* s
) {
3198 return cx
->runtime()->emptyString
;
3200 return NewStringCopyZ
<CanGC
>(cx
, s
);
3203 JS_PUBLIC_API JSString
* JS_AtomizeUCString(JSContext
* cx
, const char16_t
* s
) {
3204 return JS_AtomizeUCStringN(cx
, s
, js_strlen(s
));
3207 JS_PUBLIC_API JSString
* JS_AtomizeUCStringN(JSContext
* cx
, const char16_t
* s
,
3211 return AtomizeChars(cx
, s
, length
);
3214 JS_PUBLIC_API
size_t JS_GetStringLength(JSString
* str
) { return str
->length(); }
3216 JS_PUBLIC_API
bool JS_StringIsLinear(JSString
* str
) { return str
->isLinear(); }
3218 JS_PUBLIC_API
bool JS_DeprecatedStringHasLatin1Chars(JSString
* str
) {
3219 return str
->hasLatin1Chars();
3222 JS_PUBLIC_API
const JS::Latin1Char
* JS_GetLatin1StringCharsAndLength(
3223 JSContext
* cx
, const JS::AutoRequireNoGC
& nogc
, JSString
* str
,
3225 MOZ_ASSERT(plength
);
3229 JSLinearString
* linear
= str
->ensureLinear(cx
);
3233 *plength
= linear
->length();
3234 return linear
->latin1Chars(nogc
);
3237 JS_PUBLIC_API
const char16_t
* JS_GetTwoByteStringCharsAndLength(
3238 JSContext
* cx
, const JS::AutoRequireNoGC
& nogc
, JSString
* str
,
3240 MOZ_ASSERT(plength
);
3244 JSLinearString
* linear
= str
->ensureLinear(cx
);
3248 *plength
= linear
->length();
3249 return linear
->twoByteChars(nogc
);
3252 JS_PUBLIC_API
const char16_t
* JS_GetTwoByteExternalStringChars(JSString
* str
) {
3253 return str
->asExternal().twoByteChars();
3256 JS_PUBLIC_API
bool JS_GetStringCharAt(JSContext
* cx
, JSString
* str
,
3257 size_t index
, char16_t
* res
) {
3262 JSLinearString
* linear
= str
->ensureLinear(cx
);
3267 *res
= linear
->latin1OrTwoByteChar(index
);
3271 JS_PUBLIC_API
bool JS_CopyStringChars(JSContext
* cx
,
3272 mozilla::Range
<char16_t
> dest
,
3278 JSLinearString
* linear
= str
->ensureLinear(cx
);
3283 MOZ_ASSERT(linear
->length() <= dest
.length());
3284 CopyChars(dest
.begin().get(), *linear
);
3288 extern JS_PUBLIC_API
JS::UniqueTwoByteChars
JS_CopyStringCharsZ(JSContext
* cx
,
3293 JSLinearString
* linear
= str
->ensureLinear(cx
);
3298 size_t len
= linear
->length();
3300 static_assert(JS::MaxStringLength
< UINT32_MAX
,
3301 "len + 1 must not overflow on 32-bit platforms");
3303 UniqueTwoByteChars
chars(cx
->pod_malloc
<char16_t
>(len
+ 1));
3308 CopyChars(chars
.get(), *linear
);
3314 extern JS_PUBLIC_API JSLinearString
* JS_EnsureLinearString(JSContext
* cx
,
3319 return str
->ensureLinear(cx
);
3322 JS_PUBLIC_API
bool JS_CompareStrings(JSContext
* cx
, JSString
* str1
,
3323 JSString
* str2
, int32_t* result
) {
3327 return CompareStrings(cx
, str1
, str2
, result
);
3330 JS_PUBLIC_API
bool JS_StringEqualsAscii(JSContext
* cx
, JSString
* str
,
3331 const char* asciiBytes
, bool* match
) {
3335 JSLinearString
* linearStr
= str
->ensureLinear(cx
);
3339 *match
= StringEqualsAscii(linearStr
, asciiBytes
);
3343 JS_PUBLIC_API
bool JS_StringEqualsAscii(JSContext
* cx
, JSString
* str
,
3344 const char* asciiBytes
, size_t length
,
3349 JSLinearString
* linearStr
= str
->ensureLinear(cx
);
3353 *match
= StringEqualsAscii(linearStr
, asciiBytes
, length
);
3357 JS_PUBLIC_API
bool JS_LinearStringEqualsAscii(JSLinearString
* str
,
3358 const char* asciiBytes
) {
3359 return StringEqualsAscii(str
, asciiBytes
);
3362 JS_PUBLIC_API
bool JS_LinearStringEqualsAscii(JSLinearString
* str
,
3363 const char* asciiBytes
,
3365 return StringEqualsAscii(str
, asciiBytes
, length
);
3368 JS_PUBLIC_API
size_t JS_PutEscapedLinearString(char* buffer
, size_t size
,
3369 JSLinearString
* str
,
3371 return PutEscapedString(buffer
, size
, str
, quote
);
3374 JS_PUBLIC_API
size_t JS_PutEscapedString(JSContext
* cx
, char* buffer
,
3375 size_t size
, JSString
* str
,
3378 JSLinearString
* linearStr
= str
->ensureLinear(cx
);
3382 return PutEscapedString(buffer
, size
, linearStr
, quote
);
3385 JS_PUBLIC_API JSString
* JS_NewDependentString(JSContext
* cx
, HandleString str
,
3386 size_t start
, size_t length
) {
3389 return NewDependentString(cx
, str
, start
, length
);
3392 JS_PUBLIC_API JSString
* JS_ConcatStrings(JSContext
* cx
, HandleString left
,
3393 HandleString right
) {
3396 return ConcatStrings
<CanGC
>(cx
, left
, right
);
3399 JS_PUBLIC_API
bool JS_DecodeBytes(JSContext
* cx
, const char* src
, size_t srclen
,
3400 char16_t
* dst
, size_t* dstlenp
) {
3409 size_t dstlen
= *dstlenp
;
3411 if (srclen
> dstlen
) {
3412 CopyAndInflateChars(dst
, src
, dstlen
);
3414 gc::AutoSuppressGC
suppress(cx
);
3415 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr,
3416 JSMSG_BUFFER_TOO_SMALL
);
3420 CopyAndInflateChars(dst
, src
, srclen
);
3425 JS_PUBLIC_API
JS::UniqueChars
JS_EncodeStringToASCII(JSContext
* cx
,
3430 return js::EncodeAscii(cx
, str
);
3433 JS_PUBLIC_API
JS::UniqueChars
JS_EncodeStringToLatin1(JSContext
* cx
,
3438 return js::EncodeLatin1(cx
, str
);
3441 JS_PUBLIC_API
JS::UniqueChars
JS_EncodeStringToUTF8(JSContext
* cx
,
3446 return StringToNewUTF8CharsZ(cx
, *str
);
3449 JS_PUBLIC_API
size_t JS_GetStringEncodingLength(JSContext
* cx
, JSString
* str
) {
3453 if (!str
->ensureLinear(cx
)) {
3456 return str
->length();
3459 JS_PUBLIC_API
bool JS_EncodeStringToBuffer(JSContext
* cx
, JSString
* str
,
3460 char* buffer
, size_t length
) {
3464 JSLinearString
* linear
= str
->ensureLinear(cx
);
3469 JS::AutoCheckCannotGC nogc
;
3470 size_t writeLength
= std::min(linear
->length(), length
);
3471 if (linear
->hasLatin1Chars()) {
3472 mozilla::PodCopy(reinterpret_cast<Latin1Char
*>(buffer
),
3473 linear
->latin1Chars(nogc
), writeLength
);
3475 const char16_t
* src
= linear
->twoByteChars(nogc
);
3476 for (size_t i
= 0; i
< writeLength
; i
++) {
3477 buffer
[i
] = char(src
[i
]);
3483 JS_PUBLIC_API
mozilla::Maybe
<std::tuple
<size_t, size_t>>
3484 JS_EncodeStringToUTF8BufferPartial(JSContext
* cx
, JSString
* str
,
3485 mozilla::Span
<char> buffer
) {
3488 JS::AutoCheckCannotGC nogc
;
3489 return str
->encodeUTF8Partial(nogc
, buffer
);
3492 JS_PUBLIC_API
JS::Symbol
* JS::NewSymbol(JSContext
* cx
,
3493 HandleString description
) {
3497 cx
->check(description
);
3500 return Symbol::new_(cx
, SymbolCode::UniqueSymbol
, description
);
3503 JS_PUBLIC_API
JS::Symbol
* JS::GetSymbolFor(JSContext
* cx
, HandleString key
) {
3508 return Symbol::for_(cx
, key
);
3511 JS_PUBLIC_API JSString
* JS::GetSymbolDescription(HandleSymbol symbol
) {
3512 return symbol
->description();
3515 JS_PUBLIC_API
JS::SymbolCode
JS::GetSymbolCode(Handle
<Symbol
*> symbol
) {
3516 return symbol
->code();
3519 JS_PUBLIC_API
JS::Symbol
* JS::GetWellKnownSymbol(JSContext
* cx
,
3520 JS::SymbolCode which
) {
3521 return cx
->wellKnownSymbols().get(which
);
3524 JS_PUBLIC_API
JS::PropertyKey
JS::GetWellKnownSymbolKey(JSContext
* cx
,
3525 JS::SymbolCode which
) {
3526 return PropertyKey::Symbol(cx
->wellKnownSymbols().get(which
));
3529 static bool AddPrefix(JSContext
* cx
, JS::Handle
<JS::PropertyKey
> id
,
3530 FunctionPrefixKind prefixKind
,
3531 JS::MutableHandle
<JS::PropertyKey
> out
) {
3532 JS::Rooted
<JSAtom
*> atom(cx
, js::IdToFunctionName(cx
, id
, prefixKind
));
3537 out
.set(JS::PropertyKey::NonIntAtom(atom
));
3541 JS_PUBLIC_API
bool JS::ToGetterId(JSContext
* cx
, JS::Handle
<JS::PropertyKey
> id
,
3542 JS::MutableHandle
<JS::PropertyKey
> getterId
) {
3543 return AddPrefix(cx
, id
, FunctionPrefixKind::Get
, getterId
);
3546 JS_PUBLIC_API
bool JS::ToSetterId(JSContext
* cx
, JS::Handle
<JS::PropertyKey
> id
,
3547 JS::MutableHandle
<JS::PropertyKey
> setterId
) {
3548 return AddPrefix(cx
, id
, FunctionPrefixKind::Set
, setterId
);
3552 static bool PropertySpecNameIsDigits(JSPropertySpec::Name name
) {
3553 if (name
.isSymbol()) {
3556 const char* s
= name
.string();
3561 if (*s
< '0' || *s
> '9') {
3569 JS_PUBLIC_API
bool JS::PropertySpecNameEqualsId(JSPropertySpec::Name name
,
3571 if (name
.isSymbol()) {
3572 return id
.isWellKnownSymbol(name
.symbol());
3575 MOZ_ASSERT(!PropertySpecNameIsDigits(name
));
3576 return id
.isAtom() && JS_LinearStringEqualsAscii(id
.toAtom(), name
.string());
3579 JS_PUBLIC_API
bool JS_Stringify(JSContext
* cx
, MutableHandleValue vp
,
3580 HandleObject replacer
, HandleValue space
,
3581 JSONWriteCallback callback
, void* data
) {
3584 cx
->check(replacer
, space
);
3585 StringBuffer
sb(cx
);
3586 if (!sb
.ensureTwoByteChars()) {
3589 if (!Stringify(cx
, vp
, replacer
, space
, sb
, StringifyBehavior::Normal
)) {
3592 if (sb
.empty() && !sb
.append(cx
->names().null
)) {
3595 return callback(sb
.rawTwoByteBegin(), sb
.length(), data
);
3598 JS_PUBLIC_API
bool JS::ToJSON(JSContext
* cx
, HandleValue value
,
3599 HandleObject replacer
, HandleValue space
,
3600 JSONWriteCallback callback
, void* data
) {
3603 cx
->check(replacer
, space
);
3604 StringBuffer
sb(cx
);
3605 if (!sb
.ensureTwoByteChars()) {
3608 RootedValue
v(cx
, value
);
3609 if (!Stringify(cx
, &v
, replacer
, space
, sb
, StringifyBehavior::Normal
)) {
3615 return callback(sb
.rawTwoByteBegin(), sb
.length(), data
);
3618 JS_PUBLIC_API
bool JS::ToJSONMaybeSafely(JSContext
* cx
, JS::HandleObject input
,
3619 JSONWriteCallback callback
,
3625 StringBuffer
sb(cx
);
3626 if (!sb
.ensureTwoByteChars()) {
3630 RootedValue
inputValue(cx
, ObjectValue(*input
));
3631 if (!Stringify(cx
, &inputValue
, nullptr, NullHandleValue
, sb
,
3632 StringifyBehavior::RestrictedSafe
))
3635 if (sb
.empty() && !sb
.append(cx
->names().null
)) {
3639 return callback(sb
.rawTwoByteBegin(), sb
.length(), data
);
3642 JS_PUBLIC_API
bool JS_ParseJSON(JSContext
* cx
, const char16_t
* chars
,
3643 uint32_t len
, MutableHandleValue vp
) {
3646 return ParseJSONWithReviver(cx
, mozilla::Range
<const char16_t
>(chars
, len
),
3647 NullHandleValue
, vp
);
3650 JS_PUBLIC_API
bool JS_ParseJSON(JSContext
* cx
, HandleString str
,
3651 MutableHandleValue vp
) {
3652 return JS_ParseJSONWithReviver(cx
, str
, NullHandleValue
, vp
);
3655 JS_PUBLIC_API
bool JS_ParseJSON(JSContext
* cx
, const Latin1Char
* chars
,
3656 uint32_t len
, MutableHandleValue vp
) {
3659 return ParseJSONWithReviver(cx
, mozilla::Range
<const Latin1Char
>(chars
, len
),
3660 NullHandleValue
, vp
);
3663 JS_PUBLIC_API
bool JS_ParseJSONWithReviver(JSContext
* cx
, const char16_t
* chars
,
3664 uint32_t len
, HandleValue reviver
,
3665 MutableHandleValue vp
) {
3668 return ParseJSONWithReviver(cx
, mozilla::Range
<const char16_t
>(chars
, len
),
3672 JS_PUBLIC_API
bool JS_ParseJSONWithReviver(JSContext
* cx
, HandleString str
,
3673 HandleValue reviver
,
3674 MutableHandleValue vp
) {
3679 AutoStableStringChars
stableChars(cx
);
3680 if (!stableChars
.init(cx
, str
)) {
3684 return stableChars
.isLatin1()
3685 ? ParseJSONWithReviver(cx
, stableChars
.latin1Range(), reviver
, vp
)
3686 : ParseJSONWithReviver(cx
, stableChars
.twoByteRange(), reviver
,
3690 /************************************************************************/
3692 JS_PUBLIC_API
void JS_ReportErrorASCII(JSContext
* cx
, const char* format
, ...) {
3696 va_start(ap
, format
);
3697 ReportErrorVA(cx
, IsWarning::No
, format
, ArgumentsAreASCII
, ap
);
3701 JS_PUBLIC_API
void JS_ReportErrorLatin1(JSContext
* cx
, const char* format
,
3706 va_start(ap
, format
);
3707 ReportErrorVA(cx
, IsWarning::No
, format
, ArgumentsAreLatin1
, ap
);
3711 JS_PUBLIC_API
void JS_ReportErrorUTF8(JSContext
* cx
, const char* format
, ...) {
3715 va_start(ap
, format
);
3716 ReportErrorVA(cx
, IsWarning::No
, format
, ArgumentsAreUTF8
, ap
);
3720 JS_PUBLIC_API
void JS_ReportErrorNumberASCII(JSContext
* cx
,
3721 JSErrorCallback errorCallback
,
3723 const unsigned errorNumber
, ...) {
3725 va_start(ap
, errorNumber
);
3726 JS_ReportErrorNumberASCIIVA(cx
, errorCallback
, userRef
, errorNumber
, ap
);
3730 JS_PUBLIC_API
void JS_ReportErrorNumberASCIIVA(JSContext
* cx
,
3731 JSErrorCallback errorCallback
,
3733 const unsigned errorNumber
,
3736 ReportErrorNumberVA(cx
, IsWarning::No
, errorCallback
, userRef
, errorNumber
,
3737 ArgumentsAreASCII
, ap
);
3740 JS_PUBLIC_API
void JS_ReportErrorNumberLatin1(JSContext
* cx
,
3741 JSErrorCallback errorCallback
,
3743 const unsigned errorNumber
, ...) {
3745 va_start(ap
, errorNumber
);
3746 JS_ReportErrorNumberLatin1VA(cx
, errorCallback
, userRef
, errorNumber
, ap
);
3750 JS_PUBLIC_API
void JS_ReportErrorNumberLatin1VA(JSContext
* cx
,
3751 JSErrorCallback errorCallback
,
3753 const unsigned errorNumber
,
3756 ReportErrorNumberVA(cx
, IsWarning::No
, errorCallback
, userRef
, errorNumber
,
3757 ArgumentsAreLatin1
, ap
);
3760 JS_PUBLIC_API
void JS_ReportErrorNumberUTF8(JSContext
* cx
,
3761 JSErrorCallback errorCallback
,
3763 const unsigned errorNumber
, ...) {
3765 va_start(ap
, errorNumber
);
3766 JS_ReportErrorNumberUTF8VA(cx
, errorCallback
, userRef
, errorNumber
, ap
);
3770 JS_PUBLIC_API
void JS_ReportErrorNumberUTF8VA(JSContext
* cx
,
3771 JSErrorCallback errorCallback
,
3773 const unsigned errorNumber
,
3776 ReportErrorNumberVA(cx
, IsWarning::No
, errorCallback
, userRef
, errorNumber
,
3777 ArgumentsAreUTF8
, ap
);
3780 JS_PUBLIC_API
void JS_ReportErrorNumberUTF8Array(JSContext
* cx
,
3781 JSErrorCallback errorCallback
,
3783 const unsigned errorNumber
,
3784 const char** args
) {
3786 ReportErrorNumberUTF8Array(cx
, IsWarning::No
, errorCallback
, userRef
,
3790 JS_PUBLIC_API
void JS_ReportErrorNumberUC(JSContext
* cx
,
3791 JSErrorCallback errorCallback
,
3793 const unsigned errorNumber
, ...) {
3797 va_start(ap
, errorNumber
);
3798 ReportErrorNumberVA(cx
, IsWarning::No
, errorCallback
, userRef
, errorNumber
,
3799 ArgumentsAreUnicode
, ap
);
3803 JS_PUBLIC_API
void JS_ReportErrorNumberUCArray(JSContext
* cx
,
3804 JSErrorCallback errorCallback
,
3806 const unsigned errorNumber
,
3807 const char16_t
** args
) {
3809 ReportErrorNumberUCArray(cx
, IsWarning::No
, errorCallback
, userRef
,
3813 JS_PUBLIC_API
void JS_ReportOutOfMemory(JSContext
* cx
) {
3814 ReportOutOfMemory(cx
);
3817 JS_PUBLIC_API
void JS_ReportAllocationOverflow(JSContext
* cx
) {
3818 ReportAllocationOverflow(cx
);
3821 JS_PUBLIC_API
bool JS_ExpandErrorArgumentsASCII(JSContext
* cx
,
3822 JSErrorCallback errorCallback
,
3823 const unsigned errorNumber
,
3824 JSErrorReport
* reportp
, ...) {
3829 va_start(ap
, reportp
);
3830 AutoReportFrontendContext
fc(cx
);
3831 ok
= ExpandErrorArgumentsVA(&fc
, errorCallback
, nullptr, errorNumber
,
3832 ArgumentsAreASCII
, reportp
, ap
);
3836 /************************************************************************/
3838 JS_PUBLIC_API
bool JS_SetDefaultLocale(JSRuntime
* rt
, const char* locale
) {
3840 return rt
->setDefaultLocale(locale
);
3843 JS_PUBLIC_API UniqueChars
JS_GetDefaultLocale(JSContext
* cx
) {
3845 if (const char* locale
= cx
->runtime()->getDefaultLocale()) {
3846 return DuplicateString(cx
, locale
);
3852 JS_PUBLIC_API
void JS_ResetDefaultLocale(JSRuntime
* rt
) {
3854 rt
->resetDefaultLocale();
3857 JS_PUBLIC_API
void JS_SetLocaleCallbacks(JSRuntime
* rt
,
3858 const JSLocaleCallbacks
* callbacks
) {
3860 rt
->localeCallbacks
= callbacks
;
3863 JS_PUBLIC_API
const JSLocaleCallbacks
* JS_GetLocaleCallbacks(JSRuntime
* rt
) {
3864 /* This function can be called by a finalizer. */
3865 return rt
->localeCallbacks
;
3868 /************************************************************************/
3870 JS_PUBLIC_API
bool JS_IsExceptionPending(JSContext
* cx
) {
3871 /* This function can be called by a finalizer. */
3872 return (bool)cx
->isExceptionPending();
3875 JS_PUBLIC_API
bool JS_IsThrowingOutOfMemory(JSContext
* cx
) {
3876 return cx
->isThrowingOutOfMemory();
3879 JS_PUBLIC_API
bool JS_GetPendingException(JSContext
* cx
,
3880 MutableHandleValue vp
) {
3883 if (!cx
->isExceptionPending()) {
3886 return cx
->getPendingException(vp
);
3889 JS_PUBLIC_API
void JS_SetPendingException(JSContext
* cx
, HandleValue value
,
3890 JS::ExceptionStackBehavior behavior
) {
3893 // We don't check the compartment of `value` here, because we're not
3894 // doing anything with it other than storing it, and stored
3895 // exception values can be in an abitrary compartment.
3897 if (behavior
== JS::ExceptionStackBehavior::Capture
) {
3898 cx
->setPendingException(value
, ShouldCaptureStack::Always
);
3900 cx
->setPendingException(value
, nullptr);
3904 JS_PUBLIC_API
void JS_ClearPendingException(JSContext
* cx
) {
3906 cx
->clearPendingException();
3909 JS::AutoSaveExceptionState::AutoSaveExceptionState(JSContext
* cx
)
3910 : context(cx
), status(cx
->status
), exceptionValue(cx
), exceptionStack(cx
) {
3913 if (IsCatchableExceptionStatus(status
)) {
3914 exceptionValue
= cx
->unwrappedException();
3915 exceptionStack
= cx
->unwrappedExceptionStack();
3917 cx
->clearPendingException();
3920 void JS::AutoSaveExceptionState::drop() {
3921 status
= JS::ExceptionStatus::None
;
3922 exceptionValue
.setUndefined();
3923 exceptionStack
= nullptr;
3926 void JS::AutoSaveExceptionState::restore() {
3927 context
->status
= status
;
3928 context
->unwrappedException() = exceptionValue
;
3929 if (exceptionStack
) {
3930 context
->unwrappedExceptionStack() = &exceptionStack
->as
<SavedFrame
>();
3935 JS::AutoSaveExceptionState::~AutoSaveExceptionState() {
3936 // NOTE: An interrupt/uncatchable exception or a debugger-forced-return may be
3937 // clobbered here by the saved exception. If that is not desired, this
3938 // state should be dropped before the destructor fires.
3939 if (!context
->isExceptionPending()) {
3940 if (status
!= JS::ExceptionStatus::None
) {
3941 context
->status
= status
;
3943 if (IsCatchableExceptionStatus(status
)) {
3944 context
->unwrappedException() = exceptionValue
;
3945 if (exceptionStack
) {
3946 context
->unwrappedExceptionStack() = &exceptionStack
->as
<SavedFrame
>();
3952 JS_PUBLIC_API JSErrorReport
* JS_ErrorFromException(JSContext
* cx
,
3957 return ErrorFromException(cx
, obj
);
3960 void JSErrorReport::initBorrowedLinebuf(const char16_t
* linebufArg
,
3961 size_t linebufLengthArg
,
3962 size_t tokenOffsetArg
) {
3963 MOZ_ASSERT(linebufArg
);
3964 MOZ_ASSERT(tokenOffsetArg
<= linebufLengthArg
);
3965 MOZ_ASSERT(linebufArg
[linebufLengthArg
] == '\0');
3967 linebuf_
= linebufArg
;
3968 linebufLength_
= linebufLengthArg
;
3969 tokenOffset_
= tokenOffsetArg
;
3972 void JSErrorReport::freeLinebuf() {
3973 if (ownsLinebuf_
&& linebuf_
) {
3974 js_free((void*)linebuf_
);
3975 ownsLinebuf_
= false;
3980 JSString
* JSErrorBase::newMessageString(JSContext
* cx
) {
3982 return cx
->runtime()->emptyString
;
3985 return JS_NewStringCopyUTF8Z(cx
, message_
);
3988 void JSErrorBase::freeMessage() {
3990 js_free((void*)message_
.get());
3991 ownsMessage_
= false;
3993 message_
= JS::ConstUTF8CharsZ();
3996 JSErrorNotes::JSErrorNotes() = default;
3998 JSErrorNotes::~JSErrorNotes() = default;
4000 static UniquePtr
<JSErrorNotes::Note
> CreateErrorNoteVA(
4001 FrontendContext
* fc
, const char* filename
, unsigned sourceId
,
4002 uint32_t lineno
, JS::ColumnNumberOneOrigin column
,
4003 JSErrorCallback errorCallback
, void* userRef
, const unsigned errorNumber
,
4004 ErrorArgumentsType argumentsType
, va_list ap
) {
4005 auto note
= MakeUnique
<JSErrorNotes::Note
>();
4007 ReportOutOfMemory(fc
);
4011 note
->errorNumber
= errorNumber
;
4012 note
->filename
= JS::ConstUTF8CharsZ(filename
);
4013 note
->sourceId
= sourceId
;
4014 note
->lineno
= lineno
;
4015 note
->column
= column
;
4017 if (!ExpandErrorArgumentsVA(fc
, errorCallback
, userRef
, errorNumber
, nullptr,
4018 argumentsType
, note
.get(), ap
)) {
4025 bool JSErrorNotes::addNoteVA(FrontendContext
* fc
, const char* filename
,
4026 unsigned sourceId
, uint32_t lineno
,
4027 JS::ColumnNumberOneOrigin column
,
4028 JSErrorCallback errorCallback
, void* userRef
,
4029 const unsigned errorNumber
,
4030 ErrorArgumentsType argumentsType
, va_list ap
) {
4032 CreateErrorNoteVA(fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
4033 userRef
, errorNumber
, argumentsType
, ap
);
4038 if (!notes_
.append(std::move(note
))) {
4039 ReportOutOfMemory(fc
);
4045 bool JSErrorNotes::addNoteASCII(JSContext
* cx
, const char* filename
,
4046 unsigned sourceId
, uint32_t lineno
,
4047 JS::ColumnNumberOneOrigin column
,
4048 JSErrorCallback errorCallback
, void* userRef
,
4049 const unsigned errorNumber
, ...) {
4050 AutoReportFrontendContext
fc(cx
);
4052 va_start(ap
, errorNumber
);
4053 bool ok
= addNoteVA(&fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
4054 userRef
, errorNumber
, ArgumentsAreASCII
, ap
);
4059 bool JSErrorNotes::addNoteASCII(FrontendContext
* fc
, const char* filename
,
4060 unsigned sourceId
, uint32_t lineno
,
4061 JS::ColumnNumberOneOrigin column
,
4062 JSErrorCallback errorCallback
, void* userRef
,
4063 const unsigned errorNumber
, ...) {
4065 va_start(ap
, errorNumber
);
4066 bool ok
= addNoteVA(fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
4067 userRef
, errorNumber
, ArgumentsAreASCII
, ap
);
4072 bool JSErrorNotes::addNoteLatin1(JSContext
* cx
, const char* filename
,
4073 unsigned sourceId
, uint32_t lineno
,
4074 JS::ColumnNumberOneOrigin column
,
4075 JSErrorCallback errorCallback
, void* userRef
,
4076 const unsigned errorNumber
, ...) {
4077 AutoReportFrontendContext
fc(cx
);
4079 va_start(ap
, errorNumber
);
4080 bool ok
= addNoteVA(&fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
4081 userRef
, errorNumber
, ArgumentsAreLatin1
, ap
);
4086 bool JSErrorNotes::addNoteLatin1(FrontendContext
* fc
, const char* filename
,
4087 unsigned sourceId
, uint32_t lineno
,
4088 JS::ColumnNumberOneOrigin column
,
4089 JSErrorCallback errorCallback
, void* userRef
,
4090 const unsigned errorNumber
, ...) {
4092 va_start(ap
, errorNumber
);
4093 bool ok
= addNoteVA(fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
4094 userRef
, errorNumber
, ArgumentsAreLatin1
, ap
);
4099 bool JSErrorNotes::addNoteUTF8(JSContext
* cx
, const char* filename
,
4100 unsigned sourceId
, uint32_t lineno
,
4101 JS::ColumnNumberOneOrigin column
,
4102 JSErrorCallback errorCallback
, void* userRef
,
4103 const unsigned errorNumber
, ...) {
4104 AutoReportFrontendContext
fc(cx
);
4106 va_start(ap
, errorNumber
);
4107 bool ok
= addNoteVA(&fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
4108 userRef
, errorNumber
, ArgumentsAreUTF8
, ap
);
4113 bool JSErrorNotes::addNoteUTF8(FrontendContext
* fc
, const char* filename
,
4114 unsigned sourceId
, uint32_t lineno
,
4115 JS::ColumnNumberOneOrigin column
,
4116 JSErrorCallback errorCallback
, void* userRef
,
4117 const unsigned errorNumber
, ...) {
4119 va_start(ap
, errorNumber
);
4120 bool ok
= addNoteVA(fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
4121 userRef
, errorNumber
, ArgumentsAreUTF8
, ap
);
4126 JS_PUBLIC_API
size_t JSErrorNotes::length() { return notes_
.length(); }
4128 UniquePtr
<JSErrorNotes
> JSErrorNotes::copy(JSContext
* cx
) {
4129 auto copiedNotes
= MakeUnique
<JSErrorNotes
>();
4131 ReportOutOfMemory(cx
);
4135 for (auto&& note
: *this) {
4136 UniquePtr
<JSErrorNotes::Note
> copied
= CopyErrorNote(cx
, note
.get());
4141 if (!copiedNotes
->notes_
.append(std::move(copied
))) {
4149 JS_PUBLIC_API
JSErrorNotes::iterator
JSErrorNotes::begin() {
4150 return iterator(notes_
.begin());
4153 JS_PUBLIC_API
JSErrorNotes::iterator
JSErrorNotes::end() {
4154 return iterator(notes_
.end());
4157 extern MOZ_NEVER_INLINE JS_PUBLIC_API
void JS_AbortIfWrongThread(
4159 if (!CurrentThreadCanAccessRuntime(cx
->runtime())) {
4162 if (TlsContext
.get() != cx
) {
4168 JS_PUBLIC_API
void JS_GetGCZealBits(JSContext
* cx
, uint32_t* zealBits
,
4169 uint32_t* frequency
,
4170 uint32_t* nextScheduled
) {
4171 cx
->runtime()->gc
.getZealBits(zealBits
, frequency
, nextScheduled
);
4174 JS_PUBLIC_API
void JS_SetGCZeal(JSContext
* cx
, uint8_t zeal
,
4175 uint32_t frequency
) {
4176 cx
->runtime()->gc
.setZeal(zeal
, frequency
);
4179 JS_PUBLIC_API
void JS_UnsetGCZeal(JSContext
* cx
, uint8_t zeal
) {
4180 cx
->runtime()->gc
.unsetZeal(zeal
);
4183 JS_PUBLIC_API
void JS_ScheduleGC(JSContext
* cx
, uint32_t count
) {
4184 cx
->runtime()->gc
.setNextScheduled(count
);
4188 JS_PUBLIC_API
void JS_SetParallelParsingEnabled(JSContext
* cx
, bool enabled
) {
4189 cx
->runtime()->setParallelParsingEnabled(enabled
);
4192 JS_PUBLIC_API
void JS_SetOffthreadIonCompilationEnabled(JSContext
* cx
,
4194 cx
->runtime()->setOffthreadIonCompilationEnabled(enabled
);
4197 JS_PUBLIC_API
void JS_SetGlobalJitCompilerOption(JSContext
* cx
,
4198 JSJitCompilerOption opt
,
4200 JSRuntime
* rt
= cx
->runtime();
4202 #ifdef ENABLE_PORTABLE_BASELINE_INTERP
4203 case JSJITCOMPILER_PORTABLE_BASELINE_ENABLE
:
4205 jit::JitOptions
.portableBaselineInterpreter
= true;
4206 } else if (value
== 0) {
4207 jit::JitOptions
.portableBaselineInterpreter
= false;
4210 case JSJITCOMPILER_PORTABLE_BASELINE_WARMUP_THRESHOLD
:
4211 if (value
== uint32_t(-1)) {
4212 jit::DefaultJitOptions defaultValues
;
4213 value
= defaultValues
.portableBaselineInterpreterWarmUpThreshold
;
4215 jit::JitOptions
.portableBaselineInterpreterWarmUpThreshold
= value
;
4218 case JSJITCOMPILER_BASELINE_INTERPRETER_WARMUP_TRIGGER
:
4219 if (value
== uint32_t(-1)) {
4220 jit::DefaultJitOptions defaultValues
;
4221 value
= defaultValues
.baselineInterpreterWarmUpThreshold
;
4223 jit::JitOptions
.baselineInterpreterWarmUpThreshold
= value
;
4225 case JSJITCOMPILER_BASELINE_WARMUP_TRIGGER
:
4226 if (value
== uint32_t(-1)) {
4227 jit::DefaultJitOptions defaultValues
;
4228 value
= defaultValues
.baselineJitWarmUpThreshold
;
4230 jit::JitOptions
.baselineJitWarmUpThreshold
= value
;
4232 case JSJITCOMPILER_IC_FORCE_MEGAMORPHIC
:
4233 jit::JitOptions
.forceMegamorphicICs
= !!value
;
4235 case JSJITCOMPILER_ION_NORMAL_WARMUP_TRIGGER
:
4236 if (value
== uint32_t(-1)) {
4237 jit::JitOptions
.resetNormalIonWarmUpThreshold();
4240 jit::JitOptions
.setNormalIonWarmUpThreshold(value
);
4242 case JSJITCOMPILER_ION_GVN_ENABLE
:
4244 jit::JitOptions
.enableGvn(false);
4245 JitSpew(js::jit::JitSpew_IonScripts
, "Disable ion's GVN");
4247 jit::JitOptions
.enableGvn(true);
4248 JitSpew(js::jit::JitSpew_IonScripts
, "Enable ion's GVN");
4251 case JSJITCOMPILER_ION_FORCE_IC
:
4253 jit::JitOptions
.forceInlineCaches
= false;
4254 JitSpew(js::jit::JitSpew_IonScripts
,
4255 "Ion: Enable non-IC optimizations.");
4257 jit::JitOptions
.forceInlineCaches
= true;
4258 JitSpew(js::jit::JitSpew_IonScripts
,
4259 "Ion: Disable non-IC optimizations.");
4262 case JSJITCOMPILER_ION_CHECK_RANGE_ANALYSIS
:
4264 jit::JitOptions
.checkRangeAnalysis
= false;
4265 JitSpew(js::jit::JitSpew_IonScripts
,
4266 "Ion: Enable range analysis checks.");
4268 jit::JitOptions
.checkRangeAnalysis
= true;
4269 JitSpew(js::jit::JitSpew_IonScripts
,
4270 "Ion: Disable range analysis checks.");
4273 case JSJITCOMPILER_ION_ENABLE
:
4275 jit::JitOptions
.ion
= true;
4276 JitSpew(js::jit::JitSpew_IonScripts
, "Enable ion");
4277 } else if (value
== 0) {
4278 jit::JitOptions
.ion
= false;
4279 JitSpew(js::jit::JitSpew_IonScripts
, "Disable ion");
4282 case JSJITCOMPILER_JIT_TRUSTEDPRINCIPALS_ENABLE
:
4284 jit::JitOptions
.jitForTrustedPrincipals
= true;
4285 JitSpew(js::jit::JitSpew_IonScripts
,
4286 "Enable ion and baselinejit for trusted principals");
4287 } else if (value
== 0) {
4288 jit::JitOptions
.jitForTrustedPrincipals
= false;
4289 JitSpew(js::jit::JitSpew_IonScripts
,
4290 "Disable ion and baselinejit for trusted principals");
4293 case JSJITCOMPILER_ION_FREQUENT_BAILOUT_THRESHOLD
:
4294 if (value
== uint32_t(-1)) {
4295 jit::DefaultJitOptions defaultValues
;
4296 value
= defaultValues
.frequentBailoutThreshold
;
4298 jit::JitOptions
.frequentBailoutThreshold
= value
;
4300 case JSJITCOMPILER_BASE_REG_FOR_LOCALS
:
4302 jit::JitOptions
.baseRegForLocals
= jit::BaseRegForAddress::SP
;
4303 } else if (value
== 1) {
4304 jit::JitOptions
.baseRegForLocals
= jit::BaseRegForAddress::FP
;
4306 jit::DefaultJitOptions defaultValues
;
4307 jit::JitOptions
.baseRegForLocals
= defaultValues
.baseRegForLocals
;
4310 case JSJITCOMPILER_BASELINE_INTERPRETER_ENABLE
:
4312 jit::JitOptions
.baselineInterpreter
= true;
4313 } else if (value
== 0) {
4314 ReleaseAllJITCode(rt
->gcContext());
4315 jit::JitOptions
.baselineInterpreter
= false;
4318 case JSJITCOMPILER_BASELINE_ENABLE
:
4320 jit::JitOptions
.baselineJit
= true;
4321 ReleaseAllJITCode(rt
->gcContext());
4322 JitSpew(js::jit::JitSpew_BaselineScripts
, "Enable baseline");
4323 } else if (value
== 0) {
4324 jit::JitOptions
.baselineJit
= false;
4325 ReleaseAllJITCode(rt
->gcContext());
4326 JitSpew(js::jit::JitSpew_BaselineScripts
, "Disable baseline");
4329 case JSJITCOMPILER_NATIVE_REGEXP_ENABLE
:
4330 jit::JitOptions
.nativeRegExp
= !!value
;
4332 case JSJITCOMPILER_JIT_HINTS_ENABLE
:
4333 jit::JitOptions
.disableJitHints
= !value
;
4335 case JSJITCOMPILER_OFFTHREAD_COMPILATION_ENABLE
:
4337 rt
->setOffthreadIonCompilationEnabled(true);
4338 JitSpew(js::jit::JitSpew_IonScripts
, "Enable offthread compilation");
4339 } else if (value
== 0) {
4340 rt
->setOffthreadIonCompilationEnabled(false);
4341 JitSpew(js::jit::JitSpew_IonScripts
, "Disable offthread compilation");
4344 case JSJITCOMPILER_INLINING_BYTECODE_MAX_LENGTH
:
4345 if (value
== uint32_t(-1)) {
4346 jit::DefaultJitOptions defaultValues
;
4347 value
= defaultValues
.smallFunctionMaxBytecodeLength
;
4349 jit::JitOptions
.smallFunctionMaxBytecodeLength
= value
;
4351 case JSJITCOMPILER_JUMP_THRESHOLD
:
4352 if (value
== uint32_t(-1)) {
4353 jit::DefaultJitOptions defaultValues
;
4354 value
= defaultValues
.jumpThreshold
;
4356 jit::JitOptions
.jumpThreshold
= value
;
4358 case JSJITCOMPILER_SPECTRE_INDEX_MASKING
:
4359 jit::JitOptions
.spectreIndexMasking
= !!value
;
4361 case JSJITCOMPILER_SPECTRE_OBJECT_MITIGATIONS
:
4362 jit::JitOptions
.spectreObjectMitigations
= !!value
;
4364 case JSJITCOMPILER_SPECTRE_STRING_MITIGATIONS
:
4365 jit::JitOptions
.spectreStringMitigations
= !!value
;
4367 case JSJITCOMPILER_SPECTRE_VALUE_MASKING
:
4368 jit::JitOptions
.spectreValueMasking
= !!value
;
4370 case JSJITCOMPILER_SPECTRE_JIT_TO_CXX_CALLS
:
4371 jit::JitOptions
.spectreJitToCxxCalls
= !!value
;
4373 case JSJITCOMPILER_WRITE_PROTECT_CODE
:
4374 jit::JitOptions
.maybeSetWriteProtectCode(!!value
);
4376 case JSJITCOMPILER_WATCHTOWER_MEGAMORPHIC
:
4377 jit::JitOptions
.enableWatchtowerMegamorphic
= !!value
;
4379 case JSJITCOMPILER_WASM_FOLD_OFFSETS
:
4380 jit::JitOptions
.wasmFoldOffsets
= !!value
;
4382 case JSJITCOMPILER_WASM_DELAY_TIER2
:
4383 jit::JitOptions
.wasmDelayTier2
= !!value
;
4385 case JSJITCOMPILER_WASM_JIT_BASELINE
:
4386 JS::ContextOptionsRef(cx
).setWasmBaseline(!!value
);
4388 case JSJITCOMPILER_WASM_JIT_OPTIMIZING
:
4389 JS::ContextOptionsRef(cx
).setWasmIon(!!value
);
4392 case JSJITCOMPILER_FULL_DEBUG_CHECKS
:
4393 jit::JitOptions
.fullDebugChecks
= !!value
;
4401 JS_PUBLIC_API
bool JS_GetGlobalJitCompilerOption(JSContext
* cx
,
4402 JSJitCompilerOption opt
,
4403 uint32_t* valueOut
) {
4404 MOZ_ASSERT(valueOut
);
4405 #ifndef JS_CODEGEN_NONE
4406 JSRuntime
* rt
= cx
->runtime();
4408 case JSJITCOMPILER_BASELINE_INTERPRETER_WARMUP_TRIGGER
:
4409 *valueOut
= jit::JitOptions
.baselineInterpreterWarmUpThreshold
;
4411 case JSJITCOMPILER_BASELINE_WARMUP_TRIGGER
:
4412 *valueOut
= jit::JitOptions
.baselineJitWarmUpThreshold
;
4414 case JSJITCOMPILER_IC_FORCE_MEGAMORPHIC
:
4415 *valueOut
= jit::JitOptions
.forceMegamorphicICs
;
4417 case JSJITCOMPILER_ION_NORMAL_WARMUP_TRIGGER
:
4418 *valueOut
= jit::JitOptions
.normalIonWarmUpThreshold
;
4420 case JSJITCOMPILER_ION_FORCE_IC
:
4421 *valueOut
= jit::JitOptions
.forceInlineCaches
;
4423 case JSJITCOMPILER_ION_CHECK_RANGE_ANALYSIS
:
4424 *valueOut
= jit::JitOptions
.checkRangeAnalysis
;
4426 case JSJITCOMPILER_ION_ENABLE
:
4427 *valueOut
= jit::JitOptions
.ion
;
4429 case JSJITCOMPILER_ION_FREQUENT_BAILOUT_THRESHOLD
:
4430 *valueOut
= jit::JitOptions
.frequentBailoutThreshold
;
4432 case JSJITCOMPILER_BASE_REG_FOR_LOCALS
:
4433 *valueOut
= uint32_t(jit::JitOptions
.baseRegForLocals
);
4435 case JSJITCOMPILER_INLINING_BYTECODE_MAX_LENGTH
:
4436 *valueOut
= jit::JitOptions
.smallFunctionMaxBytecodeLength
;
4438 case JSJITCOMPILER_BASELINE_INTERPRETER_ENABLE
:
4439 *valueOut
= jit::JitOptions
.baselineInterpreter
;
4441 case JSJITCOMPILER_BASELINE_ENABLE
:
4442 *valueOut
= jit::JitOptions
.baselineJit
;
4444 case JSJITCOMPILER_NATIVE_REGEXP_ENABLE
:
4445 *valueOut
= jit::JitOptions
.nativeRegExp
;
4447 case JSJITCOMPILER_OFFTHREAD_COMPILATION_ENABLE
:
4448 *valueOut
= rt
->canUseOffthreadIonCompilation();
4450 case JSJITCOMPILER_SPECTRE_INDEX_MASKING
:
4451 *valueOut
= jit::JitOptions
.spectreIndexMasking
? 1 : 0;
4453 case JSJITCOMPILER_SPECTRE_OBJECT_MITIGATIONS
:
4454 *valueOut
= jit::JitOptions
.spectreObjectMitigations
? 1 : 0;
4456 case JSJITCOMPILER_SPECTRE_STRING_MITIGATIONS
:
4457 *valueOut
= jit::JitOptions
.spectreStringMitigations
? 1 : 0;
4459 case JSJITCOMPILER_SPECTRE_VALUE_MASKING
:
4460 *valueOut
= jit::JitOptions
.spectreValueMasking
? 1 : 0;
4462 case JSJITCOMPILER_SPECTRE_JIT_TO_CXX_CALLS
:
4463 *valueOut
= jit::JitOptions
.spectreJitToCxxCalls
? 1 : 0;
4465 case JSJITCOMPILER_WRITE_PROTECT_CODE
:
4466 *valueOut
= jit::JitOptions
.writeProtectCode
? 1 : 0;
4468 case JSJITCOMPILER_WATCHTOWER_MEGAMORPHIC
:
4469 *valueOut
= jit::JitOptions
.enableWatchtowerMegamorphic
? 1 : 0;
4471 case JSJITCOMPILER_WASM_FOLD_OFFSETS
:
4472 *valueOut
= jit::JitOptions
.wasmFoldOffsets
? 1 : 0;
4474 case JSJITCOMPILER_WASM_JIT_BASELINE
:
4475 *valueOut
= JS::ContextOptionsRef(cx
).wasmBaseline() ? 1 : 0;
4477 case JSJITCOMPILER_WASM_JIT_OPTIMIZING
:
4478 *valueOut
= JS::ContextOptionsRef(cx
).wasmIon() ? 1 : 0;
4481 case JSJITCOMPILER_FULL_DEBUG_CHECKS
:
4482 *valueOut
= jit::JitOptions
.fullDebugChecks
? 1 : 0;
4490 # ifdef ENABLE_PORTABLE_BASELINE_INTERP
4491 case JSJITCOMPILER_PORTABLE_BASELINE_ENABLE
:
4492 *valueOut
= jit::JitOptions
.portableBaselineInterpreter
;
4494 case JSJITCOMPILER_PORTABLE_BASELINE_WARMUP_THRESHOLD
:
4495 *valueOut
= jit::JitOptions
.portableBaselineInterpreterWarmUpThreshold
;
4505 JS_PUBLIC_API
void JS::DisableSpectreMitigationsAfterInit() {
4506 // This is used to turn off Spectre mitigations in pre-allocated child
4507 // processes used for isolated web content. Assert there's a single runtime
4508 // and cancel off-thread compilations, to ensure we're not racing with any
4510 JSContext
* cx
= TlsContext
.get();
4511 MOZ_RELEASE_ASSERT(cx
);
4512 MOZ_RELEASE_ASSERT(JSRuntime::hasSingleLiveRuntime());
4513 MOZ_RELEASE_ASSERT(cx
->runtime()->wasmInstances
.lock()->empty());
4515 CancelOffThreadIonCompile(cx
->runtime());
4517 jit::JitOptions
.spectreIndexMasking
= false;
4518 jit::JitOptions
.spectreObjectMitigations
= false;
4519 jit::JitOptions
.spectreStringMitigations
= false;
4520 jit::JitOptions
.spectreValueMasking
= false;
4521 jit::JitOptions
.spectreJitToCxxCalls
= false;
4524 /************************************************************************/
4526 #if !defined(STATIC_EXPORTABLE_JS_API) && !defined(STATIC_JS_API) && \
4527 defined(XP_WIN) && (defined(MOZ_MEMORY) || !defined(JS_STANDALONE))
4529 # include "util/WindowsWrapper.h"
4532 * Initialization routine for the JS DLL.
4534 BOOL WINAPI
DllMain(HINSTANCE hDLL
, DWORD dwReason
, LPVOID lpReserved
) {
4540 JS_PUBLIC_API
bool JS_IndexToId(JSContext
* cx
, uint32_t index
,
4541 MutableHandleId id
) {
4542 return IndexToId(cx
, index
, id
);
4545 JS_PUBLIC_API
bool JS_CharsToId(JSContext
* cx
, JS::TwoByteChars chars
,
4546 MutableHandleId idp
) {
4547 Rooted
<JSAtom
*> atom(cx
,
4548 AtomizeChars(cx
, chars
.begin().get(), chars
.length()));
4553 MOZ_ASSERT(!atom
->isIndex(), "API misuse: |chars| must not encode an index");
4555 idp
.set(AtomToId(atom
));
4559 JS_PUBLIC_API
bool JS_IsIdentifier(JSContext
* cx
, HandleString str
,
4560 bool* isIdentifier
) {
4563 JSLinearString
* linearStr
= str
->ensureLinear(cx
);
4568 *isIdentifier
= IsIdentifier(linearStr
);
4572 JS_PUBLIC_API
bool JS_IsIdentifier(const char16_t
* chars
, size_t length
) {
4573 return IsIdentifier(chars
, length
);
4578 void AutoFilename::reset() {
4583 if (filename_
.is
<const char*>()) {
4584 filename_
.as
<const char*>() = nullptr;
4586 filename_
.as
<UniqueChars
>().reset();
4590 void AutoFilename::setScriptSource(js::ScriptSource
* p
) {
4596 setUnowned(p
->filename());
4600 void AutoFilename::setUnowned(const char* filename
) {
4602 filename_
.as
<const char*>() = filename
? filename
: "";
4605 void AutoFilename::setOwned(UniqueChars
&& filename
) {
4607 filename_
= AsVariant(std::move(filename
));
4610 const char* AutoFilename::get() const {
4611 if (filename_
.is
<const char*>()) {
4612 return filename_
.as
<const char*>();
4614 return filename_
.as
<UniqueChars
>().get();
4617 JS_PUBLIC_API
bool DescribeScriptedCaller(JSContext
* cx
, AutoFilename
* filename
,
4619 JS::ColumnNumberOneOrigin
* column
) {
4627 *column
= JS::ColumnNumberOneOrigin();
4630 if (!cx
->compartment()) {
4634 NonBuiltinFrameIter
i(cx
, cx
->realm()->principals());
4639 // If the caller is hidden, the embedding wants us to return false here so
4640 // that it can check its own stack (see HideScriptedCaller).
4641 if (i
.activation()->scriptedCallerIsHidden()) {
4647 // For Wasm, copy out the filename, there is no script source.
4648 UniqueChars copy
= DuplicateString(i
.filename() ? i
.filename() : "");
4650 filename
->setUnowned("out of memory");
4652 filename
->setOwned(std::move(copy
));
4655 // All other frames have a script source to read the filename from.
4656 filename
->setScriptSource(i
.scriptSource());
4661 JS::TaggedColumnNumberOneOrigin columnNumber
;
4662 *lineno
= i
.computeLine(&columnNumber
);
4664 *column
= JS::ColumnNumberOneOrigin(columnNumber
.oneOriginValue());
4666 } else if (column
) {
4667 JS::TaggedColumnNumberOneOrigin columnNumber
;
4668 i
.computeLine(&columnNumber
);
4669 *column
= JS::ColumnNumberOneOrigin(columnNumber
.oneOriginValue());
4675 // Fast path to get the activation and realm to use for GetScriptedCallerGlobal.
4676 // If this returns false, the fast path didn't work out and the caller has to
4677 // use the (much slower) NonBuiltinFrameIter path.
4679 // The optimization here is that we skip Ion-inlined frames and only look at
4680 // 'outer' frames. That's fine because Ion doesn't inline cross-realm calls.
4681 // However, GetScriptedCallerGlobal has to skip self-hosted frames and Ion
4682 // can inline self-hosted scripts, so we have to be careful:
4684 // * When we see a non-self-hosted outer script, it's possible we inlined
4685 // self-hosted scripts into it but that doesn't matter because these scripts
4686 // all have the same realm/global anyway.
4688 // * When we see a self-hosted outer script, it's possible we inlined
4689 // non-self-hosted scripts into it, so we have to give up because in this
4690 // case, whether or not to skip the self-hosted frame (to the possibly
4691 // different-realm caller) requires the slow path to handle inlining. Baseline
4692 // and the interpreter don't inline so this only affects Ion.
4693 static bool GetScriptedCallerActivationRealmFast(JSContext
* cx
,
4694 Activation
** activation
,
4696 ActivationIterator
activationIter(cx
);
4698 if (activationIter
.done()) {
4699 *activation
= nullptr;
4704 if (activationIter
->isJit()) {
4705 jit::JitActivation
* act
= activationIter
->asJit();
4706 JitFrameIter
iter(act
);
4708 iter
.skipNonScriptedJSFrames();
4713 if (!iter
.isSelfHostedIgnoringInlining()) {
4715 *realm
= iter
.realm();
4719 if (iter
.isJSJit() && iter
.asJSJit().isIonScripted()) {
4720 // Ion might have inlined non-self-hosted scripts in this
4721 // self-hosted script.
4727 } else if (activationIter
->isInterpreter()) {
4728 InterpreterActivation
* act
= activationIter
->asInterpreter();
4729 for (InterpreterFrameIterator
iter(act
); !iter
.done(); ++iter
) {
4730 if (!iter
.frame()->script()->selfHosted()) {
4732 *realm
= iter
.frame()->script()->realm();
4741 JS_PUBLIC_API JSObject
* GetScriptedCallerGlobal(JSContext
* cx
) {
4742 Activation
* activation
;
4744 if (GetScriptedCallerActivationRealmFast(cx
, &activation
, &realm
)) {
4749 NonBuiltinFrameIter
i(cx
);
4753 activation
= i
.activation();
4757 MOZ_ASSERT(realm
->compartment() == activation
->compartment());
4759 // If the caller is hidden, the embedding wants us to return null here so
4760 // that it can check its own stack (see HideScriptedCaller).
4761 if (activation
->scriptedCallerIsHidden()) {
4765 GlobalObject
* global
= realm
->maybeGlobal();
4767 // No one should be running code in a realm without any live objects, so
4768 // there should definitely be a live global.
4774 JS_PUBLIC_API
void HideScriptedCaller(JSContext
* cx
) {
4777 // If there's no accessible activation on the stack, we'll return null from
4778 // DescribeScriptedCaller anyway, so there's no need to annotate anything.
4779 Activation
* act
= cx
->activation();
4783 act
->hideScriptedCaller();
4786 JS_PUBLIC_API
void UnhideScriptedCaller(JSContext
* cx
) {
4787 Activation
* act
= cx
->activation();
4791 act
->unhideScriptedCaller();
4794 } /* namespace JS */
4797 JS_PUBLIC_API
void JS::detail::AssertArgumentsAreSane(JSContext
* cx
,
4798 HandleValue value
) {
4803 #endif /* JS_DEBUG */
4805 JS_PUBLIC_API
bool JS::FinishIncrementalEncoding(JSContext
* cx
,
4806 JS::HandleScript script
,
4807 TranscodeBuffer
& buffer
) {
4811 if (!script
->scriptSource()->xdrFinalizeEncoder(cx
, buffer
)) {
4817 JS_PUBLIC_API
bool JS::FinishIncrementalEncoding(JSContext
* cx
,
4818 JS::Handle
<JSObject
*> module
,
4819 TranscodeBuffer
& buffer
) {
4820 if (!module
->as
<ModuleObject
>()
4821 .scriptSourceObject()
4823 ->xdrFinalizeEncoder(cx
, buffer
)) {
4829 JS_PUBLIC_API
void JS::AbortIncrementalEncoding(JS::HandleScript script
) {
4833 script
->scriptSource()->xdrAbortEncoder();
4836 JS_PUBLIC_API
void JS::AbortIncrementalEncoding(JS::Handle
<JSObject
*> module
) {
4837 module
->as
<ModuleObject
>().scriptSourceObject()->source()->xdrAbortEncoder();
4840 bool JS::IsWasmModuleObject(HandleObject obj
) {
4841 return obj
->canUnwrapAs
<WasmModuleObject
>();
4844 JS_PUBLIC_API RefPtr
<JS::WasmModule
> JS::GetWasmModule(HandleObject obj
) {
4845 MOZ_ASSERT(JS::IsWasmModuleObject(obj
));
4846 WasmModuleObject
& mobj
= obj
->unwrapAs
<WasmModuleObject
>();
4847 return const_cast<wasm::Module
*>(&mobj
.module());
4850 bool JS::DisableWasmHugeMemory() { return wasm::DisableHugeMemory(); }
4852 JS_PUBLIC_API
void JS::SetProcessLargeAllocationFailureCallback(
4853 JS::LargeAllocationFailureCallback lafc
) {
4854 MOZ_ASSERT(!OnLargeAllocationFailure
);
4855 OnLargeAllocationFailure
= lafc
;
4858 JS_PUBLIC_API
void JS::SetOutOfMemoryCallback(JSContext
* cx
,
4859 OutOfMemoryCallback cb
,
4861 cx
->runtime()->oomCallback
= cb
;
4862 cx
->runtime()->oomCallbackData
= data
;
4865 JS_PUBLIC_API
void JS::SetShadowRealmInitializeGlobalCallback(
4866 JSContext
* cx
, JS::GlobalInitializeCallback callback
) {
4867 cx
->runtime()->shadowRealmInitializeGlobalCallback
= callback
;
4870 JS_PUBLIC_API
void JS::SetShadowRealmGlobalCreationCallback(
4871 JSContext
* cx
, JS::GlobalCreationCallback callback
) {
4872 cx
->runtime()->shadowRealmGlobalCreationCallback
= callback
;
4875 JS::FirstSubsumedFrame::FirstSubsumedFrame(
4876 JSContext
* cx
, bool ignoreSelfHostedFrames
/* = true */)
4877 : JS::FirstSubsumedFrame(cx
, cx
->realm()->principals(),
4878 ignoreSelfHostedFrames
) {}
4880 JS_PUBLIC_API
bool JS::CaptureCurrentStack(
4881 JSContext
* cx
, JS::MutableHandleObject stackp
,
4882 JS::StackCapture
&& capture
/* = JS::StackCapture(JS::AllFrames()) */) {
4885 MOZ_RELEASE_ASSERT(cx
->realm());
4887 Realm
* realm
= cx
->realm();
4888 Rooted
<SavedFrame
*> frame(cx
);
4889 if (!realm
->savedStacks().saveCurrentStack(cx
, &frame
, std::move(capture
))) {
4892 stackp
.set(frame
.get());
4896 JS_PUBLIC_API
bool JS::IsAsyncStackCaptureEnabledForRealm(JSContext
* cx
) {
4897 if (!cx
->options().asyncStack()) {
4901 if (!cx
->options().asyncStackCaptureDebuggeeOnly() ||
4902 cx
->realm()->isDebuggee()) {
4906 return cx
->realm()->isAsyncStackCapturingEnabled
;
4909 JS_PUBLIC_API
bool JS::CopyAsyncStack(JSContext
* cx
,
4910 JS::HandleObject asyncStack
,
4911 JS::HandleString asyncCause
,
4912 JS::MutableHandleObject stackp
,
4913 const Maybe
<size_t>& maxFrameCount
) {
4916 MOZ_RELEASE_ASSERT(cx
->realm());
4918 js::AssertObjectIsSavedFrameOrWrapper(cx
, asyncStack
);
4919 Realm
* realm
= cx
->realm();
4920 Rooted
<SavedFrame
*> frame(cx
);
4921 if (!realm
->savedStacks().copyAsyncStack(cx
, asyncStack
, asyncCause
, &frame
,
4925 stackp
.set(frame
.get());
4929 JS_PUBLIC_API Zone
* JS::GetObjectZone(JSObject
* obj
) { return obj
->zone(); }
4931 JS_PUBLIC_API Zone
* JS::GetNurseryCellZone(gc::Cell
* cell
) {
4932 return cell
->nurseryZone();
4935 JS_PUBLIC_API
JS::TraceKind
JS::GCThingTraceKind(void* thing
) {
4937 return static_cast<js::gc::Cell
*>(thing
)->getTraceKind();
4940 JS_PUBLIC_API
void js::SetStackFormat(JSContext
* cx
, js::StackFormat format
) {
4941 cx
->runtime()->setStackFormat(format
);
4944 JS_PUBLIC_API
js::StackFormat
js::GetStackFormat(JSContext
* cx
) {
4945 return cx
->runtime()->stackFormat();
4948 JS_PUBLIC_API
JS::JSTimers
JS::GetJSTimers(JSContext
* cx
) {
4949 return cx
->realm()->timers
;
4954 JS_PUBLIC_API
void NoteIntentionalCrash() {
4957 reinterpret_cast<bool*>(dlsym(RTLD_DEFAULT
, "gBreakpadInjectorEnabled"));
4965 bool gSupportDifferentialTesting
= false;
4972 JS_PUBLIC_API
void JS::SetSupportDifferentialTesting(bool value
) {
4973 js::gSupportDifferentialTesting
= value
;