Bug 1842773 - Part 18: Update TypedArray length, byteLength, and byteOffset accesses...
[gecko.git] / js / src / jsapi.cpp
blob15cce6c1dbd0a9e65406da782beb5ec2da60c4fc
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/Watchtower.h"
99 #include "vm/WrapperObject.h"
100 #include "wasm/WasmModule.h"
101 #include "wasm/WasmProcess.h"
103 #include "builtin/Promise-inl.h"
104 #include "debugger/DebugAPI-inl.h"
105 #include "vm/Compartment-inl.h"
106 #include "vm/Interpreter-inl.h"
107 #include "vm/IsGivenTypeObject-inl.h" // js::IsGivenTypeObject
108 #include "vm/JSAtomUtils-inl.h" // AtomToId, PrimitiveValueToId, IndexToId, ClassName
109 #include "vm/JSFunction-inl.h"
110 #include "vm/JSScript-inl.h"
111 #include "vm/NativeObject-inl.h"
112 #include "vm/SavedStacks-inl.h"
113 #include "vm/StringType-inl.h"
115 using namespace js;
117 using mozilla::Maybe;
118 using mozilla::PodCopy;
119 using mozilla::Some;
121 using JS::AutoStableStringChars;
122 using JS::CompileOptions;
123 using JS::ReadOnlyCompileOptions;
124 using JS::SourceText;
126 // See preprocessor definition of JS_BITS_PER_WORD in jstypes.h; make sure
127 // JS_64BIT (used internally) agrees with it
128 #ifdef JS_64BIT
129 static_assert(JS_BITS_PER_WORD == 64, "values must be in sync");
130 #else
131 static_assert(JS_BITS_PER_WORD == 32, "values must be in sync");
132 #endif
134 JS_PUBLIC_API void JS::CallArgs::reportMoreArgsNeeded(JSContext* cx,
135 const char* fnname,
136 unsigned required,
137 unsigned actual) {
138 char requiredArgsStr[40];
139 SprintfLiteral(requiredArgsStr, "%u", required);
140 char actualArgsStr[40];
141 SprintfLiteral(actualArgsStr, "%u", actual);
142 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
143 JSMSG_MORE_ARGS_NEEDED, fnname, requiredArgsStr,
144 required == 1 ? "" : "s", actualArgsStr);
147 static bool ErrorTakesArguments(unsigned msg) {
148 MOZ_ASSERT(msg < JSErr_Limit);
149 unsigned argCount = js_ErrorFormatString[msg].argCount;
150 MOZ_ASSERT(argCount <= 2);
151 return argCount == 1 || argCount == 2;
154 static bool ErrorTakesObjectArgument(unsigned msg) {
155 MOZ_ASSERT(msg < JSErr_Limit);
156 unsigned argCount = js_ErrorFormatString[msg].argCount;
157 MOZ_ASSERT(argCount <= 2);
158 return argCount == 2;
161 bool JS::ObjectOpResult::reportError(JSContext* cx, HandleObject obj,
162 HandleId id) {
163 static_assert(unsigned(OkCode) == unsigned(JSMSG_NOT_AN_ERROR),
164 "unsigned value of OkCode must not be an error code");
165 MOZ_ASSERT(code_ != Uninitialized);
166 MOZ_ASSERT(!ok());
167 cx->check(obj);
169 if (code_ == JSMSG_OBJECT_NOT_EXTENSIBLE) {
170 RootedValue val(cx, ObjectValue(*obj));
171 return ReportValueError(cx, code_, JSDVG_IGNORE_STACK, val, nullptr);
174 if (ErrorTakesArguments(code_)) {
175 UniqueChars propName =
176 IdToPrintableUTF8(cx, id, IdToPrintableBehavior::IdIsPropertyKey);
177 if (!propName) {
178 return false;
181 if (code_ == JSMSG_SET_NON_OBJECT_RECEIVER) {
182 // We know that the original receiver was a primitive, so unbox it.
183 RootedValue val(cx, ObjectValue(*obj));
184 if (!obj->is<ProxyObject>()) {
185 if (!Unbox(cx, obj, &val)) {
186 return false;
189 return ReportValueError(cx, code_, JSDVG_IGNORE_STACK, val, nullptr,
190 propName.get());
193 if (ErrorTakesObjectArgument(code_)) {
194 JSObject* unwrapped = js::CheckedUnwrapStatic(obj);
195 const char* name = unwrapped ? unwrapped->getClass()->name : "Object";
196 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, code_, name,
197 propName.get());
198 return false;
201 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, code_,
202 propName.get());
203 return false;
205 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, code_);
206 return false;
209 bool JS::ObjectOpResult::reportError(JSContext* cx, HandleObject obj) {
210 MOZ_ASSERT(code_ != Uninitialized);
211 MOZ_ASSERT(!ok());
212 MOZ_ASSERT(!ErrorTakesArguments(code_));
213 cx->check(obj);
215 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, code_);
216 return false;
219 JS_PUBLIC_API bool JS::ObjectOpResult::failCantRedefineProp() {
220 return fail(JSMSG_CANT_REDEFINE_PROP);
223 JS_PUBLIC_API bool JS::ObjectOpResult::failReadOnly() {
224 return fail(JSMSG_READ_ONLY);
227 JS_PUBLIC_API bool JS::ObjectOpResult::failGetterOnly() {
228 return fail(JSMSG_GETTER_ONLY);
231 JS_PUBLIC_API bool JS::ObjectOpResult::failCantDelete() {
232 return fail(JSMSG_CANT_DELETE);
235 JS_PUBLIC_API bool JS::ObjectOpResult::failCantSetInterposed() {
236 return fail(JSMSG_CANT_SET_INTERPOSED);
239 JS_PUBLIC_API bool JS::ObjectOpResult::failCantDefineWindowElement() {
240 return fail(JSMSG_CANT_DEFINE_WINDOW_ELEMENT);
243 JS_PUBLIC_API bool JS::ObjectOpResult::failCantDeleteWindowElement() {
244 return fail(JSMSG_CANT_DELETE_WINDOW_ELEMENT);
247 JS_PUBLIC_API bool JS::ObjectOpResult::failCantDefineWindowNamedProperty() {
248 return fail(JSMSG_CANT_DEFINE_WINDOW_NAMED_PROPERTY);
251 JS_PUBLIC_API bool JS::ObjectOpResult::failCantDeleteWindowNamedProperty() {
252 return fail(JSMSG_CANT_DELETE_WINDOW_NAMED_PROPERTY);
255 JS_PUBLIC_API bool JS::ObjectOpResult::failCantDefineWindowNonConfigurable() {
256 return fail(JSMSG_CANT_DEFINE_WINDOW_NC);
259 JS_PUBLIC_API bool JS::ObjectOpResult::failCantPreventExtensions() {
260 return fail(JSMSG_CANT_PREVENT_EXTENSIONS);
263 JS_PUBLIC_API bool JS::ObjectOpResult::failCantSetProto() {
264 return fail(JSMSG_CANT_SET_PROTO);
267 JS_PUBLIC_API bool JS::ObjectOpResult::failNoNamedSetter() {
268 return fail(JSMSG_NO_NAMED_SETTER);
271 JS_PUBLIC_API bool JS::ObjectOpResult::failNoIndexedSetter() {
272 return fail(JSMSG_NO_INDEXED_SETTER);
275 JS_PUBLIC_API bool JS::ObjectOpResult::failNotDataDescriptor() {
276 return fail(JSMSG_NOT_DATA_DESCRIPTOR);
279 JS_PUBLIC_API bool JS::ObjectOpResult::failInvalidDescriptor() {
280 return fail(JSMSG_INVALID_DESCRIPTOR);
283 JS_PUBLIC_API bool JS::ObjectOpResult::failBadArrayLength() {
284 return fail(JSMSG_BAD_ARRAY_LENGTH);
287 JS_PUBLIC_API bool JS::ObjectOpResult::failBadIndex() {
288 return fail(JSMSG_BAD_INDEX);
291 JS_PUBLIC_API int64_t JS_Now() { return PRMJ_Now(); }
293 JS_PUBLIC_API Value JS_GetEmptyStringValue(JSContext* cx) {
294 return StringValue(cx->runtime()->emptyString);
297 JS_PUBLIC_API JSString* JS_GetEmptyString(JSContext* cx) {
298 MOZ_ASSERT(cx->emptyString());
299 return cx->emptyString();
302 namespace js {
304 void AssertHeapIsIdle() { MOZ_ASSERT(!JS::RuntimeHeapIsBusy()); }
306 } // namespace js
308 static void AssertHeapIsIdleOrIterating() {
309 MOZ_ASSERT(!JS::RuntimeHeapIsCollecting());
312 JS_PUBLIC_API bool JS_ValueToObject(JSContext* cx, HandleValue value,
313 MutableHandleObject objp) {
314 AssertHeapIsIdle();
315 CHECK_THREAD(cx);
316 cx->check(value);
317 if (value.isNullOrUndefined()) {
318 objp.set(nullptr);
319 return true;
321 JSObject* obj = ToObject(cx, value);
322 if (!obj) {
323 return false;
325 objp.set(obj);
326 return true;
329 JS_PUBLIC_API JSFunction* JS_ValueToFunction(JSContext* cx, HandleValue value) {
330 AssertHeapIsIdle();
331 CHECK_THREAD(cx);
332 cx->check(value);
333 return ReportIfNotFunction(cx, value);
336 JS_PUBLIC_API JSFunction* JS_ValueToConstructor(JSContext* cx,
337 HandleValue value) {
338 AssertHeapIsIdle();
339 CHECK_THREAD(cx);
340 cx->check(value);
341 return ReportIfNotFunction(cx, value);
344 JS_PUBLIC_API JSString* JS_ValueToSource(JSContext* cx, HandleValue value) {
345 AssertHeapIsIdle();
346 CHECK_THREAD(cx);
347 cx->check(value);
348 return ValueToSource(cx, value);
351 JS_PUBLIC_API bool JS_DoubleIsInt32(double d, int32_t* ip) {
352 return mozilla::NumberIsInt32(d, ip);
355 JS_PUBLIC_API JSType JS_TypeOfValue(JSContext* cx, HandleValue value) {
356 AssertHeapIsIdle();
357 CHECK_THREAD(cx);
358 cx->check(value);
359 return TypeOfValue(value);
362 JS_PUBLIC_API bool JS_IsBuiltinEvalFunction(JSFunction* fun) {
363 return IsAnyBuiltinEval(fun);
366 JS_PUBLIC_API bool JS_IsBuiltinFunctionConstructor(JSFunction* fun) {
367 return fun->isBuiltinFunctionConstructor();
370 JS_PUBLIC_API bool JS_ObjectIsBoundFunction(JSObject* obj) {
371 return obj->is<BoundFunctionObject>();
374 JS_PUBLIC_API JSObject* JS_GetBoundFunctionTarget(JSObject* obj) {
375 return obj->is<BoundFunctionObject>()
376 ? obj->as<BoundFunctionObject>().getTarget()
377 : nullptr;
380 /************************************************************************/
382 // Prevent functions from being discarded by linker, so that they are callable
383 // when debugging.
384 static void PreventDiscardingFunctions() {
385 if (reinterpret_cast<uintptr_t>(&PreventDiscardingFunctions) == 1) {
386 // Never executed.
387 memset((void*)&js::debug::GetMarkInfo, 0, 1);
388 memset((void*)&js::debug::GetMarkWordAddress, 0, 1);
389 memset((void*)&js::debug::GetMarkMask, 0, 1);
393 JS_PUBLIC_API JSContext* JS_NewContext(uint32_t maxbytes,
394 JSRuntime* parentRuntime) {
395 MOZ_ASSERT(JS::detail::libraryInitState == JS::detail::InitState::Running,
396 "must call JS_Init prior to creating any JSContexts");
398 // Prevent linker from discarding unused debug functions.
399 PreventDiscardingFunctions();
401 // Make sure that all parent runtimes are the topmost parent.
402 while (parentRuntime && parentRuntime->parentRuntime) {
403 parentRuntime = parentRuntime->parentRuntime;
406 return NewContext(maxbytes, parentRuntime);
409 JS_PUBLIC_API void JS_DestroyContext(JSContext* cx) { DestroyContext(cx); }
411 JS_PUBLIC_API void* JS_GetContextPrivate(JSContext* cx) { return cx->data; }
413 JS_PUBLIC_API void JS_SetContextPrivate(JSContext* cx, void* data) {
414 cx->data = data;
417 JS_PUBLIC_API void JS_SetFutexCanWait(JSContext* cx) {
418 cx->fx.setCanWait(true);
421 JS_PUBLIC_API JSRuntime* JS_GetParentRuntime(JSContext* cx) {
422 return cx->runtime()->parentRuntime ? cx->runtime()->parentRuntime
423 : cx->runtime();
426 JS_PUBLIC_API JSRuntime* JS_GetRuntime(JSContext* cx) { return cx->runtime(); }
428 JS_PUBLIC_API JS::ContextOptions& JS::ContextOptionsRef(JSContext* cx) {
429 return cx->options();
432 JS::ContextOptions& JS::ContextOptions::setFuzzing(bool flag) {
433 #ifdef FUZZING
434 fuzzing_ = flag;
435 #endif
436 return *this;
439 JS_PUBLIC_API const char* JS_GetImplementationVersion(void) {
440 return "JavaScript-C" MOZILLA_VERSION;
443 JS_PUBLIC_API void JS_SetDestroyZoneCallback(JSContext* cx,
444 JSDestroyZoneCallback callback) {
445 cx->runtime()->destroyZoneCallback = callback;
448 JS_PUBLIC_API void JS_SetDestroyCompartmentCallback(
449 JSContext* cx, JSDestroyCompartmentCallback callback) {
450 cx->runtime()->destroyCompartmentCallback = callback;
453 JS_PUBLIC_API void JS_SetSizeOfIncludingThisCompartmentCallback(
454 JSContext* cx, JSSizeOfIncludingThisCompartmentCallback callback) {
455 cx->runtime()->sizeOfIncludingThisCompartmentCallback = callback;
458 JS_PUBLIC_API void JS_SetErrorInterceptorCallback(
459 JSRuntime* rt, JSErrorInterceptor* callback) {
460 #if defined(NIGHTLY_BUILD)
461 rt->errorInterception.interceptor = callback;
462 #endif // defined(NIGHTLY_BUILD)
465 JS_PUBLIC_API JSErrorInterceptor* JS_GetErrorInterceptorCallback(
466 JSRuntime* rt) {
467 #if defined(NIGHTLY_BUILD)
468 return rt->errorInterception.interceptor;
469 #else // !NIGHTLY_BUILD
470 return nullptr;
471 #endif // defined(NIGHTLY_BUILD)
474 JS_PUBLIC_API Maybe<JSExnType> JS_GetErrorType(const JS::Value& val) {
475 // All errors are objects.
476 if (!val.isObject()) {
477 return mozilla::Nothing();
480 const JSObject& obj = val.toObject();
482 // All errors are `ErrorObject`.
483 if (!obj.is<js::ErrorObject>()) {
484 // Not one of the primitive errors.
485 return mozilla::Nothing();
488 const js::ErrorObject& err = obj.as<js::ErrorObject>();
489 return mozilla::Some(err.type());
492 JS_PUBLIC_API void JS_SetWrapObjectCallbacks(
493 JSContext* cx, const JSWrapObjectCallbacks* callbacks) {
494 cx->runtime()->wrapObjectCallbacks = callbacks;
497 JS_PUBLIC_API Realm* JS::EnterRealm(JSContext* cx, JSObject* target) {
498 AssertHeapIsIdle();
499 CHECK_THREAD(cx);
501 MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(target));
503 Realm* oldRealm = cx->realm();
504 cx->enterRealmOf(target);
505 return oldRealm;
508 JS_PUBLIC_API void JS::LeaveRealm(JSContext* cx, JS::Realm* oldRealm) {
509 AssertHeapIsIdle();
510 CHECK_THREAD(cx);
511 cx->leaveRealm(oldRealm);
514 JSAutoRealm::JSAutoRealm(JSContext* cx, JSObject* target)
515 : cx_(cx), oldRealm_(cx->realm()) {
516 MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(target));
517 AssertHeapIsIdleOrIterating();
518 cx_->enterRealmOf(target);
521 JSAutoRealm::JSAutoRealm(JSContext* cx, JSScript* target)
522 : cx_(cx), oldRealm_(cx->realm()) {
523 AssertHeapIsIdleOrIterating();
524 cx_->enterRealmOf(target);
527 JSAutoRealm::~JSAutoRealm() { cx_->leaveRealm(oldRealm_); }
529 JSAutoNullableRealm::JSAutoNullableRealm(JSContext* cx, JSObject* targetOrNull)
530 : cx_(cx), oldRealm_(cx->realm()) {
531 AssertHeapIsIdleOrIterating();
532 if (targetOrNull) {
533 MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(targetOrNull));
534 cx_->enterRealmOf(targetOrNull);
535 } else {
536 cx_->enterNullRealm();
540 JSAutoNullableRealm::~JSAutoNullableRealm() { cx_->leaveRealm(oldRealm_); }
542 JS_PUBLIC_API void JS_SetCompartmentPrivate(JS::Compartment* compartment,
543 void* data) {
544 compartment->data = data;
547 JS_PUBLIC_API void* JS_GetCompartmentPrivate(JS::Compartment* compartment) {
548 return compartment->data;
551 JS_PUBLIC_API void JS_MarkCrossZoneId(JSContext* cx, jsid id) {
552 cx->markId(id);
555 JS_PUBLIC_API void JS_MarkCrossZoneIdValue(JSContext* cx, const Value& value) {
556 cx->markAtomValue(value);
559 JS_PUBLIC_API void JS_SetZoneUserData(JS::Zone* zone, void* data) {
560 zone->data = data;
563 JS_PUBLIC_API void* JS_GetZoneUserData(JS::Zone* zone) { return zone->data; }
565 JS_PUBLIC_API bool JS_WrapObject(JSContext* cx, MutableHandleObject objp) {
566 AssertHeapIsIdle();
567 CHECK_THREAD(cx);
568 if (objp) {
569 JS::ExposeObjectToActiveJS(objp);
571 return cx->compartment()->wrap(cx, objp);
574 JS_PUBLIC_API bool JS_WrapValue(JSContext* cx, MutableHandleValue vp) {
575 AssertHeapIsIdle();
576 CHECK_THREAD(cx);
577 JS::ExposeValueToActiveJS(vp);
578 return cx->compartment()->wrap(cx, vp);
581 static void ReleaseAssertObjectHasNoWrappers(JSContext* cx,
582 HandleObject target) {
583 for (CompartmentsIter c(cx->runtime()); !c.done(); c.next()) {
584 if (c->lookupWrapper(target)) {
585 MOZ_CRASH("wrapper found for target object");
591 * [SMDOC] Brain transplants.
593 * Not for beginners or the squeamish.
595 * Sometimes a web spec requires us to transplant an object from one
596 * compartment to another, like when a DOM node is inserted into a document in
597 * another window and thus gets "adopted". We cannot literally change the
598 * `.compartment()` of a `JSObject`; that would break the compartment
599 * invariants. However, as usual, we have a workaround using wrappers.
601 * Of all the wrapper-based workarounds we do, it's safe to say this is the
602 * most spectacular and questionable.
604 * `JS_TransplantObject(cx, origobj, target)` changes `origobj` into a
605 * simulacrum of `target`, using highly esoteric means. To JS code, the effect
606 * is as if `origobj` magically "became" `target`, but most often what actually
607 * happens is that `origobj` gets turned into a cross-compartment wrapper for
608 * `target`. The old behavior and contents of `origobj` are overwritten or
609 * discarded.
611 * Thus, to "transplant" an object from one compartment to another:
613 * 1. Let `origobj` be the object that you want to move. First, create a
614 * clone of it, `target`, in the destination compartment.
616 * In our DOM adoption example, `target` will be a Node of the same type as
617 * `origobj`, same content, but in the adopting document. We're not done
618 * yet: the spec for DOM adoption requires that `origobj.ownerDocument`
619 * actually change. All we've done so far is make a copy.
621 * 2. Call `JS_TransplantObject(cx, origobj, target)`. This typically turns
622 * `origobj` into a wrapper for `target`, so that any JS code that has a
623 * reference to `origobj` will observe it to have the behavior of `target`
624 * going forward. In addition, all existing wrappers for `origobj` are
625 * changed into wrappers for `target`, extending the illusion to those
626 * compartments as well.
628 * During navigation, we use the above technique to transplant the WindowProxy
629 * into the new Window's compartment.
631 * A few rules:
633 * - `origobj` and `target` must be two distinct objects of the same
634 * `JSClass`. Some classes may not support transplantation; WindowProxy
635 * objects and DOM nodes are OK.
637 * - `target` should be created specifically to be passed to this function.
638 * There must be no existing cross-compartment wrappers for it; ideally
639 * there shouldn't be any pointers to it at all, except the one passed in.
641 * - `target` shouldn't be used afterwards. Instead, `JS_TransplantObject`
642 * returns a pointer to the transplanted object, which might be `target`
643 * but might be some other object in the same compartment. Use that.
645 * The reason for this last rule is that JS_TransplantObject does very strange
646 * things in some cases, like swapping `target`'s brain with that of another
647 * object. Leaving `target` behaving like its former self is not a goal.
649 * We don't have a good way to recover from failure in this function, so
650 * we intentionally crash instead.
653 static void CheckTransplantObject(JSObject* obj) {
654 #ifdef DEBUG
655 MOZ_ASSERT(!obj->is<CrossCompartmentWrapperObject>());
656 JS::AssertCellIsNotGray(obj);
657 #endif
660 JS_PUBLIC_API JSObject* JS_TransplantObject(JSContext* cx, HandleObject origobj,
661 HandleObject target) {
662 AssertHeapIsIdle();
663 MOZ_ASSERT(origobj != target);
664 CheckTransplantObject(origobj);
665 CheckTransplantObject(target);
666 ReleaseAssertObjectHasNoWrappers(cx, target);
668 RootedObject newIdentity(cx);
670 // Don't allow a compacting GC to observe any intermediate state.
671 AutoDisableCompactingGC nocgc(cx);
673 AutoDisableProxyCheck adpc;
675 AutoEnterOOMUnsafeRegion oomUnsafe;
677 JS::Compartment* destination = target->compartment();
679 if (origobj->compartment() == destination) {
680 // If the original object is in the same compartment as the
681 // destination, then we know that we won't find a wrapper in the
682 // destination's cross compartment map and that the same
683 // object will continue to work.
684 AutoRealm ar(cx, origobj);
685 JSObject::swap(cx, origobj, target, oomUnsafe);
686 newIdentity = origobj;
687 } else if (ObjectWrapperMap::Ptr p = destination->lookupWrapper(origobj)) {
688 // There might already be a wrapper for the original object in
689 // the new compartment. If there is, we use its identity and swap
690 // in the contents of |target|.
691 newIdentity = p->value().get();
693 // When we remove origv from the wrapper map, its wrapper, newIdentity,
694 // must immediately cease to be a cross-compartment wrapper. Nuke it.
695 destination->removeWrapper(p);
696 NukeCrossCompartmentWrapper(cx, newIdentity);
698 AutoRealm ar(cx, newIdentity);
699 JSObject::swap(cx, newIdentity, target, oomUnsafe);
700 } else {
701 // Otherwise, we use |target| for the new identity object.
702 newIdentity = target;
705 // Now, iterate through other scopes looking for references to the old
706 // object, and update the relevant cross-compartment wrappers. We do this
707 // even if origobj is in the same compartment as target and thus
708 // `newIdentity == origobj`, because this process also clears out any
709 // cached wrapper state.
710 if (!RemapAllWrappersForObject(cx, origobj, newIdentity)) {
711 oomUnsafe.crash("JS_TransplantObject");
714 // Lastly, update the original object to point to the new one.
715 if (origobj->compartment() != destination) {
716 RootedObject newIdentityWrapper(cx, newIdentity);
717 AutoRealm ar(cx, origobj);
718 if (!JS_WrapObject(cx, &newIdentityWrapper)) {
719 MOZ_RELEASE_ASSERT(cx->isThrowingOutOfMemory() ||
720 cx->isThrowingOverRecursed());
721 oomUnsafe.crash("JS_TransplantObject");
723 MOZ_ASSERT(Wrapper::wrappedObject(newIdentityWrapper) == newIdentity);
724 JSObject::swap(cx, origobj, newIdentityWrapper, oomUnsafe);
725 if (origobj->compartment()->lookupWrapper(newIdentity)) {
726 MOZ_ASSERT(origobj->is<CrossCompartmentWrapperObject>());
727 if (!origobj->compartment()->putWrapper(cx, newIdentity, origobj)) {
728 oomUnsafe.crash("JS_TransplantObject");
733 // The new identity object might be one of several things. Return it to avoid
734 // ambiguity.
735 JS::AssertCellIsNotGray(newIdentity);
736 return newIdentity;
739 JS_PUBLIC_API void js::RemapRemoteWindowProxies(
740 JSContext* cx, CompartmentTransplantCallback* callback,
741 MutableHandleObject target) {
742 AssertHeapIsIdle();
743 CheckTransplantObject(target);
744 ReleaseAssertObjectHasNoWrappers(cx, target);
746 // |target| can't be a remote proxy, because we expect it to get a CCW when
747 // wrapped across compartments.
748 MOZ_ASSERT(!js::IsDOMRemoteProxyObject(target));
750 // Don't allow a compacting GC to observe any intermediate state.
751 AutoDisableCompactingGC nocgc(cx);
753 AutoDisableProxyCheck adpc;
755 AutoEnterOOMUnsafeRegion oomUnsafe;
757 AutoCheckRecursionLimit recursion(cx);
758 if (!recursion.checkSystem(cx)) {
759 oomUnsafe.crash("js::RemapRemoteWindowProxies");
762 RootedObject targetCompartmentProxy(cx);
763 JS::RootedVector<JSObject*> otherProxies(cx);
765 // Use the callback to find remote proxies in all compartments that match
766 // whatever criteria callback uses.
767 for (CompartmentsIter c(cx->runtime()); !c.done(); c.next()) {
768 RootedObject remoteProxy(cx, callback->getObjectToTransplant(c));
769 if (!remoteProxy) {
770 continue;
772 // The object the callback returns should be a DOM remote proxy object in
773 // the compartment c. We rely on it being a DOM remote proxy because that
774 // means that it won't have any cross-compartment wrappers.
775 MOZ_ASSERT(js::IsDOMRemoteProxyObject(remoteProxy));
776 MOZ_ASSERT(remoteProxy->compartment() == c);
777 CheckTransplantObject(remoteProxy);
779 // Immediately turn the DOM remote proxy object into a dead proxy object
780 // so we don't have to worry about anything weird going on with it.
781 js::NukeNonCCWProxy(cx, remoteProxy);
783 if (remoteProxy->compartment() == target->compartment()) {
784 targetCompartmentProxy = remoteProxy;
785 } else if (!otherProxies.append(remoteProxy)) {
786 oomUnsafe.crash("js::RemapRemoteWindowProxies");
790 // If there was a remote proxy in |target|'s compartment, we need to use it
791 // instead of |target|, in case it had any references, so swap it. Do this
792 // before any other compartment so that the target object will be set up
793 // correctly before we start wrapping it into other compartments.
794 if (targetCompartmentProxy) {
795 AutoRealm ar(cx, targetCompartmentProxy);
796 JSObject::swap(cx, targetCompartmentProxy, target, oomUnsafe);
797 target.set(targetCompartmentProxy);
800 for (JSObject*& obj : otherProxies) {
801 RootedObject deadWrapper(cx, obj);
802 js::RemapDeadWrapper(cx, deadWrapper, target);
807 * Recompute all cross-compartment wrappers for an object, resetting state.
808 * Gecko uses this to clear Xray wrappers when doing a navigation that reuses
809 * the inner window and global object.
811 JS_PUBLIC_API bool JS_RefreshCrossCompartmentWrappers(JSContext* cx,
812 HandleObject obj) {
813 return RemapAllWrappersForObject(cx, obj, obj);
816 typedef struct JSStdName {
817 size_t atomOffset; /* offset of atom pointer in JSAtomState */
818 JSProtoKey key;
819 bool isDummy() const { return key == JSProto_Null; }
820 bool isSentinel() const { return key == JSProto_LIMIT; }
821 } JSStdName;
823 static const JSStdName* LookupStdName(const JSAtomState& names, JSAtom* name,
824 const JSStdName* table) {
825 for (unsigned i = 0; !table[i].isSentinel(); i++) {
826 if (table[i].isDummy()) {
827 continue;
829 JSAtom* atom = AtomStateOffsetToName(names, table[i].atomOffset);
830 MOZ_ASSERT(atom);
831 if (name == atom) {
832 return &table[i];
836 return nullptr;
840 * Table of standard classes, indexed by JSProtoKey. For entries where the
841 * JSProtoKey does not correspond to a class with a meaningful constructor, we
842 * insert a null entry into the table.
844 #define STD_NAME_ENTRY(name, clasp) {NAME_OFFSET(name), JSProto_##name},
845 #define STD_DUMMY_ENTRY(name, dummy) {0, JSProto_Null},
846 static const JSStdName standard_class_names[] = {
847 JS_FOR_PROTOTYPES(STD_NAME_ENTRY, STD_DUMMY_ENTRY){0, JSProto_LIMIT}};
850 * Table of top-level function and constant names and the JSProtoKey of the
851 * standard class that initializes them.
853 static const JSStdName builtin_property_names[] = {
854 {NAME_OFFSET(eval), JSProto_Object},
856 /* Global properties and functions defined by the Number class. */
857 {NAME_OFFSET(NaN), JSProto_Number},
858 {NAME_OFFSET(Infinity), JSProto_Number},
859 {NAME_OFFSET(isNaN), JSProto_Number},
860 {NAME_OFFSET(isFinite), JSProto_Number},
861 {NAME_OFFSET(parseFloat), JSProto_Number},
862 {NAME_OFFSET(parseInt), JSProto_Number},
864 /* String global functions. */
865 {NAME_OFFSET(escape), JSProto_String},
866 {NAME_OFFSET(unescape), JSProto_String},
867 {NAME_OFFSET(decodeURI), JSProto_String},
868 {NAME_OFFSET(encodeURI), JSProto_String},
869 {NAME_OFFSET(decodeURIComponent), JSProto_String},
870 {NAME_OFFSET(encodeURIComponent), JSProto_String},
871 {NAME_OFFSET(uneval), JSProto_String},
873 {0, JSProto_LIMIT}};
875 static bool SkipUneval(jsid id, JSContext* cx) {
876 return !cx->realm()->creationOptions().getToSourceEnabled() &&
877 id == NameToId(cx->names().uneval);
880 static bool SkipSharedArrayBufferConstructor(JSProtoKey key,
881 GlobalObject* global) {
882 if (key != JSProto_SharedArrayBuffer) {
883 return false;
886 const JS::RealmCreationOptions& options = global->realm()->creationOptions();
887 MOZ_ASSERT(options.getSharedMemoryAndAtomicsEnabled(),
888 "shouldn't contemplate defining SharedArrayBuffer if shared "
889 "memory is disabled");
891 // On the web, it isn't presently possible to expose the global
892 // "SharedArrayBuffer" property unless the page is cross-site-isolated. Only
893 // define this constructor if an option on the realm indicates that it should
894 // be defined.
895 return !options.defineSharedArrayBufferConstructor();
898 JS_PUBLIC_API bool JS_ResolveStandardClass(JSContext* cx, HandleObject obj,
899 HandleId id, bool* resolved) {
900 AssertHeapIsIdle();
901 CHECK_THREAD(cx);
902 cx->check(obj, id);
904 Handle<GlobalObject*> global = obj.as<GlobalObject>();
905 *resolved = false;
907 if (!id.isAtom()) {
908 return true;
911 /* Check whether we're resolving 'undefined', and define it if so. */
912 JSAtom* idAtom = id.toAtom();
913 if (idAtom == cx->names().undefined) {
914 *resolved = true;
915 return js::DefineDataProperty(
916 cx, global, id, UndefinedHandleValue,
917 JSPROP_PERMANENT | JSPROP_READONLY | JSPROP_RESOLVING);
920 // Resolve a "globalThis" self-referential property if necessary.
921 if (idAtom == cx->names().globalThis) {
922 return GlobalObject::maybeResolveGlobalThis(cx, global, resolved);
925 // Try for class constructors/prototypes named by well-known atoms.
926 const JSStdName* stdnm =
927 LookupStdName(cx->names(), idAtom, standard_class_names);
928 if (!stdnm) {
929 // Try less frequently used top-level functions and constants.
930 stdnm = LookupStdName(cx->names(), idAtom, builtin_property_names);
931 if (!stdnm) {
932 return true;
936 JSProtoKey key = stdnm->key;
937 if (key == JSProto_Null || GlobalObject::skipDeselectedConstructor(cx, key) ||
938 SkipUneval(id, cx)) {
939 return true;
942 // If this class is anonymous (or it's "SharedArrayBuffer" but that global
943 // constructor isn't supposed to be defined), then it doesn't exist as a
944 // global property, so we won't resolve anything.
945 const JSClass* clasp = ProtoKeyToClass(key);
946 if (clasp && !clasp->specShouldDefineConstructor()) {
947 return true;
949 if (SkipSharedArrayBufferConstructor(key, global)) {
950 return true;
953 if (!GlobalObject::ensureConstructor(cx, global, key)) {
954 return false;
956 *resolved = true;
957 return true;
960 JS_PUBLIC_API bool JS_MayResolveStandardClass(const JSAtomState& names, jsid id,
961 JSObject* maybeObj) {
962 MOZ_ASSERT_IF(maybeObj, maybeObj->is<GlobalObject>());
964 // The global object's resolve hook is special: JS_ResolveStandardClass
965 // initializes the prototype chain lazily. Only attempt to optimize here
966 // if we know the prototype chain has been initialized.
967 if (!maybeObj || !maybeObj->staticPrototype()) {
968 return true;
971 if (!id.isAtom()) {
972 return false;
975 JSAtom* atom = id.toAtom();
977 // This will return true even for deselected constructors. (To do
978 // better, we need a JSContext here; it's fine as it is.)
980 return atom == names.undefined || atom == names.globalThis ||
981 LookupStdName(names, atom, standard_class_names) ||
982 LookupStdName(names, atom, builtin_property_names);
985 JS_PUBLIC_API bool JS_EnumerateStandardClasses(JSContext* cx,
986 HandleObject obj) {
987 AssertHeapIsIdle();
988 CHECK_THREAD(cx);
989 cx->check(obj);
990 Handle<GlobalObject*> global = obj.as<GlobalObject>();
991 return GlobalObject::initStandardClasses(cx, global);
994 static bool EnumerateStandardClassesInTable(JSContext* cx,
995 Handle<GlobalObject*> global,
996 MutableHandleIdVector properties,
997 const JSStdName* table,
998 bool includeResolved) {
999 for (unsigned i = 0; !table[i].isSentinel(); i++) {
1000 if (table[i].isDummy()) {
1001 continue;
1004 JSProtoKey key = table[i].key;
1006 // If the standard class has been resolved, the properties have been
1007 // defined on the global so we don't need to add them here.
1008 if (!includeResolved && global->isStandardClassResolved(key)) {
1009 continue;
1012 if (GlobalObject::skipDeselectedConstructor(cx, key)) {
1013 continue;
1016 if (const JSClass* clasp = ProtoKeyToClass(key)) {
1017 if (!clasp->specShouldDefineConstructor() ||
1018 SkipSharedArrayBufferConstructor(key, global)) {
1019 continue;
1023 jsid id = NameToId(AtomStateOffsetToName(cx->names(), table[i].atomOffset));
1025 if (SkipUneval(id, cx)) {
1026 continue;
1029 if (!properties.append(id)) {
1030 return false;
1034 return true;
1037 static bool EnumerateStandardClasses(JSContext* cx, JS::HandleObject obj,
1038 JS::MutableHandleIdVector properties,
1039 bool enumerableOnly,
1040 bool includeResolved) {
1041 if (enumerableOnly) {
1042 // There are no enumerable standard classes and "undefined" is
1043 // not enumerable.
1044 return true;
1047 Handle<GlobalObject*> global = obj.as<GlobalObject>();
1049 // It's fine to always append |undefined| here, it's non-configurable and
1050 // the enumeration code filters duplicates.
1051 if (!properties.append(NameToId(cx->names().undefined))) {
1052 return false;
1055 bool resolved = false;
1056 if (!GlobalObject::maybeResolveGlobalThis(cx, global, &resolved)) {
1057 return false;
1059 if (resolved || includeResolved) {
1060 if (!properties.append(NameToId(cx->names().globalThis))) {
1061 return false;
1065 if (!EnumerateStandardClassesInTable(cx, global, properties,
1066 standard_class_names, includeResolved)) {
1067 return false;
1069 if (!EnumerateStandardClassesInTable(
1070 cx, global, properties, builtin_property_names, includeResolved)) {
1071 return false;
1074 return true;
1077 JS_PUBLIC_API bool JS_NewEnumerateStandardClasses(
1078 JSContext* cx, JS::HandleObject obj, JS::MutableHandleIdVector properties,
1079 bool enumerableOnly) {
1080 return EnumerateStandardClasses(cx, obj, properties, enumerableOnly, false);
1083 JS_PUBLIC_API bool JS_NewEnumerateStandardClassesIncludingResolved(
1084 JSContext* cx, JS::HandleObject obj, JS::MutableHandleIdVector properties,
1085 bool enumerableOnly) {
1086 return EnumerateStandardClasses(cx, obj, properties, enumerableOnly, true);
1089 JS_PUBLIC_API bool JS_GetClassObject(JSContext* cx, JSProtoKey key,
1090 MutableHandleObject objp) {
1091 AssertHeapIsIdle();
1092 CHECK_THREAD(cx);
1093 JSObject* obj = GlobalObject::getOrCreateConstructor(cx, key);
1094 if (!obj) {
1095 return false;
1097 objp.set(obj);
1098 return true;
1101 JS_PUBLIC_API bool JS_GetClassPrototype(JSContext* cx, JSProtoKey key,
1102 MutableHandleObject objp) {
1103 AssertHeapIsIdle();
1104 CHECK_THREAD(cx);
1106 // Bound functions don't have their own prototype object: they reuse the
1107 // prototype of the target object. This is typically Function.prototype so we
1108 // use that here.
1109 if (key == JSProto_BoundFunction) {
1110 key = JSProto_Function;
1113 JSObject* proto = GlobalObject::getOrCreatePrototype(cx, key);
1114 if (!proto) {
1115 return false;
1117 objp.set(proto);
1118 return true;
1121 namespace JS {
1123 JS_PUBLIC_API void ProtoKeyToId(JSContext* cx, JSProtoKey key,
1124 MutableHandleId idp) {
1125 idp.set(NameToId(ClassName(key, cx)));
1128 } /* namespace JS */
1130 JS_PUBLIC_API JSProtoKey JS_IdToProtoKey(JSContext* cx, HandleId id) {
1131 AssertHeapIsIdle();
1132 CHECK_THREAD(cx);
1133 cx->check(id);
1135 if (!id.isAtom()) {
1136 return JSProto_Null;
1139 JSAtom* atom = id.toAtom();
1140 const JSStdName* stdnm =
1141 LookupStdName(cx->names(), atom, standard_class_names);
1142 if (!stdnm) {
1143 return JSProto_Null;
1146 if (GlobalObject::skipDeselectedConstructor(cx, stdnm->key)) {
1147 return JSProto_Null;
1150 if (SkipSharedArrayBufferConstructor(stdnm->key, cx->global())) {
1151 MOZ_ASSERT(id == NameToId(cx->names().SharedArrayBuffer));
1152 return JSProto_Null;
1155 if (SkipUneval(id, cx)) {
1156 return JSProto_Null;
1159 static_assert(std::size(standard_class_names) == JSProto_LIMIT + 1);
1160 return static_cast<JSProtoKey>(stdnm - standard_class_names);
1163 extern JS_PUBLIC_API bool JS_IsGlobalObject(JSObject* obj) {
1164 return obj->is<GlobalObject>();
1167 extern JS_PUBLIC_API JSObject* JS_GlobalLexicalEnvironment(JSObject* obj) {
1168 return &obj->as<GlobalObject>().lexicalEnvironment();
1171 extern JS_PUBLIC_API bool JS_HasExtensibleLexicalEnvironment(JSObject* obj) {
1172 return obj->is<GlobalObject>() ||
1173 ObjectRealm::get(obj).getNonSyntacticLexicalEnvironment(obj);
1176 extern JS_PUBLIC_API JSObject* JS_ExtensibleLexicalEnvironment(JSObject* obj) {
1177 return ExtensibleLexicalEnvironmentObject::forVarEnvironment(obj);
1180 JS_PUBLIC_API JSObject* JS::CurrentGlobalOrNull(JSContext* cx) {
1181 AssertHeapIsIdleOrIterating();
1182 CHECK_THREAD(cx);
1183 if (!cx->realm()) {
1184 return nullptr;
1186 return cx->global();
1189 JS_PUBLIC_API JSObject* JS::GetNonCCWObjectGlobal(JSObject* obj) {
1190 AssertHeapIsIdleOrIterating();
1191 MOZ_DIAGNOSTIC_ASSERT(!IsCrossCompartmentWrapper(obj));
1192 return &obj->nonCCWGlobal();
1195 JS_PUBLIC_API bool JS::detail::ComputeThis(JSContext* cx, Value* vp,
1196 MutableHandleObject thisObject) {
1197 AssertHeapIsIdle();
1198 cx->check(vp[0], vp[1]);
1200 MutableHandleValue thisv = MutableHandleValue::fromMarkedLocation(&vp[1]);
1201 JSObject* obj = BoxNonStrictThis(cx, thisv);
1202 if (!obj) {
1203 return false;
1206 thisObject.set(obj);
1207 return true;
1210 static bool gProfileTimelineRecordingEnabled = false;
1212 JS_PUBLIC_API void JS::SetProfileTimelineRecordingEnabled(bool enabled) {
1213 gProfileTimelineRecordingEnabled = enabled;
1216 JS_PUBLIC_API bool JS::IsProfileTimelineRecordingEnabled() {
1217 return gProfileTimelineRecordingEnabled;
1220 JS_PUBLIC_API void* JS_malloc(JSContext* cx, size_t nbytes) {
1221 AssertHeapIsIdle();
1222 CHECK_THREAD(cx);
1223 return static_cast<void*>(cx->maybe_pod_malloc<uint8_t>(nbytes));
1226 JS_PUBLIC_API void* JS_realloc(JSContext* cx, void* p, size_t oldBytes,
1227 size_t newBytes) {
1228 AssertHeapIsIdle();
1229 CHECK_THREAD(cx);
1230 return static_cast<void*>(cx->maybe_pod_realloc<uint8_t>(
1231 static_cast<uint8_t*>(p), oldBytes, newBytes));
1234 JS_PUBLIC_API void JS_free(JSContext* cx, void* p) { return js_free(p); }
1236 JS_PUBLIC_API void* JS_string_malloc(JSContext* cx, size_t nbytes) {
1237 AssertHeapIsIdle();
1238 CHECK_THREAD(cx);
1239 return static_cast<void*>(
1240 cx->maybe_pod_arena_malloc<uint8_t>(js::StringBufferArena, nbytes));
1243 JS_PUBLIC_API void* JS_string_realloc(JSContext* cx, void* p, size_t oldBytes,
1244 size_t newBytes) {
1245 AssertHeapIsIdle();
1246 CHECK_THREAD(cx);
1247 return static_cast<void*>(cx->maybe_pod_arena_realloc<uint8_t>(
1248 js::StringBufferArena, static_cast<uint8_t*>(p), oldBytes, newBytes));
1251 JS_PUBLIC_API void JS_string_free(JSContext* cx, void* p) { return js_free(p); }
1253 JS_PUBLIC_API void JS::AddAssociatedMemory(JSObject* obj, size_t nbytes,
1254 JS::MemoryUse use) {
1255 MOZ_ASSERT(obj);
1256 if (!nbytes) {
1257 return;
1260 Zone* zone = obj->zone();
1261 MOZ_ASSERT(!IsInsideNursery(obj));
1262 zone->addCellMemory(obj, nbytes, js::MemoryUse(use));
1263 zone->maybeTriggerGCOnMalloc();
1266 JS_PUBLIC_API void JS::RemoveAssociatedMemory(JSObject* obj, size_t nbytes,
1267 JS::MemoryUse use) {
1268 MOZ_ASSERT(obj);
1269 if (!nbytes) {
1270 return;
1273 GCContext* gcx = obj->runtimeFromMainThread()->gcContext();
1274 gcx->removeCellMemory(obj, nbytes, js::MemoryUse(use));
1277 #undef JS_AddRoot
1279 JS_PUBLIC_API bool JS_AddExtraGCRootsTracer(JSContext* cx,
1280 JSTraceDataOp traceOp, void* data) {
1281 return cx->runtime()->gc.addBlackRootsTracer(traceOp, data);
1284 JS_PUBLIC_API void JS_RemoveExtraGCRootsTracer(JSContext* cx,
1285 JSTraceDataOp traceOp,
1286 void* data) {
1287 return cx->runtime()->gc.removeBlackRootsTracer(traceOp, data);
1290 JS_PUBLIC_API JS::GCReason JS::WantEagerMinorGC(JSRuntime* rt) {
1291 if (rt->gc.nursery().shouldCollect()) {
1292 return JS::GCReason::EAGER_NURSERY_COLLECTION;
1294 return JS::GCReason::NO_REASON;
1297 JS_PUBLIC_API JS::GCReason JS::WantEagerMajorGC(JSRuntime* rt) {
1298 return rt->gc.wantMajorGC(true);
1301 JS_PUBLIC_API void JS::MaybeRunNurseryCollection(JSRuntime* rt,
1302 JS::GCReason reason) {
1303 gc::GCRuntime& gc = rt->gc;
1304 if (gc.nursery().shouldCollect()) {
1305 gc.minorGC(reason);
1309 JS_PUBLIC_API void JS::RunNurseryCollection(
1310 JSRuntime* rt, JS::GCReason reason,
1311 mozilla::TimeDuration aSinceLastMinorGC) {
1312 gc::GCRuntime& gc = rt->gc;
1313 if (!gc.nursery().lastCollectionEndTime() ||
1314 (mozilla::TimeStamp::Now() - gc.nursery().lastCollectionEndTime() >
1315 aSinceLastMinorGC)) {
1316 gc.minorGC(reason);
1320 JS_PUBLIC_API void JS_GC(JSContext* cx, JS::GCReason reason) {
1321 AssertHeapIsIdle();
1322 JS::PrepareForFullGC(cx);
1323 cx->runtime()->gc.gc(JS::GCOptions::Normal, reason);
1326 JS_PUBLIC_API void JS_MaybeGC(JSContext* cx) {
1327 AssertHeapIsIdle();
1328 cx->runtime()->gc.maybeGC();
1331 JS_PUBLIC_API void JS_SetGCCallback(JSContext* cx, JSGCCallback cb,
1332 void* data) {
1333 AssertHeapIsIdle();
1334 cx->runtime()->gc.setGCCallback(cb, data);
1337 JS_PUBLIC_API void JS_SetObjectsTenuredCallback(JSContext* cx,
1338 JSObjectsTenuredCallback cb,
1339 void* data) {
1340 AssertHeapIsIdle();
1341 cx->runtime()->gc.setObjectsTenuredCallback(cb, data);
1344 JS_PUBLIC_API bool JS_AddFinalizeCallback(JSContext* cx, JSFinalizeCallback cb,
1345 void* data) {
1346 AssertHeapIsIdle();
1347 return cx->runtime()->gc.addFinalizeCallback(cb, data);
1350 JS_PUBLIC_API void JS_RemoveFinalizeCallback(JSContext* cx,
1351 JSFinalizeCallback cb) {
1352 cx->runtime()->gc.removeFinalizeCallback(cb);
1355 JS_PUBLIC_API void JS::SetHostCleanupFinalizationRegistryCallback(
1356 JSContext* cx, JSHostCleanupFinalizationRegistryCallback cb, void* data) {
1357 AssertHeapIsIdle();
1358 cx->runtime()->gc.setHostCleanupFinalizationRegistryCallback(cb, data);
1361 JS_PUBLIC_API void JS::ClearKeptObjects(JSContext* cx) {
1362 gc::GCRuntime* gc = &cx->runtime()->gc;
1364 for (ZonesIter zone(gc, ZoneSelector::WithAtoms); !zone.done(); zone.next()) {
1365 zone->clearKeptObjects();
1369 JS_PUBLIC_API bool JS::AtomsZoneIsCollecting(JSRuntime* runtime) {
1370 return runtime->activeGCInAtomsZone();
1373 JS_PUBLIC_API bool JS::IsAtomsZone(JS::Zone* zone) {
1374 return zone->isAtomsZone();
1377 JS_PUBLIC_API bool JS_AddWeakPointerZonesCallback(JSContext* cx,
1378 JSWeakPointerZonesCallback cb,
1379 void* data) {
1380 AssertHeapIsIdle();
1381 return cx->runtime()->gc.addWeakPointerZonesCallback(cb, data);
1384 JS_PUBLIC_API void JS_RemoveWeakPointerZonesCallback(
1385 JSContext* cx, JSWeakPointerZonesCallback cb) {
1386 cx->runtime()->gc.removeWeakPointerZonesCallback(cb);
1389 JS_PUBLIC_API bool JS_AddWeakPointerCompartmentCallback(
1390 JSContext* cx, JSWeakPointerCompartmentCallback cb, void* data) {
1391 AssertHeapIsIdle();
1392 return cx->runtime()->gc.addWeakPointerCompartmentCallback(cb, data);
1395 JS_PUBLIC_API void JS_RemoveWeakPointerCompartmentCallback(
1396 JSContext* cx, JSWeakPointerCompartmentCallback cb) {
1397 cx->runtime()->gc.removeWeakPointerCompartmentCallback(cb);
1400 JS_PUBLIC_API bool JS_UpdateWeakPointerAfterGC(JSTracer* trc,
1401 JS::Heap<JSObject*>* objp) {
1402 return TraceWeakEdge(trc, objp);
1405 JS_PUBLIC_API bool JS_UpdateWeakPointerAfterGCUnbarriered(JSTracer* trc,
1406 JSObject** objp) {
1407 return TraceManuallyBarrieredWeakEdge(trc, objp, "External weak pointer");
1410 JS_PUBLIC_API void JS_SetGCParameter(JSContext* cx, JSGCParamKey key,
1411 uint32_t value) {
1412 // Bug 1742118: JS_SetGCParameter has no way to return an error
1413 // The GC ignores invalid values internally but this is not reported to the
1414 // caller.
1415 (void)cx->runtime()->gc.setParameter(cx, key, value);
1418 JS_PUBLIC_API void JS_ResetGCParameter(JSContext* cx, JSGCParamKey key) {
1419 cx->runtime()->gc.resetParameter(cx, key);
1422 JS_PUBLIC_API uint32_t JS_GetGCParameter(JSContext* cx, JSGCParamKey key) {
1423 return cx->runtime()->gc.getParameter(key);
1426 JS_PUBLIC_API void JS_SetGCParametersBasedOnAvailableMemory(
1427 JSContext* cx, uint32_t availMemMB) {
1428 struct JSGCConfig {
1429 JSGCParamKey key;
1430 uint32_t value;
1433 static const JSGCConfig minimal[] = {
1434 {JSGC_SLICE_TIME_BUDGET_MS, 5},
1435 {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
1436 {JSGC_LARGE_HEAP_SIZE_MIN, 250},
1437 {JSGC_SMALL_HEAP_SIZE_MAX, 50},
1438 {JSGC_HIGH_FREQUENCY_SMALL_HEAP_GROWTH, 300},
1439 {JSGC_HIGH_FREQUENCY_LARGE_HEAP_GROWTH, 120},
1440 {JSGC_LOW_FREQUENCY_HEAP_GROWTH, 120},
1441 {JSGC_ALLOCATION_THRESHOLD, 15},
1442 {JSGC_MALLOC_THRESHOLD_BASE, 20},
1443 {JSGC_SMALL_HEAP_INCREMENTAL_LIMIT, 200},
1444 {JSGC_LARGE_HEAP_INCREMENTAL_LIMIT, 110},
1445 {JSGC_URGENT_THRESHOLD_MB, 8}};
1447 static const JSGCConfig nominal[] = {
1448 {JSGC_SLICE_TIME_BUDGET_MS, 5},
1449 {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1000},
1450 {JSGC_LARGE_HEAP_SIZE_MIN, 500},
1451 {JSGC_SMALL_HEAP_SIZE_MAX, 100},
1452 {JSGC_HIGH_FREQUENCY_SMALL_HEAP_GROWTH, 300},
1453 {JSGC_HIGH_FREQUENCY_LARGE_HEAP_GROWTH, 150},
1454 {JSGC_LOW_FREQUENCY_HEAP_GROWTH, 150},
1455 {JSGC_ALLOCATION_THRESHOLD, 27},
1456 {JSGC_MALLOC_THRESHOLD_BASE, 38},
1457 {JSGC_SMALL_HEAP_INCREMENTAL_LIMIT, 150},
1458 {JSGC_LARGE_HEAP_INCREMENTAL_LIMIT, 110},
1459 {JSGC_URGENT_THRESHOLD_MB, 16}};
1461 const auto& configSet = availMemMB > 512 ? nominal : minimal;
1462 for (const auto& config : configSet) {
1463 JS_SetGCParameter(cx, config.key, config.value);
1467 JS_PUBLIC_API JSString* JS_NewExternalStringLatin1(
1468 JSContext* cx, const Latin1Char* chars, size_t length,
1469 const JSExternalStringCallbacks* callbacks) {
1470 AssertHeapIsIdle();
1471 CHECK_THREAD(cx);
1472 return JSExternalString::new_(cx, chars, length, callbacks);
1475 JS_PUBLIC_API JSString* JS_NewExternalUCString(
1476 JSContext* cx, const char16_t* chars, size_t length,
1477 const JSExternalStringCallbacks* callbacks) {
1478 AssertHeapIsIdle();
1479 CHECK_THREAD(cx);
1480 return JSExternalString::new_(cx, chars, length, callbacks);
1483 JS_PUBLIC_API JSString* JS_NewMaybeExternalStringLatin1(
1484 JSContext* cx, const JS::Latin1Char* chars, size_t length,
1485 const JSExternalStringCallbacks* callbacks, bool* allocatedExternal) {
1486 AssertHeapIsIdle();
1487 CHECK_THREAD(cx);
1488 return NewMaybeExternalString(cx, chars, length, callbacks,
1489 allocatedExternal);
1492 JS_PUBLIC_API JSString* JS_NewMaybeExternalStringUTF8(
1493 JSContext* cx, const JS::UTF8Chars& utf8,
1494 const JSExternalStringCallbacks* callbacks, bool* allocatedExternal) {
1495 AssertHeapIsIdle();
1496 CHECK_THREAD(cx);
1498 JS::SmallestEncoding encoding = JS::FindSmallestEncoding(utf8);
1499 if (encoding == JS::SmallestEncoding::ASCII) {
1500 // ASCII case can use the external buffer as Latin1 buffer.
1501 return NewMaybeExternalString(
1502 cx, reinterpret_cast<JS::Latin1Char*>(utf8.begin().get()),
1503 utf8.length(), callbacks, allocatedExternal);
1506 // Non-ASCII case cannot use the external buffer.
1507 *allocatedExternal = false;
1508 return NewStringCopyUTF8N(cx, utf8, encoding);
1511 JS_PUBLIC_API JSString* JS_NewMaybeExternalUCString(
1512 JSContext* cx, const char16_t* chars, size_t length,
1513 const JSExternalStringCallbacks* callbacks, bool* allocatedExternal) {
1514 AssertHeapIsIdle();
1515 CHECK_THREAD(cx);
1516 return NewMaybeExternalString(cx, chars, length, callbacks,
1517 allocatedExternal);
1520 extern JS_PUBLIC_API const JSExternalStringCallbacks*
1521 JS_GetExternalStringCallbacks(JSString* str) {
1522 return str->asExternal().callbacks();
1525 static void SetNativeStackSize(JSContext* cx, JS::StackKind kind,
1526 JS::NativeStackSize stackSize) {
1527 #ifdef __wasi__
1528 cx->nativeStackLimit[kind] = JS::WASINativeStackLimit;
1529 #else // __wasi__
1530 if (stackSize == 0) {
1531 cx->nativeStackLimit[kind] = JS::NativeStackLimitMax;
1532 } else {
1533 cx->nativeStackLimit[kind] =
1534 JS::GetNativeStackLimit(cx->nativeStackBase(), stackSize - 1);
1536 #endif // !__wasi__
1539 JS_PUBLIC_API void JS_SetNativeStackQuota(
1540 JSContext* cx, JS::NativeStackSize systemCodeStackSize,
1541 JS::NativeStackSize trustedScriptStackSize,
1542 JS::NativeStackSize untrustedScriptStackSize) {
1543 MOZ_ASSERT(!cx->activation());
1545 if (!trustedScriptStackSize) {
1546 trustedScriptStackSize = systemCodeStackSize;
1547 } else {
1548 MOZ_ASSERT(trustedScriptStackSize < systemCodeStackSize);
1551 if (!untrustedScriptStackSize) {
1552 untrustedScriptStackSize = trustedScriptStackSize;
1553 } else {
1554 MOZ_ASSERT(untrustedScriptStackSize < trustedScriptStackSize);
1557 SetNativeStackSize(cx, JS::StackForSystemCode, systemCodeStackSize);
1558 SetNativeStackSize(cx, JS::StackForTrustedScript, trustedScriptStackSize);
1559 SetNativeStackSize(cx, JS::StackForUntrustedScript, untrustedScriptStackSize);
1561 cx->initJitStackLimit();
1564 /************************************************************************/
1566 JS_PUBLIC_API bool JS_ValueToId(JSContext* cx, HandleValue value,
1567 MutableHandleId idp) {
1568 AssertHeapIsIdle();
1569 CHECK_THREAD(cx);
1570 cx->check(value);
1571 return ToPropertyKey(cx, value, idp);
1574 JS_PUBLIC_API bool JS_StringToId(JSContext* cx, HandleString string,
1575 MutableHandleId idp) {
1576 AssertHeapIsIdle();
1577 CHECK_THREAD(cx);
1578 cx->check(string);
1579 RootedValue value(cx, StringValue(string));
1580 return PrimitiveValueToId<CanGC>(cx, value, idp);
1583 JS_PUBLIC_API bool JS_IdToValue(JSContext* cx, jsid id, MutableHandleValue vp) {
1584 AssertHeapIsIdle();
1585 CHECK_THREAD(cx);
1586 cx->check(id);
1587 vp.set(IdToValue(id));
1588 cx->check(vp);
1589 return true;
1592 JS_PUBLIC_API bool JS::ToPrimitive(JSContext* cx, HandleObject obj, JSType hint,
1593 MutableHandleValue vp) {
1594 AssertHeapIsIdle();
1595 CHECK_THREAD(cx);
1596 cx->check(obj);
1597 MOZ_ASSERT(obj != nullptr);
1598 MOZ_ASSERT(hint == JSTYPE_UNDEFINED || hint == JSTYPE_STRING ||
1599 hint == JSTYPE_NUMBER);
1600 vp.setObject(*obj);
1601 return ToPrimitiveSlow(cx, hint, vp);
1604 JS_PUBLIC_API bool JS::GetFirstArgumentAsTypeHint(JSContext* cx, CallArgs args,
1605 JSType* result) {
1606 if (!args.get(0).isString()) {
1607 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1608 JSMSG_NOT_EXPECTED_TYPE, "Symbol.toPrimitive",
1609 "\"string\", \"number\", or \"default\"",
1610 InformalValueTypeName(args.get(0)));
1611 return false;
1614 RootedString str(cx, args.get(0).toString());
1615 bool match;
1617 if (!EqualStrings(cx, str, cx->names().default_, &match)) {
1618 return false;
1620 if (match) {
1621 *result = JSTYPE_UNDEFINED;
1622 return true;
1625 if (!EqualStrings(cx, str, cx->names().string, &match)) {
1626 return false;
1628 if (match) {
1629 *result = JSTYPE_STRING;
1630 return true;
1633 if (!EqualStrings(cx, str, cx->names().number, &match)) {
1634 return false;
1636 if (match) {
1637 *result = JSTYPE_NUMBER;
1638 return true;
1641 UniqueChars bytes;
1642 const char* source = ValueToSourceForError(cx, args.get(0), bytes);
1643 if (!source) {
1644 ReportOutOfMemory(cx);
1645 return false;
1648 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
1649 JSMSG_NOT_EXPECTED_TYPE, "Symbol.toPrimitive",
1650 "\"string\", \"number\", or \"default\"", source);
1651 return false;
1654 JS_PUBLIC_API JSObject* JS_InitClass(
1655 JSContext* cx, HandleObject obj, const JSClass* protoClass,
1656 HandleObject protoProto, const char* name, JSNative constructor,
1657 unsigned nargs, const JSPropertySpec* ps, const JSFunctionSpec* fs,
1658 const JSPropertySpec* static_ps, const JSFunctionSpec* static_fs) {
1659 AssertHeapIsIdle();
1660 CHECK_THREAD(cx);
1661 cx->check(obj, protoProto);
1662 return InitClass(cx, obj, protoClass, protoProto, name, constructor, nargs,
1663 ps, fs, static_ps, static_fs);
1666 JS_PUBLIC_API bool JS_LinkConstructorAndPrototype(JSContext* cx,
1667 HandleObject ctor,
1668 HandleObject proto) {
1669 return LinkConstructorAndPrototype(cx, ctor, proto);
1672 JS_PUBLIC_API bool JS_InstanceOf(JSContext* cx, HandleObject obj,
1673 const JSClass* clasp, CallArgs* args) {
1674 AssertHeapIsIdle();
1675 CHECK_THREAD(cx);
1676 #ifdef DEBUG
1677 if (args) {
1678 cx->check(obj);
1679 cx->check(args->thisv(), args->calleev());
1681 #endif
1682 if (!obj || obj->getClass() != clasp) {
1683 if (args) {
1684 ReportIncompatibleMethod(cx, *args, clasp);
1686 return false;
1688 return true;
1691 JS_PUBLIC_API bool JS_HasInstance(JSContext* cx, HandleObject obj,
1692 HandleValue value, bool* bp) {
1693 AssertHeapIsIdle();
1694 cx->check(obj, value);
1695 return InstanceofOperator(cx, obj, value, bp);
1698 JS_PUBLIC_API JSObject* JS_GetConstructor(JSContext* cx, HandleObject proto) {
1699 AssertHeapIsIdle();
1700 CHECK_THREAD(cx);
1701 cx->check(proto);
1703 RootedValue cval(cx);
1704 if (!GetProperty(cx, proto, proto, cx->names().constructor, &cval)) {
1705 return nullptr;
1707 if (!IsFunctionObject(cval)) {
1708 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1709 JSMSG_NO_CONSTRUCTOR, proto->getClass()->name);
1710 return nullptr;
1712 return &cval.toObject();
1715 JS::RealmCreationOptions&
1716 JS::RealmCreationOptions::setNewCompartmentInSystemZone() {
1717 compSpec_ = CompartmentSpecifier::NewCompartmentInSystemZone;
1718 comp_ = nullptr;
1719 return *this;
1722 JS::RealmCreationOptions&
1723 JS::RealmCreationOptions::setNewCompartmentInExistingZone(JSObject* obj) {
1724 compSpec_ = CompartmentSpecifier::NewCompartmentInExistingZone;
1725 zone_ = obj->zone();
1726 return *this;
1729 JS::RealmCreationOptions& JS::RealmCreationOptions::setExistingCompartment(
1730 JSObject* obj) {
1731 compSpec_ = CompartmentSpecifier::ExistingCompartment;
1732 comp_ = obj->compartment();
1733 return *this;
1736 JS::RealmCreationOptions& JS::RealmCreationOptions::setExistingCompartment(
1737 JS::Compartment* compartment) {
1738 compSpec_ = CompartmentSpecifier::ExistingCompartment;
1739 comp_ = compartment;
1740 return *this;
1743 JS::RealmCreationOptions& JS::RealmCreationOptions::setNewCompartmentAndZone() {
1744 compSpec_ = CompartmentSpecifier::NewCompartmentAndZone;
1745 comp_ = nullptr;
1746 return *this;
1749 const JS::RealmCreationOptions& JS::RealmCreationOptionsRef(Realm* realm) {
1750 return realm->creationOptions();
1753 const JS::RealmCreationOptions& JS::RealmCreationOptionsRef(JSContext* cx) {
1754 return cx->realm()->creationOptions();
1757 bool JS::RealmCreationOptions::getSharedMemoryAndAtomicsEnabled() const {
1758 return sharedMemoryAndAtomics_;
1761 JS::RealmCreationOptions&
1762 JS::RealmCreationOptions::setSharedMemoryAndAtomicsEnabled(bool flag) {
1763 sharedMemoryAndAtomics_ = flag;
1764 return *this;
1767 bool JS::RealmCreationOptions::getCoopAndCoepEnabled() const {
1768 return coopAndCoep_;
1771 JS::RealmCreationOptions& JS::RealmCreationOptions::setCoopAndCoepEnabled(
1772 bool flag) {
1773 coopAndCoep_ = flag;
1774 return *this;
1777 JS::RealmCreationOptions& JS::RealmCreationOptions::setLocaleCopyZ(
1778 const char* locale) {
1779 const size_t size = strlen(locale) + 1;
1781 AutoEnterOOMUnsafeRegion oomUnsafe;
1782 char* memoryPtr = js_pod_malloc<char>(sizeof(LocaleString) + size);
1783 if (!memoryPtr) {
1784 oomUnsafe.crash("RealmCreationOptions::setLocaleCopyZ");
1787 char* localePtr = memoryPtr + sizeof(LocaleString);
1788 memcpy(localePtr, locale, size);
1790 locale_ = new (memoryPtr) LocaleString(localePtr);
1792 return *this;
1795 const JS::RealmBehaviors& JS::RealmBehaviorsRef(JS::Realm* realm) {
1796 return realm->behaviors();
1799 const JS::RealmBehaviors& JS::RealmBehaviorsRef(JSContext* cx) {
1800 return cx->realm()->behaviors();
1803 void JS::SetRealmNonLive(Realm* realm) { realm->setNonLive(); }
1805 void JS::SetRealmReduceTimerPrecisionCallerType(Realm* realm,
1806 JS::RTPCallerTypeToken type) {
1807 realm->setReduceTimerPrecisionCallerType(type);
1810 JS_PUBLIC_API JSObject* JS_NewGlobalObject(JSContext* cx, const JSClass* clasp,
1811 JSPrincipals* principals,
1812 JS::OnNewGlobalHookOption hookOption,
1813 const JS::RealmOptions& options) {
1814 MOZ_RELEASE_ASSERT(
1815 cx->runtime()->hasInitializedSelfHosting(),
1816 "Must call JS::InitSelfHostedCode() before creating a global");
1818 AssertHeapIsIdle();
1819 CHECK_THREAD(cx);
1821 return GlobalObject::new_(cx, clasp, principals, hookOption, options);
1824 JS_PUBLIC_API void JS_GlobalObjectTraceHook(JSTracer* trc, JSObject* global) {
1825 GlobalObject* globalObj = &global->as<GlobalObject>();
1826 Realm* globalRealm = globalObj->realm();
1828 // If we GC when creating the global, we may not have set that global's
1829 // realm's global pointer yet. In this case, the realm will not yet contain
1830 // anything that needs to be traced.
1831 if (globalRealm->unsafeUnbarrieredMaybeGlobal() != globalObj) {
1832 return;
1835 // Trace the realm for any GC things that should only stick around if we
1836 // know the global is live.
1837 globalRealm->traceGlobalData(trc);
1839 globalObj->traceData(trc, globalObj);
1841 if (JSTraceOp trace = globalRealm->creationOptions().getTrace()) {
1842 trace(trc, global);
1846 const JSClassOps JS::DefaultGlobalClassOps = {
1847 nullptr, // addProperty
1848 nullptr, // delProperty
1849 nullptr, // enumerate
1850 JS_NewEnumerateStandardClasses, // newEnumerate
1851 JS_ResolveStandardClass, // resolve
1852 JS_MayResolveStandardClass, // mayResolve
1853 nullptr, // finalize
1854 nullptr, // call
1855 nullptr, // construct
1856 JS_GlobalObjectTraceHook, // trace
1859 JS_PUBLIC_API void JS_FireOnNewGlobalObject(JSContext* cx,
1860 JS::HandleObject global) {
1861 // This hook is infallible, because we don't really want arbitrary script
1862 // to be able to throw errors during delicate global creation routines.
1863 // This infallibility will eat OOM and slow script, but if that happens
1864 // we'll likely run up into them again soon in a fallible context.
1865 cx->check(global);
1867 Rooted<js::GlobalObject*> globalObject(cx, &global->as<GlobalObject>());
1868 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
1869 if (JS::GetReduceMicrosecondTimePrecisionCallback()) {
1870 MOZ_DIAGNOSTIC_ASSERT(globalObject->realm()
1871 ->behaviors()
1872 .reduceTimerPrecisionCallerType()
1873 .isSome(),
1874 "Trying to create a global without setting an "
1875 "explicit RTPCallerType!");
1877 #endif
1878 DebugAPI::onNewGlobalObject(cx, globalObject);
1879 cx->runtime()->ensureRealmIsRecordingAllocations(globalObject);
1882 JS_PUBLIC_API JSObject* JS_NewObject(JSContext* cx, const JSClass* clasp) {
1883 MOZ_ASSERT(!cx->zone()->isAtomsZone());
1884 AssertHeapIsIdle();
1885 CHECK_THREAD(cx);
1887 if (!clasp) {
1888 // Default class is Object.
1889 return NewPlainObject(cx);
1892 MOZ_ASSERT(!clasp->isJSFunction());
1893 MOZ_ASSERT(clasp != &PlainObject::class_);
1894 MOZ_ASSERT(clasp != &ArrayObject::class_);
1895 MOZ_ASSERT(!(clasp->flags & JSCLASS_IS_GLOBAL));
1897 return NewBuiltinClassInstance(cx, clasp);
1900 JS_PUBLIC_API JSObject* JS_NewObjectWithGivenProto(JSContext* cx,
1901 const JSClass* clasp,
1902 HandleObject proto) {
1903 MOZ_ASSERT(!cx->zone()->isAtomsZone());
1904 AssertHeapIsIdle();
1905 CHECK_THREAD(cx);
1906 cx->check(proto);
1908 if (!clasp) {
1909 // Default class is Object.
1910 return NewPlainObjectWithProto(cx, proto);
1913 MOZ_ASSERT(!clasp->isJSFunction());
1914 MOZ_ASSERT(clasp != &PlainObject::class_);
1915 MOZ_ASSERT(clasp != &ArrayObject::class_);
1916 MOZ_ASSERT(!(clasp->flags & JSCLASS_IS_GLOBAL));
1918 return NewObjectWithGivenProto(cx, clasp, proto);
1921 JS_PUBLIC_API JSObject* JS_NewPlainObject(JSContext* cx) {
1922 MOZ_ASSERT(!cx->zone()->isAtomsZone());
1923 AssertHeapIsIdle();
1924 CHECK_THREAD(cx);
1926 return NewPlainObject(cx);
1929 JS_PUBLIC_API JSObject* JS_NewObjectForConstructor(JSContext* cx,
1930 const JSClass* clasp,
1931 const CallArgs& args) {
1932 AssertHeapIsIdle();
1933 CHECK_THREAD(cx);
1935 MOZ_ASSERT(!clasp->isJSFunction());
1936 MOZ_ASSERT(clasp != &PlainObject::class_);
1937 MOZ_ASSERT(clasp != &ArrayObject::class_);
1938 MOZ_ASSERT(!(clasp->flags & JSCLASS_IS_GLOBAL));
1940 if (!ThrowIfNotConstructing(cx, args, clasp->name)) {
1941 return nullptr;
1944 RootedObject newTarget(cx, &args.newTarget().toObject());
1945 cx->check(newTarget);
1947 RootedObject proto(cx);
1948 if (!GetPrototypeFromConstructor(cx, newTarget,
1949 JSCLASS_CACHED_PROTO_KEY(clasp), &proto)) {
1950 return nullptr;
1953 return NewObjectWithClassProto(cx, clasp, proto);
1956 JS_PUBLIC_API bool JS_IsNative(JSObject* obj) {
1957 return obj->is<NativeObject>();
1960 JS_PUBLIC_API void JS::AssertObjectBelongsToCurrentThread(JSObject* obj) {
1961 JSRuntime* rt = obj->compartment()->runtimeFromAnyThread();
1962 MOZ_RELEASE_ASSERT(CurrentThreadCanAccessRuntime(rt));
1965 JS_PUBLIC_API void JS::SetFilenameValidationCallback(
1966 JS::FilenameValidationCallback cb) {
1967 js::gFilenameValidationCallback = cb;
1970 JS_PUBLIC_API void JS::SetHostEnsureCanAddPrivateElementHook(
1971 JSContext* cx, JS::EnsureCanAddPrivateElementOp op) {
1972 cx->runtime()->canAddPrivateElement = op;
1975 /*** Standard internal methods **********************************************/
1977 JS_PUBLIC_API bool JS_GetPrototype(JSContext* cx, HandleObject obj,
1978 MutableHandleObject result) {
1979 cx->check(obj);
1980 return GetPrototype(cx, obj, result);
1983 JS_PUBLIC_API bool JS_SetPrototype(JSContext* cx, HandleObject obj,
1984 HandleObject proto) {
1985 AssertHeapIsIdle();
1986 CHECK_THREAD(cx);
1987 cx->check(obj, proto);
1989 return SetPrototype(cx, obj, proto);
1992 JS_PUBLIC_API bool JS_GetPrototypeIfOrdinary(JSContext* cx, HandleObject obj,
1993 bool* isOrdinary,
1994 MutableHandleObject result) {
1995 cx->check(obj);
1996 return GetPrototypeIfOrdinary(cx, obj, isOrdinary, result);
1999 JS_PUBLIC_API bool JS_IsExtensible(JSContext* cx, HandleObject obj,
2000 bool* extensible) {
2001 cx->check(obj);
2002 return IsExtensible(cx, obj, extensible);
2005 JS_PUBLIC_API bool JS_PreventExtensions(JSContext* cx, JS::HandleObject obj,
2006 ObjectOpResult& result) {
2007 cx->check(obj);
2008 return PreventExtensions(cx, obj, result);
2011 JS_PUBLIC_API bool JS_SetImmutablePrototype(JSContext* cx, JS::HandleObject obj,
2012 bool* succeeded) {
2013 cx->check(obj);
2014 return SetImmutablePrototype(cx, obj, succeeded);
2017 /* * */
2019 JS_PUBLIC_API bool JS_FreezeObject(JSContext* cx, HandleObject obj) {
2020 AssertHeapIsIdle();
2021 CHECK_THREAD(cx);
2022 cx->check(obj);
2023 return FreezeObject(cx, obj);
2026 static bool DeepFreezeSlot(JSContext* cx, const Value& v) {
2027 if (v.isPrimitive()) {
2028 return true;
2030 RootedObject obj(cx, &v.toObject());
2031 return JS_DeepFreezeObject(cx, obj);
2034 JS_PUBLIC_API bool JS_DeepFreezeObject(JSContext* cx, HandleObject obj) {
2035 AssertHeapIsIdle();
2036 CHECK_THREAD(cx);
2037 cx->check(obj);
2039 // Assume that non-extensible objects are already deep-frozen, to avoid
2040 // divergence.
2041 bool extensible;
2042 if (!IsExtensible(cx, obj, &extensible)) {
2043 return false;
2045 if (!extensible) {
2046 return true;
2049 if (!FreezeObject(cx, obj)) {
2050 return false;
2053 // Walk slots in obj and if any value is a non-null object, seal it.
2054 if (obj->is<NativeObject>()) {
2055 Rooted<NativeObject*> nobj(cx, &obj->as<NativeObject>());
2056 for (uint32_t i = 0, n = nobj->slotSpan(); i < n; ++i) {
2057 if (!DeepFreezeSlot(cx, nobj->getSlot(i))) {
2058 return false;
2061 for (uint32_t i = 0, n = nobj->getDenseInitializedLength(); i < n; ++i) {
2062 if (!DeepFreezeSlot(cx, nobj->getDenseElement(i))) {
2063 return false;
2068 return true;
2071 JS_PUBLIC_API bool JSPropertySpec::getValue(JSContext* cx,
2072 MutableHandleValue vp) const {
2073 MOZ_ASSERT(!isAccessor());
2075 switch (u.value.type) {
2076 case ValueWrapper::Type::String: {
2077 Rooted<JSAtom*> atom(cx,
2078 Atomize(cx, u.value.string, strlen(u.value.string)));
2079 if (!atom) {
2080 return false;
2082 vp.setString(atom);
2083 return true;
2086 case ValueWrapper::Type::Int32:
2087 vp.setInt32(u.value.int32);
2088 return true;
2090 case ValueWrapper::Type::Double:
2091 vp.setDouble(u.value.double_);
2092 return true;
2095 MOZ_CRASH("Unexpected type");
2098 bool PropertySpecNameToId(JSContext* cx, JSPropertySpec::Name name,
2099 MutableHandleId id) {
2100 if (name.isSymbol()) {
2101 id.set(PropertyKey::Symbol(cx->wellKnownSymbols().get(name.symbol())));
2102 } else {
2103 JSAtom* atom = Atomize(cx, name.string(), strlen(name.string()));
2104 if (!atom) {
2105 return false;
2107 id.set(AtomToId(atom));
2109 return true;
2112 JS_PUBLIC_API bool JS::PropertySpecNameToPermanentId(JSContext* cx,
2113 JSPropertySpec::Name name,
2114 jsid* idp) {
2115 // We are calling fromMarkedLocation(idp) even though idp points to a
2116 // location that will never be marked. This is OK because the whole point
2117 // of this API is to populate *idp with a jsid that does not need to be
2118 // marked.
2119 MutableHandleId id = MutableHandleId::fromMarkedLocation(idp);
2120 if (!PropertySpecNameToId(cx, name, id)) {
2121 return false;
2124 if (id.isString() && !PinAtom(cx, &id.toString()->asAtom())) {
2125 return false;
2128 return true;
2131 JS_PUBLIC_API bool JS::ToCompletePropertyDescriptor(
2132 JSContext* cx, HandleValue descriptor,
2133 MutableHandle<PropertyDescriptor> desc) {
2134 AssertHeapIsIdle();
2135 CHECK_THREAD(cx);
2136 cx->check(descriptor);
2137 if (!ToPropertyDescriptor(cx, descriptor, /* checkAccessors */ true, desc)) {
2138 return false;
2140 CompletePropertyDescriptor(desc);
2141 return true;
2144 JS_PUBLIC_API void JS_SetAllNonReservedSlotsToUndefined(JS::HandleObject obj) {
2145 if (!obj->is<NativeObject>()) {
2146 return;
2149 NativeObject& nobj = obj->as<NativeObject>();
2150 MOZ_RELEASE_ASSERT(!Watchtower::watchesPropertyModification(&nobj));
2151 const JSClass* clasp = obj->getClass();
2152 unsigned numReserved = JSCLASS_RESERVED_SLOTS(clasp);
2153 unsigned numSlots = nobj.slotSpan();
2154 for (unsigned i = numReserved; i < numSlots; i++) {
2155 obj->as<NativeObject>().setSlot(i, UndefinedValue());
2159 JS_PUBLIC_API void JS_SetReservedSlot(JSObject* obj, uint32_t index,
2160 const Value& value) {
2161 // Note: we don't use setReservedSlot so that this also works on swappable DOM
2162 // objects. See NativeObject::getReservedSlotRef comment.
2163 NativeObject& nobj = obj->as<NativeObject>();
2164 MOZ_ASSERT(index < JSCLASS_RESERVED_SLOTS(obj->getClass()));
2165 MOZ_ASSERT(!Watchtower::watchesPropertyModification(&nobj));
2166 nobj.setSlot(index, value);
2169 JS_PUBLIC_API void JS_InitReservedSlot(JSObject* obj, uint32_t index, void* ptr,
2170 size_t nbytes, JS::MemoryUse use) {
2171 // Note: we don't use InitReservedSlot so that this also works on swappable
2172 // DOM objects. See NativeObject::getReservedSlotRef comment.
2173 MOZ_ASSERT(index < JSCLASS_RESERVED_SLOTS(obj->getClass()));
2174 AddCellMemory(obj, nbytes, js::MemoryUse(use));
2175 obj->as<NativeObject>().initSlot(index, PrivateValue(ptr));
2178 JS_PUBLIC_API bool JS::IsMapObject(JSContext* cx, JS::HandleObject obj,
2179 bool* isMap) {
2180 return IsGivenTypeObject(cx, obj, ESClass::Map, isMap);
2183 JS_PUBLIC_API bool JS::IsSetObject(JSContext* cx, JS::HandleObject obj,
2184 bool* isSet) {
2185 return IsGivenTypeObject(cx, obj, ESClass::Set, isSet);
2188 JS_PUBLIC_API void JS_HoldPrincipals(JSPrincipals* principals) {
2189 ++principals->refcount;
2192 JS_PUBLIC_API void JS_DropPrincipals(JSContext* cx, JSPrincipals* principals) {
2193 int rc = --principals->refcount;
2194 if (rc == 0) {
2195 JS::AutoSuppressGCAnalysis nogc;
2196 cx->runtime()->destroyPrincipals(principals);
2200 JS_PUBLIC_API void JS_SetSecurityCallbacks(JSContext* cx,
2201 const JSSecurityCallbacks* scb) {
2202 MOZ_ASSERT(scb != &NullSecurityCallbacks);
2203 cx->runtime()->securityCallbacks = scb ? scb : &NullSecurityCallbacks;
2206 JS_PUBLIC_API const JSSecurityCallbacks* JS_GetSecurityCallbacks(
2207 JSContext* cx) {
2208 return (cx->runtime()->securityCallbacks != &NullSecurityCallbacks)
2209 ? cx->runtime()->securityCallbacks.ref()
2210 : nullptr;
2213 JS_PUBLIC_API void JS_SetTrustedPrincipals(JSContext* cx, JSPrincipals* prin) {
2214 cx->runtime()->setTrustedPrincipals(prin);
2217 extern JS_PUBLIC_API void JS_InitDestroyPrincipalsCallback(
2218 JSContext* cx, JSDestroyPrincipalsOp destroyPrincipals) {
2219 MOZ_ASSERT(destroyPrincipals);
2220 MOZ_ASSERT(!cx->runtime()->destroyPrincipals);
2221 cx->runtime()->destroyPrincipals = destroyPrincipals;
2224 extern JS_PUBLIC_API void JS_InitReadPrincipalsCallback(
2225 JSContext* cx, JSReadPrincipalsOp read) {
2226 MOZ_ASSERT(read);
2227 MOZ_ASSERT(!cx->runtime()->readPrincipals);
2228 cx->runtime()->readPrincipals = read;
2231 JS_PUBLIC_API JSFunction* JS_NewFunction(JSContext* cx, JSNative native,
2232 unsigned nargs, unsigned flags,
2233 const char* name) {
2234 MOZ_ASSERT(!cx->zone()->isAtomsZone());
2236 AssertHeapIsIdle();
2237 CHECK_THREAD(cx);
2239 Rooted<JSAtom*> atom(cx);
2240 if (name) {
2241 atom = Atomize(cx, name, strlen(name));
2242 if (!atom) {
2243 return nullptr;
2247 return (flags & JSFUN_CONSTRUCTOR)
2248 ? NewNativeConstructor(cx, native, nargs, atom)
2249 : NewNativeFunction(cx, native, nargs, atom);
2252 JS_PUBLIC_API JSFunction* JS::GetSelfHostedFunction(JSContext* cx,
2253 const char* selfHostedName,
2254 HandleId id,
2255 unsigned nargs) {
2256 MOZ_ASSERT(!cx->zone()->isAtomsZone());
2257 AssertHeapIsIdle();
2258 CHECK_THREAD(cx);
2259 cx->check(id);
2261 Rooted<JSAtom*> name(cx, IdToFunctionName(cx, id));
2262 if (!name) {
2263 return nullptr;
2266 JSAtom* shAtom = Atomize(cx, selfHostedName, strlen(selfHostedName));
2267 if (!shAtom) {
2268 return nullptr;
2270 Rooted<PropertyName*> shName(cx, shAtom->asPropertyName());
2271 RootedValue funVal(cx);
2272 if (!GlobalObject::getSelfHostedFunction(cx, cx->global(), shName, name,
2273 nargs, &funVal)) {
2274 return nullptr;
2276 return &funVal.toObject().as<JSFunction>();
2279 JS_PUBLIC_API JSFunction* JS::NewFunctionFromSpec(JSContext* cx,
2280 const JSFunctionSpec* fs,
2281 HandleId id) {
2282 cx->check(id);
2284 #ifdef DEBUG
2285 if (fs->name.isSymbol()) {
2286 JS::Symbol* sym = cx->wellKnownSymbols().get(fs->name.symbol());
2287 MOZ_ASSERT(PropertyKey::Symbol(sym) == id);
2288 } else {
2289 MOZ_ASSERT(id.isString() &&
2290 StringEqualsAscii(id.toLinearString(), fs->name.string()));
2292 #endif
2294 // Delay cloning self-hosted functions until they are called. This is
2295 // achieved by passing DefineFunction a nullptr JSNative which produces an
2296 // interpreted JSFunction where !hasScript. Interpreted call paths then
2297 // call InitializeLazyFunctionScript if !hasScript.
2298 if (fs->selfHostedName) {
2299 MOZ_ASSERT(!fs->call.op);
2300 MOZ_ASSERT(!fs->call.info);
2302 JSAtom* shAtom =
2303 Atomize(cx, fs->selfHostedName, strlen(fs->selfHostedName));
2304 if (!shAtom) {
2305 return nullptr;
2307 Rooted<PropertyName*> shName(cx, shAtom->asPropertyName());
2308 Rooted<JSAtom*> name(cx, IdToFunctionName(cx, id));
2309 if (!name) {
2310 return nullptr;
2312 RootedValue funVal(cx);
2313 if (!GlobalObject::getSelfHostedFunction(cx, cx->global(), shName, name,
2314 fs->nargs, &funVal)) {
2315 return nullptr;
2317 return &funVal.toObject().as<JSFunction>();
2320 Rooted<JSAtom*> atom(cx, IdToFunctionName(cx, id));
2321 if (!atom) {
2322 return nullptr;
2325 MOZ_ASSERT(fs->call.op);
2327 JSFunction* fun;
2328 if (fs->flags & JSFUN_CONSTRUCTOR) {
2329 fun = NewNativeConstructor(cx, fs->call.op, fs->nargs, atom);
2330 } else {
2331 fun = NewNativeFunction(cx, fs->call.op, fs->nargs, atom);
2333 if (!fun) {
2334 return nullptr;
2337 if (fs->call.info) {
2338 fun->setJitInfo(fs->call.info);
2340 return fun;
2343 JS_PUBLIC_API JSFunction* JS::NewFunctionFromSpec(JSContext* cx,
2344 const JSFunctionSpec* fs) {
2345 RootedId id(cx);
2346 if (!PropertySpecNameToId(cx, fs->name, &id)) {
2347 return nullptr;
2350 return NewFunctionFromSpec(cx, fs, id);
2353 JS_PUBLIC_API JSObject* JS_GetFunctionObject(JSFunction* fun) { return fun; }
2355 JS_PUBLIC_API bool JS_GetFunctionId(JSContext* cx, JS::Handle<JSFunction*> fun,
2356 JS::MutableHandle<JSString*> name) {
2357 JS::Rooted<JSAtom*> atom(cx);
2358 if (!fun->getExplicitName(cx, &atom)) {
2359 return false;
2361 name.set(atom);
2362 return true;
2365 JS_PUBLIC_API JSString* JS_GetMaybePartialFunctionId(JSFunction* fun) {
2366 return fun->maybePartialExplicitName();
2369 JS_PUBLIC_API bool JS_GetFunctionDisplayId(JSContext* cx,
2370 JS::Handle<JSFunction*> fun,
2371 JS::MutableHandle<JSString*> name) {
2372 JS::Rooted<JSAtom*> atom(cx);
2373 if (!fun->getDisplayAtom(cx, &atom)) {
2374 return false;
2376 name.set(atom);
2377 return true;
2380 JS_PUBLIC_API JSString* JS_GetMaybePartialFunctionDisplayId(JSFunction* fun) {
2381 return fun->maybePartialDisplayAtom();
2384 JS_PUBLIC_API uint16_t JS_GetFunctionArity(JSFunction* fun) {
2385 return fun->nargs();
2388 JS_PUBLIC_API bool JS_GetFunctionLength(JSContext* cx, HandleFunction fun,
2389 uint16_t* length) {
2390 cx->check(fun);
2391 return JSFunction::getLength(cx, fun, length);
2394 JS_PUBLIC_API bool JS_ObjectIsFunction(JSObject* obj) {
2395 return obj->is<JSFunction>();
2398 JS_PUBLIC_API bool JS_IsNativeFunction(JSObject* funobj, JSNative call) {
2399 if (!funobj->is<JSFunction>()) {
2400 return false;
2402 JSFunction* fun = &funobj->as<JSFunction>();
2403 return fun->isNativeFun() && fun->native() == call;
2406 extern JS_PUBLIC_API bool JS_IsConstructor(JSFunction* fun) {
2407 return fun->isConstructor();
2410 void JS::TransitiveCompileOptions::copyPODTransitiveOptions(
2411 const TransitiveCompileOptions& rhs) {
2412 // filename_, introducerFilename_, sourceMapURL_ should be handled in caller.
2414 mutedErrors_ = rhs.mutedErrors_;
2415 forceStrictMode_ = rhs.forceStrictMode_;
2416 alwaysUseFdlibm_ = rhs.alwaysUseFdlibm_;
2417 skipFilenameValidation_ = rhs.skipFilenameValidation_;
2418 hideScriptFromDebugger_ = rhs.hideScriptFromDebugger_;
2419 deferDebugMetadata_ = rhs.deferDebugMetadata_;
2420 eagerDelazificationStrategy_ = rhs.eagerDelazificationStrategy_;
2422 selfHostingMode = rhs.selfHostingMode;
2423 discardSource = rhs.discardSource;
2424 sourceIsLazy = rhs.sourceIsLazy;
2425 allowHTMLComments = rhs.allowHTMLComments;
2426 nonSyntacticScope = rhs.nonSyntacticScope;
2428 topLevelAwait = rhs.topLevelAwait;
2430 borrowBuffer = rhs.borrowBuffer;
2431 usePinnedBytecode = rhs.usePinnedBytecode;
2432 deoptimizeModuleGlobalVars = rhs.deoptimizeModuleGlobalVars;
2434 prefableOptions_ = rhs.prefableOptions_;
2436 introductionType = rhs.introductionType;
2437 introductionLineno = rhs.introductionLineno;
2438 introductionOffset = rhs.introductionOffset;
2439 hasIntroductionInfo = rhs.hasIntroductionInfo;
2442 void JS::ReadOnlyCompileOptions::copyPODNonTransitiveOptions(
2443 const ReadOnlyCompileOptions& rhs) {
2444 lineno = rhs.lineno;
2445 column = rhs.column;
2446 scriptSourceOffset = rhs.scriptSourceOffset;
2447 isRunOnce = rhs.isRunOnce;
2448 noScriptRval = rhs.noScriptRval;
2451 JS::OwningCompileOptions::OwningCompileOptions(JSContext* cx) {}
2453 void JS::OwningCompileOptions::release() {
2454 // OwningCompileOptions always owns these, so these casts are okay.
2455 js_free(const_cast<char*>(filename_.c_str()));
2456 js_free(const_cast<char16_t*>(sourceMapURL_));
2457 js_free(const_cast<char*>(introducerFilename_.c_str()));
2459 filename_ = JS::ConstUTF8CharsZ();
2460 sourceMapURL_ = nullptr;
2461 introducerFilename_ = JS::ConstUTF8CharsZ();
2464 JS::OwningCompileOptions::~OwningCompileOptions() { release(); }
2466 size_t JS::OwningCompileOptions::sizeOfExcludingThis(
2467 mozilla::MallocSizeOf mallocSizeOf) const {
2468 return mallocSizeOf(filename_.c_str()) + mallocSizeOf(sourceMapURL_) +
2469 mallocSizeOf(introducerFilename_.c_str());
2472 void JS::OwningCompileOptions::steal(JS::OwningCompileOptions&& rhs) {
2473 // Release existing string allocations.
2474 release();
2476 copyPODNonTransitiveOptions(rhs);
2477 copyPODTransitiveOptions(rhs);
2479 filename_ = rhs.filename_;
2480 rhs.filename_ = JS::ConstUTF8CharsZ();
2481 introducerFilename_ = rhs.introducerFilename_;
2482 rhs.introducerFilename_ = JS::ConstUTF8CharsZ();
2483 sourceMapURL_ = rhs.sourceMapURL_;
2484 rhs.sourceMapURL_ = nullptr;
2487 void JS::OwningCompileOptions::steal(JS::OwningDecodeOptions&& rhs) {
2488 // Release existing string allocations.
2489 release();
2491 rhs.copyPODOptionsTo(*this);
2493 introducerFilename_ = rhs.introducerFilename_;
2494 rhs.introducerFilename_ = JS::ConstUTF8CharsZ();
2497 template <typename ContextT>
2498 bool JS::OwningCompileOptions::copyImpl(ContextT* cx,
2499 const ReadOnlyCompileOptions& rhs) {
2500 // Release existing string allocations.
2501 release();
2503 copyPODNonTransitiveOptions(rhs);
2504 copyPODTransitiveOptions(rhs);
2506 if (rhs.filename()) {
2507 const char* str = DuplicateString(cx, rhs.filename().c_str()).release();
2508 if (!str) {
2509 return false;
2511 filename_ = JS::ConstUTF8CharsZ(str);
2514 if (rhs.sourceMapURL()) {
2515 sourceMapURL_ = DuplicateString(cx, rhs.sourceMapURL()).release();
2516 if (!sourceMapURL_) {
2517 return false;
2521 if (rhs.introducerFilename()) {
2522 const char* str =
2523 DuplicateString(cx, rhs.introducerFilename().c_str()).release();
2524 if (!str) {
2525 return false;
2527 introducerFilename_ = JS::ConstUTF8CharsZ(str);
2530 return true;
2533 bool JS::OwningCompileOptions::copy(JSContext* cx,
2534 const ReadOnlyCompileOptions& rhs) {
2535 return copyImpl(cx, rhs);
2538 bool JS::OwningCompileOptions::copy(JS::FrontendContext* fc,
2539 const ReadOnlyCompileOptions& rhs) {
2540 return copyImpl(fc, rhs);
2543 JS::CompileOptions::CompileOptions(JSContext* cx) {
2544 prefableOptions_ = cx->options().compileOptions();
2546 if (cx->options().asmJSOption() == AsmJSOption::Enabled) {
2547 if (!js::IsAsmJSCompilationAvailable(cx)) {
2548 prefableOptions_.setAsmJSOption(AsmJSOption::DisabledByNoWasmCompiler);
2549 } else if (cx->realm() && (cx->realm()->debuggerObservesWasm() ||
2550 cx->realm()->debuggerObservesAsmJS())) {
2551 prefableOptions_.setAsmJSOption(AsmJSOption::DisabledByDebugger);
2555 // Certain modes of operation disallow syntax parsing in general.
2556 if (coverage::IsLCovEnabled()) {
2557 eagerDelazificationStrategy_ = DelazificationOption::ParseEverythingEagerly;
2560 // Note: If we parse outside of a specific realm, we do not inherit any realm
2561 // behaviours. These can still be set manually on the options though.
2562 if (Realm* realm = cx->realm()) {
2563 alwaysUseFdlibm_ = realm->creationOptions().alwaysUseFdlibm();
2564 discardSource = realm->behaviors().discardSource();
2568 CompileOptions& CompileOptions::setIntroductionInfoToCaller(
2569 JSContext* cx, const char* introductionType,
2570 MutableHandle<JSScript*> introductionScript) {
2571 RootedScript maybeScript(cx);
2572 const char* filename;
2573 uint32_t lineno;
2574 uint32_t pcOffset;
2575 bool mutedErrors;
2576 DescribeScriptedCallerForCompilation(cx, &maybeScript, &filename, &lineno,
2577 &pcOffset, &mutedErrors);
2578 if (filename) {
2579 introductionScript.set(maybeScript);
2580 return setIntroductionInfo(filename, introductionType, lineno, pcOffset);
2582 return setIntroductionType(introductionType);
2585 JS::OwningDecodeOptions::~OwningDecodeOptions() { release(); }
2587 void JS::OwningDecodeOptions::release() {
2588 js_free(const_cast<char*>(introducerFilename_.c_str()));
2590 introducerFilename_ = JS::ConstUTF8CharsZ();
2593 bool JS::OwningDecodeOptions::copy(JS::FrontendContext* maybeFc,
2594 const JS::ReadOnlyDecodeOptions& rhs) {
2595 copyPODOptionsFrom(rhs);
2597 if (rhs.introducerFilename()) {
2598 MOZ_ASSERT(maybeFc);
2599 const char* str =
2600 DuplicateString(maybeFc, rhs.introducerFilename().c_str()).release();
2601 if (!str) {
2602 return false;
2604 introducerFilename_ = JS::ConstUTF8CharsZ(str);
2607 return true;
2610 void JS::OwningDecodeOptions::infallibleCopy(
2611 const JS::ReadOnlyDecodeOptions& rhs) {
2612 copyPODOptionsFrom(rhs);
2614 MOZ_ASSERT(!rhs.introducerFilename());
2617 size_t JS::OwningDecodeOptions::sizeOfExcludingThis(
2618 mozilla::MallocSizeOf mallocSizeOf) const {
2619 return mallocSizeOf(introducerFilename_.c_str());
2622 JS_PUBLIC_API JSObject* JS_GetGlobalFromScript(JSScript* script) {
2623 return &script->global();
2626 JS_PUBLIC_API const char* JS_GetScriptFilename(JSScript* script) {
2627 // This is called from ThreadStackHelper which can be called from another
2628 // thread or inside a signal hander, so we need to be careful in case a
2629 // copmacting GC is currently moving things around.
2630 return script->maybeForwardedFilename();
2633 JS_PUBLIC_API unsigned JS_GetScriptBaseLineNumber(JSContext* cx,
2634 JSScript* script) {
2635 return script->lineno();
2638 JS_PUBLIC_API JSScript* JS_GetFunctionScript(JSContext* cx,
2639 HandleFunction fun) {
2640 if (fun->isNativeFun()) {
2641 return nullptr;
2644 if (fun->hasBytecode()) {
2645 return fun->nonLazyScript();
2648 AutoRealm ar(cx, fun);
2649 JSScript* script = JSFunction::getOrCreateScript(cx, fun);
2650 if (!script) {
2651 MOZ_CRASH();
2653 return script;
2656 JS_PUBLIC_API JSString* JS_DecompileScript(JSContext* cx, HandleScript script) {
2657 MOZ_ASSERT(!cx->zone()->isAtomsZone());
2659 AssertHeapIsIdle();
2660 CHECK_THREAD(cx);
2661 RootedFunction fun(cx, script->function());
2662 if (fun) {
2663 return JS_DecompileFunction(cx, fun);
2665 bool haveSource;
2666 if (!ScriptSource::loadSource(cx, script->scriptSource(), &haveSource)) {
2667 return nullptr;
2669 return haveSource ? JSScript::sourceData(cx, script)
2670 : NewStringCopyZ<CanGC>(cx, "[no source]");
2673 JS_PUBLIC_API JSString* JS_DecompileFunction(JSContext* cx,
2674 HandleFunction fun) {
2675 MOZ_ASSERT(!cx->zone()->isAtomsZone());
2676 AssertHeapIsIdle();
2677 CHECK_THREAD(cx);
2678 cx->check(fun);
2679 return FunctionToString(cx, fun, /* isToSource = */ false);
2682 JS_PUBLIC_API void JS::SetScriptPrivate(JSScript* script,
2683 const JS::Value& value) {
2684 JSRuntime* rt = script->zone()->runtimeFromMainThread();
2685 script->sourceObject()->setPrivate(rt, value);
2688 JS_PUBLIC_API JS::Value JS::GetScriptPrivate(JSScript* script) {
2689 return script->sourceObject()->getPrivate();
2692 JS_PUBLIC_API JS::Value JS::GetScriptedCallerPrivate(JSContext* cx) {
2693 AssertHeapIsIdle();
2694 CHECK_THREAD(cx);
2696 NonBuiltinFrameIter iter(cx, cx->realm()->principals());
2697 if (iter.done() || !iter.hasScript()) {
2698 return UndefinedValue();
2701 return iter.script()->sourceObject()->getPrivate();
2704 JS_PUBLIC_API void JS::SetScriptPrivateReferenceHooks(
2705 JSRuntime* rt, JS::ScriptPrivateReferenceHook addRefHook,
2706 JS::ScriptPrivateReferenceHook releaseHook) {
2707 AssertHeapIsIdle();
2708 rt->scriptPrivateAddRefHook = addRefHook;
2709 rt->scriptPrivateReleaseHook = releaseHook;
2712 JS_PUBLIC_API void JS::SetWaitCallback(JSRuntime* rt,
2713 BeforeWaitCallback beforeWait,
2714 AfterWaitCallback afterWait,
2715 size_t requiredMemory) {
2716 MOZ_RELEASE_ASSERT(requiredMemory <= WAIT_CALLBACK_CLIENT_MAXMEM);
2717 MOZ_RELEASE_ASSERT((beforeWait == nullptr) == (afterWait == nullptr));
2718 rt->beforeWaitCallback = beforeWait;
2719 rt->afterWaitCallback = afterWait;
2722 JS_PUBLIC_API bool JS_CheckForInterrupt(JSContext* cx) {
2723 return js::CheckForInterrupt(cx);
2726 JS_PUBLIC_API bool JS_AddInterruptCallback(JSContext* cx,
2727 JSInterruptCallback callback) {
2728 return cx->interruptCallbacks().append(callback);
2731 JS_PUBLIC_API bool JS_DisableInterruptCallback(JSContext* cx) {
2732 bool result = cx->interruptCallbackDisabled;
2733 cx->interruptCallbackDisabled = true;
2734 return result;
2737 JS_PUBLIC_API void JS_ResetInterruptCallback(JSContext* cx, bool enable) {
2738 cx->interruptCallbackDisabled = enable;
2741 /************************************************************************/
2744 * Promises.
2746 JS_PUBLIC_API void JS::SetJobQueue(JSContext* cx, JobQueue* queue) {
2747 cx->jobQueue = queue;
2750 extern JS_PUBLIC_API void JS::SetPromiseRejectionTrackerCallback(
2751 JSContext* cx, PromiseRejectionTrackerCallback callback,
2752 void* data /* = nullptr */) {
2753 cx->promiseRejectionTrackerCallback = callback;
2754 cx->promiseRejectionTrackerCallbackData = data;
2757 extern JS_PUBLIC_API void JS::JobQueueIsEmpty(JSContext* cx) {
2758 cx->canSkipEnqueuingJobs = true;
2761 extern JS_PUBLIC_API void JS::JobQueueMayNotBeEmpty(JSContext* cx) {
2762 cx->canSkipEnqueuingJobs = false;
2765 JS_PUBLIC_API JSObject* JS::NewPromiseObject(JSContext* cx,
2766 HandleObject executor) {
2767 MOZ_ASSERT(!cx->zone()->isAtomsZone());
2768 AssertHeapIsIdle();
2769 CHECK_THREAD(cx);
2770 cx->check(executor);
2772 if (!executor) {
2773 return PromiseObject::createSkippingExecutor(cx);
2776 MOZ_ASSERT(IsCallable(executor));
2777 return PromiseObject::create(cx, executor);
2780 JS_PUBLIC_API bool JS::IsPromiseObject(JS::HandleObject obj) {
2781 return obj->is<PromiseObject>();
2784 JS_PUBLIC_API JSObject* JS::GetPromiseConstructor(JSContext* cx) {
2785 CHECK_THREAD(cx);
2786 Rooted<GlobalObject*> global(cx, cx->global());
2787 return GlobalObject::getOrCreatePromiseConstructor(cx, global);
2790 JS_PUBLIC_API JSObject* JS::GetPromisePrototype(JSContext* cx) {
2791 CHECK_THREAD(cx);
2792 Rooted<GlobalObject*> global(cx, cx->global());
2793 return GlobalObject::getOrCreatePromisePrototype(cx, global);
2796 JS_PUBLIC_API JS::PromiseState JS::GetPromiseState(JS::HandleObject promise) {
2797 PromiseObject* promiseObj = promise->maybeUnwrapIf<PromiseObject>();
2798 if (!promiseObj) {
2799 return JS::PromiseState::Pending;
2802 return promiseObj->state();
2805 JS_PUBLIC_API uint64_t JS::GetPromiseID(JS::HandleObject promise) {
2806 return promise->as<PromiseObject>().getID();
2809 JS_PUBLIC_API JS::Value JS::GetPromiseResult(JS::HandleObject promiseObj) {
2810 PromiseObject* promise = &promiseObj->as<PromiseObject>();
2811 MOZ_ASSERT(promise->state() != JS::PromiseState::Pending);
2812 return promise->state() == JS::PromiseState::Fulfilled ? promise->value()
2813 : promise->reason();
2816 JS_PUBLIC_API bool JS::GetPromiseIsHandled(JS::HandleObject promise) {
2817 PromiseObject* promiseObj = &promise->as<PromiseObject>();
2818 return !promiseObj->isUnhandled();
2821 static PromiseObject* UnwrapPromise(JSContext* cx, JS::HandleObject promise,
2822 mozilla::Maybe<AutoRealm>& ar) {
2823 AssertHeapIsIdle();
2824 CHECK_THREAD(cx);
2825 cx->check(promise);
2827 PromiseObject* promiseObj;
2828 if (IsWrapper(promise)) {
2829 promiseObj = promise->maybeUnwrapAs<PromiseObject>();
2830 if (!promiseObj) {
2831 ReportAccessDenied(cx);
2832 return nullptr;
2834 ar.emplace(cx, promiseObj);
2835 } else {
2836 promiseObj = promise.as<PromiseObject>();
2838 return promiseObj;
2841 JS_PUBLIC_API bool JS::SetSettledPromiseIsHandled(JSContext* cx,
2842 JS::HandleObject promise) {
2843 mozilla::Maybe<AutoRealm> ar;
2844 Rooted<PromiseObject*> promiseObj(cx, UnwrapPromise(cx, promise, ar));
2845 if (!promiseObj) {
2846 return false;
2848 js::SetSettledPromiseIsHandled(cx, promiseObj);
2849 return true;
2852 JS_PUBLIC_API bool JS::SetAnyPromiseIsHandled(JSContext* cx,
2853 JS::HandleObject promise) {
2854 mozilla::Maybe<AutoRealm> ar;
2855 Rooted<PromiseObject*> promiseObj(cx, UnwrapPromise(cx, promise, ar));
2856 if (!promiseObj) {
2857 return false;
2859 js::SetAnyPromiseIsHandled(cx, promiseObj);
2860 return true;
2863 JS_PUBLIC_API JSObject* JS::GetPromiseAllocationSite(JS::HandleObject promise) {
2864 return promise->as<PromiseObject>().allocationSite();
2867 JS_PUBLIC_API JSObject* JS::GetPromiseResolutionSite(JS::HandleObject promise) {
2868 return promise->as<PromiseObject>().resolutionSite();
2871 #ifdef DEBUG
2872 JS_PUBLIC_API void JS::DumpPromiseAllocationSite(JSContext* cx,
2873 JS::HandleObject promise) {
2874 RootedObject stack(cx, promise->as<PromiseObject>().allocationSite());
2875 JSPrincipals* principals = cx->realm()->principals();
2876 UniqueChars stackStr = BuildUTF8StackString(cx, principals, stack);
2877 if (stackStr) {
2878 fputs(stackStr.get(), stderr);
2882 JS_PUBLIC_API void JS::DumpPromiseResolutionSite(JSContext* cx,
2883 JS::HandleObject promise) {
2884 RootedObject stack(cx, promise->as<PromiseObject>().resolutionSite());
2885 JSPrincipals* principals = cx->realm()->principals();
2886 UniqueChars stackStr = BuildUTF8StackString(cx, principals, stack);
2887 if (stackStr) {
2888 fputs(stackStr.get(), stderr);
2891 #endif
2893 JS_PUBLIC_API JSObject* JS::CallOriginalPromiseResolve(
2894 JSContext* cx, JS::HandleValue resolutionValue) {
2895 AssertHeapIsIdle();
2896 CHECK_THREAD(cx);
2897 cx->check(resolutionValue);
2899 RootedObject promise(cx,
2900 PromiseObject::unforgeableResolve(cx, resolutionValue));
2901 MOZ_ASSERT_IF(promise, promise->canUnwrapAs<PromiseObject>());
2902 return promise;
2905 JS_PUBLIC_API JSObject* JS::CallOriginalPromiseReject(
2906 JSContext* cx, JS::HandleValue rejectionValue) {
2907 AssertHeapIsIdle();
2908 CHECK_THREAD(cx);
2909 cx->check(rejectionValue);
2911 RootedObject promise(cx,
2912 PromiseObject::unforgeableReject(cx, rejectionValue));
2913 MOZ_ASSERT_IF(promise, promise->canUnwrapAs<PromiseObject>());
2914 return promise;
2917 static bool ResolveOrRejectPromise(JSContext* cx, JS::HandleObject promiseObj,
2918 JS::HandleValue resultOrReason_,
2919 bool reject) {
2920 AssertHeapIsIdle();
2921 CHECK_THREAD(cx);
2922 cx->check(promiseObj, resultOrReason_);
2924 mozilla::Maybe<AutoRealm> ar;
2925 Rooted<PromiseObject*> promise(cx);
2926 RootedValue resultOrReason(cx, resultOrReason_);
2927 if (IsWrapper(promiseObj)) {
2928 promise = promiseObj->maybeUnwrapAs<PromiseObject>();
2929 if (!promise) {
2930 ReportAccessDenied(cx);
2931 return false;
2933 ar.emplace(cx, promise);
2934 if (!cx->compartment()->wrap(cx, &resultOrReason)) {
2935 return false;
2937 } else {
2938 promise = promiseObj.as<PromiseObject>();
2941 return reject ? PromiseObject::reject(cx, promise, resultOrReason)
2942 : PromiseObject::resolve(cx, promise, resultOrReason);
2945 JS_PUBLIC_API bool JS::ResolvePromise(JSContext* cx,
2946 JS::HandleObject promiseObj,
2947 JS::HandleValue resolutionValue) {
2948 return ResolveOrRejectPromise(cx, promiseObj, resolutionValue, false);
2951 JS_PUBLIC_API bool JS::RejectPromise(JSContext* cx, JS::HandleObject promiseObj,
2952 JS::HandleValue rejectionValue) {
2953 return ResolveOrRejectPromise(cx, promiseObj, rejectionValue, true);
2956 JS_PUBLIC_API JSObject* JS::CallOriginalPromiseThen(
2957 JSContext* cx, JS::HandleObject promiseObj, JS::HandleObject onFulfilled,
2958 JS::HandleObject onRejected) {
2959 AssertHeapIsIdle();
2960 CHECK_THREAD(cx);
2961 cx->check(promiseObj, onFulfilled, onRejected);
2963 MOZ_ASSERT_IF(onFulfilled, IsCallable(onFulfilled));
2964 MOZ_ASSERT_IF(onRejected, IsCallable(onRejected));
2966 return OriginalPromiseThen(cx, promiseObj, onFulfilled, onRejected);
2969 [[nodiscard]] static bool ReactToPromise(JSContext* cx,
2970 JS::Handle<JSObject*> promiseObj,
2971 JS::Handle<JSObject*> onFulfilled,
2972 JS::Handle<JSObject*> onRejected,
2973 UnhandledRejectionBehavior behavior) {
2974 AssertHeapIsIdle();
2975 CHECK_THREAD(cx);
2976 cx->check(promiseObj, onFulfilled, onRejected);
2978 MOZ_ASSERT_IF(onFulfilled, IsCallable(onFulfilled));
2979 MOZ_ASSERT_IF(onRejected, IsCallable(onRejected));
2981 Rooted<PromiseObject*> unwrappedPromise(cx);
2983 RootedValue promiseVal(cx, ObjectValue(*promiseObj));
2984 unwrappedPromise = UnwrapAndTypeCheckValue<PromiseObject>(
2985 cx, promiseVal, [cx, promiseObj] {
2986 JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
2987 JSMSG_INCOMPATIBLE_PROTO, "Promise",
2988 "then", promiseObj->getClass()->name);
2990 if (!unwrappedPromise) {
2991 return false;
2995 return ReactToUnwrappedPromise(cx, unwrappedPromise, onFulfilled, onRejected,
2996 behavior);
2999 JS_PUBLIC_API bool JS::AddPromiseReactions(JSContext* cx,
3000 JS::HandleObject promiseObj,
3001 JS::HandleObject onFulfilled,
3002 JS::HandleObject onRejected) {
3003 return ReactToPromise(cx, promiseObj, onFulfilled, onRejected,
3004 UnhandledRejectionBehavior::Report);
3007 JS_PUBLIC_API bool JS::AddPromiseReactionsIgnoringUnhandledRejection(
3008 JSContext* cx, JS::HandleObject promiseObj, JS::HandleObject onFulfilled,
3009 JS::HandleObject onRejected) {
3010 return ReactToPromise(cx, promiseObj, onFulfilled, onRejected,
3011 UnhandledRejectionBehavior::Ignore);
3014 JS_PUBLIC_API JS::PromiseUserInputEventHandlingState
3015 JS::GetPromiseUserInputEventHandlingState(JS::HandleObject promiseObj_) {
3016 PromiseObject* promise = promiseObj_->maybeUnwrapIf<PromiseObject>();
3017 if (!promise) {
3018 return JS::PromiseUserInputEventHandlingState::DontCare;
3021 if (!promise->requiresUserInteractionHandling()) {
3022 return JS::PromiseUserInputEventHandlingState::DontCare;
3024 if (promise->hadUserInteractionUponCreation()) {
3025 return JS::PromiseUserInputEventHandlingState::HadUserInteractionAtCreation;
3027 return JS::PromiseUserInputEventHandlingState::
3028 DidntHaveUserInteractionAtCreation;
3031 JS_PUBLIC_API bool JS::SetPromiseUserInputEventHandlingState(
3032 JS::HandleObject promiseObj_,
3033 JS::PromiseUserInputEventHandlingState state) {
3034 PromiseObject* promise = promiseObj_->maybeUnwrapIf<PromiseObject>();
3035 if (!promise) {
3036 return false;
3039 switch (state) {
3040 case JS::PromiseUserInputEventHandlingState::DontCare:
3041 promise->setRequiresUserInteractionHandling(false);
3042 break;
3043 case JS::PromiseUserInputEventHandlingState::HadUserInteractionAtCreation:
3044 promise->setRequiresUserInteractionHandling(true);
3045 promise->setHadUserInteractionUponCreation(true);
3046 break;
3047 case JS::PromiseUserInputEventHandlingState::
3048 DidntHaveUserInteractionAtCreation:
3049 promise->setRequiresUserInteractionHandling(true);
3050 promise->setHadUserInteractionUponCreation(false);
3051 break;
3052 default:
3053 MOZ_ASSERT_UNREACHABLE(
3054 "Invalid PromiseUserInputEventHandlingState enum value");
3055 return false;
3057 return true;
3061 * Unforgeable version of Promise.all for internal use.
3063 * Takes a dense array of Promise objects and returns a promise that's
3064 * resolved with an array of resolution values when all those promises ahve
3065 * been resolved, or rejected with the rejection value of the first rejected
3066 * promise.
3068 * Asserts that the array is dense and all entries are Promise objects.
3070 JS_PUBLIC_API JSObject* JS::GetWaitForAllPromise(
3071 JSContext* cx, JS::HandleObjectVector promises) {
3072 AssertHeapIsIdle();
3073 CHECK_THREAD(cx);
3075 return js::GetWaitForAllPromise(cx, promises);
3078 JS_PUBLIC_API void JS::InitDispatchToEventLoop(
3079 JSContext* cx, JS::DispatchToEventLoopCallback callback, void* closure) {
3080 cx->runtime()->offThreadPromiseState.ref().init(callback, closure);
3083 JS_PUBLIC_API void JS::ShutdownAsyncTasks(JSContext* cx) {
3084 cx->runtime()->offThreadPromiseState.ref().shutdown(cx);
3087 JS_PUBLIC_API void JS::InitConsumeStreamCallback(
3088 JSContext* cx, ConsumeStreamCallback consume,
3089 ReportStreamErrorCallback report) {
3090 cx->runtime()->consumeStreamCallback = consume;
3091 cx->runtime()->reportStreamErrorCallback = report;
3094 JS_PUBLIC_API void JS_RequestInterruptCallback(JSContext* cx) {
3095 cx->requestInterrupt(InterruptReason::CallbackUrgent);
3098 JS_PUBLIC_API void JS_RequestInterruptCallbackCanWait(JSContext* cx) {
3099 cx->requestInterrupt(InterruptReason::CallbackCanWait);
3102 JS::AutoSetAsyncStackForNewCalls::AutoSetAsyncStackForNewCalls(
3103 JSContext* cx, HandleObject stack, const char* asyncCause,
3104 JS::AutoSetAsyncStackForNewCalls::AsyncCallKind kind)
3105 : cx(cx),
3106 oldAsyncStack(cx, cx->asyncStackForNewActivations()),
3107 oldAsyncCause(cx->asyncCauseForNewActivations),
3108 oldAsyncCallIsExplicit(cx->asyncCallIsExplicit) {
3109 CHECK_THREAD(cx);
3111 // The option determines whether we actually use the new values at this
3112 // point. It will not affect restoring the previous values when the object
3113 // is destroyed, so if the option changes it won't cause consistency issues.
3114 if (!cx->options().asyncStack()) {
3115 return;
3118 SavedFrame* asyncStack = &stack->as<SavedFrame>();
3120 cx->asyncStackForNewActivations() = asyncStack;
3121 cx->asyncCauseForNewActivations = asyncCause;
3122 cx->asyncCallIsExplicit = kind == AsyncCallKind::EXPLICIT;
3125 JS::AutoSetAsyncStackForNewCalls::~AutoSetAsyncStackForNewCalls() {
3126 cx->asyncCauseForNewActivations = oldAsyncCause;
3127 cx->asyncStackForNewActivations() =
3128 oldAsyncStack ? &oldAsyncStack->as<SavedFrame>() : nullptr;
3129 cx->asyncCallIsExplicit = oldAsyncCallIsExplicit;
3132 /************************************************************************/
3133 JS_PUBLIC_API JSString* JS_NewStringCopyN(JSContext* cx, const char* s,
3134 size_t n) {
3135 AssertHeapIsIdle();
3136 CHECK_THREAD(cx);
3137 return NewStringCopyN<CanGC>(cx, s, n);
3140 JS_PUBLIC_API JSString* JS_NewStringCopyZ(JSContext* cx, const char* s) {
3141 AssertHeapIsIdle();
3142 CHECK_THREAD(cx);
3143 if (!s) {
3144 return cx->runtime()->emptyString;
3146 return NewStringCopyZ<CanGC>(cx, s);
3149 JS_PUBLIC_API JSString* JS_NewStringCopyUTF8Z(JSContext* cx,
3150 const JS::ConstUTF8CharsZ s) {
3151 AssertHeapIsIdle();
3152 CHECK_THREAD(cx);
3153 return NewStringCopyUTF8Z(cx, s);
3156 JS_PUBLIC_API JSString* JS_NewStringCopyUTF8N(JSContext* cx,
3157 const JS::UTF8Chars& s) {
3158 AssertHeapIsIdle();
3159 CHECK_THREAD(cx);
3160 return NewStringCopyUTF8N(cx, s);
3163 JS_PUBLIC_API bool JS_StringHasBeenPinned(JSContext* cx, JSString* str) {
3164 AssertHeapIsIdle();
3165 CHECK_THREAD(cx);
3167 if (!str->isAtom()) {
3168 return false;
3171 return AtomIsPinned(cx, &str->asAtom());
3174 JS_PUBLIC_API JSString* JS_AtomizeString(JSContext* cx, const char* s) {
3175 return JS_AtomizeStringN(cx, s, strlen(s));
3178 JS_PUBLIC_API JSString* JS_AtomizeStringN(JSContext* cx, const char* s,
3179 size_t length) {
3180 AssertHeapIsIdle();
3181 CHECK_THREAD(cx);
3182 return Atomize(cx, s, length);
3185 JS_PUBLIC_API JSString* JS_AtomizeAndPinString(JSContext* cx, const char* s) {
3186 return JS_AtomizeAndPinStringN(cx, s, strlen(s));
3189 JS_PUBLIC_API JSString* JS_AtomizeAndPinStringN(JSContext* cx, const char* s,
3190 size_t length) {
3191 AssertHeapIsIdle();
3192 CHECK_THREAD(cx);
3194 JSAtom* atom = cx->zone() ? Atomize(cx, s, length)
3195 : AtomizeWithoutActiveZone(cx, s, length);
3196 if (!atom || !PinAtom(cx, atom)) {
3197 return nullptr;
3200 MOZ_ASSERT(JS_StringHasBeenPinned(cx, atom));
3201 return atom;
3204 JS_PUBLIC_API JSString* JS_NewLatin1String(
3205 JSContext* cx, js::UniquePtr<JS::Latin1Char[], JS::FreePolicy> chars,
3206 size_t length) {
3207 AssertHeapIsIdle();
3208 CHECK_THREAD(cx);
3209 return NewString<CanGC>(cx, std::move(chars), length);
3212 JS_PUBLIC_API JSString* JS_NewUCString(JSContext* cx,
3213 JS::UniqueTwoByteChars chars,
3214 size_t length) {
3215 AssertHeapIsIdle();
3216 CHECK_THREAD(cx);
3217 return NewString<CanGC>(cx, std::move(chars), length);
3220 JS_PUBLIC_API JSString* JS_NewUCStringDontDeflate(JSContext* cx,
3221 JS::UniqueTwoByteChars chars,
3222 size_t length) {
3223 AssertHeapIsIdle();
3224 CHECK_THREAD(cx);
3225 return NewStringDontDeflate<CanGC>(cx, std::move(chars), length);
3228 JS_PUBLIC_API JSString* JS_NewUCStringCopyN(JSContext* cx, const char16_t* s,
3229 size_t n) {
3230 AssertHeapIsIdle();
3231 CHECK_THREAD(cx);
3232 if (!n) {
3233 return cx->names().empty_;
3235 return NewStringCopyN<CanGC>(cx, s, n);
3238 JS_PUBLIC_API JSString* JS_NewUCStringCopyZ(JSContext* cx, const char16_t* s) {
3239 AssertHeapIsIdle();
3240 CHECK_THREAD(cx);
3241 if (!s) {
3242 return cx->runtime()->emptyString;
3244 return NewStringCopyZ<CanGC>(cx, s);
3247 JS_PUBLIC_API JSString* JS_AtomizeUCString(JSContext* cx, const char16_t* s) {
3248 return JS_AtomizeUCStringN(cx, s, js_strlen(s));
3251 JS_PUBLIC_API JSString* JS_AtomizeUCStringN(JSContext* cx, const char16_t* s,
3252 size_t length) {
3253 AssertHeapIsIdle();
3254 CHECK_THREAD(cx);
3255 return AtomizeChars(cx, s, length);
3258 JS_PUBLIC_API size_t JS_GetStringLength(JSString* str) { return str->length(); }
3260 JS_PUBLIC_API bool JS_StringIsLinear(JSString* str) { return str->isLinear(); }
3262 JS_PUBLIC_API bool JS_DeprecatedStringHasLatin1Chars(JSString* str) {
3263 return str->hasLatin1Chars();
3266 JS_PUBLIC_API const JS::Latin1Char* JS_GetLatin1StringCharsAndLength(
3267 JSContext* cx, const JS::AutoRequireNoGC& nogc, JSString* str,
3268 size_t* plength) {
3269 MOZ_ASSERT(plength);
3270 AssertHeapIsIdle();
3271 CHECK_THREAD(cx);
3272 cx->check(str);
3273 JSLinearString* linear = str->ensureLinear(cx);
3274 if (!linear) {
3275 return nullptr;
3277 *plength = linear->length();
3278 return linear->latin1Chars(nogc);
3281 JS_PUBLIC_API const char16_t* JS_GetTwoByteStringCharsAndLength(
3282 JSContext* cx, const JS::AutoRequireNoGC& nogc, JSString* str,
3283 size_t* plength) {
3284 MOZ_ASSERT(plength);
3285 AssertHeapIsIdle();
3286 CHECK_THREAD(cx);
3287 cx->check(str);
3288 JSLinearString* linear = str->ensureLinear(cx);
3289 if (!linear) {
3290 return nullptr;
3292 *plength = linear->length();
3293 return linear->twoByteChars(nogc);
3296 JS_PUBLIC_API const char16_t* JS_GetTwoByteExternalStringChars(JSString* str) {
3297 return str->asExternal().twoByteChars();
3300 JS_PUBLIC_API bool JS_GetStringCharAt(JSContext* cx, JSString* str,
3301 size_t index, char16_t* res) {
3302 AssertHeapIsIdle();
3303 CHECK_THREAD(cx);
3304 cx->check(str);
3306 JSLinearString* linear = str->ensureLinear(cx);
3307 if (!linear) {
3308 return false;
3311 *res = linear->latin1OrTwoByteChar(index);
3312 return true;
3315 JS_PUBLIC_API bool JS_CopyStringChars(JSContext* cx,
3316 const mozilla::Range<char16_t>& dest,
3317 JSString* str) {
3318 AssertHeapIsIdle();
3319 CHECK_THREAD(cx);
3320 cx->check(str);
3322 JSLinearString* linear = str->ensureLinear(cx);
3323 if (!linear) {
3324 return false;
3327 MOZ_ASSERT(linear->length() <= dest.length());
3328 CopyChars(dest.begin().get(), *linear);
3329 return true;
3332 extern JS_PUBLIC_API JS::UniqueTwoByteChars JS_CopyStringCharsZ(JSContext* cx,
3333 JSString* str) {
3334 AssertHeapIsIdle();
3335 CHECK_THREAD(cx);
3337 JSLinearString* linear = str->ensureLinear(cx);
3338 if (!linear) {
3339 return nullptr;
3342 size_t len = linear->length();
3344 static_assert(JS::MaxStringLength < UINT32_MAX,
3345 "len + 1 must not overflow on 32-bit platforms");
3347 UniqueTwoByteChars chars(cx->pod_malloc<char16_t>(len + 1));
3348 if (!chars) {
3349 return nullptr;
3352 CopyChars(chars.get(), *linear);
3353 chars[len] = '\0';
3355 return chars;
3358 extern JS_PUBLIC_API JSLinearString* JS_EnsureLinearString(JSContext* cx,
3359 JSString* str) {
3360 AssertHeapIsIdle();
3361 CHECK_THREAD(cx);
3362 cx->check(str);
3363 return str->ensureLinear(cx);
3366 JS_PUBLIC_API bool JS_CompareStrings(JSContext* cx, JSString* str1,
3367 JSString* str2, int32_t* result) {
3368 AssertHeapIsIdle();
3369 CHECK_THREAD(cx);
3371 return CompareStrings(cx, str1, str2, result);
3374 JS_PUBLIC_API bool JS_StringEqualsAscii(JSContext* cx, JSString* str,
3375 const char* asciiBytes, bool* match) {
3376 AssertHeapIsIdle();
3377 CHECK_THREAD(cx);
3379 JSLinearString* linearStr = str->ensureLinear(cx);
3380 if (!linearStr) {
3381 return false;
3383 *match = StringEqualsAscii(linearStr, asciiBytes);
3384 return true;
3387 JS_PUBLIC_API bool JS_StringEqualsAscii(JSContext* cx, JSString* str,
3388 const char* asciiBytes, size_t length,
3389 bool* match) {
3390 AssertHeapIsIdle();
3391 CHECK_THREAD(cx);
3393 JSLinearString* linearStr = str->ensureLinear(cx);
3394 if (!linearStr) {
3395 return false;
3397 *match = StringEqualsAscii(linearStr, asciiBytes, length);
3398 return true;
3401 JS_PUBLIC_API bool JS_LinearStringEqualsAscii(JSLinearString* str,
3402 const char* asciiBytes) {
3403 return StringEqualsAscii(str, asciiBytes);
3406 JS_PUBLIC_API bool JS_LinearStringEqualsAscii(JSLinearString* str,
3407 const char* asciiBytes,
3408 size_t length) {
3409 return StringEqualsAscii(str, asciiBytes, length);
3412 JS_PUBLIC_API size_t JS_PutEscapedLinearString(char* buffer, size_t size,
3413 JSLinearString* str,
3414 char quote) {
3415 return PutEscapedString(buffer, size, str, quote);
3418 JS_PUBLIC_API size_t JS_PutEscapedString(JSContext* cx, char* buffer,
3419 size_t size, JSString* str,
3420 char quote) {
3421 AssertHeapIsIdle();
3422 JSLinearString* linearStr = str->ensureLinear(cx);
3423 if (!linearStr) {
3424 return size_t(-1);
3426 return PutEscapedString(buffer, size, linearStr, quote);
3429 JS_PUBLIC_API JSString* JS_NewDependentString(JSContext* cx, HandleString str,
3430 size_t start, size_t length) {
3431 AssertHeapIsIdle();
3432 CHECK_THREAD(cx);
3433 return NewDependentString(cx, str, start, length);
3436 JS_PUBLIC_API JSString* JS_ConcatStrings(JSContext* cx, HandleString left,
3437 HandleString right) {
3438 AssertHeapIsIdle();
3439 CHECK_THREAD(cx);
3440 return ConcatStrings<CanGC>(cx, left, right);
3443 JS_PUBLIC_API bool JS_DecodeBytes(JSContext* cx, const char* src, size_t srclen,
3444 char16_t* dst, size_t* dstlenp) {
3445 AssertHeapIsIdle();
3446 CHECK_THREAD(cx);
3448 if (!dst) {
3449 *dstlenp = srclen;
3450 return true;
3453 size_t dstlen = *dstlenp;
3455 if (srclen > dstlen) {
3456 CopyAndInflateChars(dst, src, dstlen);
3458 gc::AutoSuppressGC suppress(cx);
3459 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3460 JSMSG_BUFFER_TOO_SMALL);
3461 return false;
3464 CopyAndInflateChars(dst, src, srclen);
3465 *dstlenp = srclen;
3466 return true;
3469 JS_PUBLIC_API JS::UniqueChars JS_EncodeStringToASCII(JSContext* cx,
3470 JSString* str) {
3471 AssertHeapIsIdle();
3472 CHECK_THREAD(cx);
3474 return js::EncodeAscii(cx, str);
3477 JS_PUBLIC_API JS::UniqueChars JS_EncodeStringToLatin1(JSContext* cx,
3478 JSString* str) {
3479 AssertHeapIsIdle();
3480 CHECK_THREAD(cx);
3482 return js::EncodeLatin1(cx, str);
3485 JS_PUBLIC_API JS::UniqueChars JS_EncodeStringToUTF8(JSContext* cx,
3486 HandleString str) {
3487 AssertHeapIsIdle();
3488 CHECK_THREAD(cx);
3490 return StringToNewUTF8CharsZ(cx, *str);
3493 JS_PUBLIC_API size_t JS_GetStringEncodingLength(JSContext* cx, JSString* str) {
3494 AssertHeapIsIdle();
3495 CHECK_THREAD(cx);
3497 if (!str->ensureLinear(cx)) {
3498 return size_t(-1);
3500 return str->length();
3503 JS_PUBLIC_API bool JS_EncodeStringToBuffer(JSContext* cx, JSString* str,
3504 char* buffer, size_t length) {
3505 AssertHeapIsIdle();
3506 CHECK_THREAD(cx);
3508 JSLinearString* linear = str->ensureLinear(cx);
3509 if (!linear) {
3510 return false;
3513 JS::AutoCheckCannotGC nogc;
3514 size_t writeLength = std::min(linear->length(), length);
3515 if (linear->hasLatin1Chars()) {
3516 mozilla::PodCopy(reinterpret_cast<Latin1Char*>(buffer),
3517 linear->latin1Chars(nogc), writeLength);
3518 } else {
3519 const char16_t* src = linear->twoByteChars(nogc);
3520 for (size_t i = 0; i < writeLength; i++) {
3521 buffer[i] = char(src[i]);
3524 return true;
3527 JS_PUBLIC_API mozilla::Maybe<std::tuple<size_t, size_t>>
3528 JS_EncodeStringToUTF8BufferPartial(JSContext* cx, JSString* str,
3529 mozilla::Span<char> buffer) {
3530 AssertHeapIsIdle();
3531 CHECK_THREAD(cx);
3532 JS::AutoCheckCannotGC nogc;
3533 return str->encodeUTF8Partial(nogc, buffer);
3536 JS_PUBLIC_API JS::Symbol* JS::NewSymbol(JSContext* cx,
3537 HandleString description) {
3538 AssertHeapIsIdle();
3539 CHECK_THREAD(cx);
3540 if (description) {
3541 cx->check(description);
3544 return Symbol::new_(cx, SymbolCode::UniqueSymbol, description);
3547 JS_PUBLIC_API JS::Symbol* JS::GetSymbolFor(JSContext* cx, HandleString key) {
3548 AssertHeapIsIdle();
3549 CHECK_THREAD(cx);
3550 cx->check(key);
3552 return Symbol::for_(cx, key);
3555 JS_PUBLIC_API JSString* JS::GetSymbolDescription(HandleSymbol symbol) {
3556 return symbol->description();
3559 JS_PUBLIC_API JS::SymbolCode JS::GetSymbolCode(Handle<Symbol*> symbol) {
3560 return symbol->code();
3563 JS_PUBLIC_API JS::Symbol* JS::GetWellKnownSymbol(JSContext* cx,
3564 JS::SymbolCode which) {
3565 return cx->wellKnownSymbols().get(which);
3568 JS_PUBLIC_API JS::PropertyKey JS::GetWellKnownSymbolKey(JSContext* cx,
3569 JS::SymbolCode which) {
3570 return PropertyKey::Symbol(cx->wellKnownSymbols().get(which));
3573 static bool AddPrefix(JSContext* cx, JS::Handle<JS::PropertyKey> id,
3574 FunctionPrefixKind prefixKind,
3575 JS::MutableHandle<JS::PropertyKey> out) {
3576 JS::Rooted<JSAtom*> atom(cx, js::IdToFunctionName(cx, id, prefixKind));
3577 if (!atom) {
3578 return false;
3581 out.set(JS::PropertyKey::NonIntAtom(atom));
3582 return true;
3585 JS_PUBLIC_API bool JS::ToGetterId(JSContext* cx, JS::Handle<JS::PropertyKey> id,
3586 JS::MutableHandle<JS::PropertyKey> getterId) {
3587 return AddPrefix(cx, id, FunctionPrefixKind::Get, getterId);
3590 JS_PUBLIC_API bool JS::ToSetterId(JSContext* cx, JS::Handle<JS::PropertyKey> id,
3591 JS::MutableHandle<JS::PropertyKey> setterId) {
3592 return AddPrefix(cx, id, FunctionPrefixKind::Set, setterId);
3595 #ifdef DEBUG
3596 static bool PropertySpecNameIsDigits(JSPropertySpec::Name name) {
3597 if (name.isSymbol()) {
3598 return false;
3600 const char* s = name.string();
3601 if (!*s) {
3602 return false;
3604 for (; *s; s++) {
3605 if (*s < '0' || *s > '9') {
3606 return false;
3609 return true;
3611 #endif // DEBUG
3613 JS_PUBLIC_API bool JS::PropertySpecNameEqualsId(JSPropertySpec::Name name,
3614 HandleId id) {
3615 if (name.isSymbol()) {
3616 return id.isWellKnownSymbol(name.symbol());
3619 MOZ_ASSERT(!PropertySpecNameIsDigits(name));
3620 return id.isAtom() && JS_LinearStringEqualsAscii(id.toAtom(), name.string());
3623 JS_PUBLIC_API bool JS_Stringify(JSContext* cx, MutableHandleValue vp,
3624 HandleObject replacer, HandleValue space,
3625 JSONWriteCallback callback, void* data) {
3626 AssertHeapIsIdle();
3627 CHECK_THREAD(cx);
3628 cx->check(replacer, space);
3629 StringBuffer sb(cx);
3630 if (!sb.ensureTwoByteChars()) {
3631 return false;
3633 if (!Stringify(cx, vp, replacer, space, sb, StringifyBehavior::Normal)) {
3634 return false;
3636 if (sb.empty() && !sb.append(cx->names().null)) {
3637 return false;
3639 return callback(sb.rawTwoByteBegin(), sb.length(), data);
3642 JS_PUBLIC_API bool JS::ToJSON(JSContext* cx, HandleValue value,
3643 HandleObject replacer, HandleValue space,
3644 JSONWriteCallback callback, void* data) {
3645 AssertHeapIsIdle();
3646 CHECK_THREAD(cx);
3647 cx->check(replacer, space);
3648 StringBuffer sb(cx);
3649 if (!sb.ensureTwoByteChars()) {
3650 return false;
3652 RootedValue v(cx, value);
3653 if (!Stringify(cx, &v, replacer, space, sb, StringifyBehavior::Normal)) {
3654 return false;
3656 if (sb.empty()) {
3657 return true;
3659 return callback(sb.rawTwoByteBegin(), sb.length(), data);
3662 JS_PUBLIC_API bool JS::ToJSONMaybeSafely(JSContext* cx, JS::HandleObject input,
3663 JSONWriteCallback callback,
3664 void* data) {
3665 AssertHeapIsIdle();
3666 CHECK_THREAD(cx);
3667 cx->check(input);
3669 StringBuffer sb(cx);
3670 if (!sb.ensureTwoByteChars()) {
3671 return false;
3674 RootedValue inputValue(cx, ObjectValue(*input));
3675 if (!Stringify(cx, &inputValue, nullptr, NullHandleValue, sb,
3676 StringifyBehavior::RestrictedSafe))
3677 return false;
3679 if (sb.empty() && !sb.append(cx->names().null)) {
3680 return false;
3683 return callback(sb.rawTwoByteBegin(), sb.length(), data);
3686 JS_PUBLIC_API bool JS_ParseJSON(JSContext* cx, const char16_t* chars,
3687 uint32_t len, MutableHandleValue vp) {
3688 AssertHeapIsIdle();
3689 CHECK_THREAD(cx);
3690 return ParseJSONWithReviver(cx, mozilla::Range<const char16_t>(chars, len),
3691 NullHandleValue, vp);
3694 JS_PUBLIC_API bool JS_ParseJSON(JSContext* cx, HandleString str,
3695 MutableHandleValue vp) {
3696 return JS_ParseJSONWithReviver(cx, str, NullHandleValue, vp);
3699 JS_PUBLIC_API bool JS_ParseJSON(JSContext* cx, const Latin1Char* chars,
3700 uint32_t len, MutableHandleValue vp) {
3701 AssertHeapIsIdle();
3702 CHECK_THREAD(cx);
3703 return ParseJSONWithReviver(cx, mozilla::Range<const Latin1Char>(chars, len),
3704 NullHandleValue, vp);
3707 JS_PUBLIC_API bool JS_ParseJSONWithReviver(JSContext* cx, const char16_t* chars,
3708 uint32_t len, HandleValue reviver,
3709 MutableHandleValue vp) {
3710 AssertHeapIsIdle();
3711 CHECK_THREAD(cx);
3712 return ParseJSONWithReviver(cx, mozilla::Range<const char16_t>(chars, len),
3713 reviver, vp);
3716 JS_PUBLIC_API bool JS_ParseJSONWithReviver(JSContext* cx, HandleString str,
3717 HandleValue reviver,
3718 MutableHandleValue vp) {
3719 AssertHeapIsIdle();
3720 CHECK_THREAD(cx);
3721 cx->check(str);
3723 AutoStableStringChars stableChars(cx);
3724 if (!stableChars.init(cx, str)) {
3725 return false;
3728 return stableChars.isLatin1()
3729 ? ParseJSONWithReviver(cx, stableChars.latin1Range(), reviver, vp)
3730 : ParseJSONWithReviver(cx, stableChars.twoByteRange(), reviver,
3731 vp);
3734 /************************************************************************/
3736 JS_PUBLIC_API void JS_ReportErrorASCII(JSContext* cx, const char* format, ...) {
3737 va_list ap;
3739 AssertHeapIsIdle();
3740 va_start(ap, format);
3741 ReportErrorVA(cx, IsWarning::No, format, ArgumentsAreASCII, ap);
3742 va_end(ap);
3745 JS_PUBLIC_API void JS_ReportErrorLatin1(JSContext* cx, const char* format,
3746 ...) {
3747 va_list ap;
3749 AssertHeapIsIdle();
3750 va_start(ap, format);
3751 ReportErrorVA(cx, IsWarning::No, format, ArgumentsAreLatin1, ap);
3752 va_end(ap);
3755 JS_PUBLIC_API void JS_ReportErrorUTF8(JSContext* cx, const char* format, ...) {
3756 va_list ap;
3758 AssertHeapIsIdle();
3759 va_start(ap, format);
3760 ReportErrorVA(cx, IsWarning::No, format, ArgumentsAreUTF8, ap);
3761 va_end(ap);
3764 JS_PUBLIC_API void JS_ReportErrorNumberASCII(JSContext* cx,
3765 JSErrorCallback errorCallback,
3766 void* userRef,
3767 const unsigned errorNumber, ...) {
3768 va_list ap;
3769 va_start(ap, errorNumber);
3770 JS_ReportErrorNumberASCIIVA(cx, errorCallback, userRef, errorNumber, ap);
3771 va_end(ap);
3774 JS_PUBLIC_API void JS_ReportErrorNumberASCIIVA(JSContext* cx,
3775 JSErrorCallback errorCallback,
3776 void* userRef,
3777 const unsigned errorNumber,
3778 va_list ap) {
3779 AssertHeapIsIdle();
3780 ReportErrorNumberVA(cx, IsWarning::No, errorCallback, userRef, errorNumber,
3781 ArgumentsAreASCII, ap);
3784 JS_PUBLIC_API void JS_ReportErrorNumberLatin1(JSContext* cx,
3785 JSErrorCallback errorCallback,
3786 void* userRef,
3787 const unsigned errorNumber, ...) {
3788 va_list ap;
3789 va_start(ap, errorNumber);
3790 JS_ReportErrorNumberLatin1VA(cx, errorCallback, userRef, errorNumber, ap);
3791 va_end(ap);
3794 JS_PUBLIC_API void JS_ReportErrorNumberLatin1VA(JSContext* cx,
3795 JSErrorCallback errorCallback,
3796 void* userRef,
3797 const unsigned errorNumber,
3798 va_list ap) {
3799 AssertHeapIsIdle();
3800 ReportErrorNumberVA(cx, IsWarning::No, errorCallback, userRef, errorNumber,
3801 ArgumentsAreLatin1, ap);
3804 JS_PUBLIC_API void JS_ReportErrorNumberUTF8(JSContext* cx,
3805 JSErrorCallback errorCallback,
3806 void* userRef,
3807 const unsigned errorNumber, ...) {
3808 va_list ap;
3809 va_start(ap, errorNumber);
3810 JS_ReportErrorNumberUTF8VA(cx, errorCallback, userRef, errorNumber, ap);
3811 va_end(ap);
3814 JS_PUBLIC_API void JS_ReportErrorNumberUTF8VA(JSContext* cx,
3815 JSErrorCallback errorCallback,
3816 void* userRef,
3817 const unsigned errorNumber,
3818 va_list ap) {
3819 AssertHeapIsIdle();
3820 ReportErrorNumberVA(cx, IsWarning::No, errorCallback, userRef, errorNumber,
3821 ArgumentsAreUTF8, ap);
3824 JS_PUBLIC_API void JS_ReportErrorNumberUTF8Array(JSContext* cx,
3825 JSErrorCallback errorCallback,
3826 void* userRef,
3827 const unsigned errorNumber,
3828 const char** args) {
3829 AssertHeapIsIdle();
3830 ReportErrorNumberUTF8Array(cx, IsWarning::No, errorCallback, userRef,
3831 errorNumber, args);
3834 JS_PUBLIC_API void JS_ReportErrorNumberUC(JSContext* cx,
3835 JSErrorCallback errorCallback,
3836 void* userRef,
3837 const unsigned errorNumber, ...) {
3838 va_list ap;
3840 AssertHeapIsIdle();
3841 va_start(ap, errorNumber);
3842 ReportErrorNumberVA(cx, IsWarning::No, errorCallback, userRef, errorNumber,
3843 ArgumentsAreUnicode, ap);
3844 va_end(ap);
3847 JS_PUBLIC_API void JS_ReportErrorNumberUCArray(JSContext* cx,
3848 JSErrorCallback errorCallback,
3849 void* userRef,
3850 const unsigned errorNumber,
3851 const char16_t** args) {
3852 AssertHeapIsIdle();
3853 ReportErrorNumberUCArray(cx, IsWarning::No, errorCallback, userRef,
3854 errorNumber, args);
3857 JS_PUBLIC_API void JS_ReportOutOfMemory(JSContext* cx) {
3858 ReportOutOfMemory(cx);
3861 JS_PUBLIC_API void JS_ReportAllocationOverflow(JSContext* cx) {
3862 ReportAllocationOverflow(cx);
3865 JS_PUBLIC_API bool JS_ExpandErrorArgumentsASCII(JSContext* cx,
3866 JSErrorCallback errorCallback,
3867 const unsigned errorNumber,
3868 JSErrorReport* reportp, ...) {
3869 va_list ap;
3870 bool ok;
3872 AssertHeapIsIdle();
3873 va_start(ap, reportp);
3874 AutoReportFrontendContext fc(cx);
3875 ok = ExpandErrorArgumentsVA(&fc, errorCallback, nullptr, errorNumber,
3876 ArgumentsAreASCII, reportp, ap);
3877 va_end(ap);
3878 return ok;
3880 /************************************************************************/
3882 JS_PUBLIC_API bool JS_SetDefaultLocale(JSRuntime* rt, const char* locale) {
3883 AssertHeapIsIdle();
3884 return rt->setDefaultLocale(locale);
3887 JS_PUBLIC_API UniqueChars JS_GetDefaultLocale(JSContext* cx) {
3888 AssertHeapIsIdle();
3889 if (const char* locale = cx->runtime()->getDefaultLocale()) {
3890 return DuplicateString(cx, locale);
3893 return nullptr;
3896 JS_PUBLIC_API void JS_ResetDefaultLocale(JSRuntime* rt) {
3897 AssertHeapIsIdle();
3898 rt->resetDefaultLocale();
3901 JS_PUBLIC_API void JS_SetLocaleCallbacks(JSRuntime* rt,
3902 const JSLocaleCallbacks* callbacks) {
3903 AssertHeapIsIdle();
3904 rt->localeCallbacks = callbacks;
3907 JS_PUBLIC_API const JSLocaleCallbacks* JS_GetLocaleCallbacks(JSRuntime* rt) {
3908 /* This function can be called by a finalizer. */
3909 return rt->localeCallbacks;
3912 /************************************************************************/
3914 JS_PUBLIC_API bool JS_IsExceptionPending(JSContext* cx) {
3915 /* This function can be called by a finalizer. */
3916 return (bool)cx->isExceptionPending();
3919 JS_PUBLIC_API bool JS_IsThrowingOutOfMemory(JSContext* cx) {
3920 return cx->isThrowingOutOfMemory();
3923 JS_PUBLIC_API bool JS_GetPendingException(JSContext* cx,
3924 MutableHandleValue vp) {
3925 AssertHeapIsIdle();
3926 CHECK_THREAD(cx);
3927 if (!cx->isExceptionPending()) {
3928 return false;
3930 return cx->getPendingException(vp);
3933 JS_PUBLIC_API void JS_SetPendingException(JSContext* cx, HandleValue value,
3934 JS::ExceptionStackBehavior behavior) {
3935 AssertHeapIsIdle();
3936 CHECK_THREAD(cx);
3937 // We don't check the compartment of `value` here, because we're not
3938 // doing anything with it other than storing it, and stored
3939 // exception values can be in an abitrary compartment.
3941 if (behavior == JS::ExceptionStackBehavior::Capture) {
3942 cx->setPendingException(value, ShouldCaptureStack::Always);
3943 } else {
3944 cx->setPendingException(value, nullptr);
3948 JS_PUBLIC_API void JS_ClearPendingException(JSContext* cx) {
3949 AssertHeapIsIdle();
3950 cx->clearPendingException();
3953 JS::AutoSaveExceptionState::AutoSaveExceptionState(JSContext* cx)
3954 : context(cx), status(cx->status), exceptionValue(cx), exceptionStack(cx) {
3955 AssertHeapIsIdle();
3956 CHECK_THREAD(cx);
3957 if (IsCatchableExceptionStatus(status)) {
3958 exceptionValue = cx->unwrappedException();
3959 exceptionStack = cx->unwrappedExceptionStack();
3961 cx->clearPendingException();
3964 void JS::AutoSaveExceptionState::drop() {
3965 status = JS::ExceptionStatus::None;
3966 exceptionValue.setUndefined();
3967 exceptionStack = nullptr;
3970 void JS::AutoSaveExceptionState::restore() {
3971 context->status = status;
3972 context->unwrappedException() = exceptionValue;
3973 if (exceptionStack) {
3974 context->unwrappedExceptionStack() = &exceptionStack->as<SavedFrame>();
3976 drop();
3979 JS::AutoSaveExceptionState::~AutoSaveExceptionState() {
3980 // NOTE: An interrupt/uncatchable exception or a debugger-forced-return may be
3981 // clobbered here by the saved exception. If that is not desired, this
3982 // state should be dropped before the destructor fires.
3983 if (!context->isExceptionPending()) {
3984 if (status != JS::ExceptionStatus::None) {
3985 context->status = status;
3987 if (IsCatchableExceptionStatus(status)) {
3988 context->unwrappedException() = exceptionValue;
3989 if (exceptionStack) {
3990 context->unwrappedExceptionStack() = &exceptionStack->as<SavedFrame>();
3996 JS_PUBLIC_API JSErrorReport* JS_ErrorFromException(JSContext* cx,
3997 HandleObject obj) {
3998 AssertHeapIsIdle();
3999 CHECK_THREAD(cx);
4000 cx->check(obj);
4001 return ErrorFromException(cx, obj);
4004 void JSErrorReport::initBorrowedLinebuf(const char16_t* linebufArg,
4005 size_t linebufLengthArg,
4006 size_t tokenOffsetArg) {
4007 MOZ_ASSERT(linebufArg);
4008 MOZ_ASSERT(tokenOffsetArg <= linebufLengthArg);
4009 MOZ_ASSERT(linebufArg[linebufLengthArg] == '\0');
4011 linebuf_ = linebufArg;
4012 linebufLength_ = linebufLengthArg;
4013 tokenOffset_ = tokenOffsetArg;
4016 void JSErrorReport::freeLinebuf() {
4017 if (ownsLinebuf_ && linebuf_) {
4018 js_free((void*)linebuf_);
4019 ownsLinebuf_ = false;
4021 linebuf_ = nullptr;
4024 JSString* JSErrorBase::newMessageString(JSContext* cx) {
4025 if (!message_) {
4026 return cx->runtime()->emptyString;
4029 return JS_NewStringCopyUTF8Z(cx, message_);
4032 void JSErrorBase::freeMessage() {
4033 if (ownsMessage_) {
4034 js_free((void*)message_.get());
4035 ownsMessage_ = false;
4037 message_ = JS::ConstUTF8CharsZ();
4040 JSErrorNotes::JSErrorNotes() = default;
4042 JSErrorNotes::~JSErrorNotes() = default;
4044 static UniquePtr<JSErrorNotes::Note> CreateErrorNoteVA(
4045 FrontendContext* fc, const char* filename, unsigned sourceId,
4046 uint32_t lineno, JS::ColumnNumberOneOrigin column,
4047 JSErrorCallback errorCallback, void* userRef, const unsigned errorNumber,
4048 ErrorArgumentsType argumentsType, va_list ap) {
4049 auto note = MakeUnique<JSErrorNotes::Note>();
4050 if (!note) {
4051 ReportOutOfMemory(fc);
4052 return nullptr;
4055 note->errorNumber = errorNumber;
4056 note->filename = JS::ConstUTF8CharsZ(filename);
4057 note->sourceId = sourceId;
4058 note->lineno = lineno;
4059 note->column = column;
4061 if (!ExpandErrorArgumentsVA(fc, errorCallback, userRef, errorNumber, nullptr,
4062 argumentsType, note.get(), ap)) {
4063 return nullptr;
4066 return note;
4069 bool JSErrorNotes::addNoteVA(FrontendContext* fc, const char* filename,
4070 unsigned sourceId, uint32_t lineno,
4071 JS::ColumnNumberOneOrigin column,
4072 JSErrorCallback errorCallback, void* userRef,
4073 const unsigned errorNumber,
4074 ErrorArgumentsType argumentsType, va_list ap) {
4075 auto note =
4076 CreateErrorNoteVA(fc, filename, sourceId, lineno, column, errorCallback,
4077 userRef, errorNumber, argumentsType, ap);
4079 if (!note) {
4080 return false;
4082 if (!notes_.append(std::move(note))) {
4083 ReportOutOfMemory(fc);
4084 return false;
4086 return true;
4089 bool JSErrorNotes::addNoteASCII(JSContext* cx, const char* filename,
4090 unsigned sourceId, uint32_t lineno,
4091 JS::ColumnNumberOneOrigin column,
4092 JSErrorCallback errorCallback, void* userRef,
4093 const unsigned errorNumber, ...) {
4094 AutoReportFrontendContext fc(cx);
4095 va_list ap;
4096 va_start(ap, errorNumber);
4097 bool ok = addNoteVA(&fc, filename, sourceId, lineno, column, errorCallback,
4098 userRef, errorNumber, ArgumentsAreASCII, ap);
4099 va_end(ap);
4100 return ok;
4103 bool JSErrorNotes::addNoteASCII(FrontendContext* fc, const char* filename,
4104 unsigned sourceId, uint32_t lineno,
4105 JS::ColumnNumberOneOrigin column,
4106 JSErrorCallback errorCallback, void* userRef,
4107 const unsigned errorNumber, ...) {
4108 va_list ap;
4109 va_start(ap, errorNumber);
4110 bool ok = addNoteVA(fc, filename, sourceId, lineno, column, errorCallback,
4111 userRef, errorNumber, ArgumentsAreASCII, ap);
4112 va_end(ap);
4113 return ok;
4116 bool JSErrorNotes::addNoteLatin1(JSContext* cx, const char* filename,
4117 unsigned sourceId, uint32_t lineno,
4118 JS::ColumnNumberOneOrigin column,
4119 JSErrorCallback errorCallback, void* userRef,
4120 const unsigned errorNumber, ...) {
4121 AutoReportFrontendContext fc(cx);
4122 va_list ap;
4123 va_start(ap, errorNumber);
4124 bool ok = addNoteVA(&fc, filename, sourceId, lineno, column, errorCallback,
4125 userRef, errorNumber, ArgumentsAreLatin1, ap);
4126 va_end(ap);
4127 return ok;
4130 bool JSErrorNotes::addNoteLatin1(FrontendContext* fc, const char* filename,
4131 unsigned sourceId, uint32_t lineno,
4132 JS::ColumnNumberOneOrigin column,
4133 JSErrorCallback errorCallback, void* userRef,
4134 const unsigned errorNumber, ...) {
4135 va_list ap;
4136 va_start(ap, errorNumber);
4137 bool ok = addNoteVA(fc, filename, sourceId, lineno, column, errorCallback,
4138 userRef, errorNumber, ArgumentsAreLatin1, ap);
4139 va_end(ap);
4140 return ok;
4143 bool JSErrorNotes::addNoteUTF8(JSContext* cx, const char* filename,
4144 unsigned sourceId, uint32_t lineno,
4145 JS::ColumnNumberOneOrigin column,
4146 JSErrorCallback errorCallback, void* userRef,
4147 const unsigned errorNumber, ...) {
4148 AutoReportFrontendContext fc(cx);
4149 va_list ap;
4150 va_start(ap, errorNumber);
4151 bool ok = addNoteVA(&fc, filename, sourceId, lineno, column, errorCallback,
4152 userRef, errorNumber, ArgumentsAreUTF8, ap);
4153 va_end(ap);
4154 return ok;
4157 bool JSErrorNotes::addNoteUTF8(FrontendContext* fc, const char* filename,
4158 unsigned sourceId, uint32_t lineno,
4159 JS::ColumnNumberOneOrigin column,
4160 JSErrorCallback errorCallback, void* userRef,
4161 const unsigned errorNumber, ...) {
4162 va_list ap;
4163 va_start(ap, errorNumber);
4164 bool ok = addNoteVA(fc, filename, sourceId, lineno, column, errorCallback,
4165 userRef, errorNumber, ArgumentsAreUTF8, ap);
4166 va_end(ap);
4167 return ok;
4170 JS_PUBLIC_API size_t JSErrorNotes::length() { return notes_.length(); }
4172 UniquePtr<JSErrorNotes> JSErrorNotes::copy(JSContext* cx) {
4173 auto copiedNotes = MakeUnique<JSErrorNotes>();
4174 if (!copiedNotes) {
4175 ReportOutOfMemory(cx);
4176 return nullptr;
4179 for (auto&& note : *this) {
4180 UniquePtr<JSErrorNotes::Note> copied = CopyErrorNote(cx, note.get());
4181 if (!copied) {
4182 return nullptr;
4185 if (!copiedNotes->notes_.append(std::move(copied))) {
4186 return nullptr;
4190 return copiedNotes;
4193 JS_PUBLIC_API JSErrorNotes::iterator JSErrorNotes::begin() {
4194 return iterator(notes_.begin());
4197 JS_PUBLIC_API JSErrorNotes::iterator JSErrorNotes::end() {
4198 return iterator(notes_.end());
4201 extern MOZ_NEVER_INLINE JS_PUBLIC_API void JS_AbortIfWrongThread(
4202 JSContext* cx) {
4203 if (!CurrentThreadCanAccessRuntime(cx->runtime())) {
4204 MOZ_CRASH();
4206 if (TlsContext.get() != cx) {
4207 MOZ_CRASH();
4211 #ifdef JS_GC_ZEAL
4212 JS_PUBLIC_API void JS_GetGCZealBits(JSContext* cx, uint32_t* zealBits,
4213 uint32_t* frequency,
4214 uint32_t* nextScheduled) {
4215 cx->runtime()->gc.getZealBits(zealBits, frequency, nextScheduled);
4218 JS_PUBLIC_API void JS_SetGCZeal(JSContext* cx, uint8_t zeal,
4219 uint32_t frequency) {
4220 cx->runtime()->gc.setZeal(zeal, frequency);
4223 JS_PUBLIC_API void JS_UnsetGCZeal(JSContext* cx, uint8_t zeal) {
4224 cx->runtime()->gc.unsetZeal(zeal);
4227 JS_PUBLIC_API void JS_ScheduleGC(JSContext* cx, uint32_t count) {
4228 cx->runtime()->gc.setNextScheduled(count);
4230 #endif
4232 JS_PUBLIC_API void JS_SetParallelParsingEnabled(JSContext* cx, bool enabled) {
4233 cx->runtime()->setParallelParsingEnabled(enabled);
4236 JS_PUBLIC_API void JS_SetOffthreadIonCompilationEnabled(JSContext* cx,
4237 bool enabled) {
4238 cx->runtime()->setOffthreadIonCompilationEnabled(enabled);
4241 JS_PUBLIC_API void JS_SetGlobalJitCompilerOption(JSContext* cx,
4242 JSJitCompilerOption opt,
4243 uint32_t value) {
4244 JSRuntime* rt = cx->runtime();
4245 switch (opt) {
4246 #ifdef ENABLE_PORTABLE_BASELINE_INTERP
4247 case JSJITCOMPILER_PORTABLE_BASELINE_ENABLE:
4248 if (value == 1) {
4249 jit::JitOptions.portableBaselineInterpreter = true;
4250 } else if (value == 0) {
4251 jit::JitOptions.portableBaselineInterpreter = false;
4253 break;
4254 case JSJITCOMPILER_PORTABLE_BASELINE_WARMUP_THRESHOLD:
4255 if (value == uint32_t(-1)) {
4256 jit::DefaultJitOptions defaultValues;
4257 value = defaultValues.portableBaselineInterpreterWarmUpThreshold;
4259 jit::JitOptions.portableBaselineInterpreterWarmUpThreshold = value;
4260 break;
4261 #endif
4262 case JSJITCOMPILER_BASELINE_INTERPRETER_WARMUP_TRIGGER:
4263 if (value == uint32_t(-1)) {
4264 jit::DefaultJitOptions defaultValues;
4265 value = defaultValues.baselineInterpreterWarmUpThreshold;
4267 jit::JitOptions.baselineInterpreterWarmUpThreshold = value;
4268 break;
4269 case JSJITCOMPILER_BASELINE_WARMUP_TRIGGER:
4270 if (value == uint32_t(-1)) {
4271 jit::DefaultJitOptions defaultValues;
4272 value = defaultValues.baselineJitWarmUpThreshold;
4274 jit::JitOptions.baselineJitWarmUpThreshold = value;
4275 break;
4276 case JSJITCOMPILER_IC_FORCE_MEGAMORPHIC:
4277 jit::JitOptions.forceMegamorphicICs = !!value;
4278 break;
4279 case JSJITCOMPILER_ION_NORMAL_WARMUP_TRIGGER:
4280 if (value == uint32_t(-1)) {
4281 jit::JitOptions.resetNormalIonWarmUpThreshold();
4282 break;
4284 jit::JitOptions.setNormalIonWarmUpThreshold(value);
4285 break;
4286 case JSJITCOMPILER_ION_GVN_ENABLE:
4287 if (value == 0) {
4288 jit::JitOptions.enableGvn(false);
4289 JitSpew(js::jit::JitSpew_IonScripts, "Disable ion's GVN");
4290 } else {
4291 jit::JitOptions.enableGvn(true);
4292 JitSpew(js::jit::JitSpew_IonScripts, "Enable ion's GVN");
4294 break;
4295 case JSJITCOMPILER_ION_FORCE_IC:
4296 if (value == 0) {
4297 jit::JitOptions.forceInlineCaches = false;
4298 JitSpew(js::jit::JitSpew_IonScripts,
4299 "Ion: Enable non-IC optimizations.");
4300 } else {
4301 jit::JitOptions.forceInlineCaches = true;
4302 JitSpew(js::jit::JitSpew_IonScripts,
4303 "Ion: Disable non-IC optimizations.");
4305 break;
4306 case JSJITCOMPILER_ION_CHECK_RANGE_ANALYSIS:
4307 if (value == 0) {
4308 jit::JitOptions.checkRangeAnalysis = false;
4309 JitSpew(js::jit::JitSpew_IonScripts,
4310 "Ion: Enable range analysis checks.");
4311 } else {
4312 jit::JitOptions.checkRangeAnalysis = true;
4313 JitSpew(js::jit::JitSpew_IonScripts,
4314 "Ion: Disable range analysis checks.");
4316 break;
4317 case JSJITCOMPILER_ION_ENABLE:
4318 if (value == 1) {
4319 jit::JitOptions.ion = true;
4320 JitSpew(js::jit::JitSpew_IonScripts, "Enable ion");
4321 } else if (value == 0) {
4322 jit::JitOptions.ion = false;
4323 JitSpew(js::jit::JitSpew_IonScripts, "Disable ion");
4325 break;
4326 case JSJITCOMPILER_JIT_TRUSTEDPRINCIPALS_ENABLE:
4327 if (value == 1) {
4328 jit::JitOptions.jitForTrustedPrincipals = true;
4329 JitSpew(js::jit::JitSpew_IonScripts,
4330 "Enable ion and baselinejit for trusted principals");
4331 } else if (value == 0) {
4332 jit::JitOptions.jitForTrustedPrincipals = false;
4333 JitSpew(js::jit::JitSpew_IonScripts,
4334 "Disable ion and baselinejit for trusted principals");
4336 break;
4337 case JSJITCOMPILER_ION_FREQUENT_BAILOUT_THRESHOLD:
4338 if (value == uint32_t(-1)) {
4339 jit::DefaultJitOptions defaultValues;
4340 value = defaultValues.frequentBailoutThreshold;
4342 jit::JitOptions.frequentBailoutThreshold = value;
4343 break;
4344 case JSJITCOMPILER_BASE_REG_FOR_LOCALS:
4345 if (value == 0) {
4346 jit::JitOptions.baseRegForLocals = jit::BaseRegForAddress::SP;
4347 } else if (value == 1) {
4348 jit::JitOptions.baseRegForLocals = jit::BaseRegForAddress::FP;
4349 } else {
4350 jit::DefaultJitOptions defaultValues;
4351 jit::JitOptions.baseRegForLocals = defaultValues.baseRegForLocals;
4353 break;
4354 case JSJITCOMPILER_BASELINE_INTERPRETER_ENABLE:
4355 if (value == 1) {
4356 jit::JitOptions.baselineInterpreter = true;
4357 } else if (value == 0) {
4358 ReleaseAllJITCode(rt->gcContext());
4359 jit::JitOptions.baselineInterpreter = false;
4361 break;
4362 case JSJITCOMPILER_BASELINE_ENABLE:
4363 if (value == 1) {
4364 jit::JitOptions.baselineJit = true;
4365 ReleaseAllJITCode(rt->gcContext());
4366 JitSpew(js::jit::JitSpew_BaselineScripts, "Enable baseline");
4367 } else if (value == 0) {
4368 jit::JitOptions.baselineJit = false;
4369 ReleaseAllJITCode(rt->gcContext());
4370 JitSpew(js::jit::JitSpew_BaselineScripts, "Disable baseline");
4372 break;
4373 case JSJITCOMPILER_NATIVE_REGEXP_ENABLE:
4374 jit::JitOptions.nativeRegExp = !!value;
4375 break;
4376 case JSJITCOMPILER_JIT_HINTS_ENABLE:
4377 jit::JitOptions.disableJitHints = !value;
4378 break;
4379 case JSJITCOMPILER_OFFTHREAD_COMPILATION_ENABLE:
4380 if (value == 1) {
4381 rt->setOffthreadIonCompilationEnabled(true);
4382 JitSpew(js::jit::JitSpew_IonScripts, "Enable offthread compilation");
4383 } else if (value == 0) {
4384 rt->setOffthreadIonCompilationEnabled(false);
4385 JitSpew(js::jit::JitSpew_IonScripts, "Disable offthread compilation");
4387 break;
4388 case JSJITCOMPILER_INLINING_BYTECODE_MAX_LENGTH:
4389 if (value == uint32_t(-1)) {
4390 jit::DefaultJitOptions defaultValues;
4391 value = defaultValues.smallFunctionMaxBytecodeLength;
4393 jit::JitOptions.smallFunctionMaxBytecodeLength = value;
4394 break;
4395 case JSJITCOMPILER_JUMP_THRESHOLD:
4396 if (value == uint32_t(-1)) {
4397 jit::DefaultJitOptions defaultValues;
4398 value = defaultValues.jumpThreshold;
4400 jit::JitOptions.jumpThreshold = value;
4401 break;
4402 case JSJITCOMPILER_SPECTRE_INDEX_MASKING:
4403 jit::JitOptions.spectreIndexMasking = !!value;
4404 break;
4405 case JSJITCOMPILER_SPECTRE_OBJECT_MITIGATIONS:
4406 jit::JitOptions.spectreObjectMitigations = !!value;
4407 break;
4408 case JSJITCOMPILER_SPECTRE_STRING_MITIGATIONS:
4409 jit::JitOptions.spectreStringMitigations = !!value;
4410 break;
4411 case JSJITCOMPILER_SPECTRE_VALUE_MASKING:
4412 jit::JitOptions.spectreValueMasking = !!value;
4413 break;
4414 case JSJITCOMPILER_SPECTRE_JIT_TO_CXX_CALLS:
4415 jit::JitOptions.spectreJitToCxxCalls = !!value;
4416 break;
4417 case JSJITCOMPILER_WRITE_PROTECT_CODE:
4418 jit::JitOptions.maybeSetWriteProtectCode(!!value);
4419 break;
4420 case JSJITCOMPILER_WASM_FOLD_OFFSETS:
4421 jit::JitOptions.wasmFoldOffsets = !!value;
4422 break;
4423 case JSJITCOMPILER_WASM_DELAY_TIER2:
4424 jit::JitOptions.wasmDelayTier2 = !!value;
4425 break;
4426 case JSJITCOMPILER_WASM_JIT_BASELINE:
4427 JS::ContextOptionsRef(cx).setWasmBaseline(!!value);
4428 break;
4429 case JSJITCOMPILER_WASM_JIT_OPTIMIZING:
4430 JS::ContextOptionsRef(cx).setWasmIon(!!value);
4431 break;
4432 #ifdef DEBUG
4433 case JSJITCOMPILER_FULL_DEBUG_CHECKS:
4434 jit::JitOptions.fullDebugChecks = !!value;
4435 break;
4436 #endif
4437 default:
4438 break;
4442 JS_PUBLIC_API bool JS_GetGlobalJitCompilerOption(JSContext* cx,
4443 JSJitCompilerOption opt,
4444 uint32_t* valueOut) {
4445 MOZ_ASSERT(valueOut);
4446 #ifndef JS_CODEGEN_NONE
4447 JSRuntime* rt = cx->runtime();
4448 switch (opt) {
4449 case JSJITCOMPILER_BASELINE_INTERPRETER_WARMUP_TRIGGER:
4450 *valueOut = jit::JitOptions.baselineInterpreterWarmUpThreshold;
4451 break;
4452 case JSJITCOMPILER_BASELINE_WARMUP_TRIGGER:
4453 *valueOut = jit::JitOptions.baselineJitWarmUpThreshold;
4454 break;
4455 case JSJITCOMPILER_IC_FORCE_MEGAMORPHIC:
4456 *valueOut = jit::JitOptions.forceMegamorphicICs;
4457 break;
4458 case JSJITCOMPILER_ION_NORMAL_WARMUP_TRIGGER:
4459 *valueOut = jit::JitOptions.normalIonWarmUpThreshold;
4460 break;
4461 case JSJITCOMPILER_ION_FORCE_IC:
4462 *valueOut = jit::JitOptions.forceInlineCaches;
4463 break;
4464 case JSJITCOMPILER_ION_CHECK_RANGE_ANALYSIS:
4465 *valueOut = jit::JitOptions.checkRangeAnalysis;
4466 break;
4467 case JSJITCOMPILER_ION_ENABLE:
4468 *valueOut = jit::JitOptions.ion;
4469 break;
4470 case JSJITCOMPILER_ION_FREQUENT_BAILOUT_THRESHOLD:
4471 *valueOut = jit::JitOptions.frequentBailoutThreshold;
4472 break;
4473 case JSJITCOMPILER_BASE_REG_FOR_LOCALS:
4474 *valueOut = uint32_t(jit::JitOptions.baseRegForLocals);
4475 break;
4476 case JSJITCOMPILER_INLINING_BYTECODE_MAX_LENGTH:
4477 *valueOut = jit::JitOptions.smallFunctionMaxBytecodeLength;
4478 break;
4479 case JSJITCOMPILER_BASELINE_INTERPRETER_ENABLE:
4480 *valueOut = jit::JitOptions.baselineInterpreter;
4481 break;
4482 case JSJITCOMPILER_BASELINE_ENABLE:
4483 *valueOut = jit::JitOptions.baselineJit;
4484 break;
4485 case JSJITCOMPILER_NATIVE_REGEXP_ENABLE:
4486 *valueOut = jit::JitOptions.nativeRegExp;
4487 break;
4488 case JSJITCOMPILER_OFFTHREAD_COMPILATION_ENABLE:
4489 *valueOut = rt->canUseOffthreadIonCompilation();
4490 break;
4491 case JSJITCOMPILER_SPECTRE_INDEX_MASKING:
4492 *valueOut = jit::JitOptions.spectreIndexMasking ? 1 : 0;
4493 break;
4494 case JSJITCOMPILER_SPECTRE_OBJECT_MITIGATIONS:
4495 *valueOut = jit::JitOptions.spectreObjectMitigations ? 1 : 0;
4496 break;
4497 case JSJITCOMPILER_SPECTRE_STRING_MITIGATIONS:
4498 *valueOut = jit::JitOptions.spectreStringMitigations ? 1 : 0;
4499 break;
4500 case JSJITCOMPILER_SPECTRE_VALUE_MASKING:
4501 *valueOut = jit::JitOptions.spectreValueMasking ? 1 : 0;
4502 break;
4503 case JSJITCOMPILER_SPECTRE_JIT_TO_CXX_CALLS:
4504 *valueOut = jit::JitOptions.spectreJitToCxxCalls ? 1 : 0;
4505 break;
4506 case JSJITCOMPILER_WRITE_PROTECT_CODE:
4507 *valueOut = jit::JitOptions.writeProtectCode ? 1 : 0;
4508 break;
4509 case JSJITCOMPILER_WASM_FOLD_OFFSETS:
4510 *valueOut = jit::JitOptions.wasmFoldOffsets ? 1 : 0;
4511 break;
4512 case JSJITCOMPILER_WASM_JIT_BASELINE:
4513 *valueOut = JS::ContextOptionsRef(cx).wasmBaseline() ? 1 : 0;
4514 break;
4515 case JSJITCOMPILER_WASM_JIT_OPTIMIZING:
4516 *valueOut = JS::ContextOptionsRef(cx).wasmIon() ? 1 : 0;
4517 break;
4518 # ifdef DEBUG
4519 case JSJITCOMPILER_FULL_DEBUG_CHECKS:
4520 *valueOut = jit::JitOptions.fullDebugChecks ? 1 : 0;
4521 break;
4522 # endif
4523 default:
4524 return false;
4526 #else
4527 switch (opt) {
4528 # ifdef ENABLE_PORTABLE_BASELINE_INTERP
4529 case JSJITCOMPILER_PORTABLE_BASELINE_ENABLE:
4530 *valueOut = jit::JitOptions.portableBaselineInterpreter;
4531 break;
4532 case JSJITCOMPILER_PORTABLE_BASELINE_WARMUP_THRESHOLD:
4533 *valueOut = jit::JitOptions.portableBaselineInterpreterWarmUpThreshold;
4534 break;
4535 # endif
4536 default:
4537 *valueOut = 0;
4539 #endif
4540 return true;
4543 JS_PUBLIC_API void JS::DisableSpectreMitigationsAfterInit() {
4544 // This is used to turn off Spectre mitigations in pre-allocated child
4545 // processes used for isolated web content. Assert there's a single runtime
4546 // and cancel off-thread compilations, to ensure we're not racing with any
4547 // compilations.
4548 JSContext* cx = TlsContext.get();
4549 MOZ_RELEASE_ASSERT(cx);
4550 MOZ_RELEASE_ASSERT(JSRuntime::hasSingleLiveRuntime());
4551 MOZ_RELEASE_ASSERT(cx->runtime()->wasmInstances.lock()->empty());
4553 CancelOffThreadIonCompile(cx->runtime());
4555 jit::JitOptions.spectreIndexMasking = false;
4556 jit::JitOptions.spectreObjectMitigations = false;
4557 jit::JitOptions.spectreStringMitigations = false;
4558 jit::JitOptions.spectreValueMasking = false;
4559 jit::JitOptions.spectreJitToCxxCalls = false;
4562 /************************************************************************/
4564 #if !defined(STATIC_EXPORTABLE_JS_API) && !defined(STATIC_JS_API) && \
4565 defined(XP_WIN) && (defined(MOZ_MEMORY) || !defined(JS_STANDALONE))
4567 # include "util/WindowsWrapper.h"
4570 * Initialization routine for the JS DLL.
4572 BOOL WINAPI DllMain(HINSTANCE hDLL, DWORD dwReason, LPVOID lpReserved) {
4573 return TRUE;
4576 #endif
4578 JS_PUBLIC_API bool JS_IndexToId(JSContext* cx, uint32_t index,
4579 MutableHandleId id) {
4580 return IndexToId(cx, index, id);
4583 JS_PUBLIC_API bool JS_CharsToId(JSContext* cx, JS::TwoByteChars chars,
4584 MutableHandleId idp) {
4585 Rooted<JSAtom*> atom(cx,
4586 AtomizeChars(cx, chars.begin().get(), chars.length()));
4587 if (!atom) {
4588 return false;
4590 #ifdef DEBUG
4591 MOZ_ASSERT(!atom->isIndex(), "API misuse: |chars| must not encode an index");
4592 #endif
4593 idp.set(AtomToId(atom));
4594 return true;
4597 JS_PUBLIC_API bool JS_IsIdentifier(JSContext* cx, HandleString str,
4598 bool* isIdentifier) {
4599 cx->check(str);
4601 JSLinearString* linearStr = str->ensureLinear(cx);
4602 if (!linearStr) {
4603 return false;
4606 *isIdentifier = IsIdentifier(linearStr);
4607 return true;
4610 JS_PUBLIC_API bool JS_IsIdentifier(const char16_t* chars, size_t length) {
4611 return IsIdentifier(chars, length);
4614 namespace JS {
4616 void AutoFilename::reset() {
4617 if (ss_) {
4618 ss_->Release();
4619 ss_ = nullptr;
4621 if (filename_.is<const char*>()) {
4622 filename_.as<const char*>() = nullptr;
4623 } else {
4624 filename_.as<UniqueChars>().reset();
4628 void AutoFilename::setScriptSource(js::ScriptSource* p) {
4629 MOZ_ASSERT(!ss_);
4630 MOZ_ASSERT(!get());
4631 ss_ = p;
4632 if (p) {
4633 p->AddRef();
4634 setUnowned(p->filename());
4638 void AutoFilename::setUnowned(const char* filename) {
4639 MOZ_ASSERT(!get());
4640 filename_.as<const char*>() = filename ? filename : "";
4643 void AutoFilename::setOwned(UniqueChars&& filename) {
4644 MOZ_ASSERT(!get());
4645 filename_ = AsVariant(std::move(filename));
4648 const char* AutoFilename::get() const {
4649 if (filename_.is<const char*>()) {
4650 return filename_.as<const char*>();
4652 return filename_.as<UniqueChars>().get();
4655 JS_PUBLIC_API bool DescribeScriptedCaller(JSContext* cx, AutoFilename* filename,
4656 uint32_t* lineno,
4657 JS::ColumnNumberOneOrigin* column) {
4658 if (filename) {
4659 filename->reset();
4661 if (lineno) {
4662 *lineno = 0;
4664 if (column) {
4665 *column = JS::ColumnNumberOneOrigin();
4668 if (!cx->compartment()) {
4669 return false;
4672 NonBuiltinFrameIter i(cx, cx->realm()->principals());
4673 if (i.done()) {
4674 return false;
4677 // If the caller is hidden, the embedding wants us to return false here so
4678 // that it can check its own stack (see HideScriptedCaller).
4679 if (i.activation()->scriptedCallerIsHidden()) {
4680 return false;
4683 if (filename) {
4684 if (i.isWasm()) {
4685 // For Wasm, copy out the filename, there is no script source.
4686 UniqueChars copy = DuplicateString(i.filename() ? i.filename() : "");
4687 if (!copy) {
4688 filename->setUnowned("out of memory");
4689 } else {
4690 filename->setOwned(std::move(copy));
4692 } else {
4693 // All other frames have a script source to read the filename from.
4694 filename->setScriptSource(i.scriptSource());
4698 if (lineno) {
4699 JS::TaggedColumnNumberOneOrigin columnNumber;
4700 *lineno = i.computeLine(&columnNumber);
4701 if (column) {
4702 *column = JS::ColumnNumberOneOrigin(columnNumber.oneOriginValue());
4704 } else if (column) {
4705 JS::TaggedColumnNumberOneOrigin columnNumber;
4706 i.computeLine(&columnNumber);
4707 *column = JS::ColumnNumberOneOrigin(columnNumber.oneOriginValue());
4710 return true;
4713 // Fast path to get the activation and realm to use for GetScriptedCallerGlobal.
4714 // If this returns false, the fast path didn't work out and the caller has to
4715 // use the (much slower) NonBuiltinFrameIter path.
4717 // The optimization here is that we skip Ion-inlined frames and only look at
4718 // 'outer' frames. That's fine because Ion doesn't inline cross-realm calls.
4719 // However, GetScriptedCallerGlobal has to skip self-hosted frames and Ion
4720 // can inline self-hosted scripts, so we have to be careful:
4722 // * When we see a non-self-hosted outer script, it's possible we inlined
4723 // self-hosted scripts into it but that doesn't matter because these scripts
4724 // all have the same realm/global anyway.
4726 // * When we see a self-hosted outer script, it's possible we inlined
4727 // non-self-hosted scripts into it, so we have to give up because in this
4728 // case, whether or not to skip the self-hosted frame (to the possibly
4729 // different-realm caller) requires the slow path to handle inlining. Baseline
4730 // and the interpreter don't inline so this only affects Ion.
4731 static bool GetScriptedCallerActivationRealmFast(JSContext* cx,
4732 Activation** activation,
4733 Realm** realm) {
4734 ActivationIterator activationIter(cx);
4736 if (activationIter.done()) {
4737 *activation = nullptr;
4738 *realm = nullptr;
4739 return true;
4742 if (activationIter->isJit()) {
4743 jit::JitActivation* act = activationIter->asJit();
4744 JitFrameIter iter(act);
4745 while (true) {
4746 iter.skipNonScriptedJSFrames();
4747 if (iter.done()) {
4748 break;
4751 if (!iter.isSelfHostedIgnoringInlining()) {
4752 *activation = act;
4753 *realm = iter.realm();
4754 return true;
4757 if (iter.isJSJit() && iter.asJSJit().isIonScripted()) {
4758 // Ion might have inlined non-self-hosted scripts in this
4759 // self-hosted script.
4760 return false;
4763 ++iter;
4765 } else if (activationIter->isInterpreter()) {
4766 InterpreterActivation* act = activationIter->asInterpreter();
4767 for (InterpreterFrameIterator iter(act); !iter.done(); ++iter) {
4768 if (!iter.frame()->script()->selfHosted()) {
4769 *activation = act;
4770 *realm = iter.frame()->script()->realm();
4771 return true;
4776 return false;
4779 JS_PUBLIC_API JSObject* GetScriptedCallerGlobal(JSContext* cx) {
4780 Activation* activation;
4781 Realm* realm;
4782 if (GetScriptedCallerActivationRealmFast(cx, &activation, &realm)) {
4783 if (!activation) {
4784 return nullptr;
4786 } else {
4787 NonBuiltinFrameIter i(cx);
4788 if (i.done()) {
4789 return nullptr;
4791 activation = i.activation();
4792 realm = i.realm();
4795 MOZ_ASSERT(realm->compartment() == activation->compartment());
4797 // If the caller is hidden, the embedding wants us to return null here so
4798 // that it can check its own stack (see HideScriptedCaller).
4799 if (activation->scriptedCallerIsHidden()) {
4800 return nullptr;
4803 GlobalObject* global = realm->maybeGlobal();
4805 // No one should be running code in a realm without any live objects, so
4806 // there should definitely be a live global.
4807 MOZ_ASSERT(global);
4809 return global;
4812 JS_PUBLIC_API void HideScriptedCaller(JSContext* cx) {
4813 MOZ_ASSERT(cx);
4815 // If there's no accessible activation on the stack, we'll return null from
4816 // DescribeScriptedCaller anyway, so there's no need to annotate anything.
4817 Activation* act = cx->activation();
4818 if (!act) {
4819 return;
4821 act->hideScriptedCaller();
4824 JS_PUBLIC_API void UnhideScriptedCaller(JSContext* cx) {
4825 Activation* act = cx->activation();
4826 if (!act) {
4827 return;
4829 act->unhideScriptedCaller();
4832 } /* namespace JS */
4834 #ifdef JS_DEBUG
4835 JS_PUBLIC_API void JS::detail::AssertArgumentsAreSane(JSContext* cx,
4836 HandleValue value) {
4837 AssertHeapIsIdle();
4838 CHECK_THREAD(cx);
4839 cx->check(value);
4841 #endif /* JS_DEBUG */
4843 JS_PUBLIC_API bool JS::FinishIncrementalEncoding(JSContext* cx,
4844 JS::HandleScript script,
4845 TranscodeBuffer& buffer) {
4846 if (!script) {
4847 return false;
4849 if (!script->scriptSource()->xdrFinalizeEncoder(cx, buffer)) {
4850 return false;
4852 return true;
4855 JS_PUBLIC_API bool JS::FinishIncrementalEncoding(JSContext* cx,
4856 JS::Handle<JSObject*> module,
4857 TranscodeBuffer& buffer) {
4858 if (!module->as<ModuleObject>()
4859 .scriptSourceObject()
4860 ->source()
4861 ->xdrFinalizeEncoder(cx, buffer)) {
4862 return false;
4864 return true;
4867 JS_PUBLIC_API void JS::AbortIncrementalEncoding(JS::HandleScript script) {
4868 if (!script) {
4869 return;
4871 script->scriptSource()->xdrAbortEncoder();
4874 JS_PUBLIC_API void JS::AbortIncrementalEncoding(JS::Handle<JSObject*> module) {
4875 module->as<ModuleObject>().scriptSourceObject()->source()->xdrAbortEncoder();
4878 bool JS::IsWasmModuleObject(HandleObject obj) {
4879 return obj->canUnwrapAs<WasmModuleObject>();
4882 JS_PUBLIC_API RefPtr<JS::WasmModule> JS::GetWasmModule(HandleObject obj) {
4883 MOZ_ASSERT(JS::IsWasmModuleObject(obj));
4884 WasmModuleObject& mobj = obj->unwrapAs<WasmModuleObject>();
4885 return const_cast<wasm::Module*>(&mobj.module());
4888 bool JS::DisableWasmHugeMemory() { return wasm::DisableHugeMemory(); }
4890 JS_PUBLIC_API void JS::SetProcessLargeAllocationFailureCallback(
4891 JS::LargeAllocationFailureCallback lafc) {
4892 MOZ_ASSERT(!OnLargeAllocationFailure);
4893 OnLargeAllocationFailure = lafc;
4896 JS_PUBLIC_API void JS::SetOutOfMemoryCallback(JSContext* cx,
4897 OutOfMemoryCallback cb,
4898 void* data) {
4899 cx->runtime()->oomCallback = cb;
4900 cx->runtime()->oomCallbackData = data;
4903 JS_PUBLIC_API void JS::SetShadowRealmInitializeGlobalCallback(
4904 JSContext* cx, JS::GlobalInitializeCallback callback) {
4905 cx->runtime()->shadowRealmInitializeGlobalCallback = callback;
4908 JS_PUBLIC_API void JS::SetShadowRealmGlobalCreationCallback(
4909 JSContext* cx, JS::GlobalCreationCallback callback) {
4910 cx->runtime()->shadowRealmGlobalCreationCallback = callback;
4913 JS::FirstSubsumedFrame::FirstSubsumedFrame(
4914 JSContext* cx, bool ignoreSelfHostedFrames /* = true */)
4915 : JS::FirstSubsumedFrame(cx, cx->realm()->principals(),
4916 ignoreSelfHostedFrames) {}
4918 JS_PUBLIC_API bool JS::CaptureCurrentStack(
4919 JSContext* cx, JS::MutableHandleObject stackp,
4920 JS::StackCapture&& capture /* = JS::StackCapture(JS::AllFrames()) */) {
4921 AssertHeapIsIdle();
4922 CHECK_THREAD(cx);
4923 MOZ_RELEASE_ASSERT(cx->realm());
4925 Realm* realm = cx->realm();
4926 Rooted<SavedFrame*> frame(cx);
4927 if (!realm->savedStacks().saveCurrentStack(cx, &frame, std::move(capture))) {
4928 return false;
4930 stackp.set(frame.get());
4931 return true;
4934 JS_PUBLIC_API bool JS::IsAsyncStackCaptureEnabledForRealm(JSContext* cx) {
4935 if (!cx->options().asyncStack()) {
4936 return false;
4939 if (!cx->options().asyncStackCaptureDebuggeeOnly() ||
4940 cx->realm()->isDebuggee()) {
4941 return true;
4944 return cx->realm()->isAsyncStackCapturingEnabled;
4947 JS_PUBLIC_API bool JS::CopyAsyncStack(JSContext* cx,
4948 JS::HandleObject asyncStack,
4949 JS::HandleString asyncCause,
4950 JS::MutableHandleObject stackp,
4951 const Maybe<size_t>& maxFrameCount) {
4952 AssertHeapIsIdle();
4953 CHECK_THREAD(cx);
4954 MOZ_RELEASE_ASSERT(cx->realm());
4956 js::AssertObjectIsSavedFrameOrWrapper(cx, asyncStack);
4957 Realm* realm = cx->realm();
4958 Rooted<SavedFrame*> frame(cx);
4959 if (!realm->savedStacks().copyAsyncStack(cx, asyncStack, asyncCause, &frame,
4960 maxFrameCount)) {
4961 return false;
4963 stackp.set(frame.get());
4964 return true;
4967 JS_PUBLIC_API Zone* JS::GetObjectZone(JSObject* obj) { return obj->zone(); }
4969 JS_PUBLIC_API Zone* JS::GetNurseryCellZone(gc::Cell* cell) {
4970 return cell->nurseryZone();
4973 JS_PUBLIC_API JS::TraceKind JS::GCThingTraceKind(void* thing) {
4974 MOZ_ASSERT(thing);
4975 return static_cast<js::gc::Cell*>(thing)->getTraceKind();
4978 JS_PUBLIC_API void js::SetStackFormat(JSContext* cx, js::StackFormat format) {
4979 cx->runtime()->setStackFormat(format);
4982 JS_PUBLIC_API js::StackFormat js::GetStackFormat(JSContext* cx) {
4983 return cx->runtime()->stackFormat();
4986 JS_PUBLIC_API JS::JSTimers JS::GetJSTimers(JSContext* cx) {
4987 return cx->realm()->timers;
4990 namespace js {
4992 JS_PUBLIC_API void NoteIntentionalCrash() {
4993 #ifdef __linux__
4994 static bool* addr =
4995 reinterpret_cast<bool*>(dlsym(RTLD_DEFAULT, "gBreakpadInjectorEnabled"));
4996 if (addr) {
4997 *addr = false;
4999 #endif
5002 #ifdef DEBUG
5003 bool gSupportDifferentialTesting = false;
5004 #endif // DEBUG
5006 } // namespace js
5008 #ifdef DEBUG
5010 JS_PUBLIC_API void JS::SetSupportDifferentialTesting(bool value) {
5011 js::gSupportDifferentialTesting = value;
5014 #endif // DEBUG