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 "jit/TrampolineNatives.h"
44 #include "js/CallAndConstruct.h" // JS::IsCallable
45 #include "js/CharacterEncoding.h"
46 #include "js/ColumnNumber.h" // JS::TaggedColumnNumberOneOrigin, JS::ColumnNumberOneOrigin
47 #include "js/CompileOptions.h"
48 #include "js/ContextOptions.h" // JS::ContextOptions{,Ref}
49 #include "js/Conversions.h"
50 #include "js/Date.h" // JS::GetReduceMicrosecondTimePrecisionCallback
51 #include "js/ErrorInterceptor.h"
52 #include "js/ErrorReport.h" // JSErrorBase
53 #include "js/experimental/JitInfo.h" // JSJitInfo
54 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
55 #include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit
56 #include "js/GlobalObject.h"
57 #include "js/Initialization.h"
58 #include "js/Interrupt.h"
60 #include "js/LocaleSensitive.h"
61 #include "js/MemoryCallbacks.h"
62 #include "js/MemoryFunctions.h"
64 #include "js/PropertySpec.h"
66 #include "js/ScriptPrivate.h"
67 #include "js/StableStringChars.h"
68 #include "js/Stack.h" // JS::NativeStackSize, JS::NativeStackLimitMax, JS::GetNativeStackLimit
69 #include "js/StreamConsumer.h"
70 #include "js/String.h" // JS::MaxStringLength
71 #include "js/Symbol.h"
72 #include "js/TelemetryTimers.h"
73 #include "js/Utility.h"
74 #include "js/WaitCallbacks.h"
75 #include "js/WasmModule.h"
76 #include "js/Wrapper.h"
77 #include "js/WrapperCallbacks.h"
78 #include "proxy/DOMProxy.h"
79 #include "util/Identifier.h" // IsIdentifier
80 #include "util/StringBuffer.h"
81 #include "util/Text.h"
82 #include "vm/BoundFunctionObject.h"
83 #include "vm/EnvironmentObject.h"
84 #include "vm/ErrorObject.h"
85 #include "vm/ErrorReporting.h"
86 #include "vm/FunctionPrefixKind.h"
87 #include "vm/Interpreter.h"
88 #include "vm/JSAtomState.h"
89 #include "vm/JSAtomUtils.h" // Atomize, AtomizeWithoutActiveZone, AtomizeChars, PinAtom, ClassName
90 #include "vm/JSContext.h"
91 #include "vm/JSFunction.h"
92 #include "vm/JSObject.h"
93 #include "vm/JSScript.h"
94 #include "vm/PlainObject.h" // js::PlainObject
95 #include "vm/PromiseObject.h" // js::PromiseObject
96 #include "vm/Runtime.h"
97 #include "vm/SavedStacks.h"
98 #include "vm/StringType.h"
100 #include "vm/ToSource.h"
101 #include "vm/Watchtower.h"
102 #include "vm/WrapperObject.h"
103 #include "wasm/WasmModule.h"
104 #include "wasm/WasmProcess.h"
106 #include "builtin/Promise-inl.h"
107 #include "debugger/DebugAPI-inl.h"
108 #include "vm/Compartment-inl.h"
109 #include "vm/Interpreter-inl.h"
110 #include "vm/IsGivenTypeObject-inl.h" // js::IsGivenTypeObject
111 #include "vm/JSAtomUtils-inl.h" // AtomToId, PrimitiveValueToId, IndexToId, ClassName
112 #include "vm/JSFunction-inl.h"
113 #include "vm/JSScript-inl.h"
114 #include "vm/NativeObject-inl.h"
115 #include "vm/SavedStacks-inl.h"
116 #include "vm/StringType-inl.h"
120 using mozilla::Maybe
;
121 using mozilla::PodCopy
;
124 using JS::AutoStableStringChars
;
125 using JS::CompileOptions
;
126 using JS::ReadOnlyCompileOptions
;
127 using JS::SourceText
;
129 // See preprocessor definition of JS_BITS_PER_WORD in jstypes.h; make sure
130 // JS_64BIT (used internally) agrees with it
132 static_assert(JS_BITS_PER_WORD
== 64, "values must be in sync");
134 static_assert(JS_BITS_PER_WORD
== 32, "values must be in sync");
137 JS_PUBLIC_API
void JS::CallArgs::reportMoreArgsNeeded(JSContext
* cx
,
141 char requiredArgsStr
[40];
142 SprintfLiteral(requiredArgsStr
, "%u", required
);
143 char actualArgsStr
[40];
144 SprintfLiteral(actualArgsStr
, "%u", actual
);
145 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr,
146 JSMSG_MORE_ARGS_NEEDED
, fnname
, requiredArgsStr
,
147 required
== 1 ? "" : "s", actualArgsStr
);
150 static bool ErrorTakesArguments(unsigned msg
) {
151 MOZ_ASSERT(msg
< JSErr_Limit
);
152 unsigned argCount
= js_ErrorFormatString
[msg
].argCount
;
153 MOZ_ASSERT(argCount
<= 2);
154 return argCount
== 1 || argCount
== 2;
157 static bool ErrorTakesObjectArgument(unsigned msg
) {
158 MOZ_ASSERT(msg
< JSErr_Limit
);
159 unsigned argCount
= js_ErrorFormatString
[msg
].argCount
;
160 MOZ_ASSERT(argCount
<= 2);
161 return argCount
== 2;
164 bool JS::ObjectOpResult::reportError(JSContext
* cx
, HandleObject obj
,
166 static_assert(unsigned(OkCode
) == unsigned(JSMSG_NOT_AN_ERROR
),
167 "unsigned value of OkCode must not be an error code");
168 MOZ_ASSERT(code_
!= Uninitialized
);
172 if (code_
== JSMSG_OBJECT_NOT_EXTENSIBLE
) {
173 RootedValue
val(cx
, ObjectValue(*obj
));
174 return ReportValueError(cx
, code_
, JSDVG_IGNORE_STACK
, val
, nullptr);
177 if (ErrorTakesArguments(code_
)) {
178 UniqueChars propName
=
179 IdToPrintableUTF8(cx
, id
, IdToPrintableBehavior::IdIsPropertyKey
);
184 if (code_
== JSMSG_SET_NON_OBJECT_RECEIVER
) {
185 // We know that the original receiver was a primitive, so unbox it.
186 RootedValue
val(cx
, ObjectValue(*obj
));
187 if (!obj
->is
<ProxyObject
>()) {
188 if (!Unbox(cx
, obj
, &val
)) {
192 return ReportValueError(cx
, code_
, JSDVG_IGNORE_STACK
, val
, nullptr,
196 if (ErrorTakesObjectArgument(code_
)) {
197 JSObject
* unwrapped
= js::CheckedUnwrapStatic(obj
);
198 const char* name
= unwrapped
? unwrapped
->getClass()->name
: "Object";
199 JS_ReportErrorNumberUTF8(cx
, GetErrorMessage
, nullptr, code_
, name
,
204 JS_ReportErrorNumberUTF8(cx
, GetErrorMessage
, nullptr, code_
,
208 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr, code_
);
212 bool JS::ObjectOpResult::reportError(JSContext
* cx
, HandleObject obj
) {
213 MOZ_ASSERT(code_
!= Uninitialized
);
215 MOZ_ASSERT(!ErrorTakesArguments(code_
));
218 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr, code_
);
222 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantRedefineProp() {
223 return fail(JSMSG_CANT_REDEFINE_PROP
);
226 JS_PUBLIC_API
bool JS::ObjectOpResult::failReadOnly() {
227 return fail(JSMSG_READ_ONLY
);
230 JS_PUBLIC_API
bool JS::ObjectOpResult::failGetterOnly() {
231 return fail(JSMSG_GETTER_ONLY
);
234 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDelete() {
235 return fail(JSMSG_CANT_DELETE
);
238 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantSetInterposed() {
239 return fail(JSMSG_CANT_SET_INTERPOSED
);
242 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDefineWindowElement() {
243 return fail(JSMSG_CANT_DEFINE_WINDOW_ELEMENT
);
246 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDeleteWindowElement() {
247 return fail(JSMSG_CANT_DELETE_WINDOW_ELEMENT
);
250 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDefineWindowNamedProperty() {
251 return fail(JSMSG_CANT_DEFINE_WINDOW_NAMED_PROPERTY
);
254 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDeleteWindowNamedProperty() {
255 return fail(JSMSG_CANT_DELETE_WINDOW_NAMED_PROPERTY
);
258 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantDefineWindowNonConfigurable() {
259 return fail(JSMSG_CANT_DEFINE_WINDOW_NC
);
262 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantPreventExtensions() {
263 return fail(JSMSG_CANT_PREVENT_EXTENSIONS
);
266 JS_PUBLIC_API
bool JS::ObjectOpResult::failCantSetProto() {
267 return fail(JSMSG_CANT_SET_PROTO
);
270 JS_PUBLIC_API
bool JS::ObjectOpResult::failNoNamedSetter() {
271 return fail(JSMSG_NO_NAMED_SETTER
);
274 JS_PUBLIC_API
bool JS::ObjectOpResult::failNoIndexedSetter() {
275 return fail(JSMSG_NO_INDEXED_SETTER
);
278 JS_PUBLIC_API
bool JS::ObjectOpResult::failNotDataDescriptor() {
279 return fail(JSMSG_NOT_DATA_DESCRIPTOR
);
282 JS_PUBLIC_API
bool JS::ObjectOpResult::failInvalidDescriptor() {
283 return fail(JSMSG_INVALID_DESCRIPTOR
);
286 JS_PUBLIC_API
bool JS::ObjectOpResult::failBadArrayLength() {
287 return fail(JSMSG_BAD_ARRAY_LENGTH
);
290 JS_PUBLIC_API
bool JS::ObjectOpResult::failBadIndex() {
291 return fail(JSMSG_BAD_INDEX
);
294 JS_PUBLIC_API
int64_t JS_Now() { return PRMJ_Now(); }
296 JS_PUBLIC_API Value
JS_GetEmptyStringValue(JSContext
* cx
) {
297 return StringValue(cx
->runtime()->emptyString
);
300 JS_PUBLIC_API JSString
* JS_GetEmptyString(JSContext
* cx
) {
301 MOZ_ASSERT(cx
->emptyString());
302 return cx
->emptyString();
307 void AssertHeapIsIdle() { MOZ_ASSERT(!JS::RuntimeHeapIsBusy()); }
311 static void AssertHeapIsIdleOrIterating() {
312 MOZ_ASSERT(!JS::RuntimeHeapIsCollecting());
315 JS_PUBLIC_API
bool JS_ValueToObject(JSContext
* cx
, HandleValue value
,
316 MutableHandleObject objp
) {
320 if (value
.isNullOrUndefined()) {
324 JSObject
* obj
= ToObject(cx
, value
);
332 JS_PUBLIC_API JSFunction
* JS_ValueToFunction(JSContext
* cx
, HandleValue value
) {
336 return ReportIfNotFunction(cx
, value
);
339 JS_PUBLIC_API JSFunction
* JS_ValueToConstructor(JSContext
* cx
,
344 return ReportIfNotFunction(cx
, value
);
347 JS_PUBLIC_API JSString
* JS_ValueToSource(JSContext
* cx
, HandleValue value
) {
351 return ValueToSource(cx
, value
);
354 JS_PUBLIC_API
bool JS_DoubleIsInt32(double d
, int32_t* ip
) {
355 return mozilla::NumberIsInt32(d
, ip
);
358 JS_PUBLIC_API JSType
JS_TypeOfValue(JSContext
* cx
, HandleValue value
) {
362 return TypeOfValue(value
);
365 JS_PUBLIC_API
bool JS_IsBuiltinEvalFunction(JSFunction
* fun
) {
366 return IsAnyBuiltinEval(fun
);
369 JS_PUBLIC_API
bool JS_IsBuiltinFunctionConstructor(JSFunction
* fun
) {
370 return fun
->isBuiltinFunctionConstructor();
373 JS_PUBLIC_API
bool JS_ObjectIsBoundFunction(JSObject
* obj
) {
374 return obj
->is
<BoundFunctionObject
>();
377 JS_PUBLIC_API JSObject
* JS_GetBoundFunctionTarget(JSObject
* obj
) {
378 return obj
->is
<BoundFunctionObject
>()
379 ? obj
->as
<BoundFunctionObject
>().getTarget()
383 /************************************************************************/
385 // Prevent functions from being discarded by linker, so that they are callable
387 static void PreventDiscardingFunctions() {
388 if (reinterpret_cast<uintptr_t>(&PreventDiscardingFunctions
) == 1) {
390 memset((void*)&js::debug::GetMarkInfo
, 0, 1);
391 memset((void*)&js::debug::GetMarkWordAddress
, 0, 1);
392 memset((void*)&js::debug::GetMarkMask
, 0, 1);
396 JS_PUBLIC_API JSContext
* JS_NewContext(uint32_t maxbytes
,
397 JSRuntime
* parentRuntime
) {
398 MOZ_ASSERT(JS::detail::libraryInitState
== JS::detail::InitState::Running
,
399 "must call JS_Init prior to creating any JSContexts");
401 // Prevent linker from discarding unused debug functions.
402 PreventDiscardingFunctions();
404 // Make sure that all parent runtimes are the topmost parent.
405 while (parentRuntime
&& parentRuntime
->parentRuntime
) {
406 parentRuntime
= parentRuntime
->parentRuntime
;
409 return NewContext(maxbytes
, parentRuntime
);
412 JS_PUBLIC_API
void JS_DestroyContext(JSContext
* cx
) { DestroyContext(cx
); }
414 JS_PUBLIC_API
void* JS_GetContextPrivate(JSContext
* cx
) { return cx
->data
; }
416 JS_PUBLIC_API
void JS_SetContextPrivate(JSContext
* cx
, void* data
) {
420 JS_PUBLIC_API
void JS_SetFutexCanWait(JSContext
* cx
) {
421 cx
->fx
.setCanWait(true);
424 JS_PUBLIC_API JSRuntime
* JS_GetParentRuntime(JSContext
* cx
) {
425 return cx
->runtime()->parentRuntime
? cx
->runtime()->parentRuntime
429 JS_PUBLIC_API JSRuntime
* JS_GetRuntime(JSContext
* cx
) { return cx
->runtime(); }
431 JS_PUBLIC_API
JS::ContextOptions
& JS::ContextOptionsRef(JSContext
* cx
) {
432 return cx
->options();
435 JS::ContextOptions
& JS::ContextOptions::setFuzzing(bool flag
) {
442 JS_PUBLIC_API
const char* JS_GetImplementationVersion(void) {
443 return "JavaScript-C" MOZILLA_VERSION
;
446 JS_PUBLIC_API
void JS_SetDestroyZoneCallback(JSContext
* cx
,
447 JSDestroyZoneCallback callback
) {
448 cx
->runtime()->destroyZoneCallback
= callback
;
451 JS_PUBLIC_API
void JS_SetDestroyCompartmentCallback(
452 JSContext
* cx
, JSDestroyCompartmentCallback callback
) {
453 cx
->runtime()->destroyCompartmentCallback
= callback
;
456 JS_PUBLIC_API
void JS_SetSizeOfIncludingThisCompartmentCallback(
457 JSContext
* cx
, JSSizeOfIncludingThisCompartmentCallback callback
) {
458 cx
->runtime()->sizeOfIncludingThisCompartmentCallback
= callback
;
461 JS_PUBLIC_API
void JS_SetErrorInterceptorCallback(
462 JSRuntime
* rt
, JSErrorInterceptor
* callback
) {
463 #if defined(NIGHTLY_BUILD)
464 rt
->errorInterception
.interceptor
= callback
;
465 #endif // defined(NIGHTLY_BUILD)
468 JS_PUBLIC_API JSErrorInterceptor
* JS_GetErrorInterceptorCallback(
470 #if defined(NIGHTLY_BUILD)
471 return rt
->errorInterception
.interceptor
;
472 #else // !NIGHTLY_BUILD
474 #endif // defined(NIGHTLY_BUILD)
477 JS_PUBLIC_API Maybe
<JSExnType
> JS_GetErrorType(const JS::Value
& val
) {
478 // All errors are objects.
479 if (!val
.isObject()) {
480 return mozilla::Nothing();
483 const JSObject
& obj
= val
.toObject();
485 // All errors are `ErrorObject`.
486 if (!obj
.is
<js::ErrorObject
>()) {
487 // Not one of the primitive errors.
488 return mozilla::Nothing();
491 const js::ErrorObject
& err
= obj
.as
<js::ErrorObject
>();
492 return mozilla::Some(err
.type());
495 JS_PUBLIC_API
void JS_SetWrapObjectCallbacks(
496 JSContext
* cx
, const JSWrapObjectCallbacks
* callbacks
) {
497 cx
->runtime()->wrapObjectCallbacks
= callbacks
;
500 JS_PUBLIC_API Realm
* JS::EnterRealm(JSContext
* cx
, JSObject
* target
) {
504 MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(target
));
506 Realm
* oldRealm
= cx
->realm();
507 cx
->enterRealmOf(target
);
511 JS_PUBLIC_API
void JS::LeaveRealm(JSContext
* cx
, JS::Realm
* oldRealm
) {
514 cx
->leaveRealm(oldRealm
);
517 JSAutoRealm::JSAutoRealm(JSContext
* cx
, JSObject
* target
)
518 : cx_(cx
), oldRealm_(cx
->realm()) {
519 MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(target
));
520 AssertHeapIsIdleOrIterating();
521 cx_
->enterRealmOf(target
);
524 JSAutoRealm::JSAutoRealm(JSContext
* cx
, JSScript
* target
)
525 : cx_(cx
), oldRealm_(cx
->realm()) {
526 AssertHeapIsIdleOrIterating();
527 cx_
->enterRealmOf(target
);
530 JSAutoRealm::~JSAutoRealm() { cx_
->leaveRealm(oldRealm_
); }
532 JSAutoNullableRealm::JSAutoNullableRealm(JSContext
* cx
, JSObject
* targetOrNull
)
533 : cx_(cx
), oldRealm_(cx
->realm()) {
534 AssertHeapIsIdleOrIterating();
536 MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(targetOrNull
));
537 cx_
->enterRealmOf(targetOrNull
);
539 cx_
->enterNullRealm();
543 JSAutoNullableRealm::~JSAutoNullableRealm() { cx_
->leaveRealm(oldRealm_
); }
545 JS_PUBLIC_API
void JS_SetCompartmentPrivate(JS::Compartment
* compartment
,
547 compartment
->data
= data
;
550 JS_PUBLIC_API
void* JS_GetCompartmentPrivate(JS::Compartment
* compartment
) {
551 return compartment
->data
;
554 JS_PUBLIC_API
void JS_MarkCrossZoneId(JSContext
* cx
, jsid id
) {
558 JS_PUBLIC_API
void JS_MarkCrossZoneIdValue(JSContext
* cx
, const Value
& value
) {
559 cx
->markAtomValue(value
);
562 JS_PUBLIC_API
void JS_SetZoneUserData(JS::Zone
* zone
, void* data
) {
566 JS_PUBLIC_API
void* JS_GetZoneUserData(JS::Zone
* zone
) { return zone
->data
; }
568 JS_PUBLIC_API
bool JS_WrapObject(JSContext
* cx
, MutableHandleObject objp
) {
572 JS::ExposeObjectToActiveJS(objp
);
574 return cx
->compartment()->wrap(cx
, objp
);
577 JS_PUBLIC_API
bool JS_WrapValue(JSContext
* cx
, MutableHandleValue vp
) {
580 JS::ExposeValueToActiveJS(vp
);
581 return cx
->compartment()->wrap(cx
, vp
);
584 static void ReleaseAssertObjectHasNoWrappers(JSContext
* cx
,
585 HandleObject target
) {
586 for (CompartmentsIter
c(cx
->runtime()); !c
.done(); c
.next()) {
587 if (c
->lookupWrapper(target
)) {
588 MOZ_CRASH("wrapper found for target object");
594 * [SMDOC] Brain transplants.
596 * Not for beginners or the squeamish.
598 * Sometimes a web spec requires us to transplant an object from one
599 * compartment to another, like when a DOM node is inserted into a document in
600 * another window and thus gets "adopted". We cannot literally change the
601 * `.compartment()` of a `JSObject`; that would break the compartment
602 * invariants. However, as usual, we have a workaround using wrappers.
604 * Of all the wrapper-based workarounds we do, it's safe to say this is the
605 * most spectacular and questionable.
607 * `JS_TransplantObject(cx, origobj, target)` changes `origobj` into a
608 * simulacrum of `target`, using highly esoteric means. To JS code, the effect
609 * is as if `origobj` magically "became" `target`, but most often what actually
610 * happens is that `origobj` gets turned into a cross-compartment wrapper for
611 * `target`. The old behavior and contents of `origobj` are overwritten or
614 * Thus, to "transplant" an object from one compartment to another:
616 * 1. Let `origobj` be the object that you want to move. First, create a
617 * clone of it, `target`, in the destination compartment.
619 * In our DOM adoption example, `target` will be a Node of the same type as
620 * `origobj`, same content, but in the adopting document. We're not done
621 * yet: the spec for DOM adoption requires that `origobj.ownerDocument`
622 * actually change. All we've done so far is make a copy.
624 * 2. Call `JS_TransplantObject(cx, origobj, target)`. This typically turns
625 * `origobj` into a wrapper for `target`, so that any JS code that has a
626 * reference to `origobj` will observe it to have the behavior of `target`
627 * going forward. In addition, all existing wrappers for `origobj` are
628 * changed into wrappers for `target`, extending the illusion to those
629 * compartments as well.
631 * During navigation, we use the above technique to transplant the WindowProxy
632 * into the new Window's compartment.
636 * - `origobj` and `target` must be two distinct objects of the same
637 * `JSClass`. Some classes may not support transplantation; WindowProxy
638 * objects and DOM nodes are OK.
640 * - `target` should be created specifically to be passed to this function.
641 * There must be no existing cross-compartment wrappers for it; ideally
642 * there shouldn't be any pointers to it at all, except the one passed in.
644 * - `target` shouldn't be used afterwards. Instead, `JS_TransplantObject`
645 * returns a pointer to the transplanted object, which might be `target`
646 * but might be some other object in the same compartment. Use that.
648 * The reason for this last rule is that JS_TransplantObject does very strange
649 * things in some cases, like swapping `target`'s brain with that of another
650 * object. Leaving `target` behaving like its former self is not a goal.
652 * We don't have a good way to recover from failure in this function, so
653 * we intentionally crash instead.
656 static void CheckTransplantObject(JSObject
* obj
) {
658 MOZ_ASSERT(!obj
->is
<CrossCompartmentWrapperObject
>());
659 JS::AssertCellIsNotGray(obj
);
663 JS_PUBLIC_API JSObject
* JS_TransplantObject(JSContext
* cx
, HandleObject origobj
,
664 HandleObject target
) {
666 MOZ_ASSERT(origobj
!= target
);
667 CheckTransplantObject(origobj
);
668 CheckTransplantObject(target
);
669 ReleaseAssertObjectHasNoWrappers(cx
, target
);
671 RootedObject
newIdentity(cx
);
673 // Don't allow a compacting GC to observe any intermediate state.
674 AutoDisableCompactingGC
nocgc(cx
);
676 AutoDisableProxyCheck adpc
;
678 AutoEnterOOMUnsafeRegion oomUnsafe
;
680 JS::Compartment
* destination
= target
->compartment();
682 if (origobj
->compartment() == destination
) {
683 // If the original object is in the same compartment as the
684 // destination, then we know that we won't find a wrapper in the
685 // destination's cross compartment map and that the same
686 // object will continue to work.
687 AutoRealm
ar(cx
, origobj
);
688 JSObject::swap(cx
, origobj
, target
, oomUnsafe
);
689 newIdentity
= origobj
;
690 } else if (ObjectWrapperMap::Ptr p
= destination
->lookupWrapper(origobj
)) {
691 // There might already be a wrapper for the original object in
692 // the new compartment. If there is, we use its identity and swap
693 // in the contents of |target|.
694 newIdentity
= p
->value().get();
696 // When we remove origv from the wrapper map, its wrapper, newIdentity,
697 // must immediately cease to be a cross-compartment wrapper. Nuke it.
698 destination
->removeWrapper(p
);
699 NukeCrossCompartmentWrapper(cx
, newIdentity
);
701 AutoRealm
ar(cx
, newIdentity
);
702 JSObject::swap(cx
, newIdentity
, target
, oomUnsafe
);
704 // Otherwise, we use |target| for the new identity object.
705 newIdentity
= target
;
708 // Now, iterate through other scopes looking for references to the old
709 // object, and update the relevant cross-compartment wrappers. We do this
710 // even if origobj is in the same compartment as target and thus
711 // `newIdentity == origobj`, because this process also clears out any
712 // cached wrapper state.
713 if (!RemapAllWrappersForObject(cx
, origobj
, newIdentity
)) {
714 oomUnsafe
.crash("JS_TransplantObject");
717 // Lastly, update the original object to point to the new one.
718 if (origobj
->compartment() != destination
) {
719 RootedObject
newIdentityWrapper(cx
, newIdentity
);
720 AutoRealm
ar(cx
, origobj
);
721 if (!JS_WrapObject(cx
, &newIdentityWrapper
)) {
722 MOZ_RELEASE_ASSERT(cx
->isThrowingOutOfMemory() ||
723 cx
->isThrowingOverRecursed());
724 oomUnsafe
.crash("JS_TransplantObject");
726 MOZ_ASSERT(Wrapper::wrappedObject(newIdentityWrapper
) == newIdentity
);
727 JSObject::swap(cx
, origobj
, newIdentityWrapper
, oomUnsafe
);
728 if (origobj
->compartment()->lookupWrapper(newIdentity
)) {
729 MOZ_ASSERT(origobj
->is
<CrossCompartmentWrapperObject
>());
730 if (!origobj
->compartment()->putWrapper(cx
, newIdentity
, origobj
)) {
731 oomUnsafe
.crash("JS_TransplantObject");
736 // The new identity object might be one of several things. Return it to avoid
738 JS::AssertCellIsNotGray(newIdentity
);
742 JS_PUBLIC_API
void js::RemapRemoteWindowProxies(
743 JSContext
* cx
, CompartmentTransplantCallback
* callback
,
744 MutableHandleObject target
) {
746 CheckTransplantObject(target
);
747 ReleaseAssertObjectHasNoWrappers(cx
, target
);
749 // |target| can't be a remote proxy, because we expect it to get a CCW when
750 // wrapped across compartments.
751 MOZ_ASSERT(!js::IsDOMRemoteProxyObject(target
));
753 // Don't allow a compacting GC to observe any intermediate state.
754 AutoDisableCompactingGC
nocgc(cx
);
756 AutoDisableProxyCheck adpc
;
758 AutoEnterOOMUnsafeRegion oomUnsafe
;
760 AutoCheckRecursionLimit
recursion(cx
);
761 if (!recursion
.checkSystem(cx
)) {
762 oomUnsafe
.crash("js::RemapRemoteWindowProxies");
765 RootedObject
targetCompartmentProxy(cx
);
766 JS::RootedVector
<JSObject
*> otherProxies(cx
);
768 // Use the callback to find remote proxies in all compartments that match
769 // whatever criteria callback uses.
770 for (CompartmentsIter
c(cx
->runtime()); !c
.done(); c
.next()) {
771 RootedObject
remoteProxy(cx
, callback
->getObjectToTransplant(c
));
775 // The object the callback returns should be a DOM remote proxy object in
776 // the compartment c. We rely on it being a DOM remote proxy because that
777 // means that it won't have any cross-compartment wrappers.
778 MOZ_ASSERT(js::IsDOMRemoteProxyObject(remoteProxy
));
779 MOZ_ASSERT(remoteProxy
->compartment() == c
);
780 CheckTransplantObject(remoteProxy
);
782 // Immediately turn the DOM remote proxy object into a dead proxy object
783 // so we don't have to worry about anything weird going on with it.
784 js::NukeNonCCWProxy(cx
, remoteProxy
);
786 if (remoteProxy
->compartment() == target
->compartment()) {
787 targetCompartmentProxy
= remoteProxy
;
788 } else if (!otherProxies
.append(remoteProxy
)) {
789 oomUnsafe
.crash("js::RemapRemoteWindowProxies");
793 // If there was a remote proxy in |target|'s compartment, we need to use it
794 // instead of |target|, in case it had any references, so swap it. Do this
795 // before any other compartment so that the target object will be set up
796 // correctly before we start wrapping it into other compartments.
797 if (targetCompartmentProxy
) {
798 AutoRealm
ar(cx
, targetCompartmentProxy
);
799 JSObject::swap(cx
, targetCompartmentProxy
, target
, oomUnsafe
);
800 target
.set(targetCompartmentProxy
);
803 for (JSObject
*& obj
: otherProxies
) {
804 RootedObject
deadWrapper(cx
, obj
);
805 js::RemapDeadWrapper(cx
, deadWrapper
, target
);
810 * Recompute all cross-compartment wrappers for an object, resetting state.
811 * Gecko uses this to clear Xray wrappers when doing a navigation that reuses
812 * the inner window and global object.
814 JS_PUBLIC_API
bool JS_RefreshCrossCompartmentWrappers(JSContext
* cx
,
816 return RemapAllWrappersForObject(cx
, obj
, obj
);
819 typedef struct JSStdName
{
820 size_t atomOffset
; /* offset of atom pointer in JSAtomState */
822 bool isDummy() const { return key
== JSProto_Null
; }
823 bool isSentinel() const { return key
== JSProto_LIMIT
; }
826 static const JSStdName
* LookupStdName(const JSAtomState
& names
, JSAtom
* name
,
827 const JSStdName
* table
) {
828 for (unsigned i
= 0; !table
[i
].isSentinel(); i
++) {
829 if (table
[i
].isDummy()) {
832 JSAtom
* atom
= AtomStateOffsetToName(names
, table
[i
].atomOffset
);
843 * Table of standard classes, indexed by JSProtoKey. For entries where the
844 * JSProtoKey does not correspond to a class with a meaningful constructor, we
845 * insert a null entry into the table.
847 #define STD_NAME_ENTRY(name, clasp) {NAME_OFFSET(name), JSProto_##name},
848 #define STD_DUMMY_ENTRY(name, dummy) {0, JSProto_Null},
849 static const JSStdName standard_class_names
[] = {
850 JS_FOR_PROTOTYPES(STD_NAME_ENTRY
, STD_DUMMY_ENTRY
){0, JSProto_LIMIT
}};
853 * Table of top-level function and constant names and the JSProtoKey of the
854 * standard class that initializes them.
856 static const JSStdName builtin_property_names
[] = {
857 {NAME_OFFSET(eval
), JSProto_Object
},
859 /* Global properties and functions defined by the Number class. */
860 {NAME_OFFSET(NaN
), JSProto_Number
},
861 {NAME_OFFSET(Infinity
), JSProto_Number
},
862 {NAME_OFFSET(isNaN
), JSProto_Number
},
863 {NAME_OFFSET(isFinite
), JSProto_Number
},
864 {NAME_OFFSET(parseFloat
), JSProto_Number
},
865 {NAME_OFFSET(parseInt
), JSProto_Number
},
867 /* String global functions. */
868 {NAME_OFFSET(escape
), JSProto_String
},
869 {NAME_OFFSET(unescape
), JSProto_String
},
870 {NAME_OFFSET(decodeURI
), JSProto_String
},
871 {NAME_OFFSET(encodeURI
), JSProto_String
},
872 {NAME_OFFSET(decodeURIComponent
), JSProto_String
},
873 {NAME_OFFSET(encodeURIComponent
), JSProto_String
},
874 {NAME_OFFSET(uneval
), JSProto_String
},
878 static bool SkipUneval(jsid id
, JSContext
* cx
) {
879 return !cx
->realm()->creationOptions().getToSourceEnabled() &&
880 id
== NameToId(cx
->names().uneval
);
883 static bool SkipSharedArrayBufferConstructor(JSProtoKey key
,
884 GlobalObject
* global
) {
885 if (key
!= JSProto_SharedArrayBuffer
) {
889 const JS::RealmCreationOptions
& options
= global
->realm()->creationOptions();
890 MOZ_ASSERT(options
.getSharedMemoryAndAtomicsEnabled(),
891 "shouldn't contemplate defining SharedArrayBuffer if shared "
892 "memory is disabled");
894 // On the web, it isn't presently possible to expose the global
895 // "SharedArrayBuffer" property unless the page is cross-site-isolated. Only
896 // define this constructor if an option on the realm indicates that it should
898 return !options
.defineSharedArrayBufferConstructor();
901 JS_PUBLIC_API
bool JS_ResolveStandardClass(JSContext
* cx
, HandleObject obj
,
902 HandleId id
, bool* resolved
) {
907 Handle
<GlobalObject
*> global
= obj
.as
<GlobalObject
>();
914 /* Check whether we're resolving 'undefined', and define it if so. */
915 JSAtom
* idAtom
= id
.toAtom();
916 if (idAtom
== cx
->names().undefined
) {
918 return js::DefineDataProperty(
919 cx
, global
, id
, UndefinedHandleValue
,
920 JSPROP_PERMANENT
| JSPROP_READONLY
| JSPROP_RESOLVING
);
923 // Resolve a "globalThis" self-referential property if necessary.
924 if (idAtom
== cx
->names().globalThis
) {
925 return GlobalObject::maybeResolveGlobalThis(cx
, global
, resolved
);
928 // Try for class constructors/prototypes named by well-known atoms.
929 const JSStdName
* stdnm
=
930 LookupStdName(cx
->names(), idAtom
, standard_class_names
);
932 // Try less frequently used top-level functions and constants.
933 stdnm
= LookupStdName(cx
->names(), idAtom
, builtin_property_names
);
939 JSProtoKey key
= stdnm
->key
;
940 if (key
== JSProto_Null
|| GlobalObject::skipDeselectedConstructor(cx
, key
) ||
941 SkipUneval(id
, cx
)) {
945 // If this class is anonymous (or it's "SharedArrayBuffer" but that global
946 // constructor isn't supposed to be defined), then it doesn't exist as a
947 // global property, so we won't resolve anything.
948 const JSClass
* clasp
= ProtoKeyToClass(key
);
949 if (clasp
&& !clasp
->specShouldDefineConstructor()) {
952 if (SkipSharedArrayBufferConstructor(key
, global
)) {
956 if (!GlobalObject::ensureConstructor(cx
, global
, key
)) {
963 JS_PUBLIC_API
bool JS_MayResolveStandardClass(const JSAtomState
& names
, jsid id
,
964 JSObject
* maybeObj
) {
965 MOZ_ASSERT_IF(maybeObj
, maybeObj
->is
<GlobalObject
>());
967 // The global object's resolve hook is special: JS_ResolveStandardClass
968 // initializes the prototype chain lazily. Only attempt to optimize here
969 // if we know the prototype chain has been initialized.
970 if (!maybeObj
|| !maybeObj
->staticPrototype()) {
978 JSAtom
* atom
= id
.toAtom();
980 // This will return true even for deselected constructors. (To do
981 // better, we need a JSContext here; it's fine as it is.)
983 return atom
== names
.undefined
|| atom
== names
.globalThis
||
984 LookupStdName(names
, atom
, standard_class_names
) ||
985 LookupStdName(names
, atom
, builtin_property_names
);
988 JS_PUBLIC_API
bool JS_EnumerateStandardClasses(JSContext
* cx
,
993 Handle
<GlobalObject
*> global
= obj
.as
<GlobalObject
>();
994 return GlobalObject::initStandardClasses(cx
, global
);
997 static bool EnumerateStandardClassesInTable(JSContext
* cx
,
998 Handle
<GlobalObject
*> global
,
999 MutableHandleIdVector properties
,
1000 const JSStdName
* table
,
1001 bool includeResolved
) {
1002 for (unsigned i
= 0; !table
[i
].isSentinel(); i
++) {
1003 if (table
[i
].isDummy()) {
1007 JSProtoKey key
= table
[i
].key
;
1009 // If the standard class has been resolved, the properties have been
1010 // defined on the global so we don't need to add them here.
1011 if (!includeResolved
&& global
->isStandardClassResolved(key
)) {
1015 if (GlobalObject::skipDeselectedConstructor(cx
, key
)) {
1019 if (const JSClass
* clasp
= ProtoKeyToClass(key
)) {
1020 if (!clasp
->specShouldDefineConstructor() ||
1021 SkipSharedArrayBufferConstructor(key
, global
)) {
1026 jsid id
= NameToId(AtomStateOffsetToName(cx
->names(), table
[i
].atomOffset
));
1028 if (SkipUneval(id
, cx
)) {
1032 if (!properties
.append(id
)) {
1040 static bool EnumerateStandardClasses(JSContext
* cx
, JS::HandleObject obj
,
1041 JS::MutableHandleIdVector properties
,
1042 bool enumerableOnly
,
1043 bool includeResolved
) {
1044 if (enumerableOnly
) {
1045 // There are no enumerable standard classes and "undefined" is
1050 Handle
<GlobalObject
*> global
= obj
.as
<GlobalObject
>();
1052 // It's fine to always append |undefined| here, it's non-configurable and
1053 // the enumeration code filters duplicates.
1054 if (!properties
.append(NameToId(cx
->names().undefined
))) {
1058 bool resolved
= false;
1059 if (!GlobalObject::maybeResolveGlobalThis(cx
, global
, &resolved
)) {
1062 if (resolved
|| includeResolved
) {
1063 if (!properties
.append(NameToId(cx
->names().globalThis
))) {
1068 if (!EnumerateStandardClassesInTable(cx
, global
, properties
,
1069 standard_class_names
, includeResolved
)) {
1072 if (!EnumerateStandardClassesInTable(
1073 cx
, global
, properties
, builtin_property_names
, includeResolved
)) {
1080 JS_PUBLIC_API
bool JS_NewEnumerateStandardClasses(
1081 JSContext
* cx
, JS::HandleObject obj
, JS::MutableHandleIdVector properties
,
1082 bool enumerableOnly
) {
1083 return EnumerateStandardClasses(cx
, obj
, properties
, enumerableOnly
, false);
1086 JS_PUBLIC_API
bool JS_NewEnumerateStandardClassesIncludingResolved(
1087 JSContext
* cx
, JS::HandleObject obj
, JS::MutableHandleIdVector properties
,
1088 bool enumerableOnly
) {
1089 return EnumerateStandardClasses(cx
, obj
, properties
, enumerableOnly
, true);
1092 JS_PUBLIC_API
bool JS_GetClassObject(JSContext
* cx
, JSProtoKey key
,
1093 MutableHandleObject objp
) {
1096 JSObject
* obj
= GlobalObject::getOrCreateConstructor(cx
, key
);
1104 JS_PUBLIC_API
bool JS_GetClassPrototype(JSContext
* cx
, JSProtoKey key
,
1105 MutableHandleObject objp
) {
1109 // Bound functions don't have their own prototype object: they reuse the
1110 // prototype of the target object. This is typically Function.prototype so we
1112 if (key
== JSProto_BoundFunction
) {
1113 key
= JSProto_Function
;
1116 JSObject
* proto
= GlobalObject::getOrCreatePrototype(cx
, key
);
1126 JS_PUBLIC_API
void ProtoKeyToId(JSContext
* cx
, JSProtoKey key
,
1127 MutableHandleId idp
) {
1128 idp
.set(NameToId(ClassName(key
, cx
)));
1131 } /* namespace JS */
1133 JS_PUBLIC_API JSProtoKey
JS_IdToProtoKey(JSContext
* cx
, HandleId id
) {
1139 return JSProto_Null
;
1142 JSAtom
* atom
= id
.toAtom();
1143 const JSStdName
* stdnm
=
1144 LookupStdName(cx
->names(), atom
, standard_class_names
);
1146 return JSProto_Null
;
1149 if (GlobalObject::skipDeselectedConstructor(cx
, stdnm
->key
)) {
1150 return JSProto_Null
;
1153 if (SkipSharedArrayBufferConstructor(stdnm
->key
, cx
->global())) {
1154 MOZ_ASSERT(id
== NameToId(cx
->names().SharedArrayBuffer
));
1155 return JSProto_Null
;
1158 if (SkipUneval(id
, cx
)) {
1159 return JSProto_Null
;
1162 static_assert(std::size(standard_class_names
) == JSProto_LIMIT
+ 1);
1163 return static_cast<JSProtoKey
>(stdnm
- standard_class_names
);
1166 extern JS_PUBLIC_API
bool JS_IsGlobalObject(JSObject
* obj
) {
1167 return obj
->is
<GlobalObject
>();
1170 extern JS_PUBLIC_API JSObject
* JS_GlobalLexicalEnvironment(JSObject
* obj
) {
1171 return &obj
->as
<GlobalObject
>().lexicalEnvironment();
1174 extern JS_PUBLIC_API
bool JS_HasExtensibleLexicalEnvironment(JSObject
* obj
) {
1175 return obj
->is
<GlobalObject
>() ||
1176 ObjectRealm::get(obj
).getNonSyntacticLexicalEnvironment(obj
);
1179 extern JS_PUBLIC_API JSObject
* JS_ExtensibleLexicalEnvironment(JSObject
* obj
) {
1180 return ExtensibleLexicalEnvironmentObject::forVarEnvironment(obj
);
1183 JS_PUBLIC_API JSObject
* JS::CurrentGlobalOrNull(JSContext
* cx
) {
1184 AssertHeapIsIdleOrIterating();
1189 return cx
->global();
1192 JS_PUBLIC_API JSObject
* JS::GetNonCCWObjectGlobal(JSObject
* obj
) {
1193 AssertHeapIsIdleOrIterating();
1194 MOZ_DIAGNOSTIC_ASSERT(!IsCrossCompartmentWrapper(obj
));
1195 return &obj
->nonCCWGlobal();
1198 JS_PUBLIC_API
bool JS::detail::ComputeThis(JSContext
* cx
, Value
* vp
,
1199 MutableHandleObject thisObject
) {
1201 cx
->check(vp
[0], vp
[1]);
1203 MutableHandleValue thisv
= MutableHandleValue::fromMarkedLocation(&vp
[1]);
1204 JSObject
* obj
= BoxNonStrictThis(cx
, thisv
);
1209 thisObject
.set(obj
);
1213 static bool gProfileTimelineRecordingEnabled
= false;
1215 JS_PUBLIC_API
void JS::SetProfileTimelineRecordingEnabled(bool enabled
) {
1216 gProfileTimelineRecordingEnabled
= enabled
;
1219 JS_PUBLIC_API
bool JS::IsProfileTimelineRecordingEnabled() {
1220 return gProfileTimelineRecordingEnabled
;
1223 JS_PUBLIC_API
void* JS_malloc(JSContext
* cx
, size_t nbytes
) {
1226 return static_cast<void*>(cx
->maybe_pod_malloc
<uint8_t>(nbytes
));
1229 JS_PUBLIC_API
void* JS_realloc(JSContext
* cx
, void* p
, size_t oldBytes
,
1233 return static_cast<void*>(cx
->maybe_pod_realloc
<uint8_t>(
1234 static_cast<uint8_t*>(p
), oldBytes
, newBytes
));
1237 JS_PUBLIC_API
void JS_free(JSContext
* cx
, void* p
) { return js_free(p
); }
1239 JS_PUBLIC_API
void* JS_string_malloc(JSContext
* cx
, size_t nbytes
) {
1242 return static_cast<void*>(
1243 cx
->maybe_pod_arena_malloc
<uint8_t>(js::StringBufferArena
, nbytes
));
1246 JS_PUBLIC_API
void* JS_string_realloc(JSContext
* cx
, void* p
, size_t oldBytes
,
1250 return static_cast<void*>(cx
->maybe_pod_arena_realloc
<uint8_t>(
1251 js::StringBufferArena
, static_cast<uint8_t*>(p
), oldBytes
, newBytes
));
1254 JS_PUBLIC_API
void JS_string_free(JSContext
* cx
, void* p
) { return js_free(p
); }
1256 JS_PUBLIC_API
void JS::AddAssociatedMemory(JSObject
* obj
, size_t nbytes
,
1257 JS::MemoryUse use
) {
1263 Zone
* zone
= obj
->zone();
1264 MOZ_ASSERT(!IsInsideNursery(obj
));
1265 zone
->addCellMemory(obj
, nbytes
, js::MemoryUse(use
));
1266 zone
->maybeTriggerGCOnMalloc();
1269 JS_PUBLIC_API
void JS::RemoveAssociatedMemory(JSObject
* obj
, size_t nbytes
,
1270 JS::MemoryUse use
) {
1276 GCContext
* gcx
= obj
->runtimeFromMainThread()->gcContext();
1277 gcx
->removeCellMemory(obj
, nbytes
, js::MemoryUse(use
));
1282 JS_PUBLIC_API
bool JS_AddExtraGCRootsTracer(JSContext
* cx
,
1283 JSTraceDataOp traceOp
, void* data
) {
1284 return cx
->runtime()->gc
.addBlackRootsTracer(traceOp
, data
);
1287 JS_PUBLIC_API
void JS_RemoveExtraGCRootsTracer(JSContext
* cx
,
1288 JSTraceDataOp traceOp
,
1290 return cx
->runtime()->gc
.removeBlackRootsTracer(traceOp
, data
);
1293 JS_PUBLIC_API
JS::GCReason
JS::WantEagerMinorGC(JSRuntime
* rt
) {
1294 if (rt
->gc
.nursery().wantEagerCollection()) {
1295 return JS::GCReason::EAGER_NURSERY_COLLECTION
;
1297 return JS::GCReason::NO_REASON
;
1300 JS_PUBLIC_API
JS::GCReason
JS::WantEagerMajorGC(JSRuntime
* rt
) {
1301 return rt
->gc
.wantMajorGC(true);
1304 JS_PUBLIC_API
void JS::MaybeRunNurseryCollection(JSRuntime
* rt
,
1305 JS::GCReason reason
) {
1306 gc::GCRuntime
& gc
= rt
->gc
;
1307 if (gc
.nursery().wantEagerCollection()) {
1312 JS_PUBLIC_API
void JS::RunNurseryCollection(
1313 JSRuntime
* rt
, JS::GCReason reason
,
1314 mozilla::TimeDuration aSinceLastMinorGC
) {
1315 gc::GCRuntime
& gc
= rt
->gc
;
1316 if (!gc
.nursery().lastCollectionEndTime() ||
1317 (mozilla::TimeStamp::Now() - gc
.nursery().lastCollectionEndTime() >
1318 aSinceLastMinorGC
)) {
1323 JS_PUBLIC_API
void JS_GC(JSContext
* cx
, JS::GCReason reason
) {
1325 JS::PrepareForFullGC(cx
);
1326 cx
->runtime()->gc
.gc(JS::GCOptions::Normal
, reason
);
1329 JS_PUBLIC_API
void JS_MaybeGC(JSContext
* cx
) {
1331 cx
->runtime()->gc
.maybeGC();
1334 JS_PUBLIC_API
void JS_SetGCCallback(JSContext
* cx
, JSGCCallback cb
,
1337 cx
->runtime()->gc
.setGCCallback(cb
, data
);
1340 JS_PUBLIC_API
void JS_SetObjectsTenuredCallback(JSContext
* cx
,
1341 JSObjectsTenuredCallback cb
,
1344 cx
->runtime()->gc
.setObjectsTenuredCallback(cb
, data
);
1347 JS_PUBLIC_API
bool JS_AddFinalizeCallback(JSContext
* cx
, JSFinalizeCallback cb
,
1350 return cx
->runtime()->gc
.addFinalizeCallback(cb
, data
);
1353 JS_PUBLIC_API
void JS_RemoveFinalizeCallback(JSContext
* cx
,
1354 JSFinalizeCallback cb
) {
1355 cx
->runtime()->gc
.removeFinalizeCallback(cb
);
1358 JS_PUBLIC_API
void JS::SetHostCleanupFinalizationRegistryCallback(
1359 JSContext
* cx
, JSHostCleanupFinalizationRegistryCallback cb
, void* data
) {
1361 cx
->runtime()->gc
.setHostCleanupFinalizationRegistryCallback(cb
, data
);
1364 JS_PUBLIC_API
void JS::ClearKeptObjects(JSContext
* cx
) {
1365 gc::GCRuntime
* gc
= &cx
->runtime()->gc
;
1367 for (ZonesIter
zone(gc
, ZoneSelector::WithAtoms
); !zone
.done(); zone
.next()) {
1368 zone
->clearKeptObjects();
1372 JS_PUBLIC_API
bool JS::AtomsZoneIsCollecting(JSRuntime
* runtime
) {
1373 return runtime
->activeGCInAtomsZone();
1376 JS_PUBLIC_API
bool JS::IsAtomsZone(JS::Zone
* zone
) {
1377 return zone
->isAtomsZone();
1380 JS_PUBLIC_API
bool JS_AddWeakPointerZonesCallback(JSContext
* cx
,
1381 JSWeakPointerZonesCallback cb
,
1384 return cx
->runtime()->gc
.addWeakPointerZonesCallback(cb
, data
);
1387 JS_PUBLIC_API
void JS_RemoveWeakPointerZonesCallback(
1388 JSContext
* cx
, JSWeakPointerZonesCallback cb
) {
1389 cx
->runtime()->gc
.removeWeakPointerZonesCallback(cb
);
1392 JS_PUBLIC_API
bool JS_AddWeakPointerCompartmentCallback(
1393 JSContext
* cx
, JSWeakPointerCompartmentCallback cb
, void* data
) {
1395 return cx
->runtime()->gc
.addWeakPointerCompartmentCallback(cb
, data
);
1398 JS_PUBLIC_API
void JS_RemoveWeakPointerCompartmentCallback(
1399 JSContext
* cx
, JSWeakPointerCompartmentCallback cb
) {
1400 cx
->runtime()->gc
.removeWeakPointerCompartmentCallback(cb
);
1403 JS_PUBLIC_API
bool JS_UpdateWeakPointerAfterGC(JSTracer
* trc
,
1404 JS::Heap
<JSObject
*>* objp
) {
1405 return TraceWeakEdge(trc
, objp
);
1408 JS_PUBLIC_API
bool JS_UpdateWeakPointerAfterGCUnbarriered(JSTracer
* trc
,
1410 return TraceManuallyBarrieredWeakEdge(trc
, objp
, "External weak pointer");
1413 JS_PUBLIC_API
void JS_SetGCParameter(JSContext
* cx
, JSGCParamKey key
,
1415 // Bug 1742118: JS_SetGCParameter has no way to return an error
1416 // The GC ignores invalid values internally but this is not reported to the
1418 (void)cx
->runtime()->gc
.setParameter(cx
, key
, value
);
1421 JS_PUBLIC_API
void JS_ResetGCParameter(JSContext
* cx
, JSGCParamKey key
) {
1422 cx
->runtime()->gc
.resetParameter(cx
, key
);
1425 JS_PUBLIC_API
uint32_t JS_GetGCParameter(JSContext
* cx
, JSGCParamKey key
) {
1426 return cx
->runtime()->gc
.getParameter(key
);
1429 JS_PUBLIC_API
void JS_SetGCParametersBasedOnAvailableMemory(
1430 JSContext
* cx
, uint32_t availMemMB
) {
1436 static const JSGCConfig minimal
[] = {
1437 {JSGC_SLICE_TIME_BUDGET_MS
, 5},
1438 {JSGC_HIGH_FREQUENCY_TIME_LIMIT
, 1500},
1439 {JSGC_LARGE_HEAP_SIZE_MIN
, 250},
1440 {JSGC_SMALL_HEAP_SIZE_MAX
, 50},
1441 {JSGC_HIGH_FREQUENCY_SMALL_HEAP_GROWTH
, 300},
1442 {JSGC_HIGH_FREQUENCY_LARGE_HEAP_GROWTH
, 120},
1443 {JSGC_LOW_FREQUENCY_HEAP_GROWTH
, 120},
1444 {JSGC_ALLOCATION_THRESHOLD
, 15},
1445 {JSGC_MALLOC_THRESHOLD_BASE
, 20},
1446 {JSGC_SMALL_HEAP_INCREMENTAL_LIMIT
, 200},
1447 {JSGC_LARGE_HEAP_INCREMENTAL_LIMIT
, 110},
1448 {JSGC_URGENT_THRESHOLD_MB
, 8}};
1450 static const JSGCConfig nominal
[] = {
1451 {JSGC_SLICE_TIME_BUDGET_MS
, 5},
1452 {JSGC_HIGH_FREQUENCY_TIME_LIMIT
, 1000},
1453 {JSGC_LARGE_HEAP_SIZE_MIN
, 500},
1454 {JSGC_SMALL_HEAP_SIZE_MAX
, 100},
1455 {JSGC_HIGH_FREQUENCY_SMALL_HEAP_GROWTH
, 300},
1456 {JSGC_HIGH_FREQUENCY_LARGE_HEAP_GROWTH
, 150},
1457 {JSGC_LOW_FREQUENCY_HEAP_GROWTH
, 150},
1458 {JSGC_ALLOCATION_THRESHOLD
, 27},
1459 {JSGC_MALLOC_THRESHOLD_BASE
, 38},
1460 {JSGC_SMALL_HEAP_INCREMENTAL_LIMIT
, 150},
1461 {JSGC_LARGE_HEAP_INCREMENTAL_LIMIT
, 110},
1462 {JSGC_URGENT_THRESHOLD_MB
, 16}};
1464 const auto& configSet
= availMemMB
> 512 ? nominal
: minimal
;
1465 for (const auto& config
: configSet
) {
1466 JS_SetGCParameter(cx
, config
.key
, config
.value
);
1470 JS_PUBLIC_API JSString
* JS_NewExternalStringLatin1(
1471 JSContext
* cx
, const Latin1Char
* chars
, size_t length
,
1472 const JSExternalStringCallbacks
* callbacks
) {
1475 return JSExternalString::new_(cx
, chars
, length
, callbacks
);
1478 JS_PUBLIC_API JSString
* JS_NewExternalUCString(
1479 JSContext
* cx
, const char16_t
* chars
, size_t length
,
1480 const JSExternalStringCallbacks
* callbacks
) {
1483 return JSExternalString::new_(cx
, chars
, length
, callbacks
);
1486 JS_PUBLIC_API JSString
* JS_NewMaybeExternalStringLatin1(
1487 JSContext
* cx
, const JS::Latin1Char
* chars
, size_t length
,
1488 const JSExternalStringCallbacks
* callbacks
, bool* allocatedExternal
) {
1491 return NewMaybeExternalString(cx
, chars
, length
, callbacks
,
1495 JS_PUBLIC_API JSString
* JS_NewMaybeExternalStringUTF8(
1496 JSContext
* cx
, const JS::UTF8Chars
& utf8
,
1497 const JSExternalStringCallbacks
* callbacks
, bool* allocatedExternal
) {
1501 JS::SmallestEncoding encoding
= JS::FindSmallestEncoding(utf8
);
1502 if (encoding
== JS::SmallestEncoding::ASCII
) {
1503 // ASCII case can use the external buffer as Latin1 buffer.
1504 return NewMaybeExternalString(
1505 cx
, reinterpret_cast<JS::Latin1Char
*>(utf8
.begin().get()),
1506 utf8
.length(), callbacks
, allocatedExternal
);
1509 // Non-ASCII case cannot use the external buffer.
1510 *allocatedExternal
= false;
1511 return NewStringCopyUTF8N(cx
, utf8
, encoding
);
1514 JS_PUBLIC_API JSString
* JS_NewMaybeExternalUCString(
1515 JSContext
* cx
, const char16_t
* chars
, size_t length
,
1516 const JSExternalStringCallbacks
* callbacks
, bool* allocatedExternal
) {
1519 return NewMaybeExternalString(cx
, chars
, length
, callbacks
,
1523 extern JS_PUBLIC_API
const JSExternalStringCallbacks
*
1524 JS_GetExternalStringCallbacks(JSString
* str
) {
1525 return str
->asExternal().callbacks();
1528 static void SetNativeStackSize(JSContext
* cx
, JS::StackKind kind
,
1529 JS::NativeStackSize stackSize
) {
1531 cx
->nativeStackLimit
[kind
] = JS::WASINativeStackLimit
;
1533 if (stackSize
== 0) {
1534 cx
->nativeStackLimit
[kind
] = JS::NativeStackLimitMax
;
1536 cx
->nativeStackLimit
[kind
] =
1537 JS::GetNativeStackLimit(cx
->nativeStackBase(), stackSize
- 1);
1542 JS_PUBLIC_API
void JS_SetNativeStackQuota(
1543 JSContext
* cx
, JS::NativeStackSize systemCodeStackSize
,
1544 JS::NativeStackSize trustedScriptStackSize
,
1545 JS::NativeStackSize untrustedScriptStackSize
) {
1546 MOZ_ASSERT(!cx
->activation());
1548 if (!trustedScriptStackSize
) {
1549 trustedScriptStackSize
= systemCodeStackSize
;
1551 MOZ_ASSERT(trustedScriptStackSize
< systemCodeStackSize
);
1554 if (!untrustedScriptStackSize
) {
1555 untrustedScriptStackSize
= trustedScriptStackSize
;
1557 MOZ_ASSERT(untrustedScriptStackSize
< trustedScriptStackSize
);
1560 SetNativeStackSize(cx
, JS::StackForSystemCode
, systemCodeStackSize
);
1561 SetNativeStackSize(cx
, JS::StackForTrustedScript
, trustedScriptStackSize
);
1562 SetNativeStackSize(cx
, JS::StackForUntrustedScript
, untrustedScriptStackSize
);
1564 cx
->initJitStackLimit();
1567 /************************************************************************/
1569 JS_PUBLIC_API
bool JS_ValueToId(JSContext
* cx
, HandleValue value
,
1570 MutableHandleId idp
) {
1574 return ToPropertyKey(cx
, value
, idp
);
1577 JS_PUBLIC_API
bool JS_StringToId(JSContext
* cx
, HandleString string
,
1578 MutableHandleId idp
) {
1582 RootedValue
value(cx
, StringValue(string
));
1583 return PrimitiveValueToId
<CanGC
>(cx
, value
, idp
);
1586 JS_PUBLIC_API
bool JS_IdToValue(JSContext
* cx
, jsid id
, MutableHandleValue vp
) {
1590 vp
.set(IdToValue(id
));
1595 JS_PUBLIC_API
bool JS::ToPrimitive(JSContext
* cx
, HandleObject obj
, JSType hint
,
1596 MutableHandleValue vp
) {
1600 MOZ_ASSERT(obj
!= nullptr);
1601 MOZ_ASSERT(hint
== JSTYPE_UNDEFINED
|| hint
== JSTYPE_STRING
||
1602 hint
== JSTYPE_NUMBER
);
1604 return ToPrimitiveSlow(cx
, hint
, vp
);
1607 JS_PUBLIC_API
bool JS::GetFirstArgumentAsTypeHint(JSContext
* cx
,
1608 const CallArgs
& args
,
1610 if (!args
.get(0).isString()) {
1611 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr,
1612 JSMSG_NOT_EXPECTED_TYPE
, "Symbol.toPrimitive",
1613 "\"string\", \"number\", or \"default\"",
1614 InformalValueTypeName(args
.get(0)));
1618 RootedString
str(cx
, args
.get(0).toString());
1621 if (!EqualStrings(cx
, str
, cx
->names().default_
, &match
)) {
1625 *result
= JSTYPE_UNDEFINED
;
1629 if (!EqualStrings(cx
, str
, cx
->names().string
, &match
)) {
1633 *result
= JSTYPE_STRING
;
1637 if (!EqualStrings(cx
, str
, cx
->names().number
, &match
)) {
1641 *result
= JSTYPE_NUMBER
;
1646 const char* source
= ValueToSourceForError(cx
, args
.get(0), bytes
);
1648 ReportOutOfMemory(cx
);
1652 JS_ReportErrorNumberUTF8(cx
, GetErrorMessage
, nullptr,
1653 JSMSG_NOT_EXPECTED_TYPE
, "Symbol.toPrimitive",
1654 "\"string\", \"number\", or \"default\"", source
);
1658 JS_PUBLIC_API JSObject
* JS_InitClass(
1659 JSContext
* cx
, HandleObject obj
, const JSClass
* protoClass
,
1660 HandleObject protoProto
, const char* name
, JSNative constructor
,
1661 unsigned nargs
, const JSPropertySpec
* ps
, const JSFunctionSpec
* fs
,
1662 const JSPropertySpec
* static_ps
, const JSFunctionSpec
* static_fs
) {
1665 cx
->check(obj
, protoProto
);
1666 return InitClass(cx
, obj
, protoClass
, protoProto
, name
, constructor
, nargs
,
1667 ps
, fs
, static_ps
, static_fs
);
1670 JS_PUBLIC_API
bool JS_LinkConstructorAndPrototype(JSContext
* cx
,
1672 HandleObject proto
) {
1673 return LinkConstructorAndPrototype(cx
, ctor
, proto
);
1676 JS_PUBLIC_API
bool JS_InstanceOf(JSContext
* cx
, HandleObject obj
,
1677 const JSClass
* clasp
, CallArgs
* args
) {
1683 cx
->check(args
->thisv(), args
->calleev());
1686 if (!obj
|| obj
->getClass() != clasp
) {
1688 ReportIncompatibleMethod(cx
, *args
, clasp
);
1695 JS_PUBLIC_API
bool JS_HasInstance(JSContext
* cx
, HandleObject obj
,
1696 HandleValue value
, bool* bp
) {
1698 cx
->check(obj
, value
);
1699 return InstanceofOperator(cx
, obj
, value
, bp
);
1702 JS_PUBLIC_API JSObject
* JS_GetConstructor(JSContext
* cx
, HandleObject proto
) {
1707 RootedValue
cval(cx
);
1708 if (!GetProperty(cx
, proto
, proto
, cx
->names().constructor
, &cval
)) {
1711 if (!IsFunctionObject(cval
)) {
1712 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr,
1713 JSMSG_NO_CONSTRUCTOR
, proto
->getClass()->name
);
1716 return &cval
.toObject();
1719 JS::RealmCreationOptions
&
1720 JS::RealmCreationOptions::setNewCompartmentInSystemZone() {
1721 compSpec_
= CompartmentSpecifier::NewCompartmentInSystemZone
;
1726 JS::RealmCreationOptions
&
1727 JS::RealmCreationOptions::setNewCompartmentInExistingZone(JSObject
* obj
) {
1728 compSpec_
= CompartmentSpecifier::NewCompartmentInExistingZone
;
1729 zone_
= obj
->zone();
1733 JS::RealmCreationOptions
& JS::RealmCreationOptions::setExistingCompartment(
1735 compSpec_
= CompartmentSpecifier::ExistingCompartment
;
1736 comp_
= obj
->compartment();
1740 JS::RealmCreationOptions
& JS::RealmCreationOptions::setExistingCompartment(
1741 JS::Compartment
* compartment
) {
1742 compSpec_
= CompartmentSpecifier::ExistingCompartment
;
1743 comp_
= compartment
;
1747 JS::RealmCreationOptions
& JS::RealmCreationOptions::setNewCompartmentAndZone() {
1748 compSpec_
= CompartmentSpecifier::NewCompartmentAndZone
;
1753 const JS::RealmCreationOptions
& JS::RealmCreationOptionsRef(Realm
* realm
) {
1754 return realm
->creationOptions();
1757 const JS::RealmCreationOptions
& JS::RealmCreationOptionsRef(JSContext
* cx
) {
1758 return cx
->realm()->creationOptions();
1761 bool JS::RealmCreationOptions::getSharedMemoryAndAtomicsEnabled() const {
1762 return sharedMemoryAndAtomics_
;
1765 JS::RealmCreationOptions
&
1766 JS::RealmCreationOptions::setSharedMemoryAndAtomicsEnabled(bool flag
) {
1767 sharedMemoryAndAtomics_
= flag
;
1771 bool JS::RealmCreationOptions::getCoopAndCoepEnabled() const {
1772 return coopAndCoep_
;
1775 JS::RealmCreationOptions
& JS::RealmCreationOptions::setCoopAndCoepEnabled(
1777 coopAndCoep_
= flag
;
1781 JS::RealmCreationOptions
& JS::RealmCreationOptions::setLocaleCopyZ(
1782 const char* locale
) {
1783 const size_t size
= strlen(locale
) + 1;
1785 AutoEnterOOMUnsafeRegion oomUnsafe
;
1786 char* memoryPtr
= js_pod_malloc
<char>(sizeof(LocaleString
) + size
);
1788 oomUnsafe
.crash("RealmCreationOptions::setLocaleCopyZ");
1791 char* localePtr
= memoryPtr
+ sizeof(LocaleString
);
1792 memcpy(localePtr
, locale
, size
);
1794 locale_
= new (memoryPtr
) LocaleString(localePtr
);
1799 const JS::RealmBehaviors
& JS::RealmBehaviorsRef(JS::Realm
* realm
) {
1800 return realm
->behaviors();
1803 const JS::RealmBehaviors
& JS::RealmBehaviorsRef(JSContext
* cx
) {
1804 return cx
->realm()->behaviors();
1807 void JS::SetRealmNonLive(Realm
* realm
) { realm
->setNonLive(); }
1809 void JS::SetRealmReduceTimerPrecisionCallerType(Realm
* realm
,
1810 JS::RTPCallerTypeToken type
) {
1811 realm
->setReduceTimerPrecisionCallerType(type
);
1814 JS_PUBLIC_API JSObject
* JS_NewGlobalObject(JSContext
* cx
, const JSClass
* clasp
,
1815 JSPrincipals
* principals
,
1816 JS::OnNewGlobalHookOption hookOption
,
1817 const JS::RealmOptions
& options
) {
1819 cx
->runtime()->hasInitializedSelfHosting(),
1820 "Must call JS::InitSelfHostedCode() before creating a global");
1825 return GlobalObject::new_(cx
, clasp
, principals
, hookOption
, options
);
1828 JS_PUBLIC_API
void JS_GlobalObjectTraceHook(JSTracer
* trc
, JSObject
* global
) {
1829 GlobalObject
* globalObj
= &global
->as
<GlobalObject
>();
1830 Realm
* globalRealm
= globalObj
->realm();
1832 // If we GC when creating the global, we may not have set that global's
1833 // realm's global pointer yet. In this case, the realm will not yet contain
1834 // anything that needs to be traced.
1835 if (globalRealm
->unsafeUnbarrieredMaybeGlobal() != globalObj
) {
1839 // Trace the realm for any GC things that should only stick around if we
1840 // know the global is live.
1841 globalRealm
->traceGlobalData(trc
);
1843 globalObj
->traceData(trc
, globalObj
);
1845 if (JSTraceOp trace
= globalRealm
->creationOptions().getTrace()) {
1850 const JSClassOps
JS::DefaultGlobalClassOps
= {
1851 nullptr, // addProperty
1852 nullptr, // delProperty
1853 nullptr, // enumerate
1854 JS_NewEnumerateStandardClasses
, // newEnumerate
1855 JS_ResolveStandardClass
, // resolve
1856 JS_MayResolveStandardClass
, // mayResolve
1857 nullptr, // finalize
1859 nullptr, // construct
1860 JS_GlobalObjectTraceHook
, // trace
1863 JS_PUBLIC_API
void JS_FireOnNewGlobalObject(JSContext
* cx
,
1864 JS::HandleObject global
) {
1865 // This hook is infallible, because we don't really want arbitrary script
1866 // to be able to throw errors during delicate global creation routines.
1867 // This infallibility will eat OOM and slow script, but if that happens
1868 // we'll likely run up into them again soon in a fallible context.
1871 Rooted
<js::GlobalObject
*> globalObject(cx
, &global
->as
<GlobalObject
>());
1872 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
1873 if (JS::GetReduceMicrosecondTimePrecisionCallback()) {
1874 MOZ_DIAGNOSTIC_ASSERT(globalObject
->realm()
1876 .reduceTimerPrecisionCallerType()
1878 "Trying to create a global without setting an "
1879 "explicit RTPCallerType!");
1882 DebugAPI::onNewGlobalObject(cx
, globalObject
);
1883 cx
->runtime()->ensureRealmIsRecordingAllocations(globalObject
);
1886 JS_PUBLIC_API JSObject
* JS_NewObject(JSContext
* cx
, const JSClass
* clasp
) {
1887 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
1892 // Default class is Object.
1893 return NewPlainObject(cx
);
1896 MOZ_ASSERT(!clasp
->isJSFunction());
1897 MOZ_ASSERT(clasp
!= &PlainObject::class_
);
1898 MOZ_ASSERT(clasp
!= &ArrayObject::class_
);
1899 MOZ_ASSERT(!(clasp
->flags
& JSCLASS_IS_GLOBAL
));
1901 return NewBuiltinClassInstance(cx
, clasp
);
1904 JS_PUBLIC_API JSObject
* JS_NewObjectWithGivenProto(JSContext
* cx
,
1905 const JSClass
* clasp
,
1906 HandleObject proto
) {
1907 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
1913 // Default class is Object.
1914 return NewPlainObjectWithProto(cx
, proto
);
1917 MOZ_ASSERT(!clasp
->isJSFunction());
1918 MOZ_ASSERT(clasp
!= &PlainObject::class_
);
1919 MOZ_ASSERT(clasp
!= &ArrayObject::class_
);
1920 MOZ_ASSERT(!(clasp
->flags
& JSCLASS_IS_GLOBAL
));
1922 return NewObjectWithGivenProto(cx
, clasp
, proto
);
1925 JS_PUBLIC_API JSObject
* JS_NewPlainObject(JSContext
* cx
) {
1926 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
1930 return NewPlainObject(cx
);
1933 JS_PUBLIC_API JSObject
* JS_NewObjectForConstructor(JSContext
* cx
,
1934 const JSClass
* clasp
,
1935 const CallArgs
& args
) {
1939 MOZ_ASSERT(!clasp
->isJSFunction());
1940 MOZ_ASSERT(clasp
!= &PlainObject::class_
);
1941 MOZ_ASSERT(clasp
!= &ArrayObject::class_
);
1942 MOZ_ASSERT(!(clasp
->flags
& JSCLASS_IS_GLOBAL
));
1944 if (!ThrowIfNotConstructing(cx
, args
, clasp
->name
)) {
1948 RootedObject
newTarget(cx
, &args
.newTarget().toObject());
1949 cx
->check(newTarget
);
1951 RootedObject
proto(cx
);
1952 if (!GetPrototypeFromConstructor(cx
, newTarget
,
1953 JSCLASS_CACHED_PROTO_KEY(clasp
), &proto
)) {
1957 return NewObjectWithClassProto(cx
, clasp
, proto
);
1960 JS_PUBLIC_API
bool JS_IsNative(JSObject
* obj
) {
1961 return obj
->is
<NativeObject
>();
1964 JS_PUBLIC_API
void JS::AssertObjectBelongsToCurrentThread(JSObject
* obj
) {
1965 JSRuntime
* rt
= obj
->compartment()->runtimeFromAnyThread();
1966 MOZ_RELEASE_ASSERT(CurrentThreadCanAccessRuntime(rt
));
1969 JS_PUBLIC_API
void JS::SetFilenameValidationCallback(
1970 JS::FilenameValidationCallback cb
) {
1971 js::gFilenameValidationCallback
= cb
;
1974 JS_PUBLIC_API
void JS::SetHostEnsureCanAddPrivateElementHook(
1975 JSContext
* cx
, JS::EnsureCanAddPrivateElementOp op
) {
1976 cx
->runtime()->canAddPrivateElement
= op
;
1979 /*** Standard internal methods **********************************************/
1981 JS_PUBLIC_API
bool JS_GetPrototype(JSContext
* cx
, HandleObject obj
,
1982 MutableHandleObject result
) {
1984 return GetPrototype(cx
, obj
, result
);
1987 JS_PUBLIC_API
bool JS_SetPrototype(JSContext
* cx
, HandleObject obj
,
1988 HandleObject proto
) {
1991 cx
->check(obj
, proto
);
1993 return SetPrototype(cx
, obj
, proto
);
1996 JS_PUBLIC_API
bool JS_GetPrototypeIfOrdinary(JSContext
* cx
, HandleObject obj
,
1998 MutableHandleObject result
) {
2000 return GetPrototypeIfOrdinary(cx
, obj
, isOrdinary
, result
);
2003 JS_PUBLIC_API
bool JS_IsExtensible(JSContext
* cx
, HandleObject obj
,
2006 return IsExtensible(cx
, obj
, extensible
);
2009 JS_PUBLIC_API
bool JS_PreventExtensions(JSContext
* cx
, JS::HandleObject obj
,
2010 ObjectOpResult
& result
) {
2012 return PreventExtensions(cx
, obj
, result
);
2015 JS_PUBLIC_API
bool JS_SetImmutablePrototype(JSContext
* cx
, JS::HandleObject obj
,
2018 return SetImmutablePrototype(cx
, obj
, succeeded
);
2023 JS_PUBLIC_API
bool JS_FreezeObject(JSContext
* cx
, HandleObject obj
) {
2027 return FreezeObject(cx
, obj
);
2030 static bool DeepFreezeSlot(JSContext
* cx
, const Value
& v
) {
2031 if (v
.isPrimitive()) {
2034 RootedObject
obj(cx
, &v
.toObject());
2035 return JS_DeepFreezeObject(cx
, obj
);
2038 JS_PUBLIC_API
bool JS_DeepFreezeObject(JSContext
* cx
, HandleObject obj
) {
2043 // Assume that non-extensible objects are already deep-frozen, to avoid
2046 if (!IsExtensible(cx
, obj
, &extensible
)) {
2053 if (!FreezeObject(cx
, obj
)) {
2057 // Walk slots in obj and if any value is a non-null object, seal it.
2058 if (obj
->is
<NativeObject
>()) {
2059 Rooted
<NativeObject
*> nobj(cx
, &obj
->as
<NativeObject
>());
2060 for (uint32_t i
= 0, n
= nobj
->slotSpan(); i
< n
; ++i
) {
2061 if (!DeepFreezeSlot(cx
, nobj
->getSlot(i
))) {
2065 for (uint32_t i
= 0, n
= nobj
->getDenseInitializedLength(); i
< n
; ++i
) {
2066 if (!DeepFreezeSlot(cx
, nobj
->getDenseElement(i
))) {
2075 JS_PUBLIC_API
bool JSPropertySpec::getValue(JSContext
* cx
,
2076 MutableHandleValue vp
) const {
2077 MOZ_ASSERT(!isAccessor());
2079 switch (u
.value
.type
) {
2080 case ValueWrapper::Type::String
: {
2081 Rooted
<JSAtom
*> atom(cx
,
2082 Atomize(cx
, u
.value
.string
, strlen(u
.value
.string
)));
2090 case ValueWrapper::Type::Int32
:
2091 vp
.setInt32(u
.value
.int32
);
2094 case ValueWrapper::Type::Double
:
2095 vp
.setDouble(u
.value
.double_
);
2099 MOZ_CRASH("Unexpected type");
2102 bool PropertySpecNameToId(JSContext
* cx
, JSPropertySpec::Name name
,
2103 MutableHandleId id
) {
2104 if (name
.isSymbol()) {
2105 id
.set(PropertyKey::Symbol(cx
->wellKnownSymbols().get(name
.symbol())));
2107 JSAtom
* atom
= Atomize(cx
, name
.string(), strlen(name
.string()));
2111 id
.set(AtomToId(atom
));
2116 JS_PUBLIC_API
bool JS::PropertySpecNameToPermanentId(JSContext
* cx
,
2117 JSPropertySpec::Name name
,
2119 // We are calling fromMarkedLocation(idp) even though idp points to a
2120 // location that will never be marked. This is OK because the whole point
2121 // of this API is to populate *idp with a jsid that does not need to be
2123 MutableHandleId id
= MutableHandleId::fromMarkedLocation(idp
);
2124 if (!PropertySpecNameToId(cx
, name
, id
)) {
2128 if (id
.isString() && !PinAtom(cx
, &id
.toString()->asAtom())) {
2135 JS_PUBLIC_API
bool JS::ToCompletePropertyDescriptor(
2136 JSContext
* cx
, HandleValue descriptor
,
2137 MutableHandle
<PropertyDescriptor
> desc
) {
2140 cx
->check(descriptor
);
2141 if (!ToPropertyDescriptor(cx
, descriptor
, /* checkAccessors */ true, desc
)) {
2144 CompletePropertyDescriptor(desc
);
2148 JS_PUBLIC_API
void JS_SetAllNonReservedSlotsToUndefined(JS::HandleObject obj
) {
2149 if (!obj
->is
<NativeObject
>()) {
2153 NativeObject
& nobj
= obj
->as
<NativeObject
>();
2154 MOZ_RELEASE_ASSERT(!Watchtower::watchesPropertyModification(&nobj
));
2155 const JSClass
* clasp
= obj
->getClass();
2156 unsigned numReserved
= JSCLASS_RESERVED_SLOTS(clasp
);
2157 unsigned numSlots
= nobj
.slotSpan();
2158 for (unsigned i
= numReserved
; i
< numSlots
; i
++) {
2159 obj
->as
<NativeObject
>().setSlot(i
, UndefinedValue());
2163 JS_PUBLIC_API
void JS_SetReservedSlot(JSObject
* obj
, uint32_t index
,
2164 const Value
& value
) {
2165 // Note: we don't use setReservedSlot so that this also works on swappable DOM
2166 // objects. See NativeObject::getReservedSlotRef comment.
2167 NativeObject
& nobj
= obj
->as
<NativeObject
>();
2168 MOZ_ASSERT(index
< JSCLASS_RESERVED_SLOTS(obj
->getClass()));
2169 MOZ_ASSERT(!Watchtower::watchesPropertyModification(&nobj
));
2170 nobj
.setSlot(index
, value
);
2173 JS_PUBLIC_API
void JS_InitReservedSlot(JSObject
* obj
, uint32_t index
, void* ptr
,
2174 size_t nbytes
, JS::MemoryUse use
) {
2175 // Note: we don't use InitReservedSlot so that this also works on swappable
2176 // DOM objects. See NativeObject::getReservedSlotRef comment.
2177 MOZ_ASSERT(index
< JSCLASS_RESERVED_SLOTS(obj
->getClass()));
2178 AddCellMemory(obj
, nbytes
, js::MemoryUse(use
));
2179 obj
->as
<NativeObject
>().initSlot(index
, PrivateValue(ptr
));
2182 JS_PUBLIC_API
bool JS::IsMapObject(JSContext
* cx
, JS::HandleObject obj
,
2184 return IsGivenTypeObject(cx
, obj
, ESClass::Map
, isMap
);
2187 JS_PUBLIC_API
bool JS::IsSetObject(JSContext
* cx
, JS::HandleObject obj
,
2189 return IsGivenTypeObject(cx
, obj
, ESClass::Set
, isSet
);
2192 JS_PUBLIC_API
void JS_HoldPrincipals(JSPrincipals
* principals
) {
2193 ++principals
->refcount
;
2196 JS_PUBLIC_API
void JS_DropPrincipals(JSContext
* cx
, JSPrincipals
* principals
) {
2197 int rc
= --principals
->refcount
;
2199 JS::AutoSuppressGCAnalysis nogc
;
2200 cx
->runtime()->destroyPrincipals(principals
);
2204 JS_PUBLIC_API
void JS_SetSecurityCallbacks(JSContext
* cx
,
2205 const JSSecurityCallbacks
* scb
) {
2206 MOZ_ASSERT(scb
!= &NullSecurityCallbacks
);
2207 cx
->runtime()->securityCallbacks
= scb
? scb
: &NullSecurityCallbacks
;
2210 JS_PUBLIC_API
const JSSecurityCallbacks
* JS_GetSecurityCallbacks(
2212 return (cx
->runtime()->securityCallbacks
!= &NullSecurityCallbacks
)
2213 ? cx
->runtime()->securityCallbacks
.ref()
2217 JS_PUBLIC_API
void JS_SetTrustedPrincipals(JSContext
* cx
, JSPrincipals
* prin
) {
2218 cx
->runtime()->setTrustedPrincipals(prin
);
2221 extern JS_PUBLIC_API
void JS_InitDestroyPrincipalsCallback(
2222 JSContext
* cx
, JSDestroyPrincipalsOp destroyPrincipals
) {
2223 MOZ_ASSERT(destroyPrincipals
);
2224 MOZ_ASSERT(!cx
->runtime()->destroyPrincipals
);
2225 cx
->runtime()->destroyPrincipals
= destroyPrincipals
;
2228 extern JS_PUBLIC_API
void JS_InitReadPrincipalsCallback(
2229 JSContext
* cx
, JSReadPrincipalsOp read
) {
2231 MOZ_ASSERT(!cx
->runtime()->readPrincipals
);
2232 cx
->runtime()->readPrincipals
= read
;
2235 JS_PUBLIC_API JSFunction
* JS_NewFunction(JSContext
* cx
, JSNative native
,
2236 unsigned nargs
, unsigned flags
,
2238 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
2243 Rooted
<JSAtom
*> atom(cx
);
2245 atom
= Atomize(cx
, name
, strlen(name
));
2251 return (flags
& JSFUN_CONSTRUCTOR
)
2252 ? NewNativeConstructor(cx
, native
, nargs
, atom
)
2253 : NewNativeFunction(cx
, native
, nargs
, atom
);
2256 JS_PUBLIC_API JSFunction
* JS::GetSelfHostedFunction(JSContext
* cx
,
2257 const char* selfHostedName
,
2260 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
2265 Rooted
<JSAtom
*> name(cx
, IdToFunctionName(cx
, id
));
2270 JSAtom
* shAtom
= Atomize(cx
, selfHostedName
, strlen(selfHostedName
));
2274 Rooted
<PropertyName
*> shName(cx
, shAtom
->asPropertyName());
2275 RootedValue
funVal(cx
);
2276 if (!GlobalObject::getSelfHostedFunction(cx
, cx
->global(), shName
, name
,
2280 return &funVal
.toObject().as
<JSFunction
>();
2283 JS_PUBLIC_API JSFunction
* JS::NewFunctionFromSpec(JSContext
* cx
,
2284 const JSFunctionSpec
* fs
,
2289 if (fs
->name
.isSymbol()) {
2290 JS::Symbol
* sym
= cx
->wellKnownSymbols().get(fs
->name
.symbol());
2291 MOZ_ASSERT(PropertyKey::Symbol(sym
) == id
);
2293 MOZ_ASSERT(id
.isString() &&
2294 StringEqualsAscii(id
.toLinearString(), fs
->name
.string()));
2298 // Delay cloning self-hosted functions until they are called. This is
2299 // achieved by passing DefineFunction a nullptr JSNative which produces an
2300 // interpreted JSFunction where !hasScript. Interpreted call paths then
2301 // call InitializeLazyFunctionScript if !hasScript.
2302 if (fs
->selfHostedName
) {
2303 MOZ_ASSERT(!fs
->call
.op
);
2304 MOZ_ASSERT(!fs
->call
.info
);
2307 Atomize(cx
, fs
->selfHostedName
, strlen(fs
->selfHostedName
));
2311 Rooted
<PropertyName
*> shName(cx
, shAtom
->asPropertyName());
2312 Rooted
<JSAtom
*> name(cx
, IdToFunctionName(cx
, id
));
2316 RootedValue
funVal(cx
);
2317 if (!GlobalObject::getSelfHostedFunction(cx
, cx
->global(), shName
, name
,
2318 fs
->nargs
, &funVal
)) {
2321 return &funVal
.toObject().as
<JSFunction
>();
2324 Rooted
<JSAtom
*> atom(cx
, IdToFunctionName(cx
, id
));
2329 MOZ_ASSERT(fs
->call
.op
);
2332 if (fs
->flags
& JSFUN_CONSTRUCTOR
) {
2333 fun
= NewNativeConstructor(cx
, fs
->call
.op
, fs
->nargs
, atom
);
2335 fun
= NewNativeFunction(cx
, fs
->call
.op
, fs
->nargs
, atom
);
2341 if (auto* jitInfo
= fs
->call
.info
) {
2342 if (jitInfo
->type() == JSJitInfo::OpType::TrampolineNative
) {
2343 jit::SetTrampolineNativeJitEntry(cx
, fun
, jitInfo
->trampolineNative
);
2345 fun
->setJitInfo(jitInfo
);
2351 JS_PUBLIC_API JSFunction
* JS::NewFunctionFromSpec(JSContext
* cx
,
2352 const JSFunctionSpec
* fs
) {
2354 if (!PropertySpecNameToId(cx
, fs
->name
, &id
)) {
2358 return NewFunctionFromSpec(cx
, fs
, id
);
2361 JS_PUBLIC_API JSObject
* JS_GetFunctionObject(JSFunction
* fun
) { return fun
; }
2363 JS_PUBLIC_API
bool JS_GetFunctionId(JSContext
* cx
, JS::Handle
<JSFunction
*> fun
,
2364 JS::MutableHandle
<JSString
*> name
) {
2365 JS::Rooted
<JSAtom
*> atom(cx
);
2366 if (!fun
->getExplicitName(cx
, &atom
)) {
2373 JS_PUBLIC_API JSString
* JS_GetMaybePartialFunctionId(JSFunction
* fun
) {
2374 return fun
->maybePartialExplicitName();
2377 JS_PUBLIC_API
bool JS_GetFunctionDisplayId(JSContext
* cx
,
2378 JS::Handle
<JSFunction
*> fun
,
2379 JS::MutableHandle
<JSString
*> name
) {
2380 JS::Rooted
<JSAtom
*> atom(cx
);
2381 if (!fun
->getDisplayAtom(cx
, &atom
)) {
2388 JS_PUBLIC_API JSString
* JS_GetMaybePartialFunctionDisplayId(JSFunction
* fun
) {
2389 return fun
->maybePartialDisplayAtom();
2392 JS_PUBLIC_API
uint16_t JS_GetFunctionArity(JSFunction
* fun
) {
2393 return fun
->nargs();
2396 JS_PUBLIC_API
bool JS_GetFunctionLength(JSContext
* cx
, HandleFunction fun
,
2399 return JSFunction::getLength(cx
, fun
, length
);
2402 JS_PUBLIC_API
bool JS_ObjectIsFunction(JSObject
* obj
) {
2403 return obj
->is
<JSFunction
>();
2406 JS_PUBLIC_API
bool JS_IsNativeFunction(JSObject
* funobj
, JSNative call
) {
2407 if (!funobj
->is
<JSFunction
>()) {
2410 JSFunction
* fun
= &funobj
->as
<JSFunction
>();
2411 return fun
->isNativeFun() && fun
->native() == call
;
2414 extern JS_PUBLIC_API
bool JS_IsConstructor(JSFunction
* fun
) {
2415 return fun
->isConstructor();
2418 void JS::TransitiveCompileOptions::copyPODTransitiveOptions(
2419 const TransitiveCompileOptions
& rhs
) {
2420 // filename_, introducerFilename_, sourceMapURL_ should be handled in caller.
2422 mutedErrors_
= rhs
.mutedErrors_
;
2423 forceStrictMode_
= rhs
.forceStrictMode_
;
2424 alwaysUseFdlibm_
= rhs
.alwaysUseFdlibm_
;
2425 skipFilenameValidation_
= rhs
.skipFilenameValidation_
;
2426 hideScriptFromDebugger_
= rhs
.hideScriptFromDebugger_
;
2427 deferDebugMetadata_
= rhs
.deferDebugMetadata_
;
2428 eagerDelazificationStrategy_
= rhs
.eagerDelazificationStrategy_
;
2430 selfHostingMode
= rhs
.selfHostingMode
;
2431 discardSource
= rhs
.discardSource
;
2432 sourceIsLazy
= rhs
.sourceIsLazy
;
2433 allowHTMLComments
= rhs
.allowHTMLComments
;
2434 nonSyntacticScope
= rhs
.nonSyntacticScope
;
2436 topLevelAwait
= rhs
.topLevelAwait
;
2438 borrowBuffer
= rhs
.borrowBuffer
;
2439 usePinnedBytecode
= rhs
.usePinnedBytecode
;
2440 deoptimizeModuleGlobalVars
= rhs
.deoptimizeModuleGlobalVars
;
2442 prefableOptions_
= rhs
.prefableOptions_
;
2444 introductionType
= rhs
.introductionType
;
2445 introductionLineno
= rhs
.introductionLineno
;
2446 introductionOffset
= rhs
.introductionOffset
;
2447 hasIntroductionInfo
= rhs
.hasIntroductionInfo
;
2450 void JS::ReadOnlyCompileOptions::copyPODNonTransitiveOptions(
2451 const ReadOnlyCompileOptions
& rhs
) {
2452 lineno
= rhs
.lineno
;
2453 column
= rhs
.column
;
2454 scriptSourceOffset
= rhs
.scriptSourceOffset
;
2455 isRunOnce
= rhs
.isRunOnce
;
2456 noScriptRval
= rhs
.noScriptRval
;
2459 JS::OwningCompileOptions::OwningCompileOptions(JSContext
* cx
) {}
2461 void JS::OwningCompileOptions::release() {
2462 // OwningCompileOptions always owns these, so these casts are okay.
2463 js_free(const_cast<char*>(filename_
.c_str()));
2464 js_free(const_cast<char16_t
*>(sourceMapURL_
));
2465 js_free(const_cast<char*>(introducerFilename_
.c_str()));
2467 filename_
= JS::ConstUTF8CharsZ();
2468 sourceMapURL_
= nullptr;
2469 introducerFilename_
= JS::ConstUTF8CharsZ();
2472 JS::OwningCompileOptions::~OwningCompileOptions() { release(); }
2474 size_t JS::OwningCompileOptions::sizeOfExcludingThis(
2475 mozilla::MallocSizeOf mallocSizeOf
) const {
2476 return mallocSizeOf(filename_
.c_str()) + mallocSizeOf(sourceMapURL_
) +
2477 mallocSizeOf(introducerFilename_
.c_str());
2480 void JS::OwningCompileOptions::steal(JS::OwningCompileOptions
&& rhs
) {
2481 // Release existing string allocations.
2484 copyPODNonTransitiveOptions(rhs
);
2485 copyPODTransitiveOptions(rhs
);
2487 filename_
= rhs
.filename_
;
2488 rhs
.filename_
= JS::ConstUTF8CharsZ();
2489 introducerFilename_
= rhs
.introducerFilename_
;
2490 rhs
.introducerFilename_
= JS::ConstUTF8CharsZ();
2491 sourceMapURL_
= rhs
.sourceMapURL_
;
2492 rhs
.sourceMapURL_
= nullptr;
2495 void JS::OwningCompileOptions::steal(JS::OwningDecodeOptions
&& rhs
) {
2496 // Release existing string allocations.
2499 rhs
.copyPODOptionsTo(*this);
2501 introducerFilename_
= rhs
.introducerFilename_
;
2502 rhs
.introducerFilename_
= JS::ConstUTF8CharsZ();
2505 template <typename ContextT
>
2506 bool JS::OwningCompileOptions::copyImpl(ContextT
* cx
,
2507 const ReadOnlyCompileOptions
& rhs
) {
2508 // Release existing string allocations.
2511 copyPODNonTransitiveOptions(rhs
);
2512 copyPODTransitiveOptions(rhs
);
2514 if (rhs
.filename()) {
2515 const char* str
= DuplicateString(cx
, rhs
.filename().c_str()).release();
2519 filename_
= JS::ConstUTF8CharsZ(str
);
2522 if (rhs
.sourceMapURL()) {
2523 sourceMapURL_
= DuplicateString(cx
, rhs
.sourceMapURL()).release();
2524 if (!sourceMapURL_
) {
2529 if (rhs
.introducerFilename()) {
2531 DuplicateString(cx
, rhs
.introducerFilename().c_str()).release();
2535 introducerFilename_
= JS::ConstUTF8CharsZ(str
);
2541 bool JS::OwningCompileOptions::copy(JSContext
* cx
,
2542 const ReadOnlyCompileOptions
& rhs
) {
2543 return copyImpl(cx
, rhs
);
2546 bool JS::OwningCompileOptions::copy(JS::FrontendContext
* fc
,
2547 const ReadOnlyCompileOptions
& rhs
) {
2548 return copyImpl(fc
, rhs
);
2551 JS::CompileOptions::CompileOptions(JSContext
* cx
) {
2552 prefableOptions_
= cx
->options().compileOptions();
2554 if (cx
->options().asmJSOption() == AsmJSOption::Enabled
) {
2555 if (!js::IsAsmJSCompilationAvailable(cx
)) {
2556 prefableOptions_
.setAsmJSOption(AsmJSOption::DisabledByNoWasmCompiler
);
2557 } else if (cx
->realm() && (cx
->realm()->debuggerObservesWasm() ||
2558 cx
->realm()->debuggerObservesAsmJS())) {
2559 prefableOptions_
.setAsmJSOption(AsmJSOption::DisabledByDebugger
);
2563 // Certain modes of operation disallow syntax parsing in general.
2564 if (coverage::IsLCovEnabled()) {
2565 eagerDelazificationStrategy_
= DelazificationOption::ParseEverythingEagerly
;
2568 // Note: If we parse outside of a specific realm, we do not inherit any realm
2569 // behaviours. These can still be set manually on the options though.
2570 if (Realm
* realm
= cx
->realm()) {
2571 alwaysUseFdlibm_
= realm
->creationOptions().alwaysUseFdlibm();
2572 discardSource
= realm
->behaviors().discardSource();
2576 CompileOptions
& CompileOptions::setIntroductionInfoToCaller(
2577 JSContext
* cx
, const char* introductionType
,
2578 MutableHandle
<JSScript
*> introductionScript
) {
2579 RootedScript
maybeScript(cx
);
2580 const char* filename
;
2584 DescribeScriptedCallerForCompilation(cx
, &maybeScript
, &filename
, &lineno
,
2585 &pcOffset
, &mutedErrors
);
2587 introductionScript
.set(maybeScript
);
2588 return setIntroductionInfo(filename
, introductionType
, lineno
, pcOffset
);
2590 return setIntroductionType(introductionType
);
2593 JS::OwningDecodeOptions::~OwningDecodeOptions() { release(); }
2595 void JS::OwningDecodeOptions::release() {
2596 js_free(const_cast<char*>(introducerFilename_
.c_str()));
2598 introducerFilename_
= JS::ConstUTF8CharsZ();
2601 bool JS::OwningDecodeOptions::copy(JS::FrontendContext
* maybeFc
,
2602 const JS::ReadOnlyDecodeOptions
& rhs
) {
2603 copyPODOptionsFrom(rhs
);
2605 if (rhs
.introducerFilename()) {
2606 MOZ_ASSERT(maybeFc
);
2608 DuplicateString(maybeFc
, rhs
.introducerFilename().c_str()).release();
2612 introducerFilename_
= JS::ConstUTF8CharsZ(str
);
2618 void JS::OwningDecodeOptions::infallibleCopy(
2619 const JS::ReadOnlyDecodeOptions
& rhs
) {
2620 copyPODOptionsFrom(rhs
);
2622 MOZ_ASSERT(!rhs
.introducerFilename());
2625 size_t JS::OwningDecodeOptions::sizeOfExcludingThis(
2626 mozilla::MallocSizeOf mallocSizeOf
) const {
2627 return mallocSizeOf(introducerFilename_
.c_str());
2630 JS_PUBLIC_API JSObject
* JS_GetGlobalFromScript(JSScript
* script
) {
2631 return &script
->global();
2634 JS_PUBLIC_API
const char* JS_GetScriptFilename(JSScript
* script
) {
2635 // This is called from ThreadStackHelper which can be called from another
2636 // thread or inside a signal hander, so we need to be careful in case a
2637 // copmacting GC is currently moving things around.
2638 return script
->maybeForwardedFilename();
2641 JS_PUBLIC_API
unsigned JS_GetScriptBaseLineNumber(JSContext
* cx
,
2643 return script
->lineno();
2646 JS_PUBLIC_API JSScript
* JS_GetFunctionScript(JSContext
* cx
,
2647 HandleFunction fun
) {
2648 if (fun
->isNativeFun()) {
2652 if (fun
->hasBytecode()) {
2653 return fun
->nonLazyScript();
2656 AutoRealm
ar(cx
, fun
);
2657 JSScript
* script
= JSFunction::getOrCreateScript(cx
, fun
);
2664 JS_PUBLIC_API JSString
* JS_DecompileScript(JSContext
* cx
, HandleScript script
) {
2665 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
2669 RootedFunction
fun(cx
, script
->function());
2671 return JS_DecompileFunction(cx
, fun
);
2674 if (!ScriptSource::loadSource(cx
, script
->scriptSource(), &haveSource
)) {
2677 return haveSource
? JSScript::sourceData(cx
, script
)
2678 : NewStringCopyZ
<CanGC
>(cx
, "[no source]");
2681 JS_PUBLIC_API JSString
* JS_DecompileFunction(JSContext
* cx
,
2682 HandleFunction fun
) {
2683 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
2687 return FunctionToString(cx
, fun
, /* isToSource = */ false);
2690 JS_PUBLIC_API
void JS::SetScriptPrivate(JSScript
* script
,
2691 const JS::Value
& value
) {
2692 JSRuntime
* rt
= script
->zone()->runtimeFromMainThread();
2693 script
->sourceObject()->setPrivate(rt
, value
);
2696 JS_PUBLIC_API
JS::Value
JS::GetScriptPrivate(JSScript
* script
) {
2697 return script
->sourceObject()->getPrivate();
2700 JS_PUBLIC_API
JS::Value
JS::GetScriptedCallerPrivate(JSContext
* cx
) {
2704 NonBuiltinFrameIter
iter(cx
, cx
->realm()->principals());
2705 if (iter
.done() || !iter
.hasScript()) {
2706 return UndefinedValue();
2709 return iter
.script()->sourceObject()->getPrivate();
2712 JS_PUBLIC_API
void JS::SetScriptPrivateReferenceHooks(
2713 JSRuntime
* rt
, JS::ScriptPrivateReferenceHook addRefHook
,
2714 JS::ScriptPrivateReferenceHook releaseHook
) {
2716 rt
->scriptPrivateAddRefHook
= addRefHook
;
2717 rt
->scriptPrivateReleaseHook
= releaseHook
;
2720 JS_PUBLIC_API
void JS::SetWaitCallback(JSRuntime
* rt
,
2721 BeforeWaitCallback beforeWait
,
2722 AfterWaitCallback afterWait
,
2723 size_t requiredMemory
) {
2724 MOZ_RELEASE_ASSERT(requiredMemory
<= WAIT_CALLBACK_CLIENT_MAXMEM
);
2725 MOZ_RELEASE_ASSERT((beforeWait
== nullptr) == (afterWait
== nullptr));
2726 rt
->beforeWaitCallback
= beforeWait
;
2727 rt
->afterWaitCallback
= afterWait
;
2730 JS_PUBLIC_API
bool JS_CheckForInterrupt(JSContext
* cx
) {
2731 return js::CheckForInterrupt(cx
);
2734 JS_PUBLIC_API
bool JS_AddInterruptCallback(JSContext
* cx
,
2735 JSInterruptCallback callback
) {
2736 return cx
->interruptCallbacks().append(callback
);
2739 JS_PUBLIC_API
bool JS_DisableInterruptCallback(JSContext
* cx
) {
2740 bool result
= cx
->interruptCallbackDisabled
;
2741 cx
->interruptCallbackDisabled
= true;
2745 JS_PUBLIC_API
void JS_ResetInterruptCallback(JSContext
* cx
, bool enable
) {
2746 cx
->interruptCallbackDisabled
= enable
;
2749 /************************************************************************/
2754 JS_PUBLIC_API
void JS::SetJobQueue(JSContext
* cx
, JobQueue
* queue
) {
2755 cx
->jobQueue
= queue
;
2758 extern JS_PUBLIC_API
void JS::SetPromiseRejectionTrackerCallback(
2759 JSContext
* cx
, PromiseRejectionTrackerCallback callback
,
2760 void* data
/* = nullptr */) {
2761 cx
->promiseRejectionTrackerCallback
= callback
;
2762 cx
->promiseRejectionTrackerCallbackData
= data
;
2765 extern JS_PUBLIC_API
void JS::JobQueueIsEmpty(JSContext
* cx
) {
2766 cx
->canSkipEnqueuingJobs
= true;
2769 extern JS_PUBLIC_API
void JS::JobQueueMayNotBeEmpty(JSContext
* cx
) {
2770 cx
->canSkipEnqueuingJobs
= false;
2773 JS_PUBLIC_API JSObject
* JS::NewPromiseObject(JSContext
* cx
,
2774 HandleObject executor
) {
2775 MOZ_ASSERT(!cx
->zone()->isAtomsZone());
2778 cx
->check(executor
);
2781 return PromiseObject::createSkippingExecutor(cx
);
2784 MOZ_ASSERT(IsCallable(executor
));
2785 return PromiseObject::create(cx
, executor
);
2788 JS_PUBLIC_API
bool JS::IsPromiseObject(JS::HandleObject obj
) {
2789 return obj
->is
<PromiseObject
>();
2792 JS_PUBLIC_API JSObject
* JS::GetPromiseConstructor(JSContext
* cx
) {
2794 Rooted
<GlobalObject
*> global(cx
, cx
->global());
2795 return GlobalObject::getOrCreatePromiseConstructor(cx
, global
);
2798 JS_PUBLIC_API JSObject
* JS::GetPromisePrototype(JSContext
* cx
) {
2800 Rooted
<GlobalObject
*> global(cx
, cx
->global());
2801 return GlobalObject::getOrCreatePromisePrototype(cx
, global
);
2804 JS_PUBLIC_API
JS::PromiseState
JS::GetPromiseState(JS::HandleObject promise
) {
2805 PromiseObject
* promiseObj
= promise
->maybeUnwrapIf
<PromiseObject
>();
2807 return JS::PromiseState::Pending
;
2810 return promiseObj
->state();
2813 JS_PUBLIC_API
uint64_t JS::GetPromiseID(JS::HandleObject promise
) {
2814 return promise
->as
<PromiseObject
>().getID();
2817 JS_PUBLIC_API
JS::Value
JS::GetPromiseResult(JS::HandleObject promiseObj
) {
2818 PromiseObject
* promise
= &promiseObj
->as
<PromiseObject
>();
2819 MOZ_ASSERT(promise
->state() != JS::PromiseState::Pending
);
2820 return promise
->state() == JS::PromiseState::Fulfilled
? promise
->value()
2821 : promise
->reason();
2824 JS_PUBLIC_API
bool JS::GetPromiseIsHandled(JS::HandleObject promise
) {
2825 PromiseObject
* promiseObj
= &promise
->as
<PromiseObject
>();
2826 return !promiseObj
->isUnhandled();
2829 static PromiseObject
* UnwrapPromise(JSContext
* cx
, JS::HandleObject promise
,
2830 mozilla::Maybe
<AutoRealm
>& ar
) {
2835 PromiseObject
* promiseObj
;
2836 if (IsWrapper(promise
)) {
2837 promiseObj
= promise
->maybeUnwrapAs
<PromiseObject
>();
2839 ReportAccessDenied(cx
);
2842 ar
.emplace(cx
, promiseObj
);
2844 promiseObj
= promise
.as
<PromiseObject
>();
2849 JS_PUBLIC_API
bool JS::SetSettledPromiseIsHandled(JSContext
* cx
,
2850 JS::HandleObject promise
) {
2851 mozilla::Maybe
<AutoRealm
> ar
;
2852 Rooted
<PromiseObject
*> promiseObj(cx
, UnwrapPromise(cx
, promise
, ar
));
2856 js::SetSettledPromiseIsHandled(cx
, promiseObj
);
2860 JS_PUBLIC_API
bool JS::SetAnyPromiseIsHandled(JSContext
* cx
,
2861 JS::HandleObject promise
) {
2862 mozilla::Maybe
<AutoRealm
> ar
;
2863 Rooted
<PromiseObject
*> promiseObj(cx
, UnwrapPromise(cx
, promise
, ar
));
2867 js::SetAnyPromiseIsHandled(cx
, promiseObj
);
2871 JS_PUBLIC_API JSObject
* JS::GetPromiseAllocationSite(JS::HandleObject promise
) {
2872 return promise
->as
<PromiseObject
>().allocationSite();
2875 JS_PUBLIC_API JSObject
* JS::GetPromiseResolutionSite(JS::HandleObject promise
) {
2876 return promise
->as
<PromiseObject
>().resolutionSite();
2880 JS_PUBLIC_API
void JS::DumpPromiseAllocationSite(JSContext
* cx
,
2881 JS::HandleObject promise
) {
2882 RootedObject
stack(cx
, promise
->as
<PromiseObject
>().allocationSite());
2883 JSPrincipals
* principals
= cx
->realm()->principals();
2884 UniqueChars stackStr
= BuildUTF8StackString(cx
, principals
, stack
);
2886 fputs(stackStr
.get(), stderr
);
2890 JS_PUBLIC_API
void JS::DumpPromiseResolutionSite(JSContext
* cx
,
2891 JS::HandleObject promise
) {
2892 RootedObject
stack(cx
, promise
->as
<PromiseObject
>().resolutionSite());
2893 JSPrincipals
* principals
= cx
->realm()->principals();
2894 UniqueChars stackStr
= BuildUTF8StackString(cx
, principals
, stack
);
2896 fputs(stackStr
.get(), stderr
);
2901 JS_PUBLIC_API JSObject
* JS::CallOriginalPromiseResolve(
2902 JSContext
* cx
, JS::HandleValue resolutionValue
) {
2905 cx
->check(resolutionValue
);
2907 RootedObject
promise(cx
,
2908 PromiseObject::unforgeableResolve(cx
, resolutionValue
));
2909 MOZ_ASSERT_IF(promise
, promise
->canUnwrapAs
<PromiseObject
>());
2913 JS_PUBLIC_API JSObject
* JS::CallOriginalPromiseReject(
2914 JSContext
* cx
, JS::HandleValue rejectionValue
) {
2917 cx
->check(rejectionValue
);
2919 RootedObject
promise(cx
,
2920 PromiseObject::unforgeableReject(cx
, rejectionValue
));
2921 MOZ_ASSERT_IF(promise
, promise
->canUnwrapAs
<PromiseObject
>());
2925 static bool ResolveOrRejectPromise(JSContext
* cx
, JS::HandleObject promiseObj
,
2926 JS::HandleValue resultOrReason_
,
2930 cx
->check(promiseObj
, resultOrReason_
);
2932 mozilla::Maybe
<AutoRealm
> ar
;
2933 Rooted
<PromiseObject
*> promise(cx
);
2934 RootedValue
resultOrReason(cx
, resultOrReason_
);
2935 if (IsWrapper(promiseObj
)) {
2936 promise
= promiseObj
->maybeUnwrapAs
<PromiseObject
>();
2938 ReportAccessDenied(cx
);
2941 ar
.emplace(cx
, promise
);
2942 if (!cx
->compartment()->wrap(cx
, &resultOrReason
)) {
2946 promise
= promiseObj
.as
<PromiseObject
>();
2949 return reject
? PromiseObject::reject(cx
, promise
, resultOrReason
)
2950 : PromiseObject::resolve(cx
, promise
, resultOrReason
);
2953 JS_PUBLIC_API
bool JS::ResolvePromise(JSContext
* cx
,
2954 JS::HandleObject promiseObj
,
2955 JS::HandleValue resolutionValue
) {
2956 return ResolveOrRejectPromise(cx
, promiseObj
, resolutionValue
, false);
2959 JS_PUBLIC_API
bool JS::RejectPromise(JSContext
* cx
, JS::HandleObject promiseObj
,
2960 JS::HandleValue rejectionValue
) {
2961 return ResolveOrRejectPromise(cx
, promiseObj
, rejectionValue
, true);
2964 JS_PUBLIC_API JSObject
* JS::CallOriginalPromiseThen(
2965 JSContext
* cx
, JS::HandleObject promiseObj
, JS::HandleObject onFulfilled
,
2966 JS::HandleObject onRejected
) {
2969 cx
->check(promiseObj
, onFulfilled
, onRejected
);
2971 MOZ_ASSERT_IF(onFulfilled
, IsCallable(onFulfilled
));
2972 MOZ_ASSERT_IF(onRejected
, IsCallable(onRejected
));
2974 return OriginalPromiseThen(cx
, promiseObj
, onFulfilled
, onRejected
);
2977 [[nodiscard
]] static bool ReactToPromise(JSContext
* cx
,
2978 JS::Handle
<JSObject
*> promiseObj
,
2979 JS::Handle
<JSObject
*> onFulfilled
,
2980 JS::Handle
<JSObject
*> onRejected
,
2981 UnhandledRejectionBehavior behavior
) {
2984 cx
->check(promiseObj
, onFulfilled
, onRejected
);
2986 MOZ_ASSERT_IF(onFulfilled
, IsCallable(onFulfilled
));
2987 MOZ_ASSERT_IF(onRejected
, IsCallable(onRejected
));
2989 Rooted
<PromiseObject
*> unwrappedPromise(cx
);
2991 RootedValue
promiseVal(cx
, ObjectValue(*promiseObj
));
2992 unwrappedPromise
= UnwrapAndTypeCheckValue
<PromiseObject
>(
2993 cx
, promiseVal
, [cx
, promiseObj
] {
2994 JS_ReportErrorNumberLatin1(cx
, GetErrorMessage
, nullptr,
2995 JSMSG_INCOMPATIBLE_PROTO
, "Promise",
2996 "then", promiseObj
->getClass()->name
);
2998 if (!unwrappedPromise
) {
3003 return ReactToUnwrappedPromise(cx
, unwrappedPromise
, onFulfilled
, onRejected
,
3007 JS_PUBLIC_API
bool JS::AddPromiseReactions(JSContext
* cx
,
3008 JS::HandleObject promiseObj
,
3009 JS::HandleObject onFulfilled
,
3010 JS::HandleObject onRejected
) {
3011 return ReactToPromise(cx
, promiseObj
, onFulfilled
, onRejected
,
3012 UnhandledRejectionBehavior::Report
);
3015 JS_PUBLIC_API
bool JS::AddPromiseReactionsIgnoringUnhandledRejection(
3016 JSContext
* cx
, JS::HandleObject promiseObj
, JS::HandleObject onFulfilled
,
3017 JS::HandleObject onRejected
) {
3018 return ReactToPromise(cx
, promiseObj
, onFulfilled
, onRejected
,
3019 UnhandledRejectionBehavior::Ignore
);
3022 JS_PUBLIC_API
JS::PromiseUserInputEventHandlingState
3023 JS::GetPromiseUserInputEventHandlingState(JS::HandleObject promiseObj_
) {
3024 PromiseObject
* promise
= promiseObj_
->maybeUnwrapIf
<PromiseObject
>();
3026 return JS::PromiseUserInputEventHandlingState::DontCare
;
3029 if (!promise
->requiresUserInteractionHandling()) {
3030 return JS::PromiseUserInputEventHandlingState::DontCare
;
3032 if (promise
->hadUserInteractionUponCreation()) {
3033 return JS::PromiseUserInputEventHandlingState::HadUserInteractionAtCreation
;
3035 return JS::PromiseUserInputEventHandlingState::
3036 DidntHaveUserInteractionAtCreation
;
3039 JS_PUBLIC_API
bool JS::SetPromiseUserInputEventHandlingState(
3040 JS::HandleObject promiseObj_
,
3041 JS::PromiseUserInputEventHandlingState state
) {
3042 PromiseObject
* promise
= promiseObj_
->maybeUnwrapIf
<PromiseObject
>();
3048 case JS::PromiseUserInputEventHandlingState::DontCare
:
3049 promise
->setRequiresUserInteractionHandling(false);
3051 case JS::PromiseUserInputEventHandlingState::HadUserInteractionAtCreation
:
3052 promise
->setRequiresUserInteractionHandling(true);
3053 promise
->setHadUserInteractionUponCreation(true);
3055 case JS::PromiseUserInputEventHandlingState::
3056 DidntHaveUserInteractionAtCreation
:
3057 promise
->setRequiresUserInteractionHandling(true);
3058 promise
->setHadUserInteractionUponCreation(false);
3061 MOZ_ASSERT_UNREACHABLE(
3062 "Invalid PromiseUserInputEventHandlingState enum value");
3069 * Unforgeable version of Promise.all for internal use.
3071 * Takes a dense array of Promise objects and returns a promise that's
3072 * resolved with an array of resolution values when all those promises ahve
3073 * been resolved, or rejected with the rejection value of the first rejected
3076 * Asserts that the array is dense and all entries are Promise objects.
3078 JS_PUBLIC_API JSObject
* JS::GetWaitForAllPromise(
3079 JSContext
* cx
, JS::HandleObjectVector promises
) {
3083 return js::GetWaitForAllPromise(cx
, promises
);
3086 JS_PUBLIC_API
void JS::InitDispatchToEventLoop(
3087 JSContext
* cx
, JS::DispatchToEventLoopCallback callback
, void* closure
) {
3088 cx
->runtime()->offThreadPromiseState
.ref().init(callback
, closure
);
3091 JS_PUBLIC_API
void JS::ShutdownAsyncTasks(JSContext
* cx
) {
3092 cx
->runtime()->offThreadPromiseState
.ref().shutdown(cx
);
3095 JS_PUBLIC_API
void JS::InitConsumeStreamCallback(
3096 JSContext
* cx
, ConsumeStreamCallback consume
,
3097 ReportStreamErrorCallback report
) {
3098 cx
->runtime()->consumeStreamCallback
= consume
;
3099 cx
->runtime()->reportStreamErrorCallback
= report
;
3102 JS_PUBLIC_API
void JS_RequestInterruptCallback(JSContext
* cx
) {
3103 cx
->requestInterrupt(InterruptReason::CallbackUrgent
);
3106 JS_PUBLIC_API
void JS_RequestInterruptCallbackCanWait(JSContext
* cx
) {
3107 cx
->requestInterrupt(InterruptReason::CallbackCanWait
);
3110 JS::AutoSetAsyncStackForNewCalls::AutoSetAsyncStackForNewCalls(
3111 JSContext
* cx
, HandleObject stack
, const char* asyncCause
,
3112 JS::AutoSetAsyncStackForNewCalls::AsyncCallKind kind
)
3114 oldAsyncStack(cx
, cx
->asyncStackForNewActivations()),
3115 oldAsyncCause(cx
->asyncCauseForNewActivations
),
3116 oldAsyncCallIsExplicit(cx
->asyncCallIsExplicit
) {
3119 // The option determines whether we actually use the new values at this
3120 // point. It will not affect restoring the previous values when the object
3121 // is destroyed, so if the option changes it won't cause consistency issues.
3122 if (!cx
->options().asyncStack()) {
3126 SavedFrame
* asyncStack
= &stack
->as
<SavedFrame
>();
3128 cx
->asyncStackForNewActivations() = asyncStack
;
3129 cx
->asyncCauseForNewActivations
= asyncCause
;
3130 cx
->asyncCallIsExplicit
= kind
== AsyncCallKind::EXPLICIT
;
3133 JS::AutoSetAsyncStackForNewCalls::~AutoSetAsyncStackForNewCalls() {
3134 cx
->asyncCauseForNewActivations
= oldAsyncCause
;
3135 cx
->asyncStackForNewActivations() =
3136 oldAsyncStack
? &oldAsyncStack
->as
<SavedFrame
>() : nullptr;
3137 cx
->asyncCallIsExplicit
= oldAsyncCallIsExplicit
;
3140 /************************************************************************/
3141 JS_PUBLIC_API JSString
* JS_NewStringCopyN(JSContext
* cx
, const char* s
,
3145 return NewStringCopyN
<CanGC
>(cx
, s
, n
);
3148 JS_PUBLIC_API JSString
* JS_NewStringCopyZ(JSContext
* cx
, const char* s
) {
3152 return cx
->runtime()->emptyString
;
3154 return NewStringCopyZ
<CanGC
>(cx
, s
);
3157 JS_PUBLIC_API JSString
* JS_NewStringCopyUTF8Z(JSContext
* cx
,
3158 const JS::ConstUTF8CharsZ s
) {
3161 return NewStringCopyUTF8Z(cx
, s
);
3164 JS_PUBLIC_API JSString
* JS_NewStringCopyUTF8N(JSContext
* cx
,
3165 const JS::UTF8Chars
& s
) {
3168 return NewStringCopyUTF8N(cx
, s
);
3171 JS_PUBLIC_API
bool JS_StringHasBeenPinned(JSContext
* cx
, JSString
* str
) {
3175 if (!str
->isAtom()) {
3179 return AtomIsPinned(cx
, &str
->asAtom());
3182 JS_PUBLIC_API JSString
* JS_AtomizeString(JSContext
* cx
, const char* s
) {
3183 return JS_AtomizeStringN(cx
, s
, strlen(s
));
3186 JS_PUBLIC_API JSString
* JS_AtomizeStringN(JSContext
* cx
, const char* s
,
3190 return Atomize(cx
, s
, length
);
3193 JS_PUBLIC_API JSString
* JS_AtomizeAndPinString(JSContext
* cx
, const char* s
) {
3194 return JS_AtomizeAndPinStringN(cx
, s
, strlen(s
));
3197 JS_PUBLIC_API JSString
* JS_AtomizeAndPinStringN(JSContext
* cx
, const char* s
,
3202 JSAtom
* atom
= cx
->zone() ? Atomize(cx
, s
, length
)
3203 : AtomizeWithoutActiveZone(cx
, s
, length
);
3204 if (!atom
|| !PinAtom(cx
, atom
)) {
3208 MOZ_ASSERT(JS_StringHasBeenPinned(cx
, atom
));
3212 JS_PUBLIC_API JSString
* JS_NewLatin1String(
3213 JSContext
* cx
, js::UniquePtr
<JS::Latin1Char
[], JS::FreePolicy
> chars
,
3217 return NewString
<CanGC
>(cx
, std::move(chars
), length
);
3220 JS_PUBLIC_API JSString
* JS_NewUCString(JSContext
* cx
,
3221 JS::UniqueTwoByteChars chars
,
3225 return NewString
<CanGC
>(cx
, std::move(chars
), length
);
3228 JS_PUBLIC_API JSString
* JS_NewUCStringDontDeflate(JSContext
* cx
,
3229 JS::UniqueTwoByteChars chars
,
3233 return NewStringDontDeflate
<CanGC
>(cx
, std::move(chars
), length
);
3236 JS_PUBLIC_API JSString
* JS_NewUCStringCopyN(JSContext
* cx
, const char16_t
* s
,
3241 return cx
->names().empty_
;
3243 return NewStringCopyN
<CanGC
>(cx
, s
, n
);
3246 JS_PUBLIC_API JSString
* JS_NewUCStringCopyZ(JSContext
* cx
, const char16_t
* s
) {
3250 return cx
->runtime()->emptyString
;
3252 return NewStringCopyZ
<CanGC
>(cx
, s
);
3255 JS_PUBLIC_API JSString
* JS_AtomizeUCString(JSContext
* cx
, const char16_t
* s
) {
3256 return JS_AtomizeUCStringN(cx
, s
, js_strlen(s
));
3259 JS_PUBLIC_API JSString
* JS_AtomizeUCStringN(JSContext
* cx
, const char16_t
* s
,
3263 return AtomizeChars(cx
, s
, length
);
3266 JS_PUBLIC_API
size_t JS_GetStringLength(JSString
* str
) { return str
->length(); }
3268 JS_PUBLIC_API
bool JS_StringIsLinear(JSString
* str
) { return str
->isLinear(); }
3270 JS_PUBLIC_API
bool JS_DeprecatedStringHasLatin1Chars(JSString
* str
) {
3271 return str
->hasLatin1Chars();
3274 JS_PUBLIC_API
const JS::Latin1Char
* JS_GetLatin1StringCharsAndLength(
3275 JSContext
* cx
, const JS::AutoRequireNoGC
& nogc
, JSString
* str
,
3277 MOZ_ASSERT(plength
);
3281 JSLinearString
* linear
= str
->ensureLinear(cx
);
3285 *plength
= linear
->length();
3286 return linear
->latin1Chars(nogc
);
3289 JS_PUBLIC_API
const char16_t
* JS_GetTwoByteStringCharsAndLength(
3290 JSContext
* cx
, const JS::AutoRequireNoGC
& nogc
, JSString
* str
,
3292 MOZ_ASSERT(plength
);
3296 JSLinearString
* linear
= str
->ensureLinear(cx
);
3300 *plength
= linear
->length();
3301 return linear
->twoByteChars(nogc
);
3304 JS_PUBLIC_API
const char16_t
* JS_GetTwoByteExternalStringChars(JSString
* str
) {
3305 return str
->asExternal().twoByteChars();
3308 JS_PUBLIC_API
bool JS_GetStringCharAt(JSContext
* cx
, JSString
* str
,
3309 size_t index
, char16_t
* res
) {
3314 JSLinearString
* linear
= str
->ensureLinear(cx
);
3319 *res
= linear
->latin1OrTwoByteChar(index
);
3323 JS_PUBLIC_API
bool JS_CopyStringChars(JSContext
* cx
,
3324 const mozilla::Range
<char16_t
>& dest
,
3330 JSLinearString
* linear
= str
->ensureLinear(cx
);
3335 MOZ_ASSERT(linear
->length() <= dest
.length());
3336 CopyChars(dest
.begin().get(), *linear
);
3340 extern JS_PUBLIC_API
JS::UniqueTwoByteChars
JS_CopyStringCharsZ(JSContext
* cx
,
3345 JSLinearString
* linear
= str
->ensureLinear(cx
);
3350 size_t len
= linear
->length();
3352 static_assert(JS::MaxStringLength
< UINT32_MAX
,
3353 "len + 1 must not overflow on 32-bit platforms");
3355 UniqueTwoByteChars
chars(cx
->pod_malloc
<char16_t
>(len
+ 1));
3360 CopyChars(chars
.get(), *linear
);
3366 extern JS_PUBLIC_API JSLinearString
* JS_EnsureLinearString(JSContext
* cx
,
3371 return str
->ensureLinear(cx
);
3374 JS_PUBLIC_API
bool JS_CompareStrings(JSContext
* cx
, JSString
* str1
,
3375 JSString
* str2
, int32_t* result
) {
3379 return CompareStrings(cx
, str1
, str2
, result
);
3382 JS_PUBLIC_API
bool JS_StringEqualsAscii(JSContext
* cx
, JSString
* str
,
3383 const char* asciiBytes
, bool* match
) {
3387 JSLinearString
* linearStr
= str
->ensureLinear(cx
);
3391 *match
= StringEqualsAscii(linearStr
, asciiBytes
);
3395 JS_PUBLIC_API
bool JS_StringEqualsAscii(JSContext
* cx
, JSString
* str
,
3396 const char* asciiBytes
, size_t length
,
3401 JSLinearString
* linearStr
= str
->ensureLinear(cx
);
3405 *match
= StringEqualsAscii(linearStr
, asciiBytes
, length
);
3409 JS_PUBLIC_API
bool JS_LinearStringEqualsAscii(JSLinearString
* str
,
3410 const char* asciiBytes
) {
3411 return StringEqualsAscii(str
, asciiBytes
);
3414 JS_PUBLIC_API
bool JS_LinearStringEqualsAscii(JSLinearString
* str
,
3415 const char* asciiBytes
,
3417 return StringEqualsAscii(str
, asciiBytes
, length
);
3420 JS_PUBLIC_API
size_t JS_PutEscapedLinearString(char* buffer
, size_t size
,
3421 JSLinearString
* str
,
3423 return PutEscapedString(buffer
, size
, str
, quote
);
3426 JS_PUBLIC_API
size_t JS_PutEscapedString(JSContext
* cx
, char* buffer
,
3427 size_t size
, JSString
* str
,
3430 JSLinearString
* linearStr
= str
->ensureLinear(cx
);
3434 return PutEscapedString(buffer
, size
, linearStr
, quote
);
3437 JS_PUBLIC_API JSString
* JS_NewDependentString(JSContext
* cx
, HandleString str
,
3438 size_t start
, size_t length
) {
3441 return NewDependentString(cx
, str
, start
, length
);
3444 JS_PUBLIC_API JSString
* JS_ConcatStrings(JSContext
* cx
, HandleString left
,
3445 HandleString right
) {
3448 return ConcatStrings
<CanGC
>(cx
, left
, right
);
3451 JS_PUBLIC_API
bool JS_DecodeBytes(JSContext
* cx
, const char* src
, size_t srclen
,
3452 char16_t
* dst
, size_t* dstlenp
) {
3461 size_t dstlen
= *dstlenp
;
3463 if (srclen
> dstlen
) {
3464 CopyAndInflateChars(dst
, src
, dstlen
);
3466 gc::AutoSuppressGC
suppress(cx
);
3467 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr,
3468 JSMSG_BUFFER_TOO_SMALL
);
3472 CopyAndInflateChars(dst
, src
, srclen
);
3477 JS_PUBLIC_API
JS::UniqueChars
JS_EncodeStringToASCII(JSContext
* cx
,
3482 return js::EncodeAscii(cx
, str
);
3485 JS_PUBLIC_API
JS::UniqueChars
JS_EncodeStringToLatin1(JSContext
* cx
,
3490 return js::EncodeLatin1(cx
, str
);
3493 JS_PUBLIC_API
JS::UniqueChars
JS_EncodeStringToUTF8(JSContext
* cx
,
3498 return StringToNewUTF8CharsZ(cx
, *str
);
3501 JS_PUBLIC_API
size_t JS_GetStringEncodingLength(JSContext
* cx
, JSString
* str
) {
3505 if (!str
->ensureLinear(cx
)) {
3508 return str
->length();
3511 JS_PUBLIC_API
bool JS_EncodeStringToBuffer(JSContext
* cx
, JSString
* str
,
3512 char* buffer
, size_t length
) {
3516 JSLinearString
* linear
= str
->ensureLinear(cx
);
3521 JS::AutoCheckCannotGC nogc
;
3522 size_t writeLength
= std::min(linear
->length(), length
);
3523 if (linear
->hasLatin1Chars()) {
3524 mozilla::PodCopy(reinterpret_cast<Latin1Char
*>(buffer
),
3525 linear
->latin1Chars(nogc
), writeLength
);
3527 const char16_t
* src
= linear
->twoByteChars(nogc
);
3528 for (size_t i
= 0; i
< writeLength
; i
++) {
3529 buffer
[i
] = char(src
[i
]);
3535 JS_PUBLIC_API
mozilla::Maybe
<std::tuple
<size_t, size_t>>
3536 JS_EncodeStringToUTF8BufferPartial(JSContext
* cx
, JSString
* str
,
3537 mozilla::Span
<char> buffer
) {
3540 JS::AutoCheckCannotGC nogc
;
3541 return str
->encodeUTF8Partial(nogc
, buffer
);
3544 JS_PUBLIC_API
JS::Symbol
* JS::NewSymbol(JSContext
* cx
,
3545 HandleString description
) {
3549 cx
->check(description
);
3552 return Symbol::new_(cx
, SymbolCode::UniqueSymbol
, description
);
3555 JS_PUBLIC_API
JS::Symbol
* JS::GetSymbolFor(JSContext
* cx
, HandleString key
) {
3560 return Symbol::for_(cx
, key
);
3563 JS_PUBLIC_API JSString
* JS::GetSymbolDescription(HandleSymbol symbol
) {
3564 return symbol
->description();
3567 JS_PUBLIC_API
JS::SymbolCode
JS::GetSymbolCode(Handle
<Symbol
*> symbol
) {
3568 return symbol
->code();
3571 JS_PUBLIC_API
JS::Symbol
* JS::GetWellKnownSymbol(JSContext
* cx
,
3572 JS::SymbolCode which
) {
3573 return cx
->wellKnownSymbols().get(which
);
3576 JS_PUBLIC_API
JS::PropertyKey
JS::GetWellKnownSymbolKey(JSContext
* cx
,
3577 JS::SymbolCode which
) {
3578 return PropertyKey::Symbol(cx
->wellKnownSymbols().get(which
));
3581 static bool AddPrefix(JSContext
* cx
, JS::Handle
<JS::PropertyKey
> id
,
3582 FunctionPrefixKind prefixKind
,
3583 JS::MutableHandle
<JS::PropertyKey
> out
) {
3584 JS::Rooted
<JSAtom
*> atom(cx
, js::IdToFunctionName(cx
, id
, prefixKind
));
3589 out
.set(JS::PropertyKey::NonIntAtom(atom
));
3593 JS_PUBLIC_API
bool JS::ToGetterId(JSContext
* cx
, JS::Handle
<JS::PropertyKey
> id
,
3594 JS::MutableHandle
<JS::PropertyKey
> getterId
) {
3595 return AddPrefix(cx
, id
, FunctionPrefixKind::Get
, getterId
);
3598 JS_PUBLIC_API
bool JS::ToSetterId(JSContext
* cx
, JS::Handle
<JS::PropertyKey
> id
,
3599 JS::MutableHandle
<JS::PropertyKey
> setterId
) {
3600 return AddPrefix(cx
, id
, FunctionPrefixKind::Set
, setterId
);
3604 static bool PropertySpecNameIsDigits(JSPropertySpec::Name name
) {
3605 if (name
.isSymbol()) {
3608 const char* s
= name
.string();
3613 if (*s
< '0' || *s
> '9') {
3621 JS_PUBLIC_API
bool JS::PropertySpecNameEqualsId(JSPropertySpec::Name name
,
3623 if (name
.isSymbol()) {
3624 return id
.isWellKnownSymbol(name
.symbol());
3627 MOZ_ASSERT(!PropertySpecNameIsDigits(name
));
3628 return id
.isAtom() && JS_LinearStringEqualsAscii(id
.toAtom(), name
.string());
3631 JS_PUBLIC_API
bool JS_Stringify(JSContext
* cx
, MutableHandleValue vp
,
3632 HandleObject replacer
, HandleValue space
,
3633 JSONWriteCallback callback
, void* data
) {
3636 cx
->check(replacer
, space
);
3637 StringBuffer
sb(cx
);
3638 if (!sb
.ensureTwoByteChars()) {
3641 if (!Stringify(cx
, vp
, replacer
, space
, sb
, StringifyBehavior::Normal
)) {
3644 if (sb
.empty() && !sb
.append(cx
->names().null
)) {
3647 return callback(sb
.rawTwoByteBegin(), sb
.length(), data
);
3650 JS_PUBLIC_API
bool JS::ToJSON(JSContext
* cx
, HandleValue value
,
3651 HandleObject replacer
, HandleValue space
,
3652 JSONWriteCallback callback
, void* data
) {
3655 cx
->check(replacer
, space
);
3656 StringBuffer
sb(cx
);
3657 if (!sb
.ensureTwoByteChars()) {
3660 RootedValue
v(cx
, value
);
3661 if (!Stringify(cx
, &v
, replacer
, space
, sb
, StringifyBehavior::Normal
)) {
3667 return callback(sb
.rawTwoByteBegin(), sb
.length(), data
);
3670 JS_PUBLIC_API
bool JS::ToJSONMaybeSafely(JSContext
* cx
, JS::HandleObject input
,
3671 JSONWriteCallback callback
,
3677 StringBuffer
sb(cx
);
3678 if (!sb
.ensureTwoByteChars()) {
3682 RootedValue
inputValue(cx
, ObjectValue(*input
));
3683 if (!Stringify(cx
, &inputValue
, nullptr, NullHandleValue
, sb
,
3684 StringifyBehavior::RestrictedSafe
))
3687 if (sb
.empty() && !sb
.append(cx
->names().null
)) {
3691 return callback(sb
.rawTwoByteBegin(), sb
.length(), data
);
3694 JS_PUBLIC_API
bool JS_ParseJSON(JSContext
* cx
, const char16_t
* chars
,
3695 uint32_t len
, MutableHandleValue vp
) {
3698 return ParseJSONWithReviver(cx
, mozilla::Range
<const char16_t
>(chars
, len
),
3699 NullHandleValue
, vp
);
3702 JS_PUBLIC_API
bool JS_ParseJSON(JSContext
* cx
, HandleString str
,
3703 MutableHandleValue vp
) {
3704 return JS_ParseJSONWithReviver(cx
, str
, NullHandleValue
, vp
);
3707 JS_PUBLIC_API
bool JS_ParseJSON(JSContext
* cx
, const Latin1Char
* chars
,
3708 uint32_t len
, MutableHandleValue vp
) {
3711 return ParseJSONWithReviver(cx
, mozilla::Range
<const Latin1Char
>(chars
, len
),
3712 NullHandleValue
, vp
);
3715 JS_PUBLIC_API
bool JS_ParseJSONWithReviver(JSContext
* cx
, const char16_t
* chars
,
3716 uint32_t len
, HandleValue reviver
,
3717 MutableHandleValue vp
) {
3720 return ParseJSONWithReviver(cx
, mozilla::Range
<const char16_t
>(chars
, len
),
3724 JS_PUBLIC_API
bool JS_ParseJSONWithReviver(JSContext
* cx
, HandleString str
,
3725 HandleValue reviver
,
3726 MutableHandleValue vp
) {
3731 AutoStableStringChars
stableChars(cx
);
3732 if (!stableChars
.init(cx
, str
)) {
3736 return stableChars
.isLatin1()
3737 ? ParseJSONWithReviver(cx
, stableChars
.latin1Range(), reviver
, vp
)
3738 : ParseJSONWithReviver(cx
, stableChars
.twoByteRange(), reviver
,
3742 /************************************************************************/
3744 JS_PUBLIC_API
void JS_ReportErrorASCII(JSContext
* cx
, const char* format
, ...) {
3748 va_start(ap
, format
);
3749 ReportErrorVA(cx
, IsWarning::No
, format
, ArgumentsAreASCII
, ap
);
3753 JS_PUBLIC_API
void JS_ReportErrorLatin1(JSContext
* cx
, const char* format
,
3758 va_start(ap
, format
);
3759 ReportErrorVA(cx
, IsWarning::No
, format
, ArgumentsAreLatin1
, ap
);
3763 JS_PUBLIC_API
void JS_ReportErrorUTF8(JSContext
* cx
, const char* format
, ...) {
3767 va_start(ap
, format
);
3768 ReportErrorVA(cx
, IsWarning::No
, format
, ArgumentsAreUTF8
, ap
);
3772 JS_PUBLIC_API
void JS_ReportErrorNumberASCII(JSContext
* cx
,
3773 JSErrorCallback errorCallback
,
3775 const unsigned errorNumber
, ...) {
3777 va_start(ap
, errorNumber
);
3778 JS_ReportErrorNumberASCIIVA(cx
, errorCallback
, userRef
, errorNumber
, ap
);
3782 JS_PUBLIC_API
void JS_ReportErrorNumberASCIIVA(JSContext
* cx
,
3783 JSErrorCallback errorCallback
,
3785 const unsigned errorNumber
,
3788 ReportErrorNumberVA(cx
, IsWarning::No
, errorCallback
, userRef
, errorNumber
,
3789 ArgumentsAreASCII
, ap
);
3792 JS_PUBLIC_API
void JS_ReportErrorNumberLatin1(JSContext
* cx
,
3793 JSErrorCallback errorCallback
,
3795 const unsigned errorNumber
, ...) {
3797 va_start(ap
, errorNumber
);
3798 JS_ReportErrorNumberLatin1VA(cx
, errorCallback
, userRef
, errorNumber
, ap
);
3802 JS_PUBLIC_API
void JS_ReportErrorNumberLatin1VA(JSContext
* cx
,
3803 JSErrorCallback errorCallback
,
3805 const unsigned errorNumber
,
3808 ReportErrorNumberVA(cx
, IsWarning::No
, errorCallback
, userRef
, errorNumber
,
3809 ArgumentsAreLatin1
, ap
);
3812 JS_PUBLIC_API
void JS_ReportErrorNumberUTF8(JSContext
* cx
,
3813 JSErrorCallback errorCallback
,
3815 const unsigned errorNumber
, ...) {
3817 va_start(ap
, errorNumber
);
3818 JS_ReportErrorNumberUTF8VA(cx
, errorCallback
, userRef
, errorNumber
, ap
);
3822 JS_PUBLIC_API
void JS_ReportErrorNumberUTF8VA(JSContext
* cx
,
3823 JSErrorCallback errorCallback
,
3825 const unsigned errorNumber
,
3828 ReportErrorNumberVA(cx
, IsWarning::No
, errorCallback
, userRef
, errorNumber
,
3829 ArgumentsAreUTF8
, ap
);
3832 JS_PUBLIC_API
void JS_ReportErrorNumberUTF8Array(JSContext
* cx
,
3833 JSErrorCallback errorCallback
,
3835 const unsigned errorNumber
,
3836 const char** args
) {
3838 ReportErrorNumberUTF8Array(cx
, IsWarning::No
, errorCallback
, userRef
,
3842 JS_PUBLIC_API
void JS_ReportErrorNumberUC(JSContext
* cx
,
3843 JSErrorCallback errorCallback
,
3845 const unsigned errorNumber
, ...) {
3849 va_start(ap
, errorNumber
);
3850 ReportErrorNumberVA(cx
, IsWarning::No
, errorCallback
, userRef
, errorNumber
,
3851 ArgumentsAreUnicode
, ap
);
3855 JS_PUBLIC_API
void JS_ReportErrorNumberUCArray(JSContext
* cx
,
3856 JSErrorCallback errorCallback
,
3858 const unsigned errorNumber
,
3859 const char16_t
** args
) {
3861 ReportErrorNumberUCArray(cx
, IsWarning::No
, errorCallback
, userRef
,
3865 JS_PUBLIC_API
void JS_ReportOutOfMemory(JSContext
* cx
) {
3866 ReportOutOfMemory(cx
);
3869 JS_PUBLIC_API
void JS_ReportAllocationOverflow(JSContext
* cx
) {
3870 ReportAllocationOverflow(cx
);
3873 JS_PUBLIC_API
bool JS_ExpandErrorArgumentsASCII(JSContext
* cx
,
3874 JSErrorCallback errorCallback
,
3875 const unsigned errorNumber
,
3876 JSErrorReport
* reportp
, ...) {
3881 va_start(ap
, reportp
);
3882 AutoReportFrontendContext
fc(cx
);
3883 ok
= ExpandErrorArgumentsVA(&fc
, errorCallback
, nullptr, errorNumber
,
3884 ArgumentsAreASCII
, reportp
, ap
);
3888 /************************************************************************/
3890 JS_PUBLIC_API
bool JS_SetDefaultLocale(JSRuntime
* rt
, const char* locale
) {
3892 return rt
->setDefaultLocale(locale
);
3895 JS_PUBLIC_API UniqueChars
JS_GetDefaultLocale(JSContext
* cx
) {
3897 if (const char* locale
= cx
->runtime()->getDefaultLocale()) {
3898 return DuplicateString(cx
, locale
);
3904 JS_PUBLIC_API
void JS_ResetDefaultLocale(JSRuntime
* rt
) {
3906 rt
->resetDefaultLocale();
3909 JS_PUBLIC_API
void JS_SetLocaleCallbacks(JSRuntime
* rt
,
3910 const JSLocaleCallbacks
* callbacks
) {
3912 rt
->localeCallbacks
= callbacks
;
3915 JS_PUBLIC_API
const JSLocaleCallbacks
* JS_GetLocaleCallbacks(JSRuntime
* rt
) {
3916 /* This function can be called by a finalizer. */
3917 return rt
->localeCallbacks
;
3920 /************************************************************************/
3922 JS_PUBLIC_API
bool JS_IsExceptionPending(JSContext
* cx
) {
3923 /* This function can be called by a finalizer. */
3924 return (bool)cx
->isExceptionPending();
3927 JS_PUBLIC_API
bool JS_IsThrowingOutOfMemory(JSContext
* cx
) {
3928 return cx
->isThrowingOutOfMemory();
3931 JS_PUBLIC_API
bool JS_GetPendingException(JSContext
* cx
,
3932 MutableHandleValue vp
) {
3935 if (!cx
->isExceptionPending()) {
3938 return cx
->getPendingException(vp
);
3941 JS_PUBLIC_API
void JS_SetPendingException(JSContext
* cx
, HandleValue value
,
3942 JS::ExceptionStackBehavior behavior
) {
3945 // We don't check the compartment of `value` here, because we're not
3946 // doing anything with it other than storing it, and stored
3947 // exception values can be in an abitrary compartment.
3949 if (behavior
== JS::ExceptionStackBehavior::Capture
) {
3950 cx
->setPendingException(value
, ShouldCaptureStack::Always
);
3952 cx
->setPendingException(value
, nullptr);
3956 JS_PUBLIC_API
void JS_ClearPendingException(JSContext
* cx
) {
3958 cx
->clearPendingException();
3961 JS::AutoSaveExceptionState::AutoSaveExceptionState(JSContext
* cx
)
3962 : context(cx
), status(cx
->status
), exceptionValue(cx
), exceptionStack(cx
) {
3965 if (IsCatchableExceptionStatus(status
)) {
3966 exceptionValue
= cx
->unwrappedException();
3967 exceptionStack
= cx
->unwrappedExceptionStack();
3969 cx
->clearPendingException();
3972 void JS::AutoSaveExceptionState::drop() {
3973 status
= JS::ExceptionStatus::None
;
3974 exceptionValue
.setUndefined();
3975 exceptionStack
= nullptr;
3978 void JS::AutoSaveExceptionState::restore() {
3979 context
->status
= status
;
3980 context
->unwrappedException() = exceptionValue
;
3981 if (exceptionStack
) {
3982 context
->unwrappedExceptionStack() = &exceptionStack
->as
<SavedFrame
>();
3987 JS::AutoSaveExceptionState::~AutoSaveExceptionState() {
3988 // NOTE: An interrupt/uncatchable exception or a debugger-forced-return may be
3989 // clobbered here by the saved exception. If that is not desired, this
3990 // state should be dropped before the destructor fires.
3991 if (!context
->isExceptionPending()) {
3992 if (status
!= JS::ExceptionStatus::None
) {
3993 context
->status
= status
;
3995 if (IsCatchableExceptionStatus(status
)) {
3996 context
->unwrappedException() = exceptionValue
;
3997 if (exceptionStack
) {
3998 context
->unwrappedExceptionStack() = &exceptionStack
->as
<SavedFrame
>();
4004 JS_PUBLIC_API JSErrorReport
* JS_ErrorFromException(JSContext
* cx
,
4009 return ErrorFromException(cx
, obj
);
4012 void JSErrorReport::initBorrowedLinebuf(const char16_t
* linebufArg
,
4013 size_t linebufLengthArg
,
4014 size_t tokenOffsetArg
) {
4015 MOZ_ASSERT(linebufArg
);
4016 MOZ_ASSERT(tokenOffsetArg
<= linebufLengthArg
);
4017 MOZ_ASSERT(linebufArg
[linebufLengthArg
] == '\0');
4019 linebuf_
= linebufArg
;
4020 linebufLength_
= linebufLengthArg
;
4021 tokenOffset_
= tokenOffsetArg
;
4024 void JSErrorReport::freeLinebuf() {
4025 if (ownsLinebuf_
&& linebuf_
) {
4026 js_free((void*)linebuf_
);
4027 ownsLinebuf_
= false;
4032 JSString
* JSErrorBase::newMessageString(JSContext
* cx
) {
4034 return cx
->runtime()->emptyString
;
4037 return JS_NewStringCopyUTF8Z(cx
, message_
);
4040 void JSErrorBase::freeMessage() {
4042 js_free((void*)message_
.get());
4043 ownsMessage_
= false;
4045 message_
= JS::ConstUTF8CharsZ();
4048 JSErrorNotes::JSErrorNotes() = default;
4050 JSErrorNotes::~JSErrorNotes() = default;
4052 static UniquePtr
<JSErrorNotes::Note
> CreateErrorNoteVA(
4053 FrontendContext
* fc
, const char* filename
, unsigned sourceId
,
4054 uint32_t lineno
, JS::ColumnNumberOneOrigin column
,
4055 JSErrorCallback errorCallback
, void* userRef
, const unsigned errorNumber
,
4056 ErrorArgumentsType argumentsType
, va_list ap
) {
4057 auto note
= MakeUnique
<JSErrorNotes::Note
>();
4059 ReportOutOfMemory(fc
);
4063 note
->errorNumber
= errorNumber
;
4064 note
->filename
= JS::ConstUTF8CharsZ(filename
);
4065 note
->sourceId
= sourceId
;
4066 note
->lineno
= lineno
;
4067 note
->column
= column
;
4069 if (!ExpandErrorArgumentsVA(fc
, errorCallback
, userRef
, errorNumber
, nullptr,
4070 argumentsType
, note
.get(), ap
)) {
4077 bool JSErrorNotes::addNoteVA(FrontendContext
* fc
, const char* filename
,
4078 unsigned sourceId
, uint32_t lineno
,
4079 JS::ColumnNumberOneOrigin column
,
4080 JSErrorCallback errorCallback
, void* userRef
,
4081 const unsigned errorNumber
,
4082 ErrorArgumentsType argumentsType
, va_list ap
) {
4084 CreateErrorNoteVA(fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
4085 userRef
, errorNumber
, argumentsType
, ap
);
4090 if (!notes_
.append(std::move(note
))) {
4091 ReportOutOfMemory(fc
);
4097 bool JSErrorNotes::addNoteASCII(JSContext
* cx
, const char* filename
,
4098 unsigned sourceId
, uint32_t lineno
,
4099 JS::ColumnNumberOneOrigin column
,
4100 JSErrorCallback errorCallback
, void* userRef
,
4101 const unsigned errorNumber
, ...) {
4102 AutoReportFrontendContext
fc(cx
);
4104 va_start(ap
, errorNumber
);
4105 bool ok
= addNoteVA(&fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
4106 userRef
, errorNumber
, ArgumentsAreASCII
, ap
);
4111 bool JSErrorNotes::addNoteASCII(FrontendContext
* fc
, const char* filename
,
4112 unsigned sourceId
, uint32_t lineno
,
4113 JS::ColumnNumberOneOrigin column
,
4114 JSErrorCallback errorCallback
, void* userRef
,
4115 const unsigned errorNumber
, ...) {
4117 va_start(ap
, errorNumber
);
4118 bool ok
= addNoteVA(fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
4119 userRef
, errorNumber
, ArgumentsAreASCII
, ap
);
4124 bool JSErrorNotes::addNoteLatin1(JSContext
* cx
, const char* filename
,
4125 unsigned sourceId
, uint32_t lineno
,
4126 JS::ColumnNumberOneOrigin column
,
4127 JSErrorCallback errorCallback
, void* userRef
,
4128 const unsigned errorNumber
, ...) {
4129 AutoReportFrontendContext
fc(cx
);
4131 va_start(ap
, errorNumber
);
4132 bool ok
= addNoteVA(&fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
4133 userRef
, errorNumber
, ArgumentsAreLatin1
, ap
);
4138 bool JSErrorNotes::addNoteLatin1(FrontendContext
* fc
, const char* filename
,
4139 unsigned sourceId
, uint32_t lineno
,
4140 JS::ColumnNumberOneOrigin column
,
4141 JSErrorCallback errorCallback
, void* userRef
,
4142 const unsigned errorNumber
, ...) {
4144 va_start(ap
, errorNumber
);
4145 bool ok
= addNoteVA(fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
4146 userRef
, errorNumber
, ArgumentsAreLatin1
, ap
);
4151 bool JSErrorNotes::addNoteUTF8(JSContext
* cx
, const char* filename
,
4152 unsigned sourceId
, uint32_t lineno
,
4153 JS::ColumnNumberOneOrigin column
,
4154 JSErrorCallback errorCallback
, void* userRef
,
4155 const unsigned errorNumber
, ...) {
4156 AutoReportFrontendContext
fc(cx
);
4158 va_start(ap
, errorNumber
);
4159 bool ok
= addNoteVA(&fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
4160 userRef
, errorNumber
, ArgumentsAreUTF8
, ap
);
4165 bool JSErrorNotes::addNoteUTF8(FrontendContext
* fc
, const char* filename
,
4166 unsigned sourceId
, uint32_t lineno
,
4167 JS::ColumnNumberOneOrigin column
,
4168 JSErrorCallback errorCallback
, void* userRef
,
4169 const unsigned errorNumber
, ...) {
4171 va_start(ap
, errorNumber
);
4172 bool ok
= addNoteVA(fc
, filename
, sourceId
, lineno
, column
, errorCallback
,
4173 userRef
, errorNumber
, ArgumentsAreUTF8
, ap
);
4178 JS_PUBLIC_API
size_t JSErrorNotes::length() { return notes_
.length(); }
4180 UniquePtr
<JSErrorNotes
> JSErrorNotes::copy(JSContext
* cx
) {
4181 auto copiedNotes
= MakeUnique
<JSErrorNotes
>();
4183 ReportOutOfMemory(cx
);
4187 for (auto&& note
: *this) {
4188 UniquePtr
<JSErrorNotes::Note
> copied
= CopyErrorNote(cx
, note
.get());
4193 if (!copiedNotes
->notes_
.append(std::move(copied
))) {
4201 JS_PUBLIC_API
JSErrorNotes::iterator
JSErrorNotes::begin() {
4202 return iterator(notes_
.begin());
4205 JS_PUBLIC_API
JSErrorNotes::iterator
JSErrorNotes::end() {
4206 return iterator(notes_
.end());
4209 extern MOZ_NEVER_INLINE JS_PUBLIC_API
void JS_AbortIfWrongThread(
4211 if (!CurrentThreadCanAccessRuntime(cx
->runtime())) {
4214 if (TlsContext
.get() != cx
) {
4220 JS_PUBLIC_API
void JS_GetGCZealBits(JSContext
* cx
, uint32_t* zealBits
,
4221 uint32_t* frequency
,
4222 uint32_t* nextScheduled
) {
4223 cx
->runtime()->gc
.getZealBits(zealBits
, frequency
, nextScheduled
);
4226 JS_PUBLIC_API
void JS_SetGCZeal(JSContext
* cx
, uint8_t zeal
,
4227 uint32_t frequency
) {
4228 cx
->runtime()->gc
.setZeal(zeal
, frequency
);
4231 JS_PUBLIC_API
void JS_UnsetGCZeal(JSContext
* cx
, uint8_t zeal
) {
4232 cx
->runtime()->gc
.unsetZeal(zeal
);
4235 JS_PUBLIC_API
void JS_ScheduleGC(JSContext
* cx
, uint32_t count
) {
4236 cx
->runtime()->gc
.setNextScheduled(count
);
4240 JS_PUBLIC_API
void JS_SetParallelParsingEnabled(JSContext
* cx
, bool enabled
) {
4241 cx
->runtime()->setParallelParsingEnabled(enabled
);
4244 JS_PUBLIC_API
void JS_SetOffthreadIonCompilationEnabled(JSContext
* cx
,
4246 cx
->runtime()->setOffthreadIonCompilationEnabled(enabled
);
4249 JS_PUBLIC_API
void JS_SetGlobalJitCompilerOption(JSContext
* cx
,
4250 JSJitCompilerOption opt
,
4252 JSRuntime
* rt
= cx
->runtime();
4254 #ifdef ENABLE_PORTABLE_BASELINE_INTERP
4255 case JSJITCOMPILER_PORTABLE_BASELINE_ENABLE
:
4257 jit::JitOptions
.portableBaselineInterpreter
= true;
4258 } else if (value
== 0) {
4259 jit::JitOptions
.portableBaselineInterpreter
= false;
4262 case JSJITCOMPILER_PORTABLE_BASELINE_WARMUP_THRESHOLD
:
4263 if (value
== uint32_t(-1)) {
4264 jit::DefaultJitOptions defaultValues
;
4265 value
= defaultValues
.portableBaselineInterpreterWarmUpThreshold
;
4267 jit::JitOptions
.portableBaselineInterpreterWarmUpThreshold
= value
;
4270 case JSJITCOMPILER_BASELINE_INTERPRETER_WARMUP_TRIGGER
:
4271 if (value
== uint32_t(-1)) {
4272 jit::DefaultJitOptions defaultValues
;
4273 value
= defaultValues
.baselineInterpreterWarmUpThreshold
;
4275 jit::JitOptions
.baselineInterpreterWarmUpThreshold
= value
;
4277 case JSJITCOMPILER_BASELINE_WARMUP_TRIGGER
:
4278 if (value
== uint32_t(-1)) {
4279 jit::DefaultJitOptions defaultValues
;
4280 value
= defaultValues
.baselineJitWarmUpThreshold
;
4282 jit::JitOptions
.baselineJitWarmUpThreshold
= value
;
4284 case JSJITCOMPILER_IC_FORCE_MEGAMORPHIC
:
4285 jit::JitOptions
.forceMegamorphicICs
= !!value
;
4287 case JSJITCOMPILER_ION_NORMAL_WARMUP_TRIGGER
:
4288 if (value
== uint32_t(-1)) {
4289 jit::JitOptions
.resetNormalIonWarmUpThreshold();
4292 jit::JitOptions
.setNormalIonWarmUpThreshold(value
);
4294 case JSJITCOMPILER_ION_GVN_ENABLE
:
4296 jit::JitOptions
.enableGvn(false);
4297 JitSpew(js::jit::JitSpew_IonScripts
, "Disable ion's GVN");
4299 jit::JitOptions
.enableGvn(true);
4300 JitSpew(js::jit::JitSpew_IonScripts
, "Enable ion's GVN");
4303 case JSJITCOMPILER_ION_FORCE_IC
:
4305 jit::JitOptions
.forceInlineCaches
= false;
4306 JitSpew(js::jit::JitSpew_IonScripts
,
4307 "Ion: Enable non-IC optimizations.");
4309 jit::JitOptions
.forceInlineCaches
= true;
4310 JitSpew(js::jit::JitSpew_IonScripts
,
4311 "Ion: Disable non-IC optimizations.");
4314 case JSJITCOMPILER_ION_CHECK_RANGE_ANALYSIS
:
4316 jit::JitOptions
.checkRangeAnalysis
= false;
4317 JitSpew(js::jit::JitSpew_IonScripts
,
4318 "Ion: Enable range analysis checks.");
4320 jit::JitOptions
.checkRangeAnalysis
= true;
4321 JitSpew(js::jit::JitSpew_IonScripts
,
4322 "Ion: Disable range analysis checks.");
4325 case JSJITCOMPILER_ION_ENABLE
:
4327 jit::JitOptions
.ion
= true;
4328 JitSpew(js::jit::JitSpew_IonScripts
, "Enable ion");
4329 } else if (value
== 0) {
4330 jit::JitOptions
.ion
= false;
4331 JitSpew(js::jit::JitSpew_IonScripts
, "Disable ion");
4334 case JSJITCOMPILER_JIT_TRUSTEDPRINCIPALS_ENABLE
:
4336 jit::JitOptions
.jitForTrustedPrincipals
= true;
4337 JitSpew(js::jit::JitSpew_IonScripts
,
4338 "Enable ion and baselinejit for trusted principals");
4339 } else if (value
== 0) {
4340 jit::JitOptions
.jitForTrustedPrincipals
= false;
4341 JitSpew(js::jit::JitSpew_IonScripts
,
4342 "Disable ion and baselinejit for trusted principals");
4345 case JSJITCOMPILER_ION_FREQUENT_BAILOUT_THRESHOLD
:
4346 if (value
== uint32_t(-1)) {
4347 jit::DefaultJitOptions defaultValues
;
4348 value
= defaultValues
.frequentBailoutThreshold
;
4350 jit::JitOptions
.frequentBailoutThreshold
= value
;
4352 case JSJITCOMPILER_BASE_REG_FOR_LOCALS
:
4354 jit::JitOptions
.baseRegForLocals
= jit::BaseRegForAddress::SP
;
4355 } else if (value
== 1) {
4356 jit::JitOptions
.baseRegForLocals
= jit::BaseRegForAddress::FP
;
4358 jit::DefaultJitOptions defaultValues
;
4359 jit::JitOptions
.baseRegForLocals
= defaultValues
.baseRegForLocals
;
4362 case JSJITCOMPILER_BASELINE_INTERPRETER_ENABLE
:
4364 jit::JitOptions
.baselineInterpreter
= true;
4365 } else if (value
== 0) {
4366 ReleaseAllJITCode(rt
->gcContext());
4367 jit::JitOptions
.baselineInterpreter
= false;
4370 case JSJITCOMPILER_BASELINE_ENABLE
:
4372 jit::JitOptions
.baselineJit
= true;
4373 ReleaseAllJITCode(rt
->gcContext());
4374 JitSpew(js::jit::JitSpew_BaselineScripts
, "Enable baseline");
4375 } else if (value
== 0) {
4376 jit::JitOptions
.baselineJit
= false;
4377 ReleaseAllJITCode(rt
->gcContext());
4378 JitSpew(js::jit::JitSpew_BaselineScripts
, "Disable baseline");
4381 case JSJITCOMPILER_NATIVE_REGEXP_ENABLE
:
4382 jit::JitOptions
.nativeRegExp
= !!value
;
4384 case JSJITCOMPILER_JIT_HINTS_ENABLE
:
4385 jit::JitOptions
.disableJitHints
= !value
;
4387 case JSJITCOMPILER_OFFTHREAD_COMPILATION_ENABLE
:
4389 rt
->setOffthreadIonCompilationEnabled(true);
4390 JitSpew(js::jit::JitSpew_IonScripts
, "Enable offthread compilation");
4391 } else if (value
== 0) {
4392 rt
->setOffthreadIonCompilationEnabled(false);
4393 JitSpew(js::jit::JitSpew_IonScripts
, "Disable offthread compilation");
4396 case JSJITCOMPILER_INLINING_BYTECODE_MAX_LENGTH
:
4397 if (value
== uint32_t(-1)) {
4398 jit::DefaultJitOptions defaultValues
;
4399 value
= defaultValues
.smallFunctionMaxBytecodeLength
;
4401 jit::JitOptions
.smallFunctionMaxBytecodeLength
= value
;
4403 case JSJITCOMPILER_JUMP_THRESHOLD
:
4404 if (value
== uint32_t(-1)) {
4405 jit::DefaultJitOptions defaultValues
;
4406 value
= defaultValues
.jumpThreshold
;
4408 jit::JitOptions
.jumpThreshold
= value
;
4410 case JSJITCOMPILER_SPECTRE_INDEX_MASKING
:
4411 jit::JitOptions
.spectreIndexMasking
= !!value
;
4413 case JSJITCOMPILER_SPECTRE_OBJECT_MITIGATIONS
:
4414 jit::JitOptions
.spectreObjectMitigations
= !!value
;
4416 case JSJITCOMPILER_SPECTRE_STRING_MITIGATIONS
:
4417 jit::JitOptions
.spectreStringMitigations
= !!value
;
4419 case JSJITCOMPILER_SPECTRE_VALUE_MASKING
:
4420 jit::JitOptions
.spectreValueMasking
= !!value
;
4422 case JSJITCOMPILER_SPECTRE_JIT_TO_CXX_CALLS
:
4423 jit::JitOptions
.spectreJitToCxxCalls
= !!value
;
4425 case JSJITCOMPILER_WRITE_PROTECT_CODE
:
4426 jit::JitOptions
.maybeSetWriteProtectCode(!!value
);
4428 case JSJITCOMPILER_WASM_FOLD_OFFSETS
:
4429 jit::JitOptions
.wasmFoldOffsets
= !!value
;
4431 case JSJITCOMPILER_WASM_DELAY_TIER2
:
4432 jit::JitOptions
.wasmDelayTier2
= !!value
;
4434 case JSJITCOMPILER_WASM_JIT_BASELINE
:
4435 JS::ContextOptionsRef(cx
).setWasmBaseline(!!value
);
4437 case JSJITCOMPILER_WASM_JIT_OPTIMIZING
:
4438 JS::ContextOptionsRef(cx
).setWasmIon(!!value
);
4442 case JSJITCOMPILER_FULL_DEBUG_CHECKS
:
4443 jit::JitOptions
.fullDebugChecks
= !!value
;
4451 JS_PUBLIC_API
bool JS_GetGlobalJitCompilerOption(JSContext
* cx
,
4452 JSJitCompilerOption opt
,
4453 uint32_t* valueOut
) {
4454 MOZ_ASSERT(valueOut
);
4455 #ifndef JS_CODEGEN_NONE
4456 JSRuntime
* rt
= cx
->runtime();
4458 case JSJITCOMPILER_BASELINE_INTERPRETER_WARMUP_TRIGGER
:
4459 *valueOut
= jit::JitOptions
.baselineInterpreterWarmUpThreshold
;
4461 case JSJITCOMPILER_BASELINE_WARMUP_TRIGGER
:
4462 *valueOut
= jit::JitOptions
.baselineJitWarmUpThreshold
;
4464 case JSJITCOMPILER_IC_FORCE_MEGAMORPHIC
:
4465 *valueOut
= jit::JitOptions
.forceMegamorphicICs
;
4467 case JSJITCOMPILER_ION_NORMAL_WARMUP_TRIGGER
:
4468 *valueOut
= jit::JitOptions
.normalIonWarmUpThreshold
;
4470 case JSJITCOMPILER_ION_FORCE_IC
:
4471 *valueOut
= jit::JitOptions
.forceInlineCaches
;
4473 case JSJITCOMPILER_ION_CHECK_RANGE_ANALYSIS
:
4474 *valueOut
= jit::JitOptions
.checkRangeAnalysis
;
4476 case JSJITCOMPILER_ION_ENABLE
:
4477 *valueOut
= jit::JitOptions
.ion
;
4479 case JSJITCOMPILER_ION_FREQUENT_BAILOUT_THRESHOLD
:
4480 *valueOut
= jit::JitOptions
.frequentBailoutThreshold
;
4482 case JSJITCOMPILER_BASE_REG_FOR_LOCALS
:
4483 *valueOut
= uint32_t(jit::JitOptions
.baseRegForLocals
);
4485 case JSJITCOMPILER_INLINING_BYTECODE_MAX_LENGTH
:
4486 *valueOut
= jit::JitOptions
.smallFunctionMaxBytecodeLength
;
4488 case JSJITCOMPILER_BASELINE_INTERPRETER_ENABLE
:
4489 *valueOut
= jit::JitOptions
.baselineInterpreter
;
4491 case JSJITCOMPILER_BASELINE_ENABLE
:
4492 *valueOut
= jit::JitOptions
.baselineJit
;
4494 case JSJITCOMPILER_NATIVE_REGEXP_ENABLE
:
4495 *valueOut
= jit::JitOptions
.nativeRegExp
;
4497 case JSJITCOMPILER_OFFTHREAD_COMPILATION_ENABLE
:
4498 *valueOut
= rt
->canUseOffthreadIonCompilation();
4500 case JSJITCOMPILER_SPECTRE_INDEX_MASKING
:
4501 *valueOut
= jit::JitOptions
.spectreIndexMasking
? 1 : 0;
4503 case JSJITCOMPILER_SPECTRE_OBJECT_MITIGATIONS
:
4504 *valueOut
= jit::JitOptions
.spectreObjectMitigations
? 1 : 0;
4506 case JSJITCOMPILER_SPECTRE_STRING_MITIGATIONS
:
4507 *valueOut
= jit::JitOptions
.spectreStringMitigations
? 1 : 0;
4509 case JSJITCOMPILER_SPECTRE_VALUE_MASKING
:
4510 *valueOut
= jit::JitOptions
.spectreValueMasking
? 1 : 0;
4512 case JSJITCOMPILER_SPECTRE_JIT_TO_CXX_CALLS
:
4513 *valueOut
= jit::JitOptions
.spectreJitToCxxCalls
? 1 : 0;
4515 case JSJITCOMPILER_WRITE_PROTECT_CODE
:
4516 *valueOut
= jit::JitOptions
.writeProtectCode
? 1 : 0;
4518 case JSJITCOMPILER_WASM_FOLD_OFFSETS
:
4519 *valueOut
= jit::JitOptions
.wasmFoldOffsets
? 1 : 0;
4521 case JSJITCOMPILER_WASM_JIT_BASELINE
:
4522 *valueOut
= JS::ContextOptionsRef(cx
).wasmBaseline() ? 1 : 0;
4524 case JSJITCOMPILER_WASM_JIT_OPTIMIZING
:
4525 *valueOut
= JS::ContextOptionsRef(cx
).wasmIon() ? 1 : 0;
4528 case JSJITCOMPILER_FULL_DEBUG_CHECKS
:
4529 *valueOut
= jit::JitOptions
.fullDebugChecks
? 1 : 0;
4537 # ifdef ENABLE_PORTABLE_BASELINE_INTERP
4538 case JSJITCOMPILER_PORTABLE_BASELINE_ENABLE
:
4539 *valueOut
= jit::JitOptions
.portableBaselineInterpreter
;
4541 case JSJITCOMPILER_PORTABLE_BASELINE_WARMUP_THRESHOLD
:
4542 *valueOut
= jit::JitOptions
.portableBaselineInterpreterWarmUpThreshold
;
4552 JS_PUBLIC_API
void JS::DisableSpectreMitigationsAfterInit() {
4553 // This is used to turn off Spectre mitigations in pre-allocated child
4554 // processes used for isolated web content. Assert there's a single runtime
4555 // and cancel off-thread compilations, to ensure we're not racing with any
4557 JSContext
* cx
= TlsContext
.get();
4558 MOZ_RELEASE_ASSERT(cx
);
4559 MOZ_RELEASE_ASSERT(JSRuntime::hasSingleLiveRuntime());
4560 MOZ_RELEASE_ASSERT(cx
->runtime()->wasmInstances
.lock()->empty());
4562 CancelOffThreadIonCompile(cx
->runtime());
4564 jit::JitOptions
.spectreIndexMasking
= false;
4565 jit::JitOptions
.spectreObjectMitigations
= false;
4566 jit::JitOptions
.spectreStringMitigations
= false;
4567 jit::JitOptions
.spectreValueMasking
= false;
4568 jit::JitOptions
.spectreJitToCxxCalls
= false;
4571 /************************************************************************/
4573 #if !defined(STATIC_EXPORTABLE_JS_API) && !defined(STATIC_JS_API) && \
4574 defined(XP_WIN) && (defined(MOZ_MEMORY) || !defined(JS_STANDALONE))
4576 # include "util/WindowsWrapper.h"
4579 * Initialization routine for the JS DLL.
4581 BOOL WINAPI
DllMain(HINSTANCE hDLL
, DWORD dwReason
, LPVOID lpReserved
) {
4587 JS_PUBLIC_API
bool JS_IndexToId(JSContext
* cx
, uint32_t index
,
4588 MutableHandleId id
) {
4589 return IndexToId(cx
, index
, id
);
4592 JS_PUBLIC_API
bool JS_CharsToId(JSContext
* cx
, JS::TwoByteChars chars
,
4593 MutableHandleId idp
) {
4594 Rooted
<JSAtom
*> atom(cx
,
4595 AtomizeChars(cx
, chars
.begin().get(), chars
.length()));
4600 MOZ_ASSERT(!atom
->isIndex(), "API misuse: |chars| must not encode an index");
4602 idp
.set(AtomToId(atom
));
4606 JS_PUBLIC_API
bool JS_IsIdentifier(JSContext
* cx
, HandleString str
,
4607 bool* isIdentifier
) {
4610 JSLinearString
* linearStr
= str
->ensureLinear(cx
);
4615 *isIdentifier
= IsIdentifier(linearStr
);
4619 JS_PUBLIC_API
bool JS_IsIdentifier(const char16_t
* chars
, size_t length
) {
4620 return IsIdentifier(chars
, length
);
4625 void AutoFilename::reset() {
4630 if (filename_
.is
<const char*>()) {
4631 filename_
.as
<const char*>() = nullptr;
4633 filename_
.as
<UniqueChars
>().reset();
4637 void AutoFilename::setScriptSource(js::ScriptSource
* p
) {
4643 setUnowned(p
->filename());
4647 void AutoFilename::setUnowned(const char* filename
) {
4649 filename_
.as
<const char*>() = filename
? filename
: "";
4652 void AutoFilename::setOwned(UniqueChars
&& filename
) {
4654 filename_
= AsVariant(std::move(filename
));
4657 const char* AutoFilename::get() const {
4658 if (filename_
.is
<const char*>()) {
4659 return filename_
.as
<const char*>();
4661 return filename_
.as
<UniqueChars
>().get();
4664 JS_PUBLIC_API
bool DescribeScriptedCaller(JSContext
* cx
, AutoFilename
* filename
,
4666 JS::ColumnNumberOneOrigin
* column
) {
4674 *column
= JS::ColumnNumberOneOrigin();
4677 if (!cx
->compartment()) {
4681 NonBuiltinFrameIter
i(cx
, cx
->realm()->principals());
4686 // If the caller is hidden, the embedding wants us to return false here so
4687 // that it can check its own stack (see HideScriptedCaller).
4688 if (i
.activation()->scriptedCallerIsHidden()) {
4694 // For Wasm, copy out the filename, there is no script source.
4695 UniqueChars copy
= DuplicateString(i
.filename() ? i
.filename() : "");
4697 filename
->setUnowned("out of memory");
4699 filename
->setOwned(std::move(copy
));
4702 // All other frames have a script source to read the filename from.
4703 filename
->setScriptSource(i
.scriptSource());
4708 JS::TaggedColumnNumberOneOrigin columnNumber
;
4709 *lineno
= i
.computeLine(&columnNumber
);
4711 *column
= JS::ColumnNumberOneOrigin(columnNumber
.oneOriginValue());
4713 } else if (column
) {
4714 JS::TaggedColumnNumberOneOrigin columnNumber
;
4715 i
.computeLine(&columnNumber
);
4716 *column
= JS::ColumnNumberOneOrigin(columnNumber
.oneOriginValue());
4722 // Fast path to get the activation and realm to use for GetScriptedCallerGlobal.
4723 // If this returns false, the fast path didn't work out and the caller has to
4724 // use the (much slower) NonBuiltinFrameIter path.
4726 // The optimization here is that we skip Ion-inlined frames and only look at
4727 // 'outer' frames. That's fine because Ion doesn't inline cross-realm calls.
4728 // However, GetScriptedCallerGlobal has to skip self-hosted frames and Ion
4729 // can inline self-hosted scripts, so we have to be careful:
4731 // * When we see a non-self-hosted outer script, it's possible we inlined
4732 // self-hosted scripts into it but that doesn't matter because these scripts
4733 // all have the same realm/global anyway.
4735 // * When we see a self-hosted outer script, it's possible we inlined
4736 // non-self-hosted scripts into it, so we have to give up because in this
4737 // case, whether or not to skip the self-hosted frame (to the possibly
4738 // different-realm caller) requires the slow path to handle inlining. Baseline
4739 // and the interpreter don't inline so this only affects Ion.
4740 static bool GetScriptedCallerActivationRealmFast(JSContext
* cx
,
4741 Activation
** activation
,
4743 ActivationIterator
activationIter(cx
);
4745 if (activationIter
.done()) {
4746 *activation
= nullptr;
4751 if (activationIter
->isJit()) {
4752 jit::JitActivation
* act
= activationIter
->asJit();
4753 JitFrameIter
iter(act
);
4755 iter
.skipNonScriptedJSFrames();
4760 if (!iter
.isSelfHostedIgnoringInlining()) {
4762 *realm
= iter
.realm();
4766 if (iter
.isJSJit() && iter
.asJSJit().isIonScripted()) {
4767 // Ion might have inlined non-self-hosted scripts in this
4768 // self-hosted script.
4774 } else if (activationIter
->isInterpreter()) {
4775 InterpreterActivation
* act
= activationIter
->asInterpreter();
4776 for (InterpreterFrameIterator
iter(act
); !iter
.done(); ++iter
) {
4777 if (!iter
.frame()->script()->selfHosted()) {
4779 *realm
= iter
.frame()->script()->realm();
4788 JS_PUBLIC_API JSObject
* GetScriptedCallerGlobal(JSContext
* cx
) {
4789 Activation
* activation
;
4791 if (GetScriptedCallerActivationRealmFast(cx
, &activation
, &realm
)) {
4796 NonBuiltinFrameIter
i(cx
);
4800 activation
= i
.activation();
4804 MOZ_ASSERT(realm
->compartment() == activation
->compartment());
4806 // If the caller is hidden, the embedding wants us to return null here so
4807 // that it can check its own stack (see HideScriptedCaller).
4808 if (activation
->scriptedCallerIsHidden()) {
4812 GlobalObject
* global
= realm
->maybeGlobal();
4814 // No one should be running code in a realm without any live objects, so
4815 // there should definitely be a live global.
4821 JS_PUBLIC_API
void HideScriptedCaller(JSContext
* cx
) {
4824 // If there's no accessible activation on the stack, we'll return null from
4825 // DescribeScriptedCaller anyway, so there's no need to annotate anything.
4826 Activation
* act
= cx
->activation();
4830 act
->hideScriptedCaller();
4833 JS_PUBLIC_API
void UnhideScriptedCaller(JSContext
* cx
) {
4834 Activation
* act
= cx
->activation();
4838 act
->unhideScriptedCaller();
4841 } /* namespace JS */
4844 JS_PUBLIC_API
void JS::detail::AssertArgumentsAreSane(JSContext
* cx
,
4845 HandleValue value
) {
4850 #endif /* JS_DEBUG */
4852 JS_PUBLIC_API
bool JS::FinishIncrementalEncoding(JSContext
* cx
,
4853 JS::HandleScript script
,
4854 TranscodeBuffer
& buffer
) {
4858 if (!script
->scriptSource()->xdrFinalizeEncoder(cx
, buffer
)) {
4864 JS_PUBLIC_API
bool JS::FinishIncrementalEncoding(JSContext
* cx
,
4865 JS::Handle
<JSObject
*> module
,
4866 TranscodeBuffer
& buffer
) {
4867 if (!module
->as
<ModuleObject
>()
4868 .scriptSourceObject()
4870 ->xdrFinalizeEncoder(cx
, buffer
)) {
4876 JS_PUBLIC_API
void JS::AbortIncrementalEncoding(JS::HandleScript script
) {
4880 script
->scriptSource()->xdrAbortEncoder();
4883 JS_PUBLIC_API
void JS::AbortIncrementalEncoding(JS::Handle
<JSObject
*> module
) {
4884 module
->as
<ModuleObject
>().scriptSourceObject()->source()->xdrAbortEncoder();
4887 bool JS::IsWasmModuleObject(HandleObject obj
) {
4888 return obj
->canUnwrapAs
<WasmModuleObject
>();
4891 JS_PUBLIC_API RefPtr
<JS::WasmModule
> JS::GetWasmModule(HandleObject obj
) {
4892 MOZ_ASSERT(JS::IsWasmModuleObject(obj
));
4893 WasmModuleObject
& mobj
= obj
->unwrapAs
<WasmModuleObject
>();
4894 return const_cast<wasm::Module
*>(&mobj
.module());
4897 bool JS::DisableWasmHugeMemory() { return wasm::DisableHugeMemory(); }
4899 JS_PUBLIC_API
void JS::SetProcessLargeAllocationFailureCallback(
4900 JS::LargeAllocationFailureCallback lafc
) {
4901 MOZ_ASSERT(!OnLargeAllocationFailure
);
4902 OnLargeAllocationFailure
= lafc
;
4905 JS_PUBLIC_API
void JS::SetOutOfMemoryCallback(JSContext
* cx
,
4906 OutOfMemoryCallback cb
,
4908 cx
->runtime()->oomCallback
= cb
;
4909 cx
->runtime()->oomCallbackData
= data
;
4912 JS_PUBLIC_API
void JS::SetShadowRealmInitializeGlobalCallback(
4913 JSContext
* cx
, JS::GlobalInitializeCallback callback
) {
4914 cx
->runtime()->shadowRealmInitializeGlobalCallback
= callback
;
4917 JS_PUBLIC_API
void JS::SetShadowRealmGlobalCreationCallback(
4918 JSContext
* cx
, JS::GlobalCreationCallback callback
) {
4919 cx
->runtime()->shadowRealmGlobalCreationCallback
= callback
;
4922 JS::FirstSubsumedFrame::FirstSubsumedFrame(
4923 JSContext
* cx
, bool ignoreSelfHostedFrames
/* = true */)
4924 : JS::FirstSubsumedFrame(cx
, cx
->realm()->principals(),
4925 ignoreSelfHostedFrames
) {}
4927 JS_PUBLIC_API
bool JS::CaptureCurrentStack(
4928 JSContext
* cx
, JS::MutableHandleObject stackp
,
4929 JS::StackCapture
&& capture
/* = JS::StackCapture(JS::AllFrames()) */) {
4932 MOZ_RELEASE_ASSERT(cx
->realm());
4934 Realm
* realm
= cx
->realm();
4935 Rooted
<SavedFrame
*> frame(cx
);
4936 if (!realm
->savedStacks().saveCurrentStack(cx
, &frame
, std::move(capture
))) {
4939 stackp
.set(frame
.get());
4943 JS_PUBLIC_API
bool JS::IsAsyncStackCaptureEnabledForRealm(JSContext
* cx
) {
4944 if (!cx
->options().asyncStack()) {
4948 if (!cx
->options().asyncStackCaptureDebuggeeOnly() ||
4949 cx
->realm()->isDebuggee()) {
4953 return cx
->realm()->isAsyncStackCapturingEnabled
;
4956 JS_PUBLIC_API
bool JS::CopyAsyncStack(JSContext
* cx
,
4957 JS::HandleObject asyncStack
,
4958 JS::HandleString asyncCause
,
4959 JS::MutableHandleObject stackp
,
4960 const Maybe
<size_t>& maxFrameCount
) {
4963 MOZ_RELEASE_ASSERT(cx
->realm());
4965 js::AssertObjectIsSavedFrameOrWrapper(cx
, asyncStack
);
4966 Realm
* realm
= cx
->realm();
4967 Rooted
<SavedFrame
*> frame(cx
);
4968 if (!realm
->savedStacks().copyAsyncStack(cx
, asyncStack
, asyncCause
, &frame
,
4972 stackp
.set(frame
.get());
4976 JS_PUBLIC_API Zone
* JS::GetObjectZone(JSObject
* obj
) {
4977 Zone
* zone
= obj
->zone();
4979 // Check zone pointer is valid and not a poison value. See bug 1878421.
4980 MOZ_RELEASE_ASSERT(zone
->runtimeFromMainThread());
4985 JS_PUBLIC_API Zone
* JS::GetTenuredGCThingZone(GCCellPtr thing
) {
4986 js::gc::Cell
* cell
= thing
.asCell();
4987 MOZ_ASSERT(!js::gc::IsInsideNursery(cell
));
4988 Zone
* zone
= js::gc::detail::GetTenuredGCThingZone(cell
);
4990 // Check zone pointer is valid and not a poison value. See bug 1878421.
4991 MOZ_RELEASE_ASSERT(zone
->runtimeFromMainThread());
4996 JS_PUBLIC_API Zone
* JS::GetNurseryCellZone(gc::Cell
* cell
) {
4997 return cell
->nurseryZone();
5000 JS_PUBLIC_API
JS::TraceKind
JS::GCThingTraceKind(void* thing
) {
5002 return static_cast<js::gc::Cell
*>(thing
)->getTraceKind();
5005 JS_PUBLIC_API
void js::SetStackFormat(JSContext
* cx
, js::StackFormat format
) {
5006 cx
->runtime()->setStackFormat(format
);
5009 JS_PUBLIC_API
js::StackFormat
js::GetStackFormat(JSContext
* cx
) {
5010 return cx
->runtime()->stackFormat();
5013 JS_PUBLIC_API
JS::JSTimers
JS::GetJSTimers(JSContext
* cx
) {
5014 return cx
->realm()->timers
;
5019 JS_PUBLIC_API
void NoteIntentionalCrash() {
5022 reinterpret_cast<bool*>(dlsym(RTLD_DEFAULT
, "gBreakpadInjectorEnabled"));
5030 bool gSupportDifferentialTesting
= false;
5037 JS_PUBLIC_API
void JS::SetSupportDifferentialTesting(bool value
) {
5038 js::gSupportDifferentialTesting
= value
;