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