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