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/. */
6
7 /*
8 * JavaScript API.
9 */
10
11 #include "jsapi.h"
12
13 #include "mozilla/FloatingPoint.h"
14 #include "mozilla/Maybe.h"
15 #include "mozilla/PodOperations.h"
16 #include "mozilla/Sprintf.h"
17
18 #include <algorithm>
19 #ifdef __linux__
20 # include <dlfcn.h>
21 #endif
22 #include <iterator>
23 #include <stdarg.h>
24 #include <string.h>
25
26 #include "jsexn.h"
27 #include "jsfriendapi.h"
28 #include "jsmath.h"
29 #include "jstypes.h"
30
31 #include "builtin/AtomicsObject.h"
32 #include "builtin/Eval.h"
33 #include "builtin/JSON.h"
34 #include "builtin/Promise.h"
35 #include "builtin/Symbol.h"
36 #include "frontend/BytecodeCompiler.h"
37 #include "gc/FreeOp.h"
38 #include "gc/Marking.h"
39 #include "gc/PublicIterators.h"
40 #include "jit/JitSpewer.h"
41 #include "js/CallAndConstruct.h" // JS::IsCallable
42 #include "js/CharacterEncoding.h"
43 #include "js/CompileOptions.h"
44 #include "js/ContextOptions.h" // JS::ContextOptions{,Ref}
45 #include "js/Conversions.h"
46 #include "js/ErrorInterceptor.h"
47 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
48 #include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit
49 #include "js/GlobalObject.h"
50 #include "js/Initialization.h"
51 #include "js/Interrupt.h"
52 #include "js/JSON.h"
53 #include "js/LocaleSensitive.h"
54 #include "js/MemoryCallbacks.h"
55 #include "js/MemoryFunctions.h"
56 #include "js/PropertySpec.h"
57 #include "js/Proxy.h"
58 #include "js/ScriptPrivate.h"
59 #include "js/StableStringChars.h"
60 #include "js/Stack.h"
61 #include "js/StreamConsumer.h"
62 #include "js/String.h" // JS::MaxStringLength
63 #include "js/Symbol.h"
64 #include "js/TelemetryTimers.h"
65 #include "js/Utility.h"
66 #include "js/WaitCallbacks.h"
67 #include "js/WasmModule.h"
68 #include "js/Wrapper.h"
69 #include "js/WrapperCallbacks.h"
70 #include "proxy/DOMProxy.h"
71 #include "util/StringBuffer.h"
72 #include "util/Text.h"
73 #include "vm/EnvironmentObject.h"
74 #include "vm/ErrorObject.h"
75 #include "vm/ErrorReporting.h"
76 #include "vm/Interpreter.h"
77 #include "vm/JSAtom.h"
78 #include "vm/JSAtomState.h"
79 #include "vm/JSContext.h"
80 #include "vm/JSFunction.h"
81 #include "vm/JSObject.h"
82 #include "vm/JSScript.h"
83 #include "vm/PlainObject.h" // js::PlainObject
84 #include "vm/PromiseObject.h" // js::PromiseObject
85 #include "vm/Runtime.h"
86 #include "vm/SavedStacks.h"
87 #include "vm/StringType.h"
88 #include "vm/ToSource.h"
89 #include "vm/WrapperObject.h"
90 #include "wasm/WasmModule.h"
91 #include "wasm/WasmProcess.h"
92
93 #include "builtin/Promise-inl.h"
94 #include "debugger/DebugAPI-inl.h"
95 #include "vm/Compartment-inl.h"
96 #include "vm/Interpreter-inl.h"
97 #include "vm/IsGivenTypeObject-inl.h" // js::IsGivenTypeObject
98 #include "vm/JSAtom-inl.h"
99 #include "vm/JSScript-inl.h"
100 #include "vm/NativeObject-inl.h"
101 #include "vm/SavedStacks-inl.h"
102 #include "vm/StringType-inl.h"
103
104 using namespace js;
105
106 using mozilla::Maybe;
107 using mozilla::PodCopy;
108 using mozilla::Some;
109
110 using JS::AutoStableStringChars;
111 using JS::CompileOptions;
112 using JS::ReadOnlyCompileOptions;
113 using JS::SourceText;
114
115 // See preprocessor definition of JS_BITS_PER_WORD in jstypes.h; make sure
116 // JS_64BIT (used internally) agrees with it
117 #ifdef JS_64BIT
118 static_assert(JS_BITS_PER_WORD == 64, "values must be in sync");
119 #else
120 static_assert(JS_BITS_PER_WORD == 32, "values must be in sync");
121 #endif
122
reportMoreArgsNeeded(JSContext * cx,const char * fnname,unsigned required,unsigned actual)123 JS_PUBLIC_API void JS::CallArgs::reportMoreArgsNeeded(JSContext* cx,
124 const char* fnname,
125 unsigned required,
126 unsigned actual) {
127 char requiredArgsStr[40];
128 SprintfLiteral(requiredArgsStr, "%u", required);
129 char actualArgsStr[40];
130 SprintfLiteral(actualArgsStr, "%u", actual);
131 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
132 JSMSG_MORE_ARGS_NEEDED, fnname, requiredArgsStr,
133 required == 1 ? "" : "s", actualArgsStr);
134 }
135
ErrorTakesArguments(unsigned msg)136 static bool ErrorTakesArguments(unsigned msg) {
137 MOZ_ASSERT(msg < JSErr_Limit);
138 unsigned argCount = js_ErrorFormatString[msg].argCount;
139 MOZ_ASSERT(argCount <= 2);
140 return argCount == 1 || argCount == 2;
141 }
142
ErrorTakesObjectArgument(unsigned msg)143 static bool ErrorTakesObjectArgument(unsigned msg) {
144 MOZ_ASSERT(msg < JSErr_Limit);
145 unsigned argCount = js_ErrorFormatString[msg].argCount;
146 MOZ_ASSERT(argCount <= 2);
147 return argCount == 2;
148 }
149
reportError(JSContext * cx,HandleObject obj,HandleId id)150 bool JS::ObjectOpResult::reportError(JSContext* cx, HandleObject obj,
151 HandleId id) {
152 static_assert(unsigned(OkCode) == unsigned(JSMSG_NOT_AN_ERROR),
153 "unsigned value of OkCode must not be an error code");
154 MOZ_ASSERT(code_ != Uninitialized);
155 MOZ_ASSERT(!ok());
156 cx->check(obj);
157
158 if (code_ == JSMSG_OBJECT_NOT_EXTENSIBLE) {
159 RootedValue val(cx, ObjectValue(*obj));
160 return ReportValueError(cx, code_, JSDVG_IGNORE_STACK, val, nullptr);
161 }
162
163 if (ErrorTakesArguments(code_)) {
164 UniqueChars propName =
165 IdToPrintableUTF8(cx, id, IdToPrintableBehavior::IdIsPropertyKey);
166 if (!propName) {
167 return false;
168 }
169
170 if (code_ == JSMSG_SET_NON_OBJECT_RECEIVER) {
171 // We know that the original receiver was a primitive, so unbox it.
172 RootedValue val(cx, ObjectValue(*obj));
173 if (!obj->is<ProxyObject>()) {
174 if (!Unbox(cx, obj, &val)) {
175 return false;
176 }
177 }
178 return ReportValueError(cx, code_, JSDVG_IGNORE_STACK, val, nullptr,
179 propName.get());
180 }
181
182 if (ErrorTakesObjectArgument(code_)) {
183 JSObject* unwrapped = js::CheckedUnwrapStatic(obj);
184 const char* name = unwrapped ? unwrapped->getClass()->name : "Object";
185 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, code_, name,
186 propName.get());
187 return false;
188 }
189
190 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, code_,
191 propName.get());
192 return false;
193 }
194 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, code_);
195 return false;
196 }
197
reportError(JSContext * cx,HandleObject obj)198 bool JS::ObjectOpResult::reportError(JSContext* cx, HandleObject obj) {
199 MOZ_ASSERT(code_ != Uninitialized);
200 MOZ_ASSERT(!ok());
201 MOZ_ASSERT(!ErrorTakesArguments(code_));
202 cx->check(obj);
203
204 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, code_);
205 return false;
206 }
207
failCantRedefineProp()208 JS_PUBLIC_API bool JS::ObjectOpResult::failCantRedefineProp() {
209 return fail(JSMSG_CANT_REDEFINE_PROP);
210 }
211
failReadOnly()212 JS_PUBLIC_API bool JS::ObjectOpResult::failReadOnly() {
213 return fail(JSMSG_READ_ONLY);
214 }
215
failGetterOnly()216 JS_PUBLIC_API bool JS::ObjectOpResult::failGetterOnly() {
217 return fail(JSMSG_GETTER_ONLY);
218 }
219
failCantDelete()220 JS_PUBLIC_API bool JS::ObjectOpResult::failCantDelete() {
221 return fail(JSMSG_CANT_DELETE);
222 }
223
failCantSetInterposed()224 JS_PUBLIC_API bool JS::ObjectOpResult::failCantSetInterposed() {
225 return fail(JSMSG_CANT_SET_INTERPOSED);
226 }
227
failCantDefineWindowElement()228 JS_PUBLIC_API bool JS::ObjectOpResult::failCantDefineWindowElement() {
229 return fail(JSMSG_CANT_DEFINE_WINDOW_ELEMENT);
230 }
231
failCantDeleteWindowElement()232 JS_PUBLIC_API bool JS::ObjectOpResult::failCantDeleteWindowElement() {
233 return fail(JSMSG_CANT_DELETE_WINDOW_ELEMENT);
234 }
235
failCantDefineWindowNamedProperty()236 JS_PUBLIC_API bool JS::ObjectOpResult::failCantDefineWindowNamedProperty() {
237 return fail(JSMSG_CANT_DEFINE_WINDOW_NAMED_PROPERTY);
238 }
239
failCantDeleteWindowNamedProperty()240 JS_PUBLIC_API bool JS::ObjectOpResult::failCantDeleteWindowNamedProperty() {
241 return fail(JSMSG_CANT_DELETE_WINDOW_NAMED_PROPERTY);
242 }
243
failCantDefineWindowNonConfigurable()244 JS_PUBLIC_API bool JS::ObjectOpResult::failCantDefineWindowNonConfigurable() {
245 return fail(JSMSG_CANT_DEFINE_WINDOW_NC);
246 }
247
failCantPreventExtensions()248 JS_PUBLIC_API bool JS::ObjectOpResult::failCantPreventExtensions() {
249 return fail(JSMSG_CANT_PREVENT_EXTENSIONS);
250 }
251
failCantSetProto()252 JS_PUBLIC_API bool JS::ObjectOpResult::failCantSetProto() {
253 return fail(JSMSG_CANT_SET_PROTO);
254 }
255
failNoNamedSetter()256 JS_PUBLIC_API bool JS::ObjectOpResult::failNoNamedSetter() {
257 return fail(JSMSG_NO_NAMED_SETTER);
258 }
259
failNoIndexedSetter()260 JS_PUBLIC_API bool JS::ObjectOpResult::failNoIndexedSetter() {
261 return fail(JSMSG_NO_INDEXED_SETTER);
262 }
263
failNotDataDescriptor()264 JS_PUBLIC_API bool JS::ObjectOpResult::failNotDataDescriptor() {
265 return fail(JSMSG_NOT_DATA_DESCRIPTOR);
266 }
267
JS_Now()268 JS_PUBLIC_API int64_t JS_Now() { return PRMJ_Now(); }
269
JS_GetEmptyStringValue(JSContext * cx)270 JS_PUBLIC_API Value JS_GetEmptyStringValue(JSContext* cx) {
271 return StringValue(cx->runtime()->emptyString);
272 }
273
JS_GetEmptyString(JSContext * cx)274 JS_PUBLIC_API JSString* JS_GetEmptyString(JSContext* cx) {
275 MOZ_ASSERT(cx->emptyString());
276 return cx->emptyString();
277 }
278
279 namespace js {
280
AssertHeapIsIdle()281 void AssertHeapIsIdle() { MOZ_ASSERT(!JS::RuntimeHeapIsBusy()); }
282
283 } // namespace js
284
AssertHeapIsIdleOrIterating()285 static void AssertHeapIsIdleOrIterating() {
286 MOZ_ASSERT(!JS::RuntimeHeapIsCollecting());
287 }
288
JS_ValueToObject(JSContext * cx,HandleValue value,MutableHandleObject objp)289 JS_PUBLIC_API bool JS_ValueToObject(JSContext* cx, HandleValue value,
290 MutableHandleObject objp) {
291 AssertHeapIsIdle();
292 CHECK_THREAD(cx);
293 cx->check(value);
294 if (value.isNullOrUndefined()) {
295 objp.set(nullptr);
296 return true;
297 }
298 JSObject* obj = ToObject(cx, value);
299 if (!obj) {
300 return false;
301 }
302 objp.set(obj);
303 return true;
304 }
305
JS_ValueToFunction(JSContext * cx,HandleValue value)306 JS_PUBLIC_API JSFunction* JS_ValueToFunction(JSContext* cx, HandleValue value) {
307 AssertHeapIsIdle();
308 CHECK_THREAD(cx);
309 cx->check(value);
310 return ReportIfNotFunction(cx, value);
311 }
312
JS_ValueToConstructor(JSContext * cx,HandleValue value)313 JS_PUBLIC_API JSFunction* JS_ValueToConstructor(JSContext* cx,
314 HandleValue value) {
315 AssertHeapIsIdle();
316 CHECK_THREAD(cx);
317 cx->check(value);
318 return ReportIfNotFunction(cx, value);
319 }
320
JS_ValueToSource(JSContext * cx,HandleValue value)321 JS_PUBLIC_API JSString* JS_ValueToSource(JSContext* cx, HandleValue value) {
322 AssertHeapIsIdle();
323 CHECK_THREAD(cx);
324 cx->check(value);
325 return ValueToSource(cx, value);
326 }
327
JS_DoubleIsInt32(double d,int32_t * ip)328 JS_PUBLIC_API bool JS_DoubleIsInt32(double d, int32_t* ip) {
329 return mozilla::NumberIsInt32(d, ip);
330 }
331
JS_TypeOfValue(JSContext * cx,HandleValue value)332 JS_PUBLIC_API JSType JS_TypeOfValue(JSContext* cx, HandleValue value) {
333 AssertHeapIsIdle();
334 CHECK_THREAD(cx);
335 cx->check(value);
336 return TypeOfValue(value);
337 }
338
JS_IsBuiltinEvalFunction(JSFunction * fun)339 JS_PUBLIC_API bool JS_IsBuiltinEvalFunction(JSFunction* fun) {
340 return IsAnyBuiltinEval(fun);
341 }
342
JS_IsBuiltinFunctionConstructor(JSFunction * fun)343 JS_PUBLIC_API bool JS_IsBuiltinFunctionConstructor(JSFunction* fun) {
344 return fun->isBuiltinFunctionConstructor();
345 }
346
JS_IsFunctionBound(JSFunction * fun)347 JS_PUBLIC_API bool JS_IsFunctionBound(JSFunction* fun) {
348 return fun->isBoundFunction();
349 }
350
JS_GetBoundFunctionTarget(JSFunction * fun)351 JS_PUBLIC_API JSObject* JS_GetBoundFunctionTarget(JSFunction* fun) {
352 return fun->isBoundFunction() ? fun->getBoundFunctionTarget() : nullptr;
353 }
354
355 /************************************************************************/
356
357 // Prevent functions from being discarded by linker, so that they are callable
358 // when debugging.
PreventDiscardingFunctions()359 static void PreventDiscardingFunctions() {
360 if (reinterpret_cast<uintptr_t>(&PreventDiscardingFunctions) == 1) {
361 // Never executed.
362 memset((void*)&js::debug::GetMarkInfo, 0, 1);
363 memset((void*)&js::debug::GetMarkWordAddress, 0, 1);
364 memset((void*)&js::debug::GetMarkMask, 0, 1);
365 }
366 }
367
JS_NewContext(uint32_t maxbytes,JSRuntime * parentRuntime)368 JS_PUBLIC_API JSContext* JS_NewContext(uint32_t maxbytes,
369 JSRuntime* parentRuntime) {
370 MOZ_ASSERT(JS::detail::libraryInitState == JS::detail::InitState::Running,
371 "must call JS_Init prior to creating any JSContexts");
372
373 // Prevent linker from discarding unused debug functions.
374 PreventDiscardingFunctions();
375
376 // Make sure that all parent runtimes are the topmost parent.
377 while (parentRuntime && parentRuntime->parentRuntime) {
378 parentRuntime = parentRuntime->parentRuntime;
379 }
380
381 return NewContext(maxbytes, parentRuntime);
382 }
383
JS_DestroyContext(JSContext * cx)384 JS_PUBLIC_API void JS_DestroyContext(JSContext* cx) { DestroyContext(cx); }
385
JS_GetContextPrivate(JSContext * cx)386 JS_PUBLIC_API void* JS_GetContextPrivate(JSContext* cx) { return cx->data; }
387
JS_SetContextPrivate(JSContext * cx,void * data)388 JS_PUBLIC_API void JS_SetContextPrivate(JSContext* cx, void* data) {
389 cx->data = data;
390 }
391
JS_SetFutexCanWait(JSContext * cx)392 JS_PUBLIC_API void JS_SetFutexCanWait(JSContext* cx) {
393 cx->fx.setCanWait(true);
394 }
395
JS_GetParentRuntime(JSContext * cx)396 JS_PUBLIC_API JSRuntime* JS_GetParentRuntime(JSContext* cx) {
397 return cx->runtime()->parentRuntime ? cx->runtime()->parentRuntime
398 : cx->runtime();
399 }
400
JS_GetRuntime(JSContext * cx)401 JS_PUBLIC_API JSRuntime* JS_GetRuntime(JSContext* cx) { return cx->runtime(); }
402
ContextOptionsRef(JSContext * cx)403 JS_PUBLIC_API JS::ContextOptions& JS::ContextOptionsRef(JSContext* cx) {
404 return cx->options();
405 }
406
setWasmCranelift(bool flag)407 JS::ContextOptions& JS::ContextOptions::setWasmCranelift(bool flag) {
408 #ifdef ENABLE_WASM_CRANELIFT
409 wasmCranelift_ = flag;
410 #endif
411 return *this;
412 }
413
setWasmSimdWormhole(bool flag)414 JS::ContextOptions& JS::ContextOptions::setWasmSimdWormhole(bool flag) {
415 #ifdef ENABLE_WASM_SIMD_WORMHOLE
416 wasmSimdWormhole_ = flag;
417 #endif
418 return *this;
419 }
420
setFuzzing(bool flag)421 JS::ContextOptions& JS::ContextOptions::setFuzzing(bool flag) {
422 #ifdef FUZZING
423 fuzzing_ = flag;
424 #endif
425 return *this;
426 }
427
JS_GetImplementationVersion(void)428 JS_PUBLIC_API const char* JS_GetImplementationVersion(void) {
429 return "JavaScript-C" MOZILLA_VERSION;
430 }
431
JS_SetDestroyZoneCallback(JSContext * cx,JSDestroyZoneCallback callback)432 JS_PUBLIC_API void JS_SetDestroyZoneCallback(JSContext* cx,
433 JSDestroyZoneCallback callback) {
434 cx->runtime()->destroyZoneCallback = callback;
435 }
436
JS_SetDestroyCompartmentCallback(JSContext * cx,JSDestroyCompartmentCallback callback)437 JS_PUBLIC_API void JS_SetDestroyCompartmentCallback(
438 JSContext* cx, JSDestroyCompartmentCallback callback) {
439 cx->runtime()->destroyCompartmentCallback = callback;
440 }
441
JS_SetSizeOfIncludingThisCompartmentCallback(JSContext * cx,JSSizeOfIncludingThisCompartmentCallback callback)442 JS_PUBLIC_API void JS_SetSizeOfIncludingThisCompartmentCallback(
443 JSContext* cx, JSSizeOfIncludingThisCompartmentCallback callback) {
444 cx->runtime()->sizeOfIncludingThisCompartmentCallback = callback;
445 }
446
JS_SetErrorInterceptorCallback(JSRuntime * rt,JSErrorInterceptor * callback)447 JS_PUBLIC_API void JS_SetErrorInterceptorCallback(
448 JSRuntime* rt, JSErrorInterceptor* callback) {
449 #if defined(NIGHTLY_BUILD)
450 rt->errorInterception.interceptor = callback;
451 #endif // defined(NIGHTLY_BUILD)
452 }
453
JS_GetErrorInterceptorCallback(JSRuntime * rt)454 JS_PUBLIC_API JSErrorInterceptor* JS_GetErrorInterceptorCallback(
455 JSRuntime* rt) {
456 #if defined(NIGHTLY_BUILD)
457 return rt->errorInterception.interceptor;
458 #else // !NIGHTLY_BUILD
459 return nullptr;
460 #endif // defined(NIGHTLY_BUILD)
461 }
462
JS_GetErrorType(const JS::Value & val)463 JS_PUBLIC_API Maybe<JSExnType> JS_GetErrorType(const JS::Value& val) {
464 // All errors are objects.
465 if (!val.isObject()) {
466 return mozilla::Nothing();
467 }
468
469 const JSObject& obj = val.toObject();
470
471 // All errors are `ErrorObject`.
472 if (!obj.is<js::ErrorObject>()) {
473 // Not one of the primitive errors.
474 return mozilla::Nothing();
475 }
476
477 const js::ErrorObject& err = obj.as<js::ErrorObject>();
478 return mozilla::Some(err.type());
479 }
480
JS_SetWrapObjectCallbacks(JSContext * cx,const JSWrapObjectCallbacks * callbacks)481 JS_PUBLIC_API void JS_SetWrapObjectCallbacks(
482 JSContext* cx, const JSWrapObjectCallbacks* callbacks) {
483 cx->runtime()->wrapObjectCallbacks = callbacks;
484 }
485
EnterRealm(JSContext * cx,JSObject * target)486 JS_PUBLIC_API Realm* JS::EnterRealm(JSContext* cx, JSObject* target) {
487 AssertHeapIsIdle();
488 CHECK_THREAD(cx);
489
490 MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(target));
491
492 Realm* oldRealm = cx->realm();
493 cx->enterRealmOf(target);
494 return oldRealm;
495 }
496
LeaveRealm(JSContext * cx,JS::Realm * oldRealm)497 JS_PUBLIC_API void JS::LeaveRealm(JSContext* cx, JS::Realm* oldRealm) {
498 AssertHeapIsIdle();
499 CHECK_THREAD(cx);
500 cx->leaveRealm(oldRealm);
501 }
502
JSAutoRealm(JSContext * cx,JSObject * target)503 JSAutoRealm::JSAutoRealm(JSContext* cx, JSObject* target)
504 : cx_(cx), oldRealm_(cx->realm()) {
505 MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(target));
506 AssertHeapIsIdleOrIterating();
507 cx_->enterRealmOf(target);
508 }
509
JSAutoRealm(JSContext * cx,JSScript * target)510 JSAutoRealm::JSAutoRealm(JSContext* cx, JSScript* target)
511 : cx_(cx), oldRealm_(cx->realm()) {
512 AssertHeapIsIdleOrIterating();
513 cx_->enterRealmOf(target);
514 }
515
~JSAutoRealm()516 JSAutoRealm::~JSAutoRealm() { cx_->leaveRealm(oldRealm_); }
517
JSAutoNullableRealm(JSContext * cx,JSObject * targetOrNull)518 JSAutoNullableRealm::JSAutoNullableRealm(JSContext* cx, JSObject* targetOrNull)
519 : cx_(cx), oldRealm_(cx->realm()) {
520 AssertHeapIsIdleOrIterating();
521 if (targetOrNull) {
522 MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(targetOrNull));
523 cx_->enterRealmOf(targetOrNull);
524 } else {
525 cx_->enterNullRealm();
526 }
527 }
528
~JSAutoNullableRealm()529 JSAutoNullableRealm::~JSAutoNullableRealm() { cx_->leaveRealm(oldRealm_); }
530
JS_SetCompartmentPrivate(JS::Compartment * compartment,void * data)531 JS_PUBLIC_API void JS_SetCompartmentPrivate(JS::Compartment* compartment,
532 void* data) {
533 compartment->data = data;
534 }
535
JS_GetCompartmentPrivate(JS::Compartment * compartment)536 JS_PUBLIC_API void* JS_GetCompartmentPrivate(JS::Compartment* compartment) {
537 return compartment->data;
538 }
539
JS_MarkCrossZoneId(JSContext * cx,jsid id)540 JS_PUBLIC_API void JS_MarkCrossZoneId(JSContext* cx, jsid id) {
541 cx->markId(id);
542 }
543
JS_MarkCrossZoneIdValue(JSContext * cx,const Value & value)544 JS_PUBLIC_API void JS_MarkCrossZoneIdValue(JSContext* cx, const Value& value) {
545 cx->markAtomValue(value);
546 }
547
JS_SetZoneUserData(JS::Zone * zone,void * data)548 JS_PUBLIC_API void JS_SetZoneUserData(JS::Zone* zone, void* data) {
549 zone->data = data;
550 }
551
JS_GetZoneUserData(JS::Zone * zone)552 JS_PUBLIC_API void* JS_GetZoneUserData(JS::Zone* zone) { return zone->data; }
553
JS_WrapObject(JSContext * cx,MutableHandleObject objp)554 JS_PUBLIC_API bool JS_WrapObject(JSContext* cx, MutableHandleObject objp) {
555 AssertHeapIsIdle();
556 CHECK_THREAD(cx);
557 if (objp) {
558 JS::ExposeObjectToActiveJS(objp);
559 }
560 return cx->compartment()->wrap(cx, objp);
561 }
562
JS_WrapValue(JSContext * cx,MutableHandleValue vp)563 JS_PUBLIC_API bool JS_WrapValue(JSContext* cx, MutableHandleValue vp) {
564 AssertHeapIsIdle();
565 CHECK_THREAD(cx);
566 JS::ExposeValueToActiveJS(vp);
567 return cx->compartment()->wrap(cx, vp);
568 }
569
ReleaseAssertObjectHasNoWrappers(JSContext * cx,HandleObject target)570 static void ReleaseAssertObjectHasNoWrappers(JSContext* cx,
571 HandleObject target) {
572 for (CompartmentsIter c(cx->runtime()); !c.done(); c.next()) {
573 if (c->lookupWrapper(target)) {
574 MOZ_CRASH("wrapper found for target object");
575 }
576 }
577 }
578
579 /*
580 * [SMDOC] Brain transplants.
581 *
582 * Not for beginners or the squeamish.
583 *
584 * Sometimes a web spec requires us to transplant an object from one
585 * compartment to another, like when a DOM node is inserted into a document in
586 * another window and thus gets "adopted". We cannot literally change the
587 * `.compartment()` of a `JSObject`; that would break the compartment
588 * invariants. However, as usual, we have a workaround using wrappers.
589 *
590 * Of all the wrapper-based workarounds we do, it's safe to say this is the
591 * most spectacular and questionable.
592 *
593 * `JS_TransplantObject(cx, origobj, target)` changes `origobj` into a
594 * simulacrum of `target`, using highly esoteric means. To JS code, the effect
595 * is as if `origobj` magically "became" `target`, but most often what actually
596 * happens is that `origobj` gets turned into a cross-compartment wrapper for
597 * `target`. The old behavior and contents of `origobj` are overwritten or
598 * discarded.
599 *
600 * Thus, to "transplant" an object from one compartment to another:
601 *
602 * 1. Let `origobj` be the object that you want to move. First, create a
603 * clone of it, `target`, in the destination compartment.
604 *
605 * In our DOM adoption example, `target` will be a Node of the same type as
606 * `origobj`, same content, but in the adopting document. We're not done
607 * yet: the spec for DOM adoption requires that `origobj.ownerDocument`
608 * actually change. All we've done so far is make a copy.
609 *
610 * 2. Call `JS_TransplantObject(cx, origobj, target)`. This typically turns
611 * `origobj` into a wrapper for `target`, so that any JS code that has a
612 * reference to `origobj` will observe it to have the behavior of `target`
613 * going forward. In addition, all existing wrappers for `origobj` are
614 * changed into wrappers for `target`, extending the illusion to those
615 * compartments as well.
616 *
617 * During navigation, we use the above technique to transplant the WindowProxy
618 * into the new Window's compartment.
619 *
620 * A few rules:
621 *
622 * - `origobj` and `target` must be two distinct objects of the same
623 * `JSClass`. Some classes may not support transplantation; WindowProxy
624 * objects and DOM nodes are OK.
625 *
626 * - `target` should be created specifically to be passed to this function.
627 * There must be no existing cross-compartment wrappers for it; ideally
628 * there shouldn't be any pointers to it at all, except the one passed in.
629 *
630 * - `target` shouldn't be used afterwards. Instead, `JS_TransplantObject`
631 * returns a pointer to the transplanted object, which might be `target`
632 * but might be some other object in the same compartment. Use that.
633 *
634 * The reason for this last rule is that JS_TransplantObject does very strange
635 * things in some cases, like swapping `target`'s brain with that of another
636 * object. Leaving `target` behaving like its former self is not a goal.
637 *
638 * We don't have a good way to recover from failure in this function, so
639 * we intentionally crash instead.
640 */
641
CheckTransplantObject(JSObject * obj)642 static void CheckTransplantObject(JSObject* obj) {
643 #ifdef DEBUG
644 MOZ_ASSERT(!obj->is<CrossCompartmentWrapperObject>());
645 JS::AssertCellIsNotGray(obj);
646 #endif
647 }
648
JS_TransplantObject(JSContext * cx,HandleObject origobj,HandleObject target)649 JS_PUBLIC_API JSObject* JS_TransplantObject(JSContext* cx, HandleObject origobj,
650 HandleObject target) {
651 AssertHeapIsIdle();
652 MOZ_ASSERT(origobj != target);
653 CheckTransplantObject(origobj);
654 CheckTransplantObject(target);
655 ReleaseAssertObjectHasNoWrappers(cx, target);
656
657 RootedObject newIdentity(cx);
658
659 // Don't allow a compacting GC to observe any intermediate state.
660 AutoDisableCompactingGC nocgc(cx);
661
662 AutoDisableProxyCheck adpc;
663
664 AutoEnterOOMUnsafeRegion oomUnsafe;
665
666 JS::Compartment* destination = target->compartment();
667
668 if (origobj->compartment() == destination) {
669 // If the original object is in the same compartment as the
670 // destination, then we know that we won't find a wrapper in the
671 // destination's cross compartment map and that the same
672 // object will continue to work.
673 AutoRealm ar(cx, origobj);
674 JSObject::swap(cx, origobj, target, oomUnsafe);
675 newIdentity = origobj;
676 } else if (ObjectWrapperMap::Ptr p = destination->lookupWrapper(origobj)) {
677 // There might already be a wrapper for the original object in
678 // the new compartment. If there is, we use its identity and swap
679 // in the contents of |target|.
680 newIdentity = p->value().get();
681
682 // When we remove origv from the wrapper map, its wrapper, newIdentity,
683 // must immediately cease to be a cross-compartment wrapper. Nuke it.
684 destination->removeWrapper(p);
685 NukeCrossCompartmentWrapper(cx, newIdentity);
686
687 AutoRealm ar(cx, newIdentity);
688 JSObject::swap(cx, newIdentity, target, oomUnsafe);
689 } else {
690 // Otherwise, we use |target| for the new identity object.
691 newIdentity = target;
692 }
693
694 // Now, iterate through other scopes looking for references to the old
695 // object, and update the relevant cross-compartment wrappers. We do this
696 // even if origobj is in the same compartment as target and thus
697 // `newIdentity == origobj`, because this process also clears out any
698 // cached wrapper state.
699 if (!RemapAllWrappersForObject(cx, origobj, newIdentity)) {
700 oomUnsafe.crash("JS_TransplantObject");
701 }
702
703 // Lastly, update the original object to point to the new one.
704 if (origobj->compartment() != destination) {
705 RootedObject newIdentityWrapper(cx, newIdentity);
706 AutoRealm ar(cx, origobj);
707 if (!JS_WrapObject(cx, &newIdentityWrapper)) {
708 MOZ_RELEASE_ASSERT(cx->isThrowingOutOfMemory() ||
709 cx->isThrowingOverRecursed());
710 oomUnsafe.crash("JS_TransplantObject");
711 }
712 MOZ_ASSERT(Wrapper::wrappedObject(newIdentityWrapper) == newIdentity);
713 JSObject::swap(cx, origobj, newIdentityWrapper, oomUnsafe);
714 if (origobj->compartment()->lookupWrapper(newIdentity)) {
715 MOZ_ASSERT(origobj->is<CrossCompartmentWrapperObject>());
716 if (!origobj->compartment()->putWrapper(cx, newIdentity, origobj)) {
717 oomUnsafe.crash("JS_TransplantObject");
718 }
719 }
720 }
721
722 // The new identity object might be one of several things. Return it to avoid
723 // ambiguity.
724 JS::AssertCellIsNotGray(newIdentity);
725 return newIdentity;
726 }
727
RemapRemoteWindowProxies(JSContext * cx,CompartmentTransplantCallback * callback,MutableHandleObject target)728 JS_PUBLIC_API void js::RemapRemoteWindowProxies(
729 JSContext* cx, CompartmentTransplantCallback* callback,
730 MutableHandleObject target) {
731 AssertHeapIsIdle();
732 CheckTransplantObject(target);
733 ReleaseAssertObjectHasNoWrappers(cx, target);
734
735 // |target| can't be a remote proxy, because we expect it to get a CCW when
736 // wrapped across compartments.
737 MOZ_ASSERT(!js::IsDOMRemoteProxyObject(target));
738
739 // Don't allow a compacting GC to observe any intermediate state.
740 AutoDisableCompactingGC nocgc(cx);
741
742 AutoDisableProxyCheck adpc;
743
744 AutoEnterOOMUnsafeRegion oomUnsafe;
745
746 AutoCheckRecursionLimit recursion(cx);
747 if (!recursion.checkSystem(cx)) {
748 oomUnsafe.crash("js::RemapRemoteWindowProxies");
749 }
750
751 RootedObject targetCompartmentProxy(cx);
752 JS::RootedVector<JSObject*> otherProxies(cx);
753
754 // Use the callback to find remote proxies in all compartments that match
755 // whatever criteria callback uses.
756 for (CompartmentsIter c(cx->runtime()); !c.done(); c.next()) {
757 RootedObject remoteProxy(cx, callback->getObjectToTransplant(c));
758 if (!remoteProxy) {
759 continue;
760 }
761 // The object the callback returns should be a DOM remote proxy object in
762 // the compartment c. We rely on it being a DOM remote proxy because that
763 // means that it won't have any cross-compartment wrappers.
764 MOZ_ASSERT(js::IsDOMRemoteProxyObject(remoteProxy));
765 MOZ_ASSERT(remoteProxy->compartment() == c);
766 CheckTransplantObject(remoteProxy);
767
768 // Immediately turn the DOM remote proxy object into a dead proxy object
769 // so we don't have to worry about anything weird going on with it.
770 js::NukeNonCCWProxy(cx, remoteProxy);
771
772 if (remoteProxy->compartment() == target->compartment()) {
773 targetCompartmentProxy = remoteProxy;
774 } else if (!otherProxies.append(remoteProxy)) {
775 oomUnsafe.crash("js::RemapRemoteWindowProxies");
776 }
777 }
778
779 // If there was a remote proxy in |target|'s compartment, we need to use it
780 // instead of |target|, in case it had any references, so swap it. Do this
781 // before any other compartment so that the target object will be set up
782 // correctly before we start wrapping it into other compartments.
783 if (targetCompartmentProxy) {
784 AutoRealm ar(cx, targetCompartmentProxy);
785 JSObject::swap(cx, targetCompartmentProxy, target, oomUnsafe);
786 target.set(targetCompartmentProxy);
787 }
788
789 for (JSObject*& obj : otherProxies) {
790 RootedObject deadWrapper(cx, obj);
791 js::RemapDeadWrapper(cx, deadWrapper, target);
792 }
793 }
794
795 /*
796 * Recompute all cross-compartment wrappers for an object, resetting state.
797 * Gecko uses this to clear Xray wrappers when doing a navigation that reuses
798 * the inner window and global object.
799 */
JS_RefreshCrossCompartmentWrappers(JSContext * cx,HandleObject obj)800 JS_PUBLIC_API bool JS_RefreshCrossCompartmentWrappers(JSContext* cx,
801 HandleObject obj) {
802 return RemapAllWrappersForObject(cx, obj, obj);
803 }
804
805 typedef struct JSStdName {
806 size_t atomOffset; /* offset of atom pointer in JSAtomState */
807 JSProtoKey key;
isDummyJSStdName808 bool isDummy() const { return key == JSProto_Null; }
isSentinelJSStdName809 bool isSentinel() const { return key == JSProto_LIMIT; }
810 } JSStdName;
811
LookupStdName(const JSAtomState & names,JSAtom * name,const JSStdName * table)812 static const JSStdName* LookupStdName(const JSAtomState& names, JSAtom* name,
813 const JSStdName* table) {
814 for (unsigned i = 0; !table[i].isSentinel(); i++) {
815 if (table[i].isDummy()) {
816 continue;
817 }
818 JSAtom* atom = AtomStateOffsetToName(names, table[i].atomOffset);
819 MOZ_ASSERT(atom);
820 if (name == atom) {
821 return &table[i];
822 }
823 }
824
825 return nullptr;
826 }
827
828 /*
829 * Table of standard classes, indexed by JSProtoKey. For entries where the
830 * JSProtoKey does not correspond to a class with a meaningful constructor, we
831 * insert a null entry into the table.
832 */
833 #define STD_NAME_ENTRY(name, clasp) {NAME_OFFSET(name), JSProto_##name},
834 #define STD_DUMMY_ENTRY(name, dummy) {0, JSProto_Null},
835 static const JSStdName standard_class_names[] = {
836 JS_FOR_PROTOTYPES(STD_NAME_ENTRY, STD_DUMMY_ENTRY){0, JSProto_LIMIT}};
837
838 /*
839 * Table of top-level function and constant names and the JSProtoKey of the
840 * standard class that initializes them.
841 */
842 static const JSStdName builtin_property_names[] = {
843 {NAME_OFFSET(eval), JSProto_Object},
844
845 /* Global properties and functions defined by the Number class. */
846 {NAME_OFFSET(NaN), JSProto_Number},
847 {NAME_OFFSET(Infinity), JSProto_Number},
848 {NAME_OFFSET(isNaN), JSProto_Number},
849 {NAME_OFFSET(isFinite), JSProto_Number},
850 {NAME_OFFSET(parseFloat), JSProto_Number},
851 {NAME_OFFSET(parseInt), JSProto_Number},
852
853 /* String global functions. */
854 {NAME_OFFSET(escape), JSProto_String},
855 {NAME_OFFSET(unescape), JSProto_String},
856 {NAME_OFFSET(decodeURI), JSProto_String},
857 {NAME_OFFSET(encodeURI), JSProto_String},
858 {NAME_OFFSET(decodeURIComponent), JSProto_String},
859 {NAME_OFFSET(encodeURIComponent), JSProto_String},
860 {NAME_OFFSET(uneval), JSProto_String},
861
862 {0, JSProto_LIMIT}};
863
SkipUneval(jsid id,JSContext * cx)864 static bool SkipUneval(jsid id, JSContext* cx) {
865 return !cx->realm()->creationOptions().getToSourceEnabled() &&
866 id == NameToId(cx->names().uneval);
867 }
868
SkipSharedArrayBufferConstructor(JSProtoKey key,GlobalObject * global)869 static bool SkipSharedArrayBufferConstructor(JSProtoKey key,
870 GlobalObject* global) {
871 if (key != JSProto_SharedArrayBuffer) {
872 return false;
873 }
874
875 const JS::RealmCreationOptions& options = global->realm()->creationOptions();
876 MOZ_ASSERT(options.getSharedMemoryAndAtomicsEnabled(),
877 "shouldn't contemplate defining SharedArrayBuffer if shared "
878 "memory is disabled");
879
880 // On the web, it isn't presently possible to expose the global
881 // "SharedArrayBuffer" property unless the page is cross-site-isolated. Only
882 // define this constructor if an option on the realm indicates that it should
883 // be defined.
884 return !options.defineSharedArrayBufferConstructor();
885 }
886
JS_ResolveStandardClass(JSContext * cx,HandleObject obj,HandleId id,bool * resolved)887 JS_PUBLIC_API bool JS_ResolveStandardClass(JSContext* cx, HandleObject obj,
888 HandleId id, bool* resolved) {
889 AssertHeapIsIdle();
890 CHECK_THREAD(cx);
891 cx->check(obj, id);
892
893 Handle<GlobalObject*> global = obj.as<GlobalObject>();
894 *resolved = false;
895
896 if (!id.isAtom()) {
897 return true;
898 }
899
900 /* Check whether we're resolving 'undefined', and define it if so. */
901 JSAtom* idAtom = id.toAtom();
902 if (idAtom == cx->names().undefined) {
903 *resolved = true;
904 return js::DefineDataProperty(
905 cx, global, id, UndefinedHandleValue,
906 JSPROP_PERMANENT | JSPROP_READONLY | JSPROP_RESOLVING);
907 }
908
909 // Resolve a "globalThis" self-referential property if necessary.
910 if (idAtom == cx->names().globalThis) {
911 return GlobalObject::maybeResolveGlobalThis(cx, global, resolved);
912 }
913
914 do {
915 // Try for class constructors/prototypes named by well-known atoms.
916 const JSStdName* stdnm =
917 LookupStdName(cx->names(), idAtom, standard_class_names);
918 if (!stdnm) {
919 // Try less frequently used top-level functions and constants.
920 stdnm = LookupStdName(cx->names(), idAtom, builtin_property_names);
921 if (!stdnm) {
922 break;
923 }
924 }
925
926 if (GlobalObject::skipDeselectedConstructor(cx, stdnm->key) ||
927 SkipUneval(id, cx)) {
928 break;
929 }
930
931 if (JSProtoKey key = stdnm->key; key != JSProto_Null) {
932 // If this class is anonymous (or it's "SharedArrayBuffer" but that global
933 // constructor isn't supposed to be defined), then it doesn't exist as a
934 // global property, so we won't resolve anything.
935 const JSClass* clasp = ProtoKeyToClass(key);
936 if ((!clasp || clasp->specShouldDefineConstructor()) &&
937 !SkipSharedArrayBufferConstructor(key, global)) {
938 if (!GlobalObject::ensureConstructor(cx, global, key)) {
939 return false;
940 }
941
942 *resolved = true;
943 return true;
944 }
945 }
946 } while (false);
947
948 // There is no such property to resolve. An ordinary resolve hook would
949 // just return true at this point. But the global object is special in one
950 // more way: its prototype chain is lazily initialized. That is,
951 // global->getProto() might be null right now because we haven't created
952 // Object.prototype yet. Force it now.
953 return GlobalObject::getOrCreateObjectPrototype(cx, global);
954 }
955
JS_MayResolveStandardClass(const JSAtomState & names,jsid id,JSObject * maybeObj)956 JS_PUBLIC_API bool JS_MayResolveStandardClass(const JSAtomState& names, jsid id,
957 JSObject* maybeObj) {
958 MOZ_ASSERT_IF(maybeObj, maybeObj->is<GlobalObject>());
959
960 // The global object's resolve hook is special: JS_ResolveStandardClass
961 // initializes the prototype chain lazily. Only attempt to optimize here
962 // if we know the prototype chain has been initialized.
963 if (!maybeObj || !maybeObj->staticPrototype()) {
964 return true;
965 }
966
967 if (!id.isAtom()) {
968 return false;
969 }
970
971 JSAtom* atom = id.toAtom();
972
973 // This will return true even for deselected constructors. (To do
974 // better, we need a JSContext here; it's fine as it is.)
975
976 return atom == names.undefined || atom == names.globalThis ||
977 LookupStdName(names, atom, standard_class_names) ||
978 LookupStdName(names, atom, builtin_property_names);
979 }
980
JS_EnumerateStandardClasses(JSContext * cx,HandleObject obj)981 JS_PUBLIC_API bool JS_EnumerateStandardClasses(JSContext* cx,
982 HandleObject obj) {
983 AssertHeapIsIdle();
984 CHECK_THREAD(cx);
985 cx->check(obj);
986 Handle<GlobalObject*> global = obj.as<GlobalObject>();
987 return GlobalObject::initStandardClasses(cx, global);
988 }
989
EnumerateStandardClassesInTable(JSContext * cx,Handle<GlobalObject * > global,MutableHandleIdVector properties,const JSStdName * table,bool includeResolved)990 static bool EnumerateStandardClassesInTable(JSContext* cx,
991 Handle<GlobalObject*> global,
992 MutableHandleIdVector properties,
993 const JSStdName* table,
994 bool includeResolved) {
995 for (unsigned i = 0; !table[i].isSentinel(); i++) {
996 if (table[i].isDummy()) {
997 continue;
998 }
999
1000 JSProtoKey key = table[i].key;
1001
1002 // If the standard class has been resolved, the properties have been
1003 // defined on the global so we don't need to add them here.
1004 if (!includeResolved && global->isStandardClassResolved(key)) {
1005 continue;
1006 }
1007
1008 if (GlobalObject::skipDeselectedConstructor(cx, key)) {
1009 continue;
1010 }
1011
1012 if (const JSClass* clasp = ProtoKeyToClass(key)) {
1013 if (!clasp->specShouldDefineConstructor() ||
1014 SkipSharedArrayBufferConstructor(key, global)) {
1015 continue;
1016 }
1017 }
1018
1019 jsid id = NameToId(AtomStateOffsetToName(cx->names(), table[i].atomOffset));
1020
1021 if (SkipUneval(id, cx)) {
1022 continue;
1023 }
1024
1025 if (!properties.append(id)) {
1026 return false;
1027 }
1028 }
1029
1030 return true;
1031 }
1032
EnumerateStandardClasses(JSContext * cx,JS::HandleObject obj,JS::MutableHandleIdVector properties,bool enumerableOnly,bool includeResolved)1033 static bool EnumerateStandardClasses(JSContext* cx, JS::HandleObject obj,
1034 JS::MutableHandleIdVector properties,
1035 bool enumerableOnly,
1036 bool includeResolved) {
1037 if (enumerableOnly) {
1038 // There are no enumerable standard classes and "undefined" is
1039 // not enumerable.
1040 return true;
1041 }
1042
1043 Handle<GlobalObject*> global = obj.as<GlobalObject>();
1044
1045 // It's fine to always append |undefined| here, it's non-configurable and
1046 // the enumeration code filters duplicates.
1047 if (!properties.append(NameToId(cx->names().undefined))) {
1048 return false;
1049 }
1050
1051 bool resolved = false;
1052 if (!GlobalObject::maybeResolveGlobalThis(cx, global, &resolved)) {
1053 return false;
1054 }
1055 if (resolved || includeResolved) {
1056 if (!properties.append(NameToId(cx->names().globalThis))) {
1057 return false;
1058 }
1059 }
1060
1061 if (!EnumerateStandardClassesInTable(cx, global, properties,
1062 standard_class_names, includeResolved)) {
1063 return false;
1064 }
1065 if (!EnumerateStandardClassesInTable(
1066 cx, global, properties, builtin_property_names, includeResolved)) {
1067 return false;
1068 }
1069
1070 return true;
1071 }
1072
JS_NewEnumerateStandardClasses(JSContext * cx,JS::HandleObject obj,JS::MutableHandleIdVector properties,bool enumerableOnly)1073 JS_PUBLIC_API bool JS_NewEnumerateStandardClasses(
1074 JSContext* cx, JS::HandleObject obj, JS::MutableHandleIdVector properties,
1075 bool enumerableOnly) {
1076 return EnumerateStandardClasses(cx, obj, properties, enumerableOnly, false);
1077 }
1078
JS_NewEnumerateStandardClassesIncludingResolved(JSContext * cx,JS::HandleObject obj,JS::MutableHandleIdVector properties,bool enumerableOnly)1079 JS_PUBLIC_API bool JS_NewEnumerateStandardClassesIncludingResolved(
1080 JSContext* cx, JS::HandleObject obj, JS::MutableHandleIdVector properties,
1081 bool enumerableOnly) {
1082 return EnumerateStandardClasses(cx, obj, properties, enumerableOnly, true);
1083 }
1084
JS_GetClassObject(JSContext * cx,JSProtoKey key,MutableHandleObject objp)1085 JS_PUBLIC_API bool JS_GetClassObject(JSContext* cx, JSProtoKey key,
1086 MutableHandleObject objp) {
1087 AssertHeapIsIdle();
1088 CHECK_THREAD(cx);
1089 JSObject* obj = GlobalObject::getOrCreateConstructor(cx, key);
1090 if (!obj) {
1091 return false;
1092 }
1093 objp.set(obj);
1094 return true;
1095 }
1096
JS_GetClassPrototype(JSContext * cx,JSProtoKey key,MutableHandleObject objp)1097 JS_PUBLIC_API bool JS_GetClassPrototype(JSContext* cx, JSProtoKey key,
1098 MutableHandleObject objp) {
1099 AssertHeapIsIdle();
1100 CHECK_THREAD(cx);
1101 JSObject* proto = GlobalObject::getOrCreatePrototype(cx, key);
1102 if (!proto) {
1103 return false;
1104 }
1105 objp.set(proto);
1106 return true;
1107 }
1108
1109 namespace JS {
1110
ProtoKeyToId(JSContext * cx,JSProtoKey key,MutableHandleId idp)1111 JS_PUBLIC_API void ProtoKeyToId(JSContext* cx, JSProtoKey key,
1112 MutableHandleId idp) {
1113 idp.set(NameToId(ClassName(key, cx)));
1114 }
1115
1116 } /* namespace JS */
1117
JS_IdToProtoKey(JSContext * cx,HandleId id)1118 JS_PUBLIC_API JSProtoKey JS_IdToProtoKey(JSContext* cx, HandleId id) {
1119 AssertHeapIsIdle();
1120 CHECK_THREAD(cx);
1121 cx->check(id);
1122
1123 if (!id.isAtom()) {
1124 return JSProto_Null;
1125 }
1126
1127 JSAtom* atom = id.toAtom();
1128 const JSStdName* stdnm =
1129 LookupStdName(cx->names(), atom, standard_class_names);
1130 if (!stdnm) {
1131 return JSProto_Null;
1132 }
1133
1134 if (GlobalObject::skipDeselectedConstructor(cx, stdnm->key)) {
1135 return JSProto_Null;
1136 }
1137
1138 if (SkipSharedArrayBufferConstructor(stdnm->key, cx->global())) {
1139 MOZ_ASSERT(id == NameToId(cx->names().SharedArrayBuffer));
1140 return JSProto_Null;
1141 }
1142
1143 if (SkipUneval(id, cx)) {
1144 return JSProto_Null;
1145 }
1146
1147 static_assert(std::size(standard_class_names) == JSProto_LIMIT + 1);
1148 return static_cast<JSProtoKey>(stdnm - standard_class_names);
1149 }
1150
JS_IsGlobalObject(JSObject * obj)1151 extern JS_PUBLIC_API bool JS_IsGlobalObject(JSObject* obj) {
1152 return obj->is<GlobalObject>();
1153 }
1154
JS_GlobalLexicalEnvironment(JSObject * obj)1155 extern JS_PUBLIC_API JSObject* JS_GlobalLexicalEnvironment(JSObject* obj) {
1156 return &obj->as<GlobalObject>().lexicalEnvironment();
1157 }
1158
JS_HasExtensibleLexicalEnvironment(JSObject * obj)1159 extern JS_PUBLIC_API bool JS_HasExtensibleLexicalEnvironment(JSObject* obj) {
1160 return obj->is<GlobalObject>() ||
1161 ObjectRealm::get(obj).getNonSyntacticLexicalEnvironment(obj);
1162 }
1163
JS_ExtensibleLexicalEnvironment(JSObject * obj)1164 extern JS_PUBLIC_API JSObject* JS_ExtensibleLexicalEnvironment(JSObject* obj) {
1165 return ExtensibleLexicalEnvironmentObject::forVarEnvironment(obj);
1166 }
1167
CurrentGlobalOrNull(JSContext * cx)1168 JS_PUBLIC_API JSObject* JS::CurrentGlobalOrNull(JSContext* cx) {
1169 AssertHeapIsIdleOrIterating();
1170 CHECK_THREAD(cx);
1171 if (!cx->realm()) {
1172 return nullptr;
1173 }
1174 return cx->global();
1175 }
1176
GetNonCCWObjectGlobal(JSObject * obj)1177 JS_PUBLIC_API JSObject* JS::GetNonCCWObjectGlobal(JSObject* obj) {
1178 AssertHeapIsIdleOrIterating();
1179 MOZ_DIAGNOSTIC_ASSERT(!IsCrossCompartmentWrapper(obj));
1180 return &obj->nonCCWGlobal();
1181 }
1182
ComputeThis(JSContext * cx,Value * vp,MutableHandleObject thisObject)1183 JS_PUBLIC_API bool JS::detail::ComputeThis(JSContext* cx, Value* vp,
1184 MutableHandleObject thisObject) {
1185 AssertHeapIsIdle();
1186 cx->check(vp[0], vp[1]);
1187
1188 MutableHandleValue thisv = MutableHandleValue::fromMarkedLocation(&vp[1]);
1189 JSObject* obj = BoxNonStrictThis(cx, thisv);
1190 if (!obj) {
1191 return false;
1192 }
1193
1194 thisObject.set(obj);
1195 return true;
1196 }
1197
1198 static bool gProfileTimelineRecordingEnabled = false;
1199
SetProfileTimelineRecordingEnabled(bool enabled)1200 JS_PUBLIC_API void JS::SetProfileTimelineRecordingEnabled(bool enabled) {
1201 gProfileTimelineRecordingEnabled = enabled;
1202 }
1203
IsProfileTimelineRecordingEnabled()1204 JS_PUBLIC_API bool JS::IsProfileTimelineRecordingEnabled() {
1205 return gProfileTimelineRecordingEnabled;
1206 }
1207
JS_malloc(JSContext * cx,size_t nbytes)1208 JS_PUBLIC_API void* JS_malloc(JSContext* cx, size_t nbytes) {
1209 AssertHeapIsIdle();
1210 CHECK_THREAD(cx);
1211 return static_cast<void*>(cx->maybe_pod_malloc<uint8_t>(nbytes));
1212 }
1213
JS_realloc(JSContext * cx,void * p,size_t oldBytes,size_t newBytes)1214 JS_PUBLIC_API void* JS_realloc(JSContext* cx, void* p, size_t oldBytes,
1215 size_t newBytes) {
1216 AssertHeapIsIdle();
1217 CHECK_THREAD(cx);
1218 return static_cast<void*>(cx->maybe_pod_realloc<uint8_t>(
1219 static_cast<uint8_t*>(p), oldBytes, newBytes));
1220 }
1221
JS_free(JSContext * cx,void * p)1222 JS_PUBLIC_API void JS_free(JSContext* cx, void* p) { return js_free(p); }
1223
JS_string_malloc(JSContext * cx,size_t nbytes)1224 JS_PUBLIC_API void* JS_string_malloc(JSContext* cx, size_t nbytes) {
1225 AssertHeapIsIdle();
1226 CHECK_THREAD(cx);
1227 return static_cast<void*>(
1228 cx->maybe_pod_arena_malloc<uint8_t>(js::StringBufferArena, nbytes));
1229 }
1230
JS_string_realloc(JSContext * cx,void * p,size_t oldBytes,size_t newBytes)1231 JS_PUBLIC_API void* JS_string_realloc(JSContext* cx, void* p, size_t oldBytes,
1232 size_t newBytes) {
1233 AssertHeapIsIdle();
1234 CHECK_THREAD(cx);
1235 return static_cast<void*>(cx->maybe_pod_arena_realloc<uint8_t>(
1236 js::StringBufferArena, static_cast<uint8_t*>(p), oldBytes, newBytes));
1237 }
1238
JS_string_free(JSContext * cx,void * p)1239 JS_PUBLIC_API void JS_string_free(JSContext* cx, void* p) { return js_free(p); }
1240
JS_freeop(JSFreeOp * fop,void * p)1241 JS_PUBLIC_API void JS_freeop(JSFreeOp* fop, void* p) {
1242 return fop->freeUntracked(p);
1243 }
1244
AddAssociatedMemory(JSObject * obj,size_t nbytes,JS::MemoryUse use)1245 JS_PUBLIC_API void JS::AddAssociatedMemory(JSObject* obj, size_t nbytes,
1246 JS::MemoryUse use) {
1247 MOZ_ASSERT(obj);
1248 if (!nbytes) {
1249 return;
1250 }
1251
1252 Zone* zone = obj->zone();
1253 MOZ_ASSERT(!IsInsideNursery(obj));
1254 zone->addCellMemory(obj, nbytes, js::MemoryUse(use));
1255 zone->maybeTriggerGCOnMalloc();
1256 }
1257
RemoveAssociatedMemory(JSObject * obj,size_t nbytes,JS::MemoryUse use)1258 JS_PUBLIC_API void JS::RemoveAssociatedMemory(JSObject* obj, size_t nbytes,
1259 JS::MemoryUse use) {
1260 MOZ_ASSERT(obj);
1261 if (!nbytes) {
1262 return;
1263 }
1264
1265 JSRuntime* rt = obj->runtimeFromAnyThread();
1266 rt->defaultFreeOp()->removeCellMemory(obj, nbytes, js::MemoryUse(use));
1267 }
1268
1269 #undef JS_AddRoot
1270
JS_AddExtraGCRootsTracer(JSContext * cx,JSTraceDataOp traceOp,void * data)1271 JS_PUBLIC_API bool JS_AddExtraGCRootsTracer(JSContext* cx,
1272 JSTraceDataOp traceOp, void* data) {
1273 return cx->runtime()->gc.addBlackRootsTracer(traceOp, data);
1274 }
1275
JS_RemoveExtraGCRootsTracer(JSContext * cx,JSTraceDataOp traceOp,void * data)1276 JS_PUBLIC_API void JS_RemoveExtraGCRootsTracer(JSContext* cx,
1277 JSTraceDataOp traceOp,
1278 void* data) {
1279 return cx->runtime()->gc.removeBlackRootsTracer(traceOp, data);
1280 }
1281
IsIdleGCTaskNeeded(JSRuntime * rt)1282 JS_PUBLIC_API bool JS::IsIdleGCTaskNeeded(JSRuntime* rt) {
1283 // Currently, we only collect nursery during idle time.
1284 return rt->gc.nursery().shouldCollect();
1285 }
1286
RunIdleTimeGCTask(JSRuntime * rt)1287 JS_PUBLIC_API void JS::RunIdleTimeGCTask(JSRuntime* rt) {
1288 gc::GCRuntime& gc = rt->gc;
1289 if (gc.nursery().shouldCollect()) {
1290 gc.minorGC(JS::GCReason::IDLE_TIME_COLLECTION);
1291 }
1292 }
1293
JS_GC(JSContext * cx,JS::GCReason reason)1294 JS_PUBLIC_API void JS_GC(JSContext* cx, JS::GCReason reason) {
1295 AssertHeapIsIdle();
1296 JS::PrepareForFullGC(cx);
1297 cx->runtime()->gc.gc(JS::GCOptions::Normal, reason);
1298 }
1299
JS_MaybeGC(JSContext * cx)1300 JS_PUBLIC_API void JS_MaybeGC(JSContext* cx) {
1301 AssertHeapIsIdle();
1302 cx->runtime()->gc.maybeGC();
1303 }
1304
JS_SetGCCallback(JSContext * cx,JSGCCallback cb,void * data)1305 JS_PUBLIC_API void JS_SetGCCallback(JSContext* cx, JSGCCallback cb,
1306 void* data) {
1307 AssertHeapIsIdle();
1308 cx->runtime()->gc.setGCCallback(cb, data);
1309 }
1310
JS_SetObjectsTenuredCallback(JSContext * cx,JSObjectsTenuredCallback cb,void * data)1311 JS_PUBLIC_API void JS_SetObjectsTenuredCallback(JSContext* cx,
1312 JSObjectsTenuredCallback cb,
1313 void* data) {
1314 AssertHeapIsIdle();
1315 cx->runtime()->gc.setObjectsTenuredCallback(cb, data);
1316 }
1317
JS_AddFinalizeCallback(JSContext * cx,JSFinalizeCallback cb,void * data)1318 JS_PUBLIC_API bool JS_AddFinalizeCallback(JSContext* cx, JSFinalizeCallback cb,
1319 void* data) {
1320 AssertHeapIsIdle();
1321 return cx->runtime()->gc.addFinalizeCallback(cb, data);
1322 }
1323
JS_RemoveFinalizeCallback(JSContext * cx,JSFinalizeCallback cb)1324 JS_PUBLIC_API void JS_RemoveFinalizeCallback(JSContext* cx,
1325 JSFinalizeCallback cb) {
1326 cx->runtime()->gc.removeFinalizeCallback(cb);
1327 }
1328
SetHostCleanupFinalizationRegistryCallback(JSContext * cx,JSHostCleanupFinalizationRegistryCallback cb,void * data)1329 JS_PUBLIC_API void JS::SetHostCleanupFinalizationRegistryCallback(
1330 JSContext* cx, JSHostCleanupFinalizationRegistryCallback cb, void* data) {
1331 AssertHeapIsIdle();
1332 cx->runtime()->gc.setHostCleanupFinalizationRegistryCallback(cb, data);
1333 }
1334
ClearKeptObjects(JSContext * cx)1335 JS_PUBLIC_API void JS::ClearKeptObjects(JSContext* cx) {
1336 gc::GCRuntime* gc = &cx->runtime()->gc;
1337
1338 for (ZonesIter zone(gc, ZoneSelector::WithAtoms); !zone.done(); zone.next()) {
1339 zone->clearKeptObjects();
1340 }
1341 }
1342
AtomsZoneIsCollecting(JSRuntime * runtime)1343 JS_PUBLIC_API bool JS::AtomsZoneIsCollecting(JSRuntime* runtime) {
1344 return runtime->activeGCInAtomsZone();
1345 }
1346
IsAtomsZone(JS::Zone * zone)1347 JS_PUBLIC_API bool JS::IsAtomsZone(JS::Zone* zone) {
1348 return zone->isAtomsZone();
1349 }
1350
JS_AddWeakPointerZonesCallback(JSContext * cx,JSWeakPointerZonesCallback cb,void * data)1351 JS_PUBLIC_API bool JS_AddWeakPointerZonesCallback(JSContext* cx,
1352 JSWeakPointerZonesCallback cb,
1353 void* data) {
1354 AssertHeapIsIdle();
1355 return cx->runtime()->gc.addWeakPointerZonesCallback(cb, data);
1356 }
1357
JS_RemoveWeakPointerZonesCallback(JSContext * cx,JSWeakPointerZonesCallback cb)1358 JS_PUBLIC_API void JS_RemoveWeakPointerZonesCallback(
1359 JSContext* cx, JSWeakPointerZonesCallback cb) {
1360 cx->runtime()->gc.removeWeakPointerZonesCallback(cb);
1361 }
1362
JS_AddWeakPointerCompartmentCallback(JSContext * cx,JSWeakPointerCompartmentCallback cb,void * data)1363 JS_PUBLIC_API bool JS_AddWeakPointerCompartmentCallback(
1364 JSContext* cx, JSWeakPointerCompartmentCallback cb, void* data) {
1365 AssertHeapIsIdle();
1366 return cx->runtime()->gc.addWeakPointerCompartmentCallback(cb, data);
1367 }
1368
JS_RemoveWeakPointerCompartmentCallback(JSContext * cx,JSWeakPointerCompartmentCallback cb)1369 JS_PUBLIC_API void JS_RemoveWeakPointerCompartmentCallback(
1370 JSContext* cx, JSWeakPointerCompartmentCallback cb) {
1371 cx->runtime()->gc.removeWeakPointerCompartmentCallback(cb);
1372 }
1373
JS_UpdateWeakPointerAfterGC(JSTracer * trc,JS::Heap<JSObject * > * objp)1374 JS_PUBLIC_API bool JS_UpdateWeakPointerAfterGC(JSTracer* trc,
1375 JS::Heap<JSObject*>* objp) {
1376 return TraceWeakEdge(trc, objp);
1377 }
1378
JS_UpdateWeakPointerAfterGCUnbarriered(JSTracer * trc,JSObject ** objp)1379 JS_PUBLIC_API bool JS_UpdateWeakPointerAfterGCUnbarriered(JSTracer* trc,
1380 JSObject** objp) {
1381 return TraceManuallyBarrieredWeakEdge(trc, objp, "External weak pointer");
1382 }
1383
JS_SetGCParameter(JSContext * cx,JSGCParamKey key,uint32_t value)1384 JS_PUBLIC_API void JS_SetGCParameter(JSContext* cx, JSGCParamKey key,
1385 uint32_t value) {
1386 MOZ_ALWAYS_TRUE(cx->runtime()->gc.setParameter(key, value));
1387 }
1388
JS_ResetGCParameter(JSContext * cx,JSGCParamKey key)1389 JS_PUBLIC_API void JS_ResetGCParameter(JSContext* cx, JSGCParamKey key) {
1390 cx->runtime()->gc.resetParameter(key);
1391 }
1392
JS_GetGCParameter(JSContext * cx,JSGCParamKey key)1393 JS_PUBLIC_API uint32_t JS_GetGCParameter(JSContext* cx, JSGCParamKey key) {
1394 return cx->runtime()->gc.getParameter(key);
1395 }
1396
JS_SetGCParametersBasedOnAvailableMemory(JSContext * cx,uint32_t availMemMB)1397 JS_PUBLIC_API void JS_SetGCParametersBasedOnAvailableMemory(
1398 JSContext* cx, uint32_t availMemMB) {
1399 struct JSGCConfig {
1400 JSGCParamKey key;
1401 uint32_t value;
1402 };
1403
1404 static const JSGCConfig minimal[] = {
1405 {JSGC_SLICE_TIME_BUDGET_MS, 5},
1406 {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
1407 {JSGC_LARGE_HEAP_SIZE_MIN, 250},
1408 {JSGC_SMALL_HEAP_SIZE_MAX, 50},
1409 {JSGC_HIGH_FREQUENCY_SMALL_HEAP_GROWTH, 300},
1410 {JSGC_HIGH_FREQUENCY_LARGE_HEAP_GROWTH, 120},
1411 {JSGC_LOW_FREQUENCY_HEAP_GROWTH, 120},
1412 {JSGC_ALLOCATION_THRESHOLD, 15},
1413 {JSGC_MALLOC_THRESHOLD_BASE, 20},
1414 {JSGC_SMALL_HEAP_INCREMENTAL_LIMIT, 200},
1415 {JSGC_LARGE_HEAP_INCREMENTAL_LIMIT, 110},
1416 {JSGC_URGENT_THRESHOLD_MB, 8}};
1417
1418 static const JSGCConfig nominal[] = {
1419 {JSGC_SLICE_TIME_BUDGET_MS, 5},
1420 {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1000},
1421 {JSGC_LARGE_HEAP_SIZE_MIN, 500},
1422 {JSGC_SMALL_HEAP_SIZE_MAX, 100},
1423 {JSGC_HIGH_FREQUENCY_SMALL_HEAP_GROWTH, 300},
1424 {JSGC_HIGH_FREQUENCY_LARGE_HEAP_GROWTH, 150},
1425 {JSGC_LOW_FREQUENCY_HEAP_GROWTH, 150},
1426 {JSGC_ALLOCATION_THRESHOLD, 27},
1427 {JSGC_MALLOC_THRESHOLD_BASE, 38},
1428 {JSGC_SMALL_HEAP_INCREMENTAL_LIMIT, 140},
1429 {JSGC_LARGE_HEAP_INCREMENTAL_LIMIT, 110},
1430 {JSGC_URGENT_THRESHOLD_MB, 16}};
1431
1432 const auto& configSet = availMemMB > 512 ? nominal : minimal;
1433 for (const auto& config : configSet) {
1434 JS_SetGCParameter(cx, config.key, config.value);
1435 }
1436 }
1437
JS_NewExternalString(JSContext * cx,const char16_t * chars,size_t length,const JSExternalStringCallbacks * callbacks)1438 JS_PUBLIC_API JSString* JS_NewExternalString(
1439 JSContext* cx, const char16_t* chars, size_t length,
1440 const JSExternalStringCallbacks* callbacks) {
1441 AssertHeapIsIdle();
1442 CHECK_THREAD(cx);
1443 return JSExternalString::new_(cx, chars, length, callbacks);
1444 }
1445
JS_NewMaybeExternalString(JSContext * cx,const char16_t * chars,size_t length,const JSExternalStringCallbacks * callbacks,bool * allocatedExternal)1446 JS_PUBLIC_API JSString* JS_NewMaybeExternalString(
1447 JSContext* cx, const char16_t* chars, size_t length,
1448 const JSExternalStringCallbacks* callbacks, bool* allocatedExternal) {
1449 AssertHeapIsIdle();
1450 CHECK_THREAD(cx);
1451 return NewMaybeExternalString(cx, chars, length, callbacks,
1452 allocatedExternal);
1453 }
1454
1455 extern JS_PUBLIC_API const JSExternalStringCallbacks*
JS_GetExternalStringCallbacks(JSString * str)1456 JS_GetExternalStringCallbacks(JSString* str) {
1457 return str->asExternal().callbacks();
1458 }
1459
SetNativeStackLimit(JSContext * cx,JS::StackKind kind,size_t stackSize)1460 static void SetNativeStackLimit(JSContext* cx, JS::StackKind kind,
1461 size_t stackSize) {
1462 #ifdef __wasi__
1463 // WASI makes this easy: we build with the "stack-first" wasm-ld option, so
1464 // the stack grows downward toward zero. Let's set a limit just a bit above
1465 // this so that we catch an overflow before a Wasm trap occurs.
1466 cx->nativeStackLimit[kind] = 1024;
1467 #else // __wasi__
1468 # if JS_STACK_GROWTH_DIRECTION > 0
1469 if (stackSize == 0) {
1470 cx->nativeStackLimit[kind] = UINTPTR_MAX;
1471 } else {
1472 MOZ_ASSERT(cx->nativeStackBase() <= size_t(-1) - stackSize);
1473 cx->nativeStackLimit[kind] = cx->nativeStackBase() + stackSize - 1;
1474 }
1475 # else // stack grows up
1476 if (stackSize == 0) {
1477 cx->nativeStackLimit[kind] = 0;
1478 } else {
1479 MOZ_ASSERT(cx->nativeStackBase() >= stackSize);
1480 cx->nativeStackLimit[kind] = cx->nativeStackBase() - (stackSize - 1);
1481 }
1482 # endif // stack grows down
1483 #endif // !__wasi__
1484 }
1485
JS_SetNativeStackQuota(JSContext * cx,size_t systemCodeStackSize,size_t trustedScriptStackSize,size_t untrustedScriptStackSize)1486 JS_PUBLIC_API void JS_SetNativeStackQuota(JSContext* cx,
1487 size_t systemCodeStackSize,
1488 size_t trustedScriptStackSize,
1489 size_t untrustedScriptStackSize) {
1490 MOZ_ASSERT(!cx->activation());
1491
1492 if (!trustedScriptStackSize) {
1493 trustedScriptStackSize = systemCodeStackSize;
1494 } else {
1495 MOZ_ASSERT(trustedScriptStackSize < systemCodeStackSize);
1496 }
1497
1498 if (!untrustedScriptStackSize) {
1499 untrustedScriptStackSize = trustedScriptStackSize;
1500 } else {
1501 MOZ_ASSERT(untrustedScriptStackSize < trustedScriptStackSize);
1502 }
1503
1504 SetNativeStackLimit(cx, JS::StackForSystemCode, systemCodeStackSize);
1505 SetNativeStackLimit(cx, JS::StackForTrustedScript, trustedScriptStackSize);
1506 SetNativeStackLimit(cx, JS::StackForUntrustedScript,
1507 untrustedScriptStackSize);
1508
1509 if (cx->isMainThreadContext()) {
1510 cx->initJitStackLimit();
1511 }
1512 }
1513
1514 /************************************************************************/
1515
JS_ValueToId(JSContext * cx,HandleValue value,MutableHandleId idp)1516 JS_PUBLIC_API bool JS_ValueToId(JSContext* cx, HandleValue value,
1517 MutableHandleId idp) {
1518 AssertHeapIsIdle();
1519 CHECK_THREAD(cx);
1520 cx->check(value);
1521 return ToPropertyKey(cx, value, idp);
1522 }
1523
JS_StringToId(JSContext * cx,HandleString string,MutableHandleId idp)1524 JS_PUBLIC_API bool JS_StringToId(JSContext* cx, HandleString string,
1525 MutableHandleId idp) {
1526 AssertHeapIsIdle();
1527 CHECK_THREAD(cx);
1528 cx->check(string);
1529 RootedValue value(cx, StringValue(string));
1530 return PrimitiveValueToId<CanGC>(cx, value, idp);
1531 }
1532
JS_IdToValue(JSContext * cx,jsid id,MutableHandleValue vp)1533 JS_PUBLIC_API bool JS_IdToValue(JSContext* cx, jsid id, MutableHandleValue vp) {
1534 AssertHeapIsIdle();
1535 CHECK_THREAD(cx);
1536 cx->check(id);
1537 vp.set(IdToValue(id));
1538 cx->check(vp);
1539 return true;
1540 }
1541
ToPrimitive(JSContext * cx,HandleObject obj,JSType hint,MutableHandleValue vp)1542 JS_PUBLIC_API bool JS::ToPrimitive(JSContext* cx, HandleObject obj, JSType hint,
1543 MutableHandleValue vp) {
1544 AssertHeapIsIdle();
1545 CHECK_THREAD(cx);
1546 cx->check(obj);
1547 MOZ_ASSERT(obj != nullptr);
1548 MOZ_ASSERT(hint == JSTYPE_UNDEFINED || hint == JSTYPE_STRING ||
1549 hint == JSTYPE_NUMBER);
1550 vp.setObject(*obj);
1551 return ToPrimitiveSlow(cx, hint, vp);
1552 }
1553
GetFirstArgumentAsTypeHint(JSContext * cx,CallArgs args,JSType * result)1554 JS_PUBLIC_API bool JS::GetFirstArgumentAsTypeHint(JSContext* cx, CallArgs args,
1555 JSType* result) {
1556 if (!args.get(0).isString()) {
1557 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1558 JSMSG_NOT_EXPECTED_TYPE, "Symbol.toPrimitive",
1559 "\"string\", \"number\", or \"default\"",
1560 InformalValueTypeName(args.get(0)));
1561 return false;
1562 }
1563
1564 RootedString str(cx, args.get(0).toString());
1565 bool match;
1566
1567 if (!EqualStrings(cx, str, cx->names().default_, &match)) {
1568 return false;
1569 }
1570 if (match) {
1571 *result = JSTYPE_UNDEFINED;
1572 return true;
1573 }
1574
1575 if (!EqualStrings(cx, str, cx->names().string, &match)) {
1576 return false;
1577 }
1578 if (match) {
1579 *result = JSTYPE_STRING;
1580 return true;
1581 }
1582
1583 if (!EqualStrings(cx, str, cx->names().number, &match)) {
1584 return false;
1585 }
1586 if (match) {
1587 *result = JSTYPE_NUMBER;
1588 return true;
1589 }
1590
1591 UniqueChars bytes;
1592 const char* source = ValueToSourceForError(cx, args.get(0), bytes);
1593 if (!source) {
1594 ReportOutOfMemory(cx);
1595 return false;
1596 }
1597
1598 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
1599 JSMSG_NOT_EXPECTED_TYPE, "Symbol.toPrimitive",
1600 "\"string\", \"number\", or \"default\"", source);
1601 return false;
1602 }
1603
JS_InitClass(JSContext * cx,HandleObject obj,HandleObject parent_proto,const JSClass * clasp,JSNative constructor,unsigned nargs,const JSPropertySpec * ps,const JSFunctionSpec * fs,const JSPropertySpec * static_ps,const JSFunctionSpec * static_fs)1604 JS_PUBLIC_API JSObject* JS_InitClass(JSContext* cx, HandleObject obj,
1605 HandleObject parent_proto,
1606 const JSClass* clasp, JSNative constructor,
1607 unsigned nargs, const JSPropertySpec* ps,
1608 const JSFunctionSpec* fs,
1609 const JSPropertySpec* static_ps,
1610 const JSFunctionSpec* static_fs) {
1611 AssertHeapIsIdle();
1612 CHECK_THREAD(cx);
1613 cx->check(obj, parent_proto);
1614 return InitClass(cx, obj, parent_proto, clasp, constructor, nargs, ps, fs,
1615 static_ps, static_fs);
1616 }
1617
JS_LinkConstructorAndPrototype(JSContext * cx,HandleObject ctor,HandleObject proto)1618 JS_PUBLIC_API bool JS_LinkConstructorAndPrototype(JSContext* cx,
1619 HandleObject ctor,
1620 HandleObject proto) {
1621 return LinkConstructorAndPrototype(cx, ctor, proto);
1622 }
1623
JS_InstanceOf(JSContext * cx,HandleObject obj,const JSClass * clasp,CallArgs * args)1624 JS_PUBLIC_API bool JS_InstanceOf(JSContext* cx, HandleObject obj,
1625 const JSClass* clasp, CallArgs* args) {
1626 AssertHeapIsIdle();
1627 CHECK_THREAD(cx);
1628 #ifdef DEBUG
1629 if (args) {
1630 cx->check(obj);
1631 cx->check(args->thisv(), args->calleev());
1632 }
1633 #endif
1634 if (!obj || obj->getClass() != clasp) {
1635 if (args) {
1636 ReportIncompatibleMethod(cx, *args, clasp);
1637 }
1638 return false;
1639 }
1640 return true;
1641 }
1642
JS_HasInstance(JSContext * cx,HandleObject obj,HandleValue value,bool * bp)1643 JS_PUBLIC_API bool JS_HasInstance(JSContext* cx, HandleObject obj,
1644 HandleValue value, bool* bp) {
1645 AssertHeapIsIdle();
1646 cx->check(obj, value);
1647 return HasInstance(cx, obj, value, bp);
1648 }
1649
JS_GetConstructor(JSContext * cx,HandleObject proto)1650 JS_PUBLIC_API JSObject* JS_GetConstructor(JSContext* cx, HandleObject proto) {
1651 AssertHeapIsIdle();
1652 CHECK_THREAD(cx);
1653 cx->check(proto);
1654
1655 RootedValue cval(cx);
1656 if (!GetProperty(cx, proto, proto, cx->names().constructor, &cval)) {
1657 return nullptr;
1658 }
1659 if (!IsFunctionObject(cval)) {
1660 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1661 JSMSG_NO_CONSTRUCTOR, proto->getClass()->name);
1662 return nullptr;
1663 }
1664 return &cval.toObject();
1665 }
1666
1667 JS::RealmCreationOptions&
setNewCompartmentInSystemZone()1668 JS::RealmCreationOptions::setNewCompartmentInSystemZone() {
1669 compSpec_ = CompartmentSpecifier::NewCompartmentInSystemZone;
1670 comp_ = nullptr;
1671 return *this;
1672 }
1673
1674 JS::RealmCreationOptions&
setNewCompartmentInExistingZone(JSObject * obj)1675 JS::RealmCreationOptions::setNewCompartmentInExistingZone(JSObject* obj) {
1676 compSpec_ = CompartmentSpecifier::NewCompartmentInExistingZone;
1677 zone_ = obj->zone();
1678 return *this;
1679 }
1680
setExistingCompartment(JSObject * obj)1681 JS::RealmCreationOptions& JS::RealmCreationOptions::setExistingCompartment(
1682 JSObject* obj) {
1683 compSpec_ = CompartmentSpecifier::ExistingCompartment;
1684 comp_ = obj->compartment();
1685 return *this;
1686 }
1687
setExistingCompartment(JS::Compartment * compartment)1688 JS::RealmCreationOptions& JS::RealmCreationOptions::setExistingCompartment(
1689 JS::Compartment* compartment) {
1690 compSpec_ = CompartmentSpecifier::ExistingCompartment;
1691 comp_ = compartment;
1692 return *this;
1693 }
1694
setNewCompartmentAndZone()1695 JS::RealmCreationOptions& JS::RealmCreationOptions::setNewCompartmentAndZone() {
1696 compSpec_ = CompartmentSpecifier::NewCompartmentAndZone;
1697 comp_ = nullptr;
1698 return *this;
1699 }
1700
RealmCreationOptionsRef(Realm * realm)1701 const JS::RealmCreationOptions& JS::RealmCreationOptionsRef(Realm* realm) {
1702 return realm->creationOptions();
1703 }
1704
RealmCreationOptionsRef(JSContext * cx)1705 const JS::RealmCreationOptions& JS::RealmCreationOptionsRef(JSContext* cx) {
1706 return cx->realm()->creationOptions();
1707 }
1708
getSharedMemoryAndAtomicsEnabled() const1709 bool JS::RealmCreationOptions::getSharedMemoryAndAtomicsEnabled() const {
1710 return sharedMemoryAndAtomics_;
1711 }
1712
1713 JS::RealmCreationOptions&
setSharedMemoryAndAtomicsEnabled(bool flag)1714 JS::RealmCreationOptions::setSharedMemoryAndAtomicsEnabled(bool flag) {
1715 sharedMemoryAndAtomics_ = flag;
1716 return *this;
1717 }
1718
getCoopAndCoepEnabled() const1719 bool JS::RealmCreationOptions::getCoopAndCoepEnabled() const {
1720 return coopAndCoep_;
1721 }
1722
setCoopAndCoepEnabled(bool flag)1723 JS::RealmCreationOptions& JS::RealmCreationOptions::setCoopAndCoepEnabled(
1724 bool flag) {
1725 coopAndCoep_ = flag;
1726 return *this;
1727 }
1728
RealmBehaviorsRef(JS::Realm * realm)1729 const JS::RealmBehaviors& JS::RealmBehaviorsRef(JS::Realm* realm) {
1730 return realm->behaviors();
1731 }
1732
RealmBehaviorsRef(JSContext * cx)1733 const JS::RealmBehaviors& JS::RealmBehaviorsRef(JSContext* cx) {
1734 return cx->realm()->behaviors();
1735 }
1736
SetRealmNonLive(Realm * realm)1737 void JS::SetRealmNonLive(Realm* realm) { realm->setNonLive(); }
1738
JS_NewGlobalObject(JSContext * cx,const JSClass * clasp,JSPrincipals * principals,JS::OnNewGlobalHookOption hookOption,const JS::RealmOptions & options)1739 JS_PUBLIC_API JSObject* JS_NewGlobalObject(JSContext* cx, const JSClass* clasp,
1740 JSPrincipals* principals,
1741 JS::OnNewGlobalHookOption hookOption,
1742 const JS::RealmOptions& options) {
1743 MOZ_RELEASE_ASSERT(
1744 cx->runtime()->hasInitializedSelfHosting(),
1745 "Must call JS::InitSelfHostedCode() before creating a global");
1746
1747 AssertHeapIsIdle();
1748 CHECK_THREAD(cx);
1749
1750 return GlobalObject::new_(cx, clasp, principals, hookOption, options);
1751 }
1752
JS_GlobalObjectTraceHook(JSTracer * trc,JSObject * global)1753 JS_PUBLIC_API void JS_GlobalObjectTraceHook(JSTracer* trc, JSObject* global) {
1754 GlobalObject* globalObj = &global->as<GlobalObject>();
1755 Realm* globalRealm = globalObj->realm();
1756
1757 // If we GC when creating the global, we may not have set that global's
1758 // realm's global pointer yet. In this case, the realm will not yet contain
1759 // anything that needs to be traced.
1760 if (globalRealm->unsafeUnbarrieredMaybeGlobal() != globalObj) {
1761 return;
1762 }
1763
1764 // Trace the realm for any GC things that should only stick around if we
1765 // know the global is live.
1766 globalRealm->traceGlobalData(trc);
1767
1768 globalObj->traceData(trc, globalObj);
1769
1770 if (JSTraceOp trace = globalRealm->creationOptions().getTrace()) {
1771 trace(trc, global);
1772 }
1773 }
1774
1775 const JSClassOps JS::DefaultGlobalClassOps = {
1776 nullptr, // addProperty
1777 nullptr, // delProperty
1778 nullptr, // enumerate
1779 JS_NewEnumerateStandardClasses, // newEnumerate
1780 JS_ResolveStandardClass, // resolve
1781 JS_MayResolveStandardClass, // mayResolve
1782 nullptr, // finalize
1783 nullptr, // call
1784 nullptr, // hasInstance
1785 nullptr, // construct
1786 JS_GlobalObjectTraceHook, // trace
1787 };
1788
JS_FireOnNewGlobalObject(JSContext * cx,JS::HandleObject global)1789 JS_PUBLIC_API void JS_FireOnNewGlobalObject(JSContext* cx,
1790 JS::HandleObject global) {
1791 // This hook is infallible, because we don't really want arbitrary script
1792 // to be able to throw errors during delicate global creation routines.
1793 // This infallibility will eat OOM and slow script, but if that happens
1794 // we'll likely run up into them again soon in a fallible context.
1795 cx->check(global);
1796 Rooted<js::GlobalObject*> globalObject(cx, &global->as<GlobalObject>());
1797 DebugAPI::onNewGlobalObject(cx, globalObject);
1798 cx->runtime()->ensureRealmIsRecordingAllocations(globalObject);
1799 }
1800
JS_NewObject(JSContext * cx,const JSClass * clasp)1801 JS_PUBLIC_API JSObject* JS_NewObject(JSContext* cx, const JSClass* clasp) {
1802 MOZ_ASSERT(!cx->zone()->isAtomsZone());
1803 AssertHeapIsIdle();
1804 CHECK_THREAD(cx);
1805
1806 if (!clasp) {
1807 // Default class is Object.
1808 return NewPlainObject(cx);
1809 }
1810
1811 MOZ_ASSERT(!clasp->isJSFunction());
1812 MOZ_ASSERT(clasp != &PlainObject::class_);
1813 MOZ_ASSERT(!(clasp->flags & JSCLASS_IS_GLOBAL));
1814
1815 return NewBuiltinClassInstance(cx, clasp);
1816 }
1817
JS_NewObjectWithGivenProto(JSContext * cx,const JSClass * clasp,HandleObject proto)1818 JS_PUBLIC_API JSObject* JS_NewObjectWithGivenProto(JSContext* cx,
1819 const JSClass* clasp,
1820 HandleObject proto) {
1821 MOZ_ASSERT(!cx->zone()->isAtomsZone());
1822 AssertHeapIsIdle();
1823 CHECK_THREAD(cx);
1824 cx->check(proto);
1825
1826 if (!clasp) {
1827 // Default class is Object.
1828 return NewPlainObjectWithProto(cx, proto);
1829 }
1830
1831 MOZ_ASSERT(!clasp->isJSFunction());
1832 MOZ_ASSERT(clasp != &PlainObject::class_);
1833 MOZ_ASSERT(!(clasp->flags & JSCLASS_IS_GLOBAL));
1834
1835 return NewObjectWithGivenProto(cx, clasp, proto);
1836 }
1837
JS_NewPlainObject(JSContext * cx)1838 JS_PUBLIC_API JSObject* JS_NewPlainObject(JSContext* cx) {
1839 MOZ_ASSERT(!cx->zone()->isAtomsZone());
1840 AssertHeapIsIdle();
1841 CHECK_THREAD(cx);
1842
1843 return NewPlainObject(cx);
1844 }
1845
JS_NewObjectForConstructor(JSContext * cx,const JSClass * clasp,const CallArgs & args)1846 JS_PUBLIC_API JSObject* JS_NewObjectForConstructor(JSContext* cx,
1847 const JSClass* clasp,
1848 const CallArgs& args) {
1849 AssertHeapIsIdle();
1850 CHECK_THREAD(cx);
1851
1852 if (!ThrowIfNotConstructing(cx, args, clasp->name)) {
1853 return nullptr;
1854 }
1855
1856 RootedObject newTarget(cx, &args.newTarget().toObject());
1857 cx->check(newTarget);
1858 return CreateThis(cx, clasp, newTarget);
1859 }
1860
JS_IsNative(JSObject * obj)1861 JS_PUBLIC_API bool JS_IsNative(JSObject* obj) {
1862 return obj->is<NativeObject>();
1863 }
1864
AssertObjectBelongsToCurrentThread(JSObject * obj)1865 JS_PUBLIC_API void JS::AssertObjectBelongsToCurrentThread(JSObject* obj) {
1866 JSRuntime* rt = obj->compartment()->runtimeFromAnyThread();
1867 MOZ_RELEASE_ASSERT(CurrentThreadCanAccessRuntime(rt));
1868 }
1869
SetFilenameValidationCallback(JS::FilenameValidationCallback cb)1870 JS_PUBLIC_API void JS::SetFilenameValidationCallback(
1871 JS::FilenameValidationCallback cb) {
1872 js::gFilenameValidationCallback = cb;
1873 }
1874
1875 /*** Standard internal methods **********************************************/
1876
JS_GetPrototype(JSContext * cx,HandleObject obj,MutableHandleObject result)1877 JS_PUBLIC_API bool JS_GetPrototype(JSContext* cx, HandleObject obj,
1878 MutableHandleObject result) {
1879 cx->check(obj);
1880 return GetPrototype(cx, obj, result);
1881 }
1882
JS_SetPrototype(JSContext * cx,HandleObject obj,HandleObject proto)1883 JS_PUBLIC_API bool JS_SetPrototype(JSContext* cx, HandleObject obj,
1884 HandleObject proto) {
1885 AssertHeapIsIdle();
1886 CHECK_THREAD(cx);
1887 cx->check(obj, proto);
1888
1889 return SetPrototype(cx, obj, proto);
1890 }
1891
JS_GetPrototypeIfOrdinary(JSContext * cx,HandleObject obj,bool * isOrdinary,MutableHandleObject result)1892 JS_PUBLIC_API bool JS_GetPrototypeIfOrdinary(JSContext* cx, HandleObject obj,
1893 bool* isOrdinary,
1894 MutableHandleObject result) {
1895 cx->check(obj);
1896 return GetPrototypeIfOrdinary(cx, obj, isOrdinary, result);
1897 }
1898
JS_IsExtensible(JSContext * cx,HandleObject obj,bool * extensible)1899 JS_PUBLIC_API bool JS_IsExtensible(JSContext* cx, HandleObject obj,
1900 bool* extensible) {
1901 cx->check(obj);
1902 return IsExtensible(cx, obj, extensible);
1903 }
1904
JS_PreventExtensions(JSContext * cx,JS::HandleObject obj,ObjectOpResult & result)1905 JS_PUBLIC_API bool JS_PreventExtensions(JSContext* cx, JS::HandleObject obj,
1906 ObjectOpResult& result) {
1907 cx->check(obj);
1908 return PreventExtensions(cx, obj, result);
1909 }
1910
JS_SetImmutablePrototype(JSContext * cx,JS::HandleObject obj,bool * succeeded)1911 JS_PUBLIC_API bool JS_SetImmutablePrototype(JSContext* cx, JS::HandleObject obj,
1912 bool* succeeded) {
1913 cx->check(obj);
1914 return SetImmutablePrototype(cx, obj, succeeded);
1915 }
1916
1917 /* * */
1918
JS_FreezeObject(JSContext * cx,HandleObject obj)1919 JS_PUBLIC_API bool JS_FreezeObject(JSContext* cx, HandleObject obj) {
1920 AssertHeapIsIdle();
1921 CHECK_THREAD(cx);
1922 cx->check(obj);
1923 return FreezeObject(cx, obj);
1924 }
1925
DeepFreezeSlot(JSContext * cx,const Value & v)1926 static bool DeepFreezeSlot(JSContext* cx, const Value& v) {
1927 if (v.isPrimitive()) {
1928 return true;
1929 }
1930 RootedObject obj(cx, &v.toObject());
1931 return JS_DeepFreezeObject(cx, obj);
1932 }
1933
JS_DeepFreezeObject(JSContext * cx,HandleObject obj)1934 JS_PUBLIC_API bool JS_DeepFreezeObject(JSContext* cx, HandleObject obj) {
1935 AssertHeapIsIdle();
1936 CHECK_THREAD(cx);
1937 cx->check(obj);
1938
1939 // Assume that non-extensible objects are already deep-frozen, to avoid
1940 // divergence.
1941 bool extensible;
1942 if (!IsExtensible(cx, obj, &extensible)) {
1943 return false;
1944 }
1945 if (!extensible) {
1946 return true;
1947 }
1948
1949 if (!FreezeObject(cx, obj)) {
1950 return false;
1951 }
1952
1953 // Walk slots in obj and if any value is a non-null object, seal it.
1954 if (obj->is<NativeObject>()) {
1955 RootedNativeObject nobj(cx, &obj->as<NativeObject>());
1956 for (uint32_t i = 0, n = nobj->slotSpan(); i < n; ++i) {
1957 if (!DeepFreezeSlot(cx, nobj->getSlot(i))) {
1958 return false;
1959 }
1960 }
1961 for (uint32_t i = 0, n = nobj->getDenseInitializedLength(); i < n; ++i) {
1962 if (!DeepFreezeSlot(cx, nobj->getDenseElement(i))) {
1963 return false;
1964 }
1965 }
1966 }
1967
1968 return true;
1969 }
1970
getValue(JSContext * cx,MutableHandleValue vp) const1971 JS_PUBLIC_API bool JSPropertySpec::getValue(JSContext* cx,
1972 MutableHandleValue vp) const {
1973 MOZ_ASSERT(!isAccessor());
1974
1975 switch (u.value.type) {
1976 case ValueWrapper::Type::String: {
1977 RootedAtom atom(cx, Atomize(cx, u.value.string, strlen(u.value.string)));
1978 if (!atom) {
1979 return false;
1980 }
1981 vp.setString(atom);
1982 return true;
1983 }
1984
1985 case ValueWrapper::Type::Int32:
1986 vp.setInt32(u.value.int32);
1987 return true;
1988
1989 case ValueWrapper::Type::Double:
1990 vp.setDouble(u.value.double_);
1991 return true;
1992 }
1993
1994 MOZ_CRASH("Unexpected type");
1995 }
1996
PropertySpecNameToId(JSContext * cx,JSPropertySpec::Name name,MutableHandleId id)1997 bool PropertySpecNameToId(JSContext* cx, JSPropertySpec::Name name,
1998 MutableHandleId id) {
1999 if (name.isSymbol()) {
2000 id.set(PropertyKey::Symbol(cx->wellKnownSymbols().get(name.symbol())));
2001 } else {
2002 JSAtom* atom = Atomize(cx, name.string(), strlen(name.string()));
2003 if (!atom) {
2004 return false;
2005 }
2006 id.set(AtomToId(atom));
2007 }
2008 return true;
2009 }
2010
PropertySpecNameToPermanentId(JSContext * cx,JSPropertySpec::Name name,jsid * idp)2011 JS_PUBLIC_API bool JS::PropertySpecNameToPermanentId(JSContext* cx,
2012 JSPropertySpec::Name name,
2013 jsid* idp) {
2014 // We are calling fromMarkedLocation(idp) even though idp points to a
2015 // location that will never be marked. This is OK because the whole point
2016 // of this API is to populate *idp with a jsid that does not need to be
2017 // marked.
2018 MutableHandleId id = MutableHandleId::fromMarkedLocation(idp);
2019 if (!PropertySpecNameToId(cx, name, id)) {
2020 return false;
2021 }
2022
2023 if (id.isString() && !PinAtom(cx, &id.toString()->asAtom())) {
2024 return false;
2025 }
2026
2027 return true;
2028 }
2029
ObjectToCompletePropertyDescriptor(JSContext * cx,HandleObject obj,HandleValue descObj,MutableHandle<PropertyDescriptor> desc)2030 JS_PUBLIC_API bool JS::ObjectToCompletePropertyDescriptor(
2031 JSContext* cx, HandleObject obj, HandleValue descObj,
2032 MutableHandle<PropertyDescriptor> desc) {
2033 // |obj| can be in a different compartment here. The caller is responsible
2034 // for wrapping it (see JS_WrapPropertyDescriptor).
2035 cx->check(descObj);
2036 if (!ToPropertyDescriptor(cx, descObj, true, desc)) {
2037 return false;
2038 }
2039 CompletePropertyDescriptor(desc);
2040 return true;
2041 }
2042
JS_SetAllNonReservedSlotsToUndefined(JS::HandleObject obj)2043 JS_PUBLIC_API void JS_SetAllNonReservedSlotsToUndefined(JS::HandleObject obj) {
2044 if (!obj->is<NativeObject>()) {
2045 return;
2046 }
2047
2048 const JSClass* clasp = obj->getClass();
2049 unsigned numReserved = JSCLASS_RESERVED_SLOTS(clasp);
2050 unsigned numSlots = obj->as<NativeObject>().slotSpan();
2051 for (unsigned i = numReserved; i < numSlots; i++) {
2052 obj->as<NativeObject>().setSlot(i, UndefinedValue());
2053 }
2054 }
2055
JS_SetReservedSlot(JSObject * obj,uint32_t index,const Value & value)2056 JS_PUBLIC_API void JS_SetReservedSlot(JSObject* obj, uint32_t index,
2057 const Value& value) {
2058 // Note: we don't use setReservedSlot so that this also works on swappable DOM
2059 // objects. See NativeObject::getReservedSlotRef comment.
2060 MOZ_ASSERT(index < JSCLASS_RESERVED_SLOTS(obj->getClass()));
2061 obj->as<NativeObject>().setSlot(index, value);
2062 }
2063
JS_InitReservedSlot(JSObject * obj,uint32_t index,void * ptr,size_t nbytes,JS::MemoryUse use)2064 JS_PUBLIC_API void JS_InitReservedSlot(JSObject* obj, uint32_t index, void* ptr,
2065 size_t nbytes, JS::MemoryUse use) {
2066 // Note: we don't use InitReservedSlot so that this also works on swappable
2067 // DOM objects. See NativeObject::getReservedSlotRef comment.
2068 MOZ_ASSERT(index < JSCLASS_RESERVED_SLOTS(obj->getClass()));
2069 AddCellMemory(obj, nbytes, js::MemoryUse(use));
2070 obj->as<NativeObject>().initSlot(index, PrivateValue(ptr));
2071 }
2072
IsMapObject(JSContext * cx,JS::HandleObject obj,bool * isMap)2073 JS_PUBLIC_API bool JS::IsMapObject(JSContext* cx, JS::HandleObject obj,
2074 bool* isMap) {
2075 return IsGivenTypeObject(cx, obj, ESClass::Map, isMap);
2076 }
2077
IsSetObject(JSContext * cx,JS::HandleObject obj,bool * isSet)2078 JS_PUBLIC_API bool JS::IsSetObject(JSContext* cx, JS::HandleObject obj,
2079 bool* isSet) {
2080 return IsGivenTypeObject(cx, obj, ESClass::Set, isSet);
2081 }
2082
JS_HoldPrincipals(JSPrincipals * principals)2083 JS_PUBLIC_API void JS_HoldPrincipals(JSPrincipals* principals) {
2084 ++principals->refcount;
2085 }
2086
JS_DropPrincipals(JSContext * cx,JSPrincipals * principals)2087 JS_PUBLIC_API void JS_DropPrincipals(JSContext* cx, JSPrincipals* principals) {
2088 int rc = --principals->refcount;
2089 if (rc == 0) {
2090 JS::AutoSuppressGCAnalysis nogc;
2091 cx->runtime()->destroyPrincipals(principals);
2092 }
2093 }
2094
JS_SetSecurityCallbacks(JSContext * cx,const JSSecurityCallbacks * scb)2095 JS_PUBLIC_API void JS_SetSecurityCallbacks(JSContext* cx,
2096 const JSSecurityCallbacks* scb) {
2097 MOZ_ASSERT(scb != &NullSecurityCallbacks);
2098 cx->runtime()->securityCallbacks = scb ? scb : &NullSecurityCallbacks;
2099 }
2100
JS_GetSecurityCallbacks(JSContext * cx)2101 JS_PUBLIC_API const JSSecurityCallbacks* JS_GetSecurityCallbacks(
2102 JSContext* cx) {
2103 return (cx->runtime()->securityCallbacks != &NullSecurityCallbacks)
2104 ? cx->runtime()->securityCallbacks.ref()
2105 : nullptr;
2106 }
2107
JS_SetTrustedPrincipals(JSContext * cx,JSPrincipals * prin)2108 JS_PUBLIC_API void JS_SetTrustedPrincipals(JSContext* cx, JSPrincipals* prin) {
2109 cx->runtime()->setTrustedPrincipals(prin);
2110 }
2111
JS_InitDestroyPrincipalsCallback(JSContext * cx,JSDestroyPrincipalsOp destroyPrincipals)2112 extern JS_PUBLIC_API void JS_InitDestroyPrincipalsCallback(
2113 JSContext* cx, JSDestroyPrincipalsOp destroyPrincipals) {
2114 MOZ_ASSERT(destroyPrincipals);
2115 MOZ_ASSERT(!cx->runtime()->destroyPrincipals);
2116 cx->runtime()->destroyPrincipals = destroyPrincipals;
2117 }
2118
JS_InitReadPrincipalsCallback(JSContext * cx,JSReadPrincipalsOp read)2119 extern JS_PUBLIC_API void JS_InitReadPrincipalsCallback(
2120 JSContext* cx, JSReadPrincipalsOp read) {
2121 MOZ_ASSERT(read);
2122 MOZ_ASSERT(!cx->runtime()->readPrincipals);
2123 cx->runtime()->readPrincipals = read;
2124 }
2125
JS_NewFunction(JSContext * cx,JSNative native,unsigned nargs,unsigned flags,const char * name)2126 JS_PUBLIC_API JSFunction* JS_NewFunction(JSContext* cx, JSNative native,
2127 unsigned nargs, unsigned flags,
2128 const char* name) {
2129 MOZ_ASSERT(!cx->zone()->isAtomsZone());
2130
2131 AssertHeapIsIdle();
2132 CHECK_THREAD(cx);
2133
2134 RootedAtom atom(cx);
2135 if (name) {
2136 atom = Atomize(cx, name, strlen(name));
2137 if (!atom) {
2138 return nullptr;
2139 }
2140 }
2141
2142 return (flags & JSFUN_CONSTRUCTOR)
2143 ? NewNativeConstructor(cx, native, nargs, atom)
2144 : NewNativeFunction(cx, native, nargs, atom);
2145 }
2146
GetSelfHostedFunction(JSContext * cx,const char * selfHostedName,HandleId id,unsigned nargs)2147 JS_PUBLIC_API JSFunction* JS::GetSelfHostedFunction(JSContext* cx,
2148 const char* selfHostedName,
2149 HandleId id,
2150 unsigned nargs) {
2151 MOZ_ASSERT(!cx->zone()->isAtomsZone());
2152 AssertHeapIsIdle();
2153 CHECK_THREAD(cx);
2154 cx->check(id);
2155
2156 RootedAtom name(cx, IdToFunctionName(cx, id));
2157 if (!name) {
2158 return nullptr;
2159 }
2160
2161 JSAtom* shAtom = Atomize(cx, selfHostedName, strlen(selfHostedName));
2162 if (!shAtom) {
2163 return nullptr;
2164 }
2165 RootedPropertyName shName(cx, shAtom->asPropertyName());
2166 RootedValue funVal(cx);
2167 if (!GlobalObject::getSelfHostedFunction(cx, cx->global(), shName, name,
2168 nargs, &funVal)) {
2169 return nullptr;
2170 }
2171 return &funVal.toObject().as<JSFunction>();
2172 }
2173
NewFunctionFromSpec(JSContext * cx,const JSFunctionSpec * fs,HandleId id)2174 JS_PUBLIC_API JSFunction* JS::NewFunctionFromSpec(JSContext* cx,
2175 const JSFunctionSpec* fs,
2176 HandleId id) {
2177 cx->check(id);
2178
2179 #ifdef DEBUG
2180 if (fs->name.isSymbol()) {
2181 JS::Symbol* sym = cx->wellKnownSymbols().get(fs->name.symbol());
2182 MOZ_ASSERT(PropertyKey::Symbol(sym) == id);
2183 } else {
2184 MOZ_ASSERT(id.isString() &&
2185 StringEqualsAscii(id.toLinearString(), fs->name.string()));
2186 }
2187 #endif
2188
2189 // Delay cloning self-hosted functions until they are called. This is
2190 // achieved by passing DefineFunction a nullptr JSNative which produces an
2191 // interpreted JSFunction where !hasScript. Interpreted call paths then
2192 // call InitializeLazyFunctionScript if !hasScript.
2193 if (fs->selfHostedName) {
2194 MOZ_ASSERT(!fs->call.op);
2195 MOZ_ASSERT(!fs->call.info);
2196
2197 JSAtom* shAtom =
2198 Atomize(cx, fs->selfHostedName, strlen(fs->selfHostedName));
2199 if (!shAtom) {
2200 return nullptr;
2201 }
2202 RootedPropertyName shName(cx, shAtom->asPropertyName());
2203 RootedAtom name(cx, IdToFunctionName(cx, id));
2204 if (!name) {
2205 return nullptr;
2206 }
2207 RootedValue funVal(cx);
2208 if (!GlobalObject::getSelfHostedFunction(cx, cx->global(), shName, name,
2209 fs->nargs, &funVal)) {
2210 return nullptr;
2211 }
2212 return &funVal.toObject().as<JSFunction>();
2213 }
2214
2215 RootedAtom atom(cx, IdToFunctionName(cx, id));
2216 if (!atom) {
2217 return nullptr;
2218 }
2219
2220 MOZ_ASSERT(fs->call.op);
2221
2222 JSFunction* fun;
2223 if (fs->flags & JSFUN_CONSTRUCTOR) {
2224 fun = NewNativeConstructor(cx, fs->call.op, fs->nargs, atom);
2225 } else {
2226 fun = NewNativeFunction(cx, fs->call.op, fs->nargs, atom);
2227 }
2228 if (!fun) {
2229 return nullptr;
2230 }
2231
2232 if (fs->call.info) {
2233 fun->setJitInfo(fs->call.info);
2234 }
2235 return fun;
2236 }
2237
NewFunctionFromSpec(JSContext * cx,const JSFunctionSpec * fs)2238 JS_PUBLIC_API JSFunction* JS::NewFunctionFromSpec(JSContext* cx,
2239 const JSFunctionSpec* fs) {
2240 RootedId id(cx);
2241 if (!PropertySpecNameToId(cx, fs->name, &id)) {
2242 return nullptr;
2243 }
2244
2245 return NewFunctionFromSpec(cx, fs, id);
2246 }
2247
JS_GetFunctionObject(JSFunction * fun)2248 JS_PUBLIC_API JSObject* JS_GetFunctionObject(JSFunction* fun) { return fun; }
2249
JS_GetFunctionId(JSFunction * fun)2250 JS_PUBLIC_API JSString* JS_GetFunctionId(JSFunction* fun) {
2251 return fun->explicitName();
2252 }
2253
JS_GetFunctionDisplayId(JSFunction * fun)2254 JS_PUBLIC_API JSString* JS_GetFunctionDisplayId(JSFunction* fun) {
2255 return fun->displayAtom();
2256 }
2257
JS_GetFunctionArity(JSFunction * fun)2258 JS_PUBLIC_API uint16_t JS_GetFunctionArity(JSFunction* fun) {
2259 return fun->nargs();
2260 }
2261
JS_GetFunctionLength(JSContext * cx,HandleFunction fun,uint16_t * length)2262 JS_PUBLIC_API bool JS_GetFunctionLength(JSContext* cx, HandleFunction fun,
2263 uint16_t* length) {
2264 cx->check(fun);
2265 return JSFunction::getLength(cx, fun, length);
2266 }
2267
JS_ObjectIsFunction(JSObject * obj)2268 JS_PUBLIC_API bool JS_ObjectIsFunction(JSObject* obj) {
2269 return obj->is<JSFunction>();
2270 }
2271
JS_IsNativeFunction(JSObject * funobj,JSNative call)2272 JS_PUBLIC_API bool JS_IsNativeFunction(JSObject* funobj, JSNative call) {
2273 if (!funobj->is<JSFunction>()) {
2274 return false;
2275 }
2276 JSFunction* fun = &funobj->as<JSFunction>();
2277 return fun->isNativeFun() && fun->native() == call;
2278 }
2279
JS_IsConstructor(JSFunction * fun)2280 extern JS_PUBLIC_API bool JS_IsConstructor(JSFunction* fun) {
2281 return fun->isConstructor();
2282 }
2283
copyPODTransitiveOptions(const TransitiveCompileOptions & rhs)2284 void JS::TransitiveCompileOptions::copyPODTransitiveOptions(
2285 const TransitiveCompileOptions& rhs) {
2286 // filename_, introducerFilename_, sourceMapURL_ should be handled in caller.
2287
2288 mutedErrors_ = rhs.mutedErrors_;
2289 forceStrictMode_ = rhs.forceStrictMode_;
2290 sourcePragmas_ = rhs.sourcePragmas_;
2291 skipFilenameValidation_ = rhs.skipFilenameValidation_;
2292 hideScriptFromDebugger_ = rhs.hideScriptFromDebugger_;
2293 deferDebugMetadata_ = rhs.deferDebugMetadata_;
2294 eagerDelazificationStrategy_ = rhs.eagerDelazificationStrategy_;
2295
2296 selfHostingMode = rhs.selfHostingMode;
2297 asmJSOption = rhs.asmJSOption;
2298 throwOnAsmJSValidationFailureOption = rhs.throwOnAsmJSValidationFailureOption;
2299 forceAsync = rhs.forceAsync;
2300 discardSource = rhs.discardSource;
2301 sourceIsLazy = rhs.sourceIsLazy;
2302 allowHTMLComments = rhs.allowHTMLComments;
2303 nonSyntacticScope = rhs.nonSyntacticScope;
2304
2305 topLevelAwait = rhs.topLevelAwait;
2306 importAssertions = rhs.importAssertions;
2307 useFdlibmForSinCosTan = rhs.useFdlibmForSinCosTan;
2308
2309 borrowBuffer = rhs.borrowBuffer;
2310 usePinnedBytecode = rhs.usePinnedBytecode;
2311 allocateInstantiationStorage = rhs.allocateInstantiationStorage;
2312
2313 introductionType = rhs.introductionType;
2314 introductionLineno = rhs.introductionLineno;
2315 introductionOffset = rhs.introductionOffset;
2316 hasIntroductionInfo = rhs.hasIntroductionInfo;
2317 };
2318
copyPODNonTransitiveOptions(const ReadOnlyCompileOptions & rhs)2319 void JS::ReadOnlyCompileOptions::copyPODNonTransitiveOptions(
2320 const ReadOnlyCompileOptions& rhs) {
2321 lineno = rhs.lineno;
2322 column = rhs.column;
2323 scriptSourceOffset = rhs.scriptSourceOffset;
2324 isRunOnce = rhs.isRunOnce;
2325 noScriptRval = rhs.noScriptRval;
2326 }
2327
OwningCompileOptions(JSContext * cx)2328 JS::OwningCompileOptions::OwningCompileOptions(JSContext* cx)
2329 : ReadOnlyCompileOptions() {}
2330
release()2331 void JS::OwningCompileOptions::release() {
2332 // OwningCompileOptions always owns these, so these casts are okay.
2333 js_free(const_cast<char*>(filename_));
2334 js_free(const_cast<char16_t*>(sourceMapURL_));
2335 js_free(const_cast<char*>(introducerFilename_));
2336
2337 filename_ = nullptr;
2338 sourceMapURL_ = nullptr;
2339 introducerFilename_ = nullptr;
2340 }
2341
~OwningCompileOptions()2342 JS::OwningCompileOptions::~OwningCompileOptions() { release(); }
2343
sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const2344 size_t JS::OwningCompileOptions::sizeOfExcludingThis(
2345 mozilla::MallocSizeOf mallocSizeOf) const {
2346 return mallocSizeOf(filename_) + mallocSizeOf(sourceMapURL_) +
2347 mallocSizeOf(introducerFilename_);
2348 }
2349
copy(JSContext * cx,const ReadOnlyCompileOptions & rhs)2350 bool JS::OwningCompileOptions::copy(JSContext* cx,
2351 const ReadOnlyCompileOptions& rhs) {
2352 // Release existing string allocations.
2353 release();
2354
2355 copyPODNonTransitiveOptions(rhs);
2356 copyPODTransitiveOptions(rhs);
2357
2358 if (rhs.filename()) {
2359 filename_ = DuplicateString(cx, rhs.filename()).release();
2360 if (!filename_) {
2361 return false;
2362 }
2363 }
2364
2365 if (rhs.sourceMapURL()) {
2366 sourceMapURL_ = DuplicateString(cx, rhs.sourceMapURL()).release();
2367 if (!sourceMapURL_) {
2368 return false;
2369 }
2370 }
2371
2372 if (rhs.introducerFilename()) {
2373 introducerFilename_ =
2374 DuplicateString(cx, rhs.introducerFilename()).release();
2375 if (!introducerFilename_) {
2376 return false;
2377 }
2378 }
2379
2380 return true;
2381 }
2382
CompileOptions(JSContext * cx)2383 JS::CompileOptions::CompileOptions(JSContext* cx) : ReadOnlyCompileOptions() {
2384 if (!js::IsAsmJSCompilationAvailable(cx)) {
2385 // Distinguishing the cases is just for error reporting.
2386 asmJSOption = !cx->options().asmJS()
2387 ? AsmJSOption::DisabledByAsmJSPref
2388 : AsmJSOption::DisabledByNoWasmCompiler;
2389 } else if (cx->realm() && cx->realm()->debuggerObservesAsmJS()) {
2390 asmJSOption = AsmJSOption::DisabledByDebugger;
2391 } else {
2392 asmJSOption = AsmJSOption::Enabled;
2393 }
2394 throwOnAsmJSValidationFailureOption =
2395 cx->options().throwOnAsmJSValidationFailure();
2396
2397 importAssertions = cx->options().importAssertions();
2398
2399 useFdlibmForSinCosTan = math_use_fdlibm_for_sin_cos_tan();
2400
2401 sourcePragmas_ = cx->options().sourcePragmas();
2402
2403 // Certain modes of operation force strict-mode in general.
2404 forceStrictMode_ = cx->options().strictMode();
2405
2406 // Certain modes of operation disallow syntax parsing in general.
2407 if (coverage::IsLCovEnabled()) {
2408 eagerDelazificationStrategy_ = DelazificationOption::ParseEverythingEagerly;
2409 }
2410
2411 // Note: If we parse outside of a specific realm, we do not inherit any realm
2412 // behaviours. These can still be set manually on the options though.
2413 if (cx->realm()) {
2414 discardSource = cx->realm()->behaviors().discardSource();
2415 }
2416 }
2417
setIntroductionInfoToCaller(JSContext * cx,const char * introductionType,MutableHandle<JSScript * > introductionScript)2418 CompileOptions& CompileOptions::setIntroductionInfoToCaller(
2419 JSContext* cx, const char* introductionType,
2420 MutableHandle<JSScript*> introductionScript) {
2421 RootedScript maybeScript(cx);
2422 const char* filename;
2423 unsigned lineno;
2424 uint32_t pcOffset;
2425 bool mutedErrors;
2426 DescribeScriptedCallerForCompilation(cx, &maybeScript, &filename, &lineno,
2427 &pcOffset, &mutedErrors);
2428 if (filename) {
2429 introductionScript.set(maybeScript);
2430 return setIntroductionInfo(filename, introductionType, lineno, pcOffset);
2431 }
2432 return setIntroductionType(introductionType);
2433 }
2434
JS_GetGlobalFromScript(JSScript * script)2435 JS_PUBLIC_API JSObject* JS_GetGlobalFromScript(JSScript* script) {
2436 return &script->global();
2437 }
2438
JS_GetScriptFilename(JSScript * script)2439 JS_PUBLIC_API const char* JS_GetScriptFilename(JSScript* script) {
2440 // This is called from ThreadStackHelper which can be called from another
2441 // thread or inside a signal hander, so we need to be careful in case a
2442 // copmacting GC is currently moving things around.
2443 return script->maybeForwardedFilename();
2444 }
2445
JS_GetScriptBaseLineNumber(JSContext * cx,JSScript * script)2446 JS_PUBLIC_API unsigned JS_GetScriptBaseLineNumber(JSContext* cx,
2447 JSScript* script) {
2448 return script->lineno();
2449 }
2450
JS_GetFunctionScript(JSContext * cx,HandleFunction fun)2451 JS_PUBLIC_API JSScript* JS_GetFunctionScript(JSContext* cx,
2452 HandleFunction fun) {
2453 if (fun->isNativeFun()) {
2454 return nullptr;
2455 }
2456
2457 if (fun->hasBytecode()) {
2458 return fun->nonLazyScript();
2459 }
2460
2461 AutoRealm ar(cx, fun);
2462 JSScript* script = JSFunction::getOrCreateScript(cx, fun);
2463 if (!script) {
2464 MOZ_CRASH();
2465 }
2466 return script;
2467 }
2468
JS_DecompileScript(JSContext * cx,HandleScript script)2469 JS_PUBLIC_API JSString* JS_DecompileScript(JSContext* cx, HandleScript script) {
2470 MOZ_ASSERT(!cx->zone()->isAtomsZone());
2471
2472 AssertHeapIsIdle();
2473 CHECK_THREAD(cx);
2474 RootedFunction fun(cx, script->function());
2475 if (fun) {
2476 return JS_DecompileFunction(cx, fun);
2477 }
2478 bool haveSource;
2479 if (!ScriptSource::loadSource(cx, script->scriptSource(), &haveSource)) {
2480 return nullptr;
2481 }
2482 return haveSource ? JSScript::sourceData(cx, script)
2483 : NewStringCopyZ<CanGC>(cx, "[no source]");
2484 }
2485
JS_DecompileFunction(JSContext * cx,HandleFunction fun)2486 JS_PUBLIC_API JSString* JS_DecompileFunction(JSContext* cx,
2487 HandleFunction fun) {
2488 MOZ_ASSERT(!cx->zone()->isAtomsZone());
2489 AssertHeapIsIdle();
2490 CHECK_THREAD(cx);
2491 cx->check(fun);
2492 return FunctionToString(cx, fun, /* isToSource = */ false);
2493 }
2494
SetScriptPrivate(JSScript * script,const JS::Value & value)2495 JS_PUBLIC_API void JS::SetScriptPrivate(JSScript* script,
2496 const JS::Value& value) {
2497 JSRuntime* rt = script->zone()->runtimeFromMainThread();
2498 script->sourceObject()->setPrivate(rt, value);
2499 }
2500
GetScriptPrivate(JSScript * script)2501 JS_PUBLIC_API JS::Value JS::GetScriptPrivate(JSScript* script) {
2502 return script->sourceObject()->getPrivate();
2503 }
2504
GetScriptedCallerPrivate(JSContext * cx)2505 JS_PUBLIC_API JS::Value JS::GetScriptedCallerPrivate(JSContext* cx) {
2506 AssertHeapIsIdle();
2507 CHECK_THREAD(cx);
2508
2509 NonBuiltinFrameIter iter(cx, cx->realm()->principals());
2510 if (iter.done() || !iter.hasScript()) {
2511 return UndefinedValue();
2512 }
2513
2514 return iter.script()->sourceObject()->getPrivate();
2515 }
2516
SetScriptPrivateReferenceHooks(JSRuntime * rt,JS::ScriptPrivateReferenceHook addRefHook,JS::ScriptPrivateReferenceHook releaseHook)2517 JS_PUBLIC_API void JS::SetScriptPrivateReferenceHooks(
2518 JSRuntime* rt, JS::ScriptPrivateReferenceHook addRefHook,
2519 JS::ScriptPrivateReferenceHook releaseHook) {
2520 AssertHeapIsIdle();
2521 rt->scriptPrivateAddRefHook = addRefHook;
2522 rt->scriptPrivateReleaseHook = releaseHook;
2523 }
2524
SetWaitCallback(JSRuntime * rt,BeforeWaitCallback beforeWait,AfterWaitCallback afterWait,size_t requiredMemory)2525 JS_PUBLIC_API void JS::SetWaitCallback(JSRuntime* rt,
2526 BeforeWaitCallback beforeWait,
2527 AfterWaitCallback afterWait,
2528 size_t requiredMemory) {
2529 MOZ_RELEASE_ASSERT(requiredMemory <= WAIT_CALLBACK_CLIENT_MAXMEM);
2530 MOZ_RELEASE_ASSERT((beforeWait == nullptr) == (afterWait == nullptr));
2531 rt->beforeWaitCallback = beforeWait;
2532 rt->afterWaitCallback = afterWait;
2533 }
2534
JS_CheckForInterrupt(JSContext * cx)2535 JS_PUBLIC_API bool JS_CheckForInterrupt(JSContext* cx) {
2536 return js::CheckForInterrupt(cx);
2537 }
2538
JS_AddInterruptCallback(JSContext * cx,JSInterruptCallback callback)2539 JS_PUBLIC_API bool JS_AddInterruptCallback(JSContext* cx,
2540 JSInterruptCallback callback) {
2541 return cx->interruptCallbacks().append(callback);
2542 }
2543
JS_DisableInterruptCallback(JSContext * cx)2544 JS_PUBLIC_API bool JS_DisableInterruptCallback(JSContext* cx) {
2545 bool result = cx->interruptCallbackDisabled;
2546 cx->interruptCallbackDisabled = true;
2547 return result;
2548 }
2549
JS_ResetInterruptCallback(JSContext * cx,bool enable)2550 JS_PUBLIC_API void JS_ResetInterruptCallback(JSContext* cx, bool enable) {
2551 cx->interruptCallbackDisabled = enable;
2552 }
2553
2554 /************************************************************************/
2555
2556 /*
2557 * Promises.
2558 */
SetJobQueue(JSContext * cx,JobQueue * queue)2559 JS_PUBLIC_API void JS::SetJobQueue(JSContext* cx, JobQueue* queue) {
2560 cx->jobQueue = queue;
2561 }
2562
SetPromiseRejectionTrackerCallback(JSContext * cx,PromiseRejectionTrackerCallback callback,void * data)2563 extern JS_PUBLIC_API void JS::SetPromiseRejectionTrackerCallback(
2564 JSContext* cx, PromiseRejectionTrackerCallback callback,
2565 void* data /* = nullptr */) {
2566 cx->promiseRejectionTrackerCallback = callback;
2567 cx->promiseRejectionTrackerCallbackData = data;
2568 }
2569
JobQueueIsEmpty(JSContext * cx)2570 extern JS_PUBLIC_API void JS::JobQueueIsEmpty(JSContext* cx) {
2571 cx->canSkipEnqueuingJobs = true;
2572 }
2573
JobQueueMayNotBeEmpty(JSContext * cx)2574 extern JS_PUBLIC_API void JS::JobQueueMayNotBeEmpty(JSContext* cx) {
2575 cx->canSkipEnqueuingJobs = false;
2576 }
2577
NewPromiseObject(JSContext * cx,HandleObject executor)2578 JS_PUBLIC_API JSObject* JS::NewPromiseObject(JSContext* cx,
2579 HandleObject executor) {
2580 MOZ_ASSERT(!cx->zone()->isAtomsZone());
2581 AssertHeapIsIdle();
2582 CHECK_THREAD(cx);
2583 cx->check(executor);
2584
2585 if (!executor) {
2586 return PromiseObject::createSkippingExecutor(cx);
2587 }
2588
2589 MOZ_ASSERT(IsCallable(executor));
2590 return PromiseObject::create(cx, executor);
2591 }
2592
IsPromiseObject(JS::HandleObject obj)2593 JS_PUBLIC_API bool JS::IsPromiseObject(JS::HandleObject obj) {
2594 return obj->is<PromiseObject>();
2595 }
2596
GetPromiseConstructor(JSContext * cx)2597 JS_PUBLIC_API JSObject* JS::GetPromiseConstructor(JSContext* cx) {
2598 CHECK_THREAD(cx);
2599 Rooted<GlobalObject*> global(cx, cx->global());
2600 return GlobalObject::getOrCreatePromiseConstructor(cx, global);
2601 }
2602
GetPromisePrototype(JSContext * cx)2603 JS_PUBLIC_API JSObject* JS::GetPromisePrototype(JSContext* cx) {
2604 CHECK_THREAD(cx);
2605 Rooted<GlobalObject*> global(cx, cx->global());
2606 return GlobalObject::getOrCreatePromisePrototype(cx, global);
2607 }
2608
GetPromiseState(JS::HandleObject promise)2609 JS_PUBLIC_API JS::PromiseState JS::GetPromiseState(JS::HandleObject promise) {
2610 PromiseObject* promiseObj = promise->maybeUnwrapIf<PromiseObject>();
2611 if (!promiseObj) {
2612 return JS::PromiseState::Pending;
2613 }
2614
2615 return promiseObj->state();
2616 }
2617
GetPromiseID(JS::HandleObject promise)2618 JS_PUBLIC_API uint64_t JS::GetPromiseID(JS::HandleObject promise) {
2619 return promise->as<PromiseObject>().getID();
2620 }
2621
GetPromiseResult(JS::HandleObject promiseObj)2622 JS_PUBLIC_API JS::Value JS::GetPromiseResult(JS::HandleObject promiseObj) {
2623 PromiseObject* promise = &promiseObj->as<PromiseObject>();
2624 MOZ_ASSERT(promise->state() != JS::PromiseState::Pending);
2625 return promise->state() == JS::PromiseState::Fulfilled ? promise->value()
2626 : promise->reason();
2627 }
2628
GetPromiseIsHandled(JS::HandleObject promise)2629 JS_PUBLIC_API bool JS::GetPromiseIsHandled(JS::HandleObject promise) {
2630 PromiseObject* promiseObj = &promise->as<PromiseObject>();
2631 return !promiseObj->isUnhandled();
2632 }
2633
UnwrapPromise(JSContext * cx,JS::HandleObject promise,mozilla::Maybe<AutoRealm> & ar)2634 static PromiseObject* UnwrapPromise(JSContext* cx, JS::HandleObject promise,
2635 mozilla::Maybe<AutoRealm>& ar) {
2636 AssertHeapIsIdle();
2637 CHECK_THREAD(cx);
2638 cx->check(promise);
2639
2640 PromiseObject* promiseObj;
2641 if (IsWrapper(promise)) {
2642 promiseObj = promise->maybeUnwrapAs<PromiseObject>();
2643 if (!promiseObj) {
2644 ReportAccessDenied(cx);
2645 return nullptr;
2646 }
2647 ar.emplace(cx, promiseObj);
2648 } else {
2649 promiseObj = promise.as<PromiseObject>();
2650 }
2651 return promiseObj;
2652 }
2653
SetSettledPromiseIsHandled(JSContext * cx,JS::HandleObject promise)2654 JS_PUBLIC_API bool JS::SetSettledPromiseIsHandled(JSContext* cx,
2655 JS::HandleObject promise) {
2656 mozilla::Maybe<AutoRealm> ar;
2657 Rooted<PromiseObject*> promiseObj(cx, UnwrapPromise(cx, promise, ar));
2658 if (!promiseObj) {
2659 return false;
2660 }
2661 js::SetSettledPromiseIsHandled(cx, promiseObj);
2662 return true;
2663 }
2664
SetAnyPromiseIsHandled(JSContext * cx,JS::HandleObject promise)2665 JS_PUBLIC_API bool JS::SetAnyPromiseIsHandled(JSContext* cx,
2666 JS::HandleObject promise) {
2667 mozilla::Maybe<AutoRealm> ar;
2668 Rooted<PromiseObject*> promiseObj(cx, UnwrapPromise(cx, promise, ar));
2669 if (!promiseObj) {
2670 return false;
2671 }
2672 js::SetAnyPromiseIsHandled(cx, promiseObj);
2673 return true;
2674 }
2675
GetPromiseAllocationSite(JS::HandleObject promise)2676 JS_PUBLIC_API JSObject* JS::GetPromiseAllocationSite(JS::HandleObject promise) {
2677 return promise->as<PromiseObject>().allocationSite();
2678 }
2679
GetPromiseResolutionSite(JS::HandleObject promise)2680 JS_PUBLIC_API JSObject* JS::GetPromiseResolutionSite(JS::HandleObject promise) {
2681 return promise->as<PromiseObject>().resolutionSite();
2682 }
2683
2684 #ifdef DEBUG
DumpPromiseAllocationSite(JSContext * cx,JS::HandleObject promise)2685 JS_PUBLIC_API void JS::DumpPromiseAllocationSite(JSContext* cx,
2686 JS::HandleObject promise) {
2687 RootedObject stack(cx, promise->as<PromiseObject>().allocationSite());
2688 JSPrincipals* principals = cx->realm()->principals();
2689 UniqueChars stackStr = BuildUTF8StackString(cx, principals, stack);
2690 if (stackStr) {
2691 fputs(stackStr.get(), stderr);
2692 }
2693 }
2694
DumpPromiseResolutionSite(JSContext * cx,JS::HandleObject promise)2695 JS_PUBLIC_API void JS::DumpPromiseResolutionSite(JSContext* cx,
2696 JS::HandleObject promise) {
2697 RootedObject stack(cx, promise->as<PromiseObject>().resolutionSite());
2698 JSPrincipals* principals = cx->realm()->principals();
2699 UniqueChars stackStr = BuildUTF8StackString(cx, principals, stack);
2700 if (stackStr) {
2701 fputs(stackStr.get(), stderr);
2702 }
2703 }
2704 #endif
2705
CallOriginalPromiseResolve(JSContext * cx,JS::HandleValue resolutionValue)2706 JS_PUBLIC_API JSObject* JS::CallOriginalPromiseResolve(
2707 JSContext* cx, JS::HandleValue resolutionValue) {
2708 AssertHeapIsIdle();
2709 CHECK_THREAD(cx);
2710 cx->check(resolutionValue);
2711
2712 RootedObject promise(cx,
2713 PromiseObject::unforgeableResolve(cx, resolutionValue));
2714 MOZ_ASSERT_IF(promise, promise->canUnwrapAs<PromiseObject>());
2715 return promise;
2716 }
2717
CallOriginalPromiseReject(JSContext * cx,JS::HandleValue rejectionValue)2718 JS_PUBLIC_API JSObject* JS::CallOriginalPromiseReject(
2719 JSContext* cx, JS::HandleValue rejectionValue) {
2720 AssertHeapIsIdle();
2721 CHECK_THREAD(cx);
2722 cx->check(rejectionValue);
2723
2724 RootedObject promise(cx,
2725 PromiseObject::unforgeableReject(cx, rejectionValue));
2726 MOZ_ASSERT_IF(promise, promise->canUnwrapAs<PromiseObject>());
2727 return promise;
2728 }
2729
ResolveOrRejectPromise(JSContext * cx,JS::HandleObject promiseObj,JS::HandleValue resultOrReason_,bool reject)2730 static bool ResolveOrRejectPromise(JSContext* cx, JS::HandleObject promiseObj,
2731 JS::HandleValue resultOrReason_,
2732 bool reject) {
2733 AssertHeapIsIdle();
2734 CHECK_THREAD(cx);
2735 cx->check(promiseObj, resultOrReason_);
2736
2737 mozilla::Maybe<AutoRealm> ar;
2738 Rooted<PromiseObject*> promise(cx);
2739 RootedValue resultOrReason(cx, resultOrReason_);
2740 if (IsWrapper(promiseObj)) {
2741 promise = promiseObj->maybeUnwrapAs<PromiseObject>();
2742 if (!promise) {
2743 ReportAccessDenied(cx);
2744 return false;
2745 }
2746 ar.emplace(cx, promise);
2747 if (!cx->compartment()->wrap(cx, &resultOrReason)) {
2748 return false;
2749 }
2750 } else {
2751 promise = promiseObj.as<PromiseObject>();
2752 }
2753
2754 return reject ? PromiseObject::reject(cx, promise, resultOrReason)
2755 : PromiseObject::resolve(cx, promise, resultOrReason);
2756 }
2757
ResolvePromise(JSContext * cx,JS::HandleObject promiseObj,JS::HandleValue resolutionValue)2758 JS_PUBLIC_API bool JS::ResolvePromise(JSContext* cx,
2759 JS::HandleObject promiseObj,
2760 JS::HandleValue resolutionValue) {
2761 return ResolveOrRejectPromise(cx, promiseObj, resolutionValue, false);
2762 }
2763
RejectPromise(JSContext * cx,JS::HandleObject promiseObj,JS::HandleValue rejectionValue)2764 JS_PUBLIC_API bool JS::RejectPromise(JSContext* cx, JS::HandleObject promiseObj,
2765 JS::HandleValue rejectionValue) {
2766 return ResolveOrRejectPromise(cx, promiseObj, rejectionValue, true);
2767 }
2768
CallOriginalPromiseThen(JSContext * cx,JS::HandleObject promiseObj,JS::HandleObject onFulfilled,JS::HandleObject onRejected)2769 JS_PUBLIC_API JSObject* JS::CallOriginalPromiseThen(
2770 JSContext* cx, JS::HandleObject promiseObj, JS::HandleObject onFulfilled,
2771 JS::HandleObject onRejected) {
2772 AssertHeapIsIdle();
2773 CHECK_THREAD(cx);
2774 cx->check(promiseObj, onFulfilled, onRejected);
2775
2776 MOZ_ASSERT_IF(onFulfilled, IsCallable(onFulfilled));
2777 MOZ_ASSERT_IF(onRejected, IsCallable(onRejected));
2778
2779 return OriginalPromiseThen(cx, promiseObj, onFulfilled, onRejected);
2780 }
2781
ReactToPromise(JSContext * cx,JS::Handle<JSObject * > promiseObj,JS::Handle<JSObject * > onFulfilled,JS::Handle<JSObject * > onRejected,UnhandledRejectionBehavior behavior)2782 [[nodiscard]] static bool ReactToPromise(JSContext* cx,
2783 JS::Handle<JSObject*> promiseObj,
2784 JS::Handle<JSObject*> onFulfilled,
2785 JS::Handle<JSObject*> onRejected,
2786 UnhandledRejectionBehavior behavior) {
2787 AssertHeapIsIdle();
2788 CHECK_THREAD(cx);
2789 cx->check(promiseObj, onFulfilled, onRejected);
2790
2791 MOZ_ASSERT_IF(onFulfilled, IsCallable(onFulfilled));
2792 MOZ_ASSERT_IF(onRejected, IsCallable(onRejected));
2793
2794 Rooted<PromiseObject*> unwrappedPromise(cx);
2795 {
2796 RootedValue promiseVal(cx, ObjectValue(*promiseObj));
2797 unwrappedPromise = UnwrapAndTypeCheckValue<PromiseObject>(
2798 cx, promiseVal, [cx, promiseObj] {
2799 JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
2800 JSMSG_INCOMPATIBLE_PROTO, "Promise",
2801 "then", promiseObj->getClass()->name);
2802 });
2803 if (!unwrappedPromise) {
2804 return false;
2805 }
2806 }
2807
2808 return ReactToUnwrappedPromise(cx, unwrappedPromise, onFulfilled, onRejected,
2809 behavior);
2810 }
2811
AddPromiseReactions(JSContext * cx,JS::HandleObject promiseObj,JS::HandleObject onFulfilled,JS::HandleObject onRejected)2812 JS_PUBLIC_API bool JS::AddPromiseReactions(JSContext* cx,
2813 JS::HandleObject promiseObj,
2814 JS::HandleObject onFulfilled,
2815 JS::HandleObject onRejected) {
2816 return ReactToPromise(cx, promiseObj, onFulfilled, onRejected,
2817 UnhandledRejectionBehavior::Report);
2818 }
2819
AddPromiseReactionsIgnoringUnhandledRejection(JSContext * cx,JS::HandleObject promiseObj,JS::HandleObject onFulfilled,JS::HandleObject onRejected)2820 JS_PUBLIC_API bool JS::AddPromiseReactionsIgnoringUnhandledRejection(
2821 JSContext* cx, JS::HandleObject promiseObj, JS::HandleObject onFulfilled,
2822 JS::HandleObject onRejected) {
2823 return ReactToPromise(cx, promiseObj, onFulfilled, onRejected,
2824 UnhandledRejectionBehavior::Ignore);
2825 }
2826
2827 JS_PUBLIC_API JS::PromiseUserInputEventHandlingState
GetPromiseUserInputEventHandlingState(JS::HandleObject promiseObj_)2828 JS::GetPromiseUserInputEventHandlingState(JS::HandleObject promiseObj_) {
2829 PromiseObject* promise = promiseObj_->maybeUnwrapIf<PromiseObject>();
2830 if (!promise) {
2831 return JS::PromiseUserInputEventHandlingState::DontCare;
2832 }
2833
2834 if (!promise->requiresUserInteractionHandling()) {
2835 return JS::PromiseUserInputEventHandlingState::DontCare;
2836 }
2837 if (promise->hadUserInteractionUponCreation()) {
2838 return JS::PromiseUserInputEventHandlingState::HadUserInteractionAtCreation;
2839 }
2840 return JS::PromiseUserInputEventHandlingState::
2841 DidntHaveUserInteractionAtCreation;
2842 }
2843
SetPromiseUserInputEventHandlingState(JS::HandleObject promiseObj_,JS::PromiseUserInputEventHandlingState state)2844 JS_PUBLIC_API bool JS::SetPromiseUserInputEventHandlingState(
2845 JS::HandleObject promiseObj_,
2846 JS::PromiseUserInputEventHandlingState state) {
2847 PromiseObject* promise = promiseObj_->maybeUnwrapIf<PromiseObject>();
2848 if (!promise) {
2849 return false;
2850 }
2851
2852 switch (state) {
2853 case JS::PromiseUserInputEventHandlingState::DontCare:
2854 promise->setRequiresUserInteractionHandling(false);
2855 break;
2856 case JS::PromiseUserInputEventHandlingState::HadUserInteractionAtCreation:
2857 promise->setRequiresUserInteractionHandling(true);
2858 promise->setHadUserInteractionUponCreation(true);
2859 break;
2860 case JS::PromiseUserInputEventHandlingState::
2861 DidntHaveUserInteractionAtCreation:
2862 promise->setRequiresUserInteractionHandling(true);
2863 promise->setHadUserInteractionUponCreation(false);
2864 break;
2865 default:
2866 MOZ_ASSERT_UNREACHABLE(
2867 "Invalid PromiseUserInputEventHandlingState enum value");
2868 return false;
2869 }
2870 return true;
2871 }
2872
2873 /**
2874 * Unforgeable version of Promise.all for internal use.
2875 *
2876 * Takes a dense array of Promise objects and returns a promise that's
2877 * resolved with an array of resolution values when all those promises ahve
2878 * been resolved, or rejected with the rejection value of the first rejected
2879 * promise.
2880 *
2881 * Asserts that the array is dense and all entries are Promise objects.
2882 */
GetWaitForAllPromise(JSContext * cx,JS::HandleObjectVector promises)2883 JS_PUBLIC_API JSObject* JS::GetWaitForAllPromise(
2884 JSContext* cx, JS::HandleObjectVector promises) {
2885 AssertHeapIsIdle();
2886 CHECK_THREAD(cx);
2887
2888 return js::GetWaitForAllPromise(cx, promises);
2889 }
2890
InitDispatchToEventLoop(JSContext * cx,JS::DispatchToEventLoopCallback callback,void * closure)2891 JS_PUBLIC_API void JS::InitDispatchToEventLoop(
2892 JSContext* cx, JS::DispatchToEventLoopCallback callback, void* closure) {
2893 cx->runtime()->offThreadPromiseState.ref().init(callback, closure);
2894 }
2895
ShutdownAsyncTasks(JSContext * cx)2896 JS_PUBLIC_API void JS::ShutdownAsyncTasks(JSContext* cx) {
2897 cx->runtime()->offThreadPromiseState.ref().shutdown(cx);
2898 }
2899
InitConsumeStreamCallback(JSContext * cx,ConsumeStreamCallback consume,ReportStreamErrorCallback report)2900 JS_PUBLIC_API void JS::InitConsumeStreamCallback(
2901 JSContext* cx, ConsumeStreamCallback consume,
2902 ReportStreamErrorCallback report) {
2903 cx->runtime()->consumeStreamCallback = consume;
2904 cx->runtime()->reportStreamErrorCallback = report;
2905 }
2906
JS_RequestInterruptCallback(JSContext * cx)2907 JS_PUBLIC_API void JS_RequestInterruptCallback(JSContext* cx) {
2908 cx->requestInterrupt(InterruptReason::CallbackUrgent);
2909 }
2910
JS_RequestInterruptCallbackCanWait(JSContext * cx)2911 JS_PUBLIC_API void JS_RequestInterruptCallbackCanWait(JSContext* cx) {
2912 cx->requestInterrupt(InterruptReason::CallbackCanWait);
2913 }
2914
AutoSetAsyncStackForNewCalls(JSContext * cx,HandleObject stack,const char * asyncCause,JS::AutoSetAsyncStackForNewCalls::AsyncCallKind kind)2915 JS::AutoSetAsyncStackForNewCalls::AutoSetAsyncStackForNewCalls(
2916 JSContext* cx, HandleObject stack, const char* asyncCause,
2917 JS::AutoSetAsyncStackForNewCalls::AsyncCallKind kind)
2918 : cx(cx),
2919 oldAsyncStack(cx, cx->asyncStackForNewActivations()),
2920 oldAsyncCause(cx->asyncCauseForNewActivations),
2921 oldAsyncCallIsExplicit(cx->asyncCallIsExplicit) {
2922 CHECK_THREAD(cx);
2923
2924 // The option determines whether we actually use the new values at this
2925 // point. It will not affect restoring the previous values when the object
2926 // is destroyed, so if the option changes it won't cause consistency issues.
2927 if (!cx->options().asyncStack()) {
2928 return;
2929 }
2930
2931 SavedFrame* asyncStack = &stack->as<SavedFrame>();
2932
2933 cx->asyncStackForNewActivations() = asyncStack;
2934 cx->asyncCauseForNewActivations = asyncCause;
2935 cx->asyncCallIsExplicit = kind == AsyncCallKind::EXPLICIT;
2936 }
2937
~AutoSetAsyncStackForNewCalls()2938 JS::AutoSetAsyncStackForNewCalls::~AutoSetAsyncStackForNewCalls() {
2939 cx->asyncCauseForNewActivations = oldAsyncCause;
2940 cx->asyncStackForNewActivations() =
2941 oldAsyncStack ? &oldAsyncStack->as<SavedFrame>() : nullptr;
2942 cx->asyncCallIsExplicit = oldAsyncCallIsExplicit;
2943 }
2944
2945 /************************************************************************/
JS_NewStringCopyN(JSContext * cx,const char * s,size_t n)2946 JS_PUBLIC_API JSString* JS_NewStringCopyN(JSContext* cx, const char* s,
2947 size_t n) {
2948 AssertHeapIsIdle();
2949 CHECK_THREAD(cx);
2950 return NewStringCopyN<CanGC>(cx, s, n);
2951 }
2952
JS_NewStringCopyZ(JSContext * cx,const char * s)2953 JS_PUBLIC_API JSString* JS_NewStringCopyZ(JSContext* cx, const char* s) {
2954 AssertHeapIsIdle();
2955 CHECK_THREAD(cx);
2956 if (!s) {
2957 return cx->runtime()->emptyString;
2958 }
2959 return NewStringCopyZ<CanGC>(cx, s);
2960 }
2961
JS_NewStringCopyUTF8Z(JSContext * cx,const JS::ConstUTF8CharsZ s)2962 JS_PUBLIC_API JSString* JS_NewStringCopyUTF8Z(JSContext* cx,
2963 const JS::ConstUTF8CharsZ s) {
2964 AssertHeapIsIdle();
2965 CHECK_THREAD(cx);
2966 return NewStringCopyUTF8Z(cx, s);
2967 }
2968
JS_NewStringCopyUTF8N(JSContext * cx,const JS::UTF8Chars s)2969 JS_PUBLIC_API JSString* JS_NewStringCopyUTF8N(JSContext* cx,
2970 const JS::UTF8Chars s) {
2971 AssertHeapIsIdle();
2972 CHECK_THREAD(cx);
2973 return NewStringCopyUTF8N(cx, s);
2974 }
2975
JS_StringHasBeenPinned(JSContext * cx,JSString * str)2976 JS_PUBLIC_API bool JS_StringHasBeenPinned(JSContext* cx, JSString* str) {
2977 AssertHeapIsIdle();
2978 CHECK_THREAD(cx);
2979
2980 if (!str->isAtom()) {
2981 return false;
2982 }
2983
2984 return AtomIsPinned(cx, &str->asAtom());
2985 }
2986
JS_AtomizeString(JSContext * cx,const char * s)2987 JS_PUBLIC_API JSString* JS_AtomizeString(JSContext* cx, const char* s) {
2988 return JS_AtomizeStringN(cx, s, strlen(s));
2989 }
2990
JS_AtomizeStringN(JSContext * cx,const char * s,size_t length)2991 JS_PUBLIC_API JSString* JS_AtomizeStringN(JSContext* cx, const char* s,
2992 size_t length) {
2993 AssertHeapIsIdle();
2994 CHECK_THREAD(cx);
2995 return Atomize(cx, s, length);
2996 }
2997
JS_AtomizeAndPinString(JSContext * cx,const char * s)2998 JS_PUBLIC_API JSString* JS_AtomizeAndPinString(JSContext* cx, const char* s) {
2999 return JS_AtomizeAndPinStringN(cx, s, strlen(s));
3000 }
3001
JS_AtomizeAndPinStringN(JSContext * cx,const char * s,size_t length)3002 JS_PUBLIC_API JSString* JS_AtomizeAndPinStringN(JSContext* cx, const char* s,
3003 size_t length) {
3004 AssertHeapIsIdle();
3005 CHECK_THREAD(cx);
3006
3007 JSAtom* atom = cx->zone() ? Atomize(cx, s, length)
3008 : AtomizeWithoutActiveZone(cx, s, length);
3009 if (!atom || !PinAtom(cx, atom)) {
3010 return nullptr;
3011 }
3012
3013 MOZ_ASSERT(JS_StringHasBeenPinned(cx, atom));
3014 return atom;
3015 }
3016
JS_NewLatin1String(JSContext * cx,js::UniquePtr<JS::Latin1Char[],JS::FreePolicy> chars,size_t length)3017 JS_PUBLIC_API JSString* JS_NewLatin1String(
3018 JSContext* cx, js::UniquePtr<JS::Latin1Char[], JS::FreePolicy> chars,
3019 size_t length) {
3020 AssertHeapIsIdle();
3021 CHECK_THREAD(cx);
3022 return NewString<CanGC>(cx, std::move(chars), length);
3023 }
3024
JS_NewUCString(JSContext * cx,JS::UniqueTwoByteChars chars,size_t length)3025 JS_PUBLIC_API JSString* JS_NewUCString(JSContext* cx,
3026 JS::UniqueTwoByteChars chars,
3027 size_t length) {
3028 AssertHeapIsIdle();
3029 CHECK_THREAD(cx);
3030 return NewString<CanGC>(cx, std::move(chars), length);
3031 }
3032
JS_NewUCStringDontDeflate(JSContext * cx,JS::UniqueTwoByteChars chars,size_t length)3033 JS_PUBLIC_API JSString* JS_NewUCStringDontDeflate(JSContext* cx,
3034 JS::UniqueTwoByteChars chars,
3035 size_t length) {
3036 AssertHeapIsIdle();
3037 CHECK_THREAD(cx);
3038 return NewStringDontDeflate<CanGC>(cx, std::move(chars), length);
3039 }
3040
JS_NewUCStringCopyN(JSContext * cx,const char16_t * s,size_t n)3041 JS_PUBLIC_API JSString* JS_NewUCStringCopyN(JSContext* cx, const char16_t* s,
3042 size_t n) {
3043 AssertHeapIsIdle();
3044 CHECK_THREAD(cx);
3045 if (!n) {
3046 return cx->names().empty;
3047 }
3048 return NewStringCopyN<CanGC>(cx, s, n);
3049 }
3050
JS_NewUCStringCopyZ(JSContext * cx,const char16_t * s)3051 JS_PUBLIC_API JSString* JS_NewUCStringCopyZ(JSContext* cx, const char16_t* s) {
3052 AssertHeapIsIdle();
3053 CHECK_THREAD(cx);
3054 if (!s) {
3055 return cx->runtime()->emptyString;
3056 }
3057 return NewStringCopyZ<CanGC>(cx, s);
3058 }
3059
JS_AtomizeUCString(JSContext * cx,const char16_t * s)3060 JS_PUBLIC_API JSString* JS_AtomizeUCString(JSContext* cx, const char16_t* s) {
3061 return JS_AtomizeUCStringN(cx, s, js_strlen(s));
3062 }
3063
JS_AtomizeUCStringN(JSContext * cx,const char16_t * s,size_t length)3064 JS_PUBLIC_API JSString* JS_AtomizeUCStringN(JSContext* cx, const char16_t* s,
3065 size_t length) {
3066 AssertHeapIsIdle();
3067 CHECK_THREAD(cx);
3068 return AtomizeChars(cx, s, length);
3069 }
3070
JS_GetStringLength(JSString * str)3071 JS_PUBLIC_API size_t JS_GetStringLength(JSString* str) { return str->length(); }
3072
JS_StringIsLinear(JSString * str)3073 JS_PUBLIC_API bool JS_StringIsLinear(JSString* str) { return str->isLinear(); }
3074
JS_DeprecatedStringHasLatin1Chars(JSString * str)3075 JS_PUBLIC_API bool JS_DeprecatedStringHasLatin1Chars(JSString* str) {
3076 return str->hasLatin1Chars();
3077 }
3078
JS_GetLatin1StringCharsAndLength(JSContext * cx,const JS::AutoRequireNoGC & nogc,JSString * str,size_t * plength)3079 JS_PUBLIC_API const JS::Latin1Char* JS_GetLatin1StringCharsAndLength(
3080 JSContext* cx, const JS::AutoRequireNoGC& nogc, JSString* str,
3081 size_t* plength) {
3082 MOZ_ASSERT(plength);
3083 AssertHeapIsIdle();
3084 CHECK_THREAD(cx);
3085 cx->check(str);
3086 JSLinearString* linear = str->ensureLinear(cx);
3087 if (!linear) {
3088 return nullptr;
3089 }
3090 *plength = linear->length();
3091 return linear->latin1Chars(nogc);
3092 }
3093
JS_GetTwoByteStringCharsAndLength(JSContext * cx,const JS::AutoRequireNoGC & nogc,JSString * str,size_t * plength)3094 JS_PUBLIC_API const char16_t* JS_GetTwoByteStringCharsAndLength(
3095 JSContext* cx, const JS::AutoRequireNoGC& nogc, JSString* str,
3096 size_t* plength) {
3097 MOZ_ASSERT(plength);
3098 AssertHeapIsIdle();
3099 CHECK_THREAD(cx);
3100 cx->check(str);
3101 JSLinearString* linear = str->ensureLinear(cx);
3102 if (!linear) {
3103 return nullptr;
3104 }
3105 *plength = linear->length();
3106 return linear->twoByteChars(nogc);
3107 }
3108
JS_GetTwoByteExternalStringChars(JSString * str)3109 JS_PUBLIC_API const char16_t* JS_GetTwoByteExternalStringChars(JSString* str) {
3110 return str->asExternal().twoByteChars();
3111 }
3112
JS_GetStringCharAt(JSContext * cx,JSString * str,size_t index,char16_t * res)3113 JS_PUBLIC_API bool JS_GetStringCharAt(JSContext* cx, JSString* str,
3114 size_t index, char16_t* res) {
3115 AssertHeapIsIdle();
3116 CHECK_THREAD(cx);
3117 cx->check(str);
3118
3119 JSLinearString* linear = str->ensureLinear(cx);
3120 if (!linear) {
3121 return false;
3122 }
3123
3124 *res = linear->latin1OrTwoByteChar(index);
3125 return true;
3126 }
3127
JS_CopyStringChars(JSContext * cx,mozilla::Range<char16_t> dest,JSString * str)3128 JS_PUBLIC_API bool JS_CopyStringChars(JSContext* cx,
3129 mozilla::Range<char16_t> dest,
3130 JSString* str) {
3131 AssertHeapIsIdle();
3132 CHECK_THREAD(cx);
3133 cx->check(str);
3134
3135 JSLinearString* linear = str->ensureLinear(cx);
3136 if (!linear) {
3137 return false;
3138 }
3139
3140 MOZ_ASSERT(linear->length() <= dest.length());
3141 CopyChars(dest.begin().get(), *linear);
3142 return true;
3143 }
3144
JS_CopyStringCharsZ(JSContext * cx,JSString * str)3145 extern JS_PUBLIC_API JS::UniqueTwoByteChars JS_CopyStringCharsZ(JSContext* cx,
3146 JSString* str) {
3147 AssertHeapIsIdle();
3148 CHECK_THREAD(cx);
3149
3150 JSLinearString* linear = str->ensureLinear(cx);
3151 if (!linear) {
3152 return nullptr;
3153 }
3154
3155 size_t len = linear->length();
3156
3157 static_assert(JS::MaxStringLength < UINT32_MAX,
3158 "len + 1 must not overflow on 32-bit platforms");
3159
3160 UniqueTwoByteChars chars(cx->pod_malloc<char16_t>(len + 1));
3161 if (!chars) {
3162 return nullptr;
3163 }
3164
3165 CopyChars(chars.get(), *linear);
3166 chars[len] = '\0';
3167
3168 return chars;
3169 }
3170
JS_EnsureLinearString(JSContext * cx,JSString * str)3171 extern JS_PUBLIC_API JSLinearString* JS_EnsureLinearString(JSContext* cx,
3172 JSString* str) {
3173 AssertHeapIsIdle();
3174 CHECK_THREAD(cx);
3175 cx->check(str);
3176 return str->ensureLinear(cx);
3177 }
3178
JS_CompareStrings(JSContext * cx,JSString * str1,JSString * str2,int32_t * result)3179 JS_PUBLIC_API bool JS_CompareStrings(JSContext* cx, JSString* str1,
3180 JSString* str2, int32_t* result) {
3181 AssertHeapIsIdle();
3182 CHECK_THREAD(cx);
3183
3184 return CompareStrings(cx, str1, str2, result);
3185 }
3186
JS_StringEqualsAscii(JSContext * cx,JSString * str,const char * asciiBytes,bool * match)3187 JS_PUBLIC_API bool JS_StringEqualsAscii(JSContext* cx, JSString* str,
3188 const char* asciiBytes, bool* match) {
3189 AssertHeapIsIdle();
3190 CHECK_THREAD(cx);
3191
3192 JSLinearString* linearStr = str->ensureLinear(cx);
3193 if (!linearStr) {
3194 return false;
3195 }
3196 *match = StringEqualsAscii(linearStr, asciiBytes);
3197 return true;
3198 }
3199
JS_StringEqualsAscii(JSContext * cx,JSString * str,const char * asciiBytes,size_t length,bool * match)3200 JS_PUBLIC_API bool JS_StringEqualsAscii(JSContext* cx, JSString* str,
3201 const char* asciiBytes, size_t length,
3202 bool* match) {
3203 AssertHeapIsIdle();
3204 CHECK_THREAD(cx);
3205
3206 JSLinearString* linearStr = str->ensureLinear(cx);
3207 if (!linearStr) {
3208 return false;
3209 }
3210 *match = StringEqualsAscii(linearStr, asciiBytes, length);
3211 return true;
3212 }
3213
JS_LinearStringEqualsAscii(JSLinearString * str,const char * asciiBytes)3214 JS_PUBLIC_API bool JS_LinearStringEqualsAscii(JSLinearString* str,
3215 const char* asciiBytes) {
3216 return StringEqualsAscii(str, asciiBytes);
3217 }
3218
JS_LinearStringEqualsAscii(JSLinearString * str,const char * asciiBytes,size_t length)3219 JS_PUBLIC_API bool JS_LinearStringEqualsAscii(JSLinearString* str,
3220 const char* asciiBytes,
3221 size_t length) {
3222 return StringEqualsAscii(str, asciiBytes, length);
3223 }
3224
JS_PutEscapedLinearString(char * buffer,size_t size,JSLinearString * str,char quote)3225 JS_PUBLIC_API size_t JS_PutEscapedLinearString(char* buffer, size_t size,
3226 JSLinearString* str,
3227 char quote) {
3228 return PutEscapedString(buffer, size, str, quote);
3229 }
3230
JS_PutEscapedString(JSContext * cx,char * buffer,size_t size,JSString * str,char quote)3231 JS_PUBLIC_API size_t JS_PutEscapedString(JSContext* cx, char* buffer,
3232 size_t size, JSString* str,
3233 char quote) {
3234 AssertHeapIsIdle();
3235 JSLinearString* linearStr = str->ensureLinear(cx);
3236 if (!linearStr) {
3237 return size_t(-1);
3238 }
3239 return PutEscapedString(buffer, size, linearStr, quote);
3240 }
3241
JS_NewDependentString(JSContext * cx,HandleString str,size_t start,size_t length)3242 JS_PUBLIC_API JSString* JS_NewDependentString(JSContext* cx, HandleString str,
3243 size_t start, size_t length) {
3244 AssertHeapIsIdle();
3245 CHECK_THREAD(cx);
3246 return NewDependentString(cx, str, start, length);
3247 }
3248
JS_ConcatStrings(JSContext * cx,HandleString left,HandleString right)3249 JS_PUBLIC_API JSString* JS_ConcatStrings(JSContext* cx, HandleString left,
3250 HandleString right) {
3251 AssertHeapIsIdle();
3252 CHECK_THREAD(cx);
3253 return ConcatStrings<CanGC>(cx, left, right);
3254 }
3255
JS_DecodeBytes(JSContext * cx,const char * src,size_t srclen,char16_t * dst,size_t * dstlenp)3256 JS_PUBLIC_API bool JS_DecodeBytes(JSContext* cx, const char* src, size_t srclen,
3257 char16_t* dst, size_t* dstlenp) {
3258 AssertHeapIsIdle();
3259 CHECK_THREAD(cx);
3260
3261 if (!dst) {
3262 *dstlenp = srclen;
3263 return true;
3264 }
3265
3266 size_t dstlen = *dstlenp;
3267
3268 if (srclen > dstlen) {
3269 CopyAndInflateChars(dst, src, dstlen);
3270
3271 gc::AutoSuppressGC suppress(cx);
3272 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3273 JSMSG_BUFFER_TOO_SMALL);
3274 return false;
3275 }
3276
3277 CopyAndInflateChars(dst, src, srclen);
3278 *dstlenp = srclen;
3279 return true;
3280 }
3281
JS_EncodeStringToASCII(JSContext * cx,JSString * str)3282 JS_PUBLIC_API JS::UniqueChars JS_EncodeStringToASCII(JSContext* cx,
3283 JSString* str) {
3284 AssertHeapIsIdle();
3285 CHECK_THREAD(cx);
3286
3287 return js::EncodeAscii(cx, str);
3288 }
3289
JS_EncodeStringToLatin1(JSContext * cx,JSString * str)3290 JS_PUBLIC_API JS::UniqueChars JS_EncodeStringToLatin1(JSContext* cx,
3291 JSString* str) {
3292 AssertHeapIsIdle();
3293 CHECK_THREAD(cx);
3294
3295 return js::EncodeLatin1(cx, str);
3296 }
3297
JS_EncodeStringToUTF8(JSContext * cx,HandleString str)3298 JS_PUBLIC_API JS::UniqueChars JS_EncodeStringToUTF8(JSContext* cx,
3299 HandleString str) {
3300 AssertHeapIsIdle();
3301 CHECK_THREAD(cx);
3302
3303 return StringToNewUTF8CharsZ(cx, *str);
3304 }
3305
JS_GetStringEncodingLength(JSContext * cx,JSString * str)3306 JS_PUBLIC_API size_t JS_GetStringEncodingLength(JSContext* cx, JSString* str) {
3307 AssertHeapIsIdle();
3308 CHECK_THREAD(cx);
3309
3310 if (!str->ensureLinear(cx)) {
3311 return size_t(-1);
3312 }
3313 return str->length();
3314 }
3315
JS_EncodeStringToBuffer(JSContext * cx,JSString * str,char * buffer,size_t length)3316 JS_PUBLIC_API bool JS_EncodeStringToBuffer(JSContext* cx, JSString* str,
3317 char* buffer, size_t length) {
3318 AssertHeapIsIdle();
3319 CHECK_THREAD(cx);
3320
3321 JSLinearString* linear = str->ensureLinear(cx);
3322 if (!linear) {
3323 return false;
3324 }
3325
3326 JS::AutoCheckCannotGC nogc;
3327 size_t writeLength = std::min(linear->length(), length);
3328 if (linear->hasLatin1Chars()) {
3329 mozilla::PodCopy(reinterpret_cast<Latin1Char*>(buffer),
3330 linear->latin1Chars(nogc), writeLength);
3331 } else {
3332 const char16_t* src = linear->twoByteChars(nogc);
3333 for (size_t i = 0; i < writeLength; i++) {
3334 buffer[i] = char(src[i]);
3335 }
3336 }
3337 return true;
3338 }
3339
3340 JS_PUBLIC_API mozilla::Maybe<mozilla::Tuple<size_t, size_t>>
JS_EncodeStringToUTF8BufferPartial(JSContext * cx,JSString * str,mozilla::Span<char> buffer)3341 JS_EncodeStringToUTF8BufferPartial(JSContext* cx, JSString* str,
3342 mozilla::Span<char> buffer) {
3343 AssertHeapIsIdle();
3344 CHECK_THREAD(cx);
3345 JS::AutoCheckCannotGC nogc;
3346 return str->encodeUTF8Partial(nogc, buffer);
3347 }
3348
NewSymbol(JSContext * cx,HandleString description)3349 JS_PUBLIC_API JS::Symbol* JS::NewSymbol(JSContext* cx,
3350 HandleString description) {
3351 AssertHeapIsIdle();
3352 CHECK_THREAD(cx);
3353 if (description) {
3354 cx->check(description);
3355 }
3356
3357 return Symbol::new_(cx, SymbolCode::UniqueSymbol, description);
3358 }
3359
GetSymbolFor(JSContext * cx,HandleString key)3360 JS_PUBLIC_API JS::Symbol* JS::GetSymbolFor(JSContext* cx, HandleString key) {
3361 AssertHeapIsIdle();
3362 CHECK_THREAD(cx);
3363 cx->check(key);
3364
3365 return Symbol::for_(cx, key);
3366 }
3367
GetSymbolDescription(HandleSymbol symbol)3368 JS_PUBLIC_API JSString* JS::GetSymbolDescription(HandleSymbol symbol) {
3369 return symbol->description();
3370 }
3371
GetSymbolCode(Handle<Symbol * > symbol)3372 JS_PUBLIC_API JS::SymbolCode JS::GetSymbolCode(Handle<Symbol*> symbol) {
3373 return symbol->code();
3374 }
3375
GetWellKnownSymbol(JSContext * cx,JS::SymbolCode which)3376 JS_PUBLIC_API JS::Symbol* JS::GetWellKnownSymbol(JSContext* cx,
3377 JS::SymbolCode which) {
3378 return cx->wellKnownSymbols().get(which);
3379 }
3380
GetWellKnownSymbolKey(JSContext * cx,JS::SymbolCode which)3381 JS_PUBLIC_API JS::PropertyKey JS::GetWellKnownSymbolKey(JSContext* cx,
3382 JS::SymbolCode which) {
3383 return PropertyKey::Symbol(cx->wellKnownSymbols().get(which));
3384 }
3385
3386 #ifdef DEBUG
PropertySpecNameIsDigits(JSPropertySpec::Name name)3387 static bool PropertySpecNameIsDigits(JSPropertySpec::Name name) {
3388 if (name.isSymbol()) {
3389 return false;
3390 }
3391 const char* s = name.string();
3392 if (!*s) {
3393 return false;
3394 }
3395 for (; *s; s++) {
3396 if (*s < '0' || *s > '9') {
3397 return false;
3398 }
3399 }
3400 return true;
3401 }
3402 #endif // DEBUG
3403
PropertySpecNameEqualsId(JSPropertySpec::Name name,HandleId id)3404 JS_PUBLIC_API bool JS::PropertySpecNameEqualsId(JSPropertySpec::Name name,
3405 HandleId id) {
3406 if (name.isSymbol()) {
3407 return id.isWellKnownSymbol(name.symbol());
3408 }
3409
3410 MOZ_ASSERT(!PropertySpecNameIsDigits(name));
3411 return id.isAtom() && JS_LinearStringEqualsAscii(id.toAtom(), name.string());
3412 }
3413
JS_Stringify(JSContext * cx,MutableHandleValue vp,HandleObject replacer,HandleValue space,JSONWriteCallback callback,void * data)3414 JS_PUBLIC_API bool JS_Stringify(JSContext* cx, MutableHandleValue vp,
3415 HandleObject replacer, HandleValue space,
3416 JSONWriteCallback callback, void* data) {
3417 AssertHeapIsIdle();
3418 CHECK_THREAD(cx);
3419 cx->check(replacer, space);
3420 StringBuffer sb(cx);
3421 if (!sb.ensureTwoByteChars()) {
3422 return false;
3423 }
3424 if (!Stringify(cx, vp, replacer, space, sb, StringifyBehavior::Normal)) {
3425 return false;
3426 }
3427 if (sb.empty() && !sb.append(cx->names().null)) {
3428 return false;
3429 }
3430 return callback(sb.rawTwoByteBegin(), sb.length(), data);
3431 }
3432
ToJSONMaybeSafely(JSContext * cx,JS::HandleObject input,JSONWriteCallback callback,void * data)3433 JS_PUBLIC_API bool JS::ToJSONMaybeSafely(JSContext* cx, JS::HandleObject input,
3434 JSONWriteCallback callback,
3435 void* data) {
3436 AssertHeapIsIdle();
3437 CHECK_THREAD(cx);
3438 cx->check(input);
3439
3440 StringBuffer sb(cx);
3441 if (!sb.ensureTwoByteChars()) {
3442 return false;
3443 }
3444
3445 RootedValue inputValue(cx, ObjectValue(*input));
3446 if (!Stringify(cx, &inputValue, nullptr, NullHandleValue, sb,
3447 StringifyBehavior::RestrictedSafe))
3448 return false;
3449
3450 if (sb.empty() && !sb.append(cx->names().null)) {
3451 return false;
3452 }
3453
3454 return callback(sb.rawTwoByteBegin(), sb.length(), data);
3455 }
3456
JS_ParseJSON(JSContext * cx,const char16_t * chars,uint32_t len,MutableHandleValue vp)3457 JS_PUBLIC_API bool JS_ParseJSON(JSContext* cx, const char16_t* chars,
3458 uint32_t len, MutableHandleValue vp) {
3459 AssertHeapIsIdle();
3460 CHECK_THREAD(cx);
3461 return ParseJSONWithReviver(cx, mozilla::Range<const char16_t>(chars, len),
3462 NullHandleValue, vp);
3463 }
3464
JS_ParseJSON(JSContext * cx,HandleString str,MutableHandleValue vp)3465 JS_PUBLIC_API bool JS_ParseJSON(JSContext* cx, HandleString str,
3466 MutableHandleValue vp) {
3467 return JS_ParseJSONWithReviver(cx, str, NullHandleValue, vp);
3468 }
3469
JS_ParseJSONWithReviver(JSContext * cx,const char16_t * chars,uint32_t len,HandleValue reviver,MutableHandleValue vp)3470 JS_PUBLIC_API bool JS_ParseJSONWithReviver(JSContext* cx, const char16_t* chars,
3471 uint32_t len, HandleValue reviver,
3472 MutableHandleValue vp) {
3473 AssertHeapIsIdle();
3474 CHECK_THREAD(cx);
3475 return ParseJSONWithReviver(cx, mozilla::Range<const char16_t>(chars, len),
3476 reviver, vp);
3477 }
3478
JS_ParseJSONWithReviver(JSContext * cx,HandleString str,HandleValue reviver,MutableHandleValue vp)3479 JS_PUBLIC_API bool JS_ParseJSONWithReviver(JSContext* cx, HandleString str,
3480 HandleValue reviver,
3481 MutableHandleValue vp) {
3482 AssertHeapIsIdle();
3483 CHECK_THREAD(cx);
3484 cx->check(str);
3485
3486 AutoStableStringChars stableChars(cx);
3487 if (!stableChars.init(cx, str)) {
3488 return false;
3489 }
3490
3491 return stableChars.isLatin1()
3492 ? ParseJSONWithReviver(cx, stableChars.latin1Range(), reviver, vp)
3493 : ParseJSONWithReviver(cx, stableChars.twoByteRange(), reviver,
3494 vp);
3495 }
3496
3497 /************************************************************************/
3498
JS_ReportErrorASCII(JSContext * cx,const char * format,...)3499 JS_PUBLIC_API void JS_ReportErrorASCII(JSContext* cx, const char* format, ...) {
3500 va_list ap;
3501
3502 AssertHeapIsIdle();
3503 va_start(ap, format);
3504 ReportErrorVA(cx, IsWarning::No, format, ArgumentsAreASCII, ap);
3505 va_end(ap);
3506 }
3507
JS_ReportErrorLatin1(JSContext * cx,const char * format,...)3508 JS_PUBLIC_API void JS_ReportErrorLatin1(JSContext* cx, const char* format,
3509 ...) {
3510 va_list ap;
3511
3512 AssertHeapIsIdle();
3513 va_start(ap, format);
3514 ReportErrorVA(cx, IsWarning::No, format, ArgumentsAreLatin1, ap);
3515 va_end(ap);
3516 }
3517
JS_ReportErrorUTF8(JSContext * cx,const char * format,...)3518 JS_PUBLIC_API void JS_ReportErrorUTF8(JSContext* cx, const char* format, ...) {
3519 va_list ap;
3520
3521 AssertHeapIsIdle();
3522 va_start(ap, format);
3523 ReportErrorVA(cx, IsWarning::No, format, ArgumentsAreUTF8, ap);
3524 va_end(ap);
3525 }
3526
JS_ReportErrorNumberASCII(JSContext * cx,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,...)3527 JS_PUBLIC_API void JS_ReportErrorNumberASCII(JSContext* cx,
3528 JSErrorCallback errorCallback,
3529 void* userRef,
3530 const unsigned errorNumber, ...) {
3531 va_list ap;
3532 va_start(ap, errorNumber);
3533 JS_ReportErrorNumberASCIIVA(cx, errorCallback, userRef, errorNumber, ap);
3534 va_end(ap);
3535 }
3536
JS_ReportErrorNumberASCIIVA(JSContext * cx,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,va_list ap)3537 JS_PUBLIC_API void JS_ReportErrorNumberASCIIVA(JSContext* cx,
3538 JSErrorCallback errorCallback,
3539 void* userRef,
3540 const unsigned errorNumber,
3541 va_list ap) {
3542 AssertHeapIsIdle();
3543 ReportErrorNumberVA(cx, IsWarning::No, errorCallback, userRef, errorNumber,
3544 ArgumentsAreASCII, ap);
3545 }
3546
JS_ReportErrorNumberLatin1(JSContext * cx,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,...)3547 JS_PUBLIC_API void JS_ReportErrorNumberLatin1(JSContext* cx,
3548 JSErrorCallback errorCallback,
3549 void* userRef,
3550 const unsigned errorNumber, ...) {
3551 va_list ap;
3552 va_start(ap, errorNumber);
3553 JS_ReportErrorNumberLatin1VA(cx, errorCallback, userRef, errorNumber, ap);
3554 va_end(ap);
3555 }
3556
JS_ReportErrorNumberLatin1VA(JSContext * cx,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,va_list ap)3557 JS_PUBLIC_API void JS_ReportErrorNumberLatin1VA(JSContext* cx,
3558 JSErrorCallback errorCallback,
3559 void* userRef,
3560 const unsigned errorNumber,
3561 va_list ap) {
3562 AssertHeapIsIdle();
3563 ReportErrorNumberVA(cx, IsWarning::No, errorCallback, userRef, errorNumber,
3564 ArgumentsAreLatin1, ap);
3565 }
3566
JS_ReportErrorNumberUTF8(JSContext * cx,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,...)3567 JS_PUBLIC_API void JS_ReportErrorNumberUTF8(JSContext* cx,
3568 JSErrorCallback errorCallback,
3569 void* userRef,
3570 const unsigned errorNumber, ...) {
3571 va_list ap;
3572 va_start(ap, errorNumber);
3573 JS_ReportErrorNumberUTF8VA(cx, errorCallback, userRef, errorNumber, ap);
3574 va_end(ap);
3575 }
3576
JS_ReportErrorNumberUTF8VA(JSContext * cx,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,va_list ap)3577 JS_PUBLIC_API void JS_ReportErrorNumberUTF8VA(JSContext* cx,
3578 JSErrorCallback errorCallback,
3579 void* userRef,
3580 const unsigned errorNumber,
3581 va_list ap) {
3582 AssertHeapIsIdle();
3583 ReportErrorNumberVA(cx, IsWarning::No, errorCallback, userRef, errorNumber,
3584 ArgumentsAreUTF8, ap);
3585 }
3586
JS_ReportErrorNumberUTF8Array(JSContext * cx,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,const char ** args)3587 JS_PUBLIC_API void JS_ReportErrorNumberUTF8Array(JSContext* cx,
3588 JSErrorCallback errorCallback,
3589 void* userRef,
3590 const unsigned errorNumber,
3591 const char** args) {
3592 AssertHeapIsIdle();
3593 ReportErrorNumberUTF8Array(cx, IsWarning::No, errorCallback, userRef,
3594 errorNumber, args);
3595 }
3596
JS_ReportErrorNumberUC(JSContext * cx,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,...)3597 JS_PUBLIC_API void JS_ReportErrorNumberUC(JSContext* cx,
3598 JSErrorCallback errorCallback,
3599 void* userRef,
3600 const unsigned errorNumber, ...) {
3601 va_list ap;
3602
3603 AssertHeapIsIdle();
3604 va_start(ap, errorNumber);
3605 ReportErrorNumberVA(cx, IsWarning::No, errorCallback, userRef, errorNumber,
3606 ArgumentsAreUnicode, ap);
3607 va_end(ap);
3608 }
3609
JS_ReportErrorNumberUCArray(JSContext * cx,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,const char16_t ** args)3610 JS_PUBLIC_API void JS_ReportErrorNumberUCArray(JSContext* cx,
3611 JSErrorCallback errorCallback,
3612 void* userRef,
3613 const unsigned errorNumber,
3614 const char16_t** args) {
3615 AssertHeapIsIdle();
3616 ReportErrorNumberUCArray(cx, IsWarning::No, errorCallback, userRef,
3617 errorNumber, args);
3618 }
3619
JS_ReportOutOfMemory(JSContext * cx)3620 JS_PUBLIC_API void JS_ReportOutOfMemory(JSContext* cx) {
3621 ReportOutOfMemory(cx);
3622 }
3623
JS_ReportAllocationOverflow(JSContext * cx)3624 JS_PUBLIC_API void JS_ReportAllocationOverflow(JSContext* cx) {
3625 ReportAllocationOverflow(cx);
3626 }
3627
JS_ExpandErrorArgumentsASCII(JSContext * cx,JSErrorCallback errorCallback,const unsigned errorNumber,JSErrorReport * reportp,...)3628 JS_PUBLIC_API bool JS_ExpandErrorArgumentsASCII(JSContext* cx,
3629 JSErrorCallback errorCallback,
3630 const unsigned errorNumber,
3631 JSErrorReport* reportp, ...) {
3632 va_list ap;
3633 bool ok;
3634
3635 AssertHeapIsIdle();
3636 va_start(ap, reportp);
3637 ok = ExpandErrorArgumentsVA(cx, errorCallback, nullptr, errorNumber,
3638 ArgumentsAreASCII, reportp, ap);
3639 va_end(ap);
3640 return ok;
3641 }
3642 /************************************************************************/
3643
JS_SetDefaultLocale(JSRuntime * rt,const char * locale)3644 JS_PUBLIC_API bool JS_SetDefaultLocale(JSRuntime* rt, const char* locale) {
3645 AssertHeapIsIdle();
3646 return rt->setDefaultLocale(locale);
3647 }
3648
JS_GetDefaultLocale(JSContext * cx)3649 JS_PUBLIC_API UniqueChars JS_GetDefaultLocale(JSContext* cx) {
3650 AssertHeapIsIdle();
3651 if (const char* locale = cx->runtime()->getDefaultLocale()) {
3652 return DuplicateString(cx, locale);
3653 }
3654
3655 return nullptr;
3656 }
3657
JS_ResetDefaultLocale(JSRuntime * rt)3658 JS_PUBLIC_API void JS_ResetDefaultLocale(JSRuntime* rt) {
3659 AssertHeapIsIdle();
3660 rt->resetDefaultLocale();
3661 }
3662
JS_SetLocaleCallbacks(JSRuntime * rt,const JSLocaleCallbacks * callbacks)3663 JS_PUBLIC_API void JS_SetLocaleCallbacks(JSRuntime* rt,
3664 const JSLocaleCallbacks* callbacks) {
3665 AssertHeapIsIdle();
3666 rt->localeCallbacks = callbacks;
3667 }
3668
JS_GetLocaleCallbacks(JSRuntime * rt)3669 JS_PUBLIC_API const JSLocaleCallbacks* JS_GetLocaleCallbacks(JSRuntime* rt) {
3670 /* This function can be called by a finalizer. */
3671 return rt->localeCallbacks;
3672 }
3673
3674 /************************************************************************/
3675
JS_IsExceptionPending(JSContext * cx)3676 JS_PUBLIC_API bool JS_IsExceptionPending(JSContext* cx) {
3677 /* This function can be called by a finalizer. */
3678 return (bool)cx->isExceptionPending();
3679 }
3680
JS_IsThrowingOutOfMemory(JSContext * cx)3681 JS_PUBLIC_API bool JS_IsThrowingOutOfMemory(JSContext* cx) {
3682 return cx->isThrowingOutOfMemory();
3683 }
3684
JS_GetPendingException(JSContext * cx,MutableHandleValue vp)3685 JS_PUBLIC_API bool JS_GetPendingException(JSContext* cx,
3686 MutableHandleValue vp) {
3687 AssertHeapIsIdle();
3688 CHECK_THREAD(cx);
3689 if (!cx->isExceptionPending()) {
3690 return false;
3691 }
3692 return cx->getPendingException(vp);
3693 }
3694
JS_SetPendingException(JSContext * cx,HandleValue value,JS::ExceptionStackBehavior behavior)3695 JS_PUBLIC_API void JS_SetPendingException(JSContext* cx, HandleValue value,
3696 JS::ExceptionStackBehavior behavior) {
3697 AssertHeapIsIdle();
3698 CHECK_THREAD(cx);
3699 // We don't check the compartment of `value` here, because we're not
3700 // doing anything with it other than storing it, and stored
3701 // exception values can be in an abitrary compartment.
3702
3703 if (behavior == JS::ExceptionStackBehavior::Capture) {
3704 cx->setPendingException(value, ShouldCaptureStack::Always);
3705 } else {
3706 cx->setPendingException(value, nullptr);
3707 }
3708 }
3709
JS_ClearPendingException(JSContext * cx)3710 JS_PUBLIC_API void JS_ClearPendingException(JSContext* cx) {
3711 AssertHeapIsIdle();
3712 cx->clearPendingException();
3713 }
3714
AutoSaveExceptionState(JSContext * cx)3715 JS::AutoSaveExceptionState::AutoSaveExceptionState(JSContext* cx)
3716 : context(cx), status(cx->status), exceptionValue(cx), exceptionStack(cx) {
3717 AssertHeapIsIdle();
3718 CHECK_THREAD(cx);
3719 if (IsCatchableExceptionStatus(status)) {
3720 exceptionValue = cx->unwrappedException();
3721 exceptionStack = cx->unwrappedExceptionStack();
3722 }
3723 cx->clearPendingException();
3724 }
3725
drop()3726 void JS::AutoSaveExceptionState::drop() {
3727 status = JS::ExceptionStatus::None;
3728 exceptionValue.setUndefined();
3729 exceptionStack = nullptr;
3730 }
3731
restore()3732 void JS::AutoSaveExceptionState::restore() {
3733 context->status = status;
3734 context->unwrappedException() = exceptionValue;
3735 if (exceptionStack) {
3736 context->unwrappedExceptionStack() = &exceptionStack->as<SavedFrame>();
3737 }
3738 drop();
3739 }
3740
~AutoSaveExceptionState()3741 JS::AutoSaveExceptionState::~AutoSaveExceptionState() {
3742 // NOTE: An interrupt/uncatchable exception or a debugger-forced-return may be
3743 // clobbered here by the saved exception. If that is not desired, this
3744 // state should be dropped before the destructor fires.
3745 if (!context->isExceptionPending()) {
3746 if (status != JS::ExceptionStatus::None) {
3747 context->status = status;
3748 }
3749 if (IsCatchableExceptionStatus(status)) {
3750 context->unwrappedException() = exceptionValue;
3751 if (exceptionStack) {
3752 context->unwrappedExceptionStack() = &exceptionStack->as<SavedFrame>();
3753 }
3754 }
3755 }
3756 }
3757
JS_ErrorFromException(JSContext * cx,HandleObject obj)3758 JS_PUBLIC_API JSErrorReport* JS_ErrorFromException(JSContext* cx,
3759 HandleObject obj) {
3760 AssertHeapIsIdle();
3761 CHECK_THREAD(cx);
3762 cx->check(obj);
3763 return ErrorFromException(cx, obj);
3764 }
3765
initBorrowedLinebuf(const char16_t * linebufArg,size_t linebufLengthArg,size_t tokenOffsetArg)3766 void JSErrorReport::initBorrowedLinebuf(const char16_t* linebufArg,
3767 size_t linebufLengthArg,
3768 size_t tokenOffsetArg) {
3769 MOZ_ASSERT(linebufArg);
3770 MOZ_ASSERT(tokenOffsetArg <= linebufLengthArg);
3771 MOZ_ASSERT(linebufArg[linebufLengthArg] == '\0');
3772
3773 linebuf_ = linebufArg;
3774 linebufLength_ = linebufLengthArg;
3775 tokenOffset_ = tokenOffsetArg;
3776 }
3777
freeLinebuf()3778 void JSErrorReport::freeLinebuf() {
3779 if (ownsLinebuf_ && linebuf_) {
3780 js_free((void*)linebuf_);
3781 ownsLinebuf_ = false;
3782 }
3783 linebuf_ = nullptr;
3784 }
3785
newMessageString(JSContext * cx)3786 JSString* JSErrorBase::newMessageString(JSContext* cx) {
3787 if (!message_) {
3788 return cx->runtime()->emptyString;
3789 }
3790
3791 return JS_NewStringCopyUTF8Z(cx, message_);
3792 }
3793
freeMessage()3794 void JSErrorBase::freeMessage() {
3795 if (ownsMessage_) {
3796 js_free((void*)message_.get());
3797 ownsMessage_ = false;
3798 }
3799 message_ = JS::ConstUTF8CharsZ();
3800 }
3801
JSErrorNotes()3802 JSErrorNotes::JSErrorNotes() : notes_() {}
3803
3804 JSErrorNotes::~JSErrorNotes() = default;
3805
CreateErrorNoteVA(JSContext * cx,const char * filename,unsigned sourceId,unsigned lineno,unsigned column,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,ErrorArgumentsType argumentsType,va_list ap)3806 static UniquePtr<JSErrorNotes::Note> CreateErrorNoteVA(
3807 JSContext* cx, const char* filename, unsigned sourceId, unsigned lineno,
3808 unsigned column, JSErrorCallback errorCallback, void* userRef,
3809 const unsigned errorNumber, ErrorArgumentsType argumentsType, va_list ap) {
3810 auto note = MakeUnique<JSErrorNotes::Note>();
3811 if (!note) {
3812 ReportOutOfMemory(cx);
3813 return nullptr;
3814 }
3815
3816 note->errorNumber = errorNumber;
3817 note->filename = filename;
3818 note->sourceId = sourceId;
3819 note->lineno = lineno;
3820 note->column = column;
3821
3822 if (!ExpandErrorArgumentsVA(cx, errorCallback, userRef, errorNumber, nullptr,
3823 argumentsType, note.get(), ap)) {
3824 return nullptr;
3825 }
3826
3827 return note;
3828 }
3829
addNoteASCII(JSContext * cx,const char * filename,unsigned sourceId,unsigned lineno,unsigned column,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,...)3830 bool JSErrorNotes::addNoteASCII(JSContext* cx, const char* filename,
3831 unsigned sourceId, unsigned lineno,
3832 unsigned column, JSErrorCallback errorCallback,
3833 void* userRef, const unsigned errorNumber,
3834 ...) {
3835 va_list ap;
3836 va_start(ap, errorNumber);
3837 auto note =
3838 CreateErrorNoteVA(cx, filename, sourceId, lineno, column, errorCallback,
3839 userRef, errorNumber, ArgumentsAreASCII, ap);
3840 va_end(ap);
3841
3842 if (!note) {
3843 return false;
3844 }
3845 if (!notes_.append(std::move(note))) {
3846 ReportOutOfMemory(cx);
3847 return false;
3848 }
3849 return true;
3850 }
3851
addNoteLatin1(JSContext * cx,const char * filename,unsigned sourceId,unsigned lineno,unsigned column,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,...)3852 bool JSErrorNotes::addNoteLatin1(JSContext* cx, const char* filename,
3853 unsigned sourceId, unsigned lineno,
3854 unsigned column, JSErrorCallback errorCallback,
3855 void* userRef, const unsigned errorNumber,
3856 ...) {
3857 va_list ap;
3858 va_start(ap, errorNumber);
3859 auto note =
3860 CreateErrorNoteVA(cx, filename, sourceId, lineno, column, errorCallback,
3861 userRef, errorNumber, ArgumentsAreLatin1, ap);
3862 va_end(ap);
3863
3864 if (!note) {
3865 return false;
3866 }
3867 if (!notes_.append(std::move(note))) {
3868 ReportOutOfMemory(cx);
3869 return false;
3870 }
3871 return true;
3872 }
3873
addNoteUTF8(JSContext * cx,const char * filename,unsigned sourceId,unsigned lineno,unsigned column,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,...)3874 bool JSErrorNotes::addNoteUTF8(JSContext* cx, const char* filename,
3875 unsigned sourceId, unsigned lineno,
3876 unsigned column, JSErrorCallback errorCallback,
3877 void* userRef, const unsigned errorNumber, ...) {
3878 va_list ap;
3879 va_start(ap, errorNumber);
3880 auto note =
3881 CreateErrorNoteVA(cx, filename, sourceId, lineno, column, errorCallback,
3882 userRef, errorNumber, ArgumentsAreUTF8, ap);
3883 va_end(ap);
3884
3885 if (!note) {
3886 return false;
3887 }
3888 if (!notes_.append(std::move(note))) {
3889 ReportOutOfMemory(cx);
3890 return false;
3891 }
3892 return true;
3893 }
3894
length()3895 JS_PUBLIC_API size_t JSErrorNotes::length() { return notes_.length(); }
3896
copy(JSContext * cx)3897 UniquePtr<JSErrorNotes> JSErrorNotes::copy(JSContext* cx) {
3898 auto copiedNotes = MakeUnique<JSErrorNotes>();
3899 if (!copiedNotes) {
3900 ReportOutOfMemory(cx);
3901 return nullptr;
3902 }
3903
3904 for (auto&& note : *this) {
3905 UniquePtr<JSErrorNotes::Note> copied = CopyErrorNote(cx, note.get());
3906 if (!copied) {
3907 return nullptr;
3908 }
3909
3910 if (!copiedNotes->notes_.append(std::move(copied))) {
3911 return nullptr;
3912 }
3913 }
3914
3915 return copiedNotes;
3916 }
3917
begin()3918 JS_PUBLIC_API JSErrorNotes::iterator JSErrorNotes::begin() {
3919 return iterator(notes_.begin());
3920 }
3921
end()3922 JS_PUBLIC_API JSErrorNotes::iterator JSErrorNotes::end() {
3923 return iterator(notes_.end());
3924 }
3925
JS_AbortIfWrongThread(JSContext * cx)3926 extern MOZ_NEVER_INLINE JS_PUBLIC_API void JS_AbortIfWrongThread(
3927 JSContext* cx) {
3928 if (!CurrentThreadCanAccessRuntime(cx->runtime())) {
3929 MOZ_CRASH();
3930 }
3931 if (TlsContext.get() != cx) {
3932 MOZ_CRASH();
3933 }
3934 }
3935
3936 #ifdef JS_GC_ZEAL
JS_GetGCZealBits(JSContext * cx,uint32_t * zealBits,uint32_t * frequency,uint32_t * nextScheduled)3937 JS_PUBLIC_API void JS_GetGCZealBits(JSContext* cx, uint32_t* zealBits,
3938 uint32_t* frequency,
3939 uint32_t* nextScheduled) {
3940 cx->runtime()->gc.getZealBits(zealBits, frequency, nextScheduled);
3941 }
3942
JS_SetGCZeal(JSContext * cx,uint8_t zeal,uint32_t frequency)3943 JS_PUBLIC_API void JS_SetGCZeal(JSContext* cx, uint8_t zeal,
3944 uint32_t frequency) {
3945 cx->runtime()->gc.setZeal(zeal, frequency);
3946 }
3947
JS_UnsetGCZeal(JSContext * cx,uint8_t zeal)3948 JS_PUBLIC_API void JS_UnsetGCZeal(JSContext* cx, uint8_t zeal) {
3949 cx->runtime()->gc.unsetZeal(zeal);
3950 }
3951
JS_ScheduleGC(JSContext * cx,uint32_t count)3952 JS_PUBLIC_API void JS_ScheduleGC(JSContext* cx, uint32_t count) {
3953 cx->runtime()->gc.setNextScheduled(count);
3954 }
3955 #endif
3956
JS_SetParallelParsingEnabled(JSContext * cx,bool enabled)3957 JS_PUBLIC_API void JS_SetParallelParsingEnabled(JSContext* cx, bool enabled) {
3958 cx->runtime()->setParallelParsingEnabled(enabled);
3959 }
3960
JS_SetOffthreadIonCompilationEnabled(JSContext * cx,bool enabled)3961 JS_PUBLIC_API void JS_SetOffthreadIonCompilationEnabled(JSContext* cx,
3962 bool enabled) {
3963 cx->runtime()->setOffthreadIonCompilationEnabled(enabled);
3964 }
3965
JS_SetGlobalJitCompilerOption(JSContext * cx,JSJitCompilerOption opt,uint32_t value)3966 JS_PUBLIC_API void JS_SetGlobalJitCompilerOption(JSContext* cx,
3967 JSJitCompilerOption opt,
3968 uint32_t value) {
3969 JSRuntime* rt = cx->runtime();
3970 switch (opt) {
3971 case JSJITCOMPILER_BASELINE_INTERPRETER_WARMUP_TRIGGER:
3972 if (value == uint32_t(-1)) {
3973 jit::DefaultJitOptions defaultValues;
3974 value = defaultValues.baselineInterpreterWarmUpThreshold;
3975 }
3976 jit::JitOptions.baselineInterpreterWarmUpThreshold = value;
3977 break;
3978 case JSJITCOMPILER_BASELINE_WARMUP_TRIGGER:
3979 if (value == uint32_t(-1)) {
3980 jit::DefaultJitOptions defaultValues;
3981 value = defaultValues.baselineJitWarmUpThreshold;
3982 }
3983 jit::JitOptions.baselineJitWarmUpThreshold = value;
3984 break;
3985 case JSJITCOMPILER_IC_FORCE_MEGAMORPHIC:
3986 jit::JitOptions.forceMegamorphicICs = !!value;
3987 break;
3988 case JSJITCOMPILER_ION_NORMAL_WARMUP_TRIGGER:
3989 if (value == uint32_t(-1)) {
3990 jit::JitOptions.resetNormalIonWarmUpThreshold();
3991 break;
3992 }
3993 jit::JitOptions.setNormalIonWarmUpThreshold(value);
3994 break;
3995 case JSJITCOMPILER_ION_GVN_ENABLE:
3996 if (value == 0) {
3997 jit::JitOptions.enableGvn(false);
3998 JitSpew(js::jit::JitSpew_IonScripts, "Disable ion's GVN");
3999 } else {
4000 jit::JitOptions.enableGvn(true);
4001 JitSpew(js::jit::JitSpew_IonScripts, "Enable ion's GVN");
4002 }
4003 break;
4004 case JSJITCOMPILER_ION_FORCE_IC:
4005 if (value == 0) {
4006 jit::JitOptions.forceInlineCaches = false;
4007 JitSpew(js::jit::JitSpew_IonScripts,
4008 "Ion: Enable non-IC optimizations.");
4009 } else {
4010 jit::JitOptions.forceInlineCaches = true;
4011 JitSpew(js::jit::JitSpew_IonScripts,
4012 "Ion: Disable non-IC optimizations.");
4013 }
4014 break;
4015 case JSJITCOMPILER_ION_CHECK_RANGE_ANALYSIS:
4016 if (value == 0) {
4017 jit::JitOptions.checkRangeAnalysis = false;
4018 JitSpew(js::jit::JitSpew_IonScripts,
4019 "Ion: Enable range analysis checks.");
4020 } else {
4021 jit::JitOptions.checkRangeAnalysis = true;
4022 JitSpew(js::jit::JitSpew_IonScripts,
4023 "Ion: Disable range analysis checks.");
4024 }
4025 break;
4026 case JSJITCOMPILER_ION_ENABLE:
4027 if (value == 1) {
4028 jit::JitOptions.ion = true;
4029 JitSpew(js::jit::JitSpew_IonScripts, "Enable ion");
4030 } else if (value == 0) {
4031 jit::JitOptions.ion = false;
4032 JitSpew(js::jit::JitSpew_IonScripts, "Disable ion");
4033 }
4034 break;
4035 case JSJITCOMPILER_JIT_TRUSTEDPRINCIPALS_ENABLE:
4036 if (value == 1) {
4037 jit::JitOptions.jitForTrustedPrincipals = true;
4038 JitSpew(js::jit::JitSpew_IonScripts,
4039 "Enable ion and baselinejit for trusted principals");
4040 } else if (value == 0) {
4041 jit::JitOptions.jitForTrustedPrincipals = false;
4042 JitSpew(js::jit::JitSpew_IonScripts,
4043 "Disable ion and baselinejit for trusted principals");
4044 }
4045 break;
4046 case JSJITCOMPILER_ION_FREQUENT_BAILOUT_THRESHOLD:
4047 if (value == uint32_t(-1)) {
4048 jit::DefaultJitOptions defaultValues;
4049 value = defaultValues.frequentBailoutThreshold;
4050 }
4051 jit::JitOptions.frequentBailoutThreshold = value;
4052 break;
4053 case JSJITCOMPILER_BASELINE_INTERPRETER_ENABLE:
4054 if (value == 1) {
4055 jit::JitOptions.baselineInterpreter = true;
4056 } else if (value == 0) {
4057 ReleaseAllJITCode(rt->defaultFreeOp());
4058 jit::JitOptions.baselineInterpreter = false;
4059 }
4060 break;
4061 case JSJITCOMPILER_BASELINE_ENABLE:
4062 if (value == 1) {
4063 jit::JitOptions.baselineJit = true;
4064 ReleaseAllJITCode(rt->defaultFreeOp());
4065 JitSpew(js::jit::JitSpew_BaselineScripts, "Enable baseline");
4066 } else if (value == 0) {
4067 jit::JitOptions.baselineJit = false;
4068 ReleaseAllJITCode(rt->defaultFreeOp());
4069 JitSpew(js::jit::JitSpew_BaselineScripts, "Disable baseline");
4070 }
4071 break;
4072 case JSJITCOMPILER_NATIVE_REGEXP_ENABLE:
4073 jit::JitOptions.nativeRegExp = !!value;
4074 break;
4075 case JSJITCOMPILER_OFFTHREAD_COMPILATION_ENABLE:
4076 if (value == 1) {
4077 rt->setOffthreadIonCompilationEnabled(true);
4078 JitSpew(js::jit::JitSpew_IonScripts, "Enable offthread compilation");
4079 } else if (value == 0) {
4080 rt->setOffthreadIonCompilationEnabled(false);
4081 JitSpew(js::jit::JitSpew_IonScripts, "Disable offthread compilation");
4082 }
4083 break;
4084 case JSJITCOMPILER_INLINING_BYTECODE_MAX_LENGTH:
4085 if (value == uint32_t(-1)) {
4086 jit::DefaultJitOptions defaultValues;
4087 value = defaultValues.smallFunctionMaxBytecodeLength;
4088 }
4089 jit::JitOptions.smallFunctionMaxBytecodeLength = value;
4090 break;
4091 case JSJITCOMPILER_JUMP_THRESHOLD:
4092 if (value == uint32_t(-1)) {
4093 jit::DefaultJitOptions defaultValues;
4094 value = defaultValues.jumpThreshold;
4095 }
4096 jit::JitOptions.jumpThreshold = value;
4097 break;
4098 case JSJITCOMPILER_SPECTRE_INDEX_MASKING:
4099 jit::JitOptions.spectreIndexMasking = !!value;
4100 break;
4101 case JSJITCOMPILER_SPECTRE_OBJECT_MITIGATIONS:
4102 jit::JitOptions.spectreObjectMitigations = !!value;
4103 break;
4104 case JSJITCOMPILER_SPECTRE_STRING_MITIGATIONS:
4105 jit::JitOptions.spectreStringMitigations = !!value;
4106 break;
4107 case JSJITCOMPILER_SPECTRE_VALUE_MASKING:
4108 jit::JitOptions.spectreValueMasking = !!value;
4109 break;
4110 case JSJITCOMPILER_SPECTRE_JIT_TO_CXX_CALLS:
4111 jit::JitOptions.spectreJitToCxxCalls = !!value;
4112 break;
4113 case JSJITCOMPILER_WATCHTOWER_MEGAMORPHIC:
4114 jit::JitOptions.enableWatchtowerMegamorphic = !!value;
4115 break;
4116 case JSJITCOMPILER_WASM_FOLD_OFFSETS:
4117 jit::JitOptions.wasmFoldOffsets = !!value;
4118 break;
4119 case JSJITCOMPILER_WASM_DELAY_TIER2:
4120 jit::JitOptions.wasmDelayTier2 = !!value;
4121 break;
4122 case JSJITCOMPILER_WASM_JIT_BASELINE:
4123 JS::ContextOptionsRef(cx).setWasmBaseline(!!value);
4124 break;
4125 case JSJITCOMPILER_WASM_JIT_OPTIMIZING:
4126 #ifdef ENABLE_WASM_CRANELIFT
4127 JS::ContextOptionsRef(cx).setWasmCranelift(!!value);
4128 JS::ContextOptionsRef(cx).setWasmIon(!value);
4129 #else
4130 JS::ContextOptionsRef(cx).setWasmIon(!!value);
4131 JS::ContextOptionsRef(cx).setWasmCranelift(!value);
4132 #endif
4133 break;
4134 #ifdef DEBUG
4135 case JSJITCOMPILER_FULL_DEBUG_CHECKS:
4136 jit::JitOptions.fullDebugChecks = !!value;
4137 break;
4138 #endif
4139 default:
4140 break;
4141 }
4142 }
4143
JS_GetGlobalJitCompilerOption(JSContext * cx,JSJitCompilerOption opt,uint32_t * valueOut)4144 JS_PUBLIC_API bool JS_GetGlobalJitCompilerOption(JSContext* cx,
4145 JSJitCompilerOption opt,
4146 uint32_t* valueOut) {
4147 MOZ_ASSERT(valueOut);
4148 #ifndef JS_CODEGEN_NONE
4149 JSRuntime* rt = cx->runtime();
4150 switch (opt) {
4151 case JSJITCOMPILER_BASELINE_INTERPRETER_WARMUP_TRIGGER:
4152 *valueOut = jit::JitOptions.baselineInterpreterWarmUpThreshold;
4153 break;
4154 case JSJITCOMPILER_BASELINE_WARMUP_TRIGGER:
4155 *valueOut = jit::JitOptions.baselineJitWarmUpThreshold;
4156 break;
4157 case JSJITCOMPILER_IC_FORCE_MEGAMORPHIC:
4158 *valueOut = jit::JitOptions.forceMegamorphicICs;
4159 break;
4160 case JSJITCOMPILER_ION_NORMAL_WARMUP_TRIGGER:
4161 *valueOut = jit::JitOptions.normalIonWarmUpThreshold;
4162 break;
4163 case JSJITCOMPILER_ION_FORCE_IC:
4164 *valueOut = jit::JitOptions.forceInlineCaches;
4165 break;
4166 case JSJITCOMPILER_ION_CHECK_RANGE_ANALYSIS:
4167 *valueOut = jit::JitOptions.checkRangeAnalysis;
4168 break;
4169 case JSJITCOMPILER_ION_ENABLE:
4170 *valueOut = jit::JitOptions.ion;
4171 break;
4172 case JSJITCOMPILER_ION_FREQUENT_BAILOUT_THRESHOLD:
4173 *valueOut = jit::JitOptions.frequentBailoutThreshold;
4174 break;
4175 case JSJITCOMPILER_INLINING_BYTECODE_MAX_LENGTH:
4176 *valueOut = jit::JitOptions.smallFunctionMaxBytecodeLength;
4177 break;
4178 case JSJITCOMPILER_BASELINE_INTERPRETER_ENABLE:
4179 *valueOut = jit::JitOptions.baselineInterpreter;
4180 break;
4181 case JSJITCOMPILER_BASELINE_ENABLE:
4182 *valueOut = jit::JitOptions.baselineJit;
4183 break;
4184 case JSJITCOMPILER_NATIVE_REGEXP_ENABLE:
4185 *valueOut = jit::JitOptions.nativeRegExp;
4186 break;
4187 case JSJITCOMPILER_OFFTHREAD_COMPILATION_ENABLE:
4188 *valueOut = rt->canUseOffthreadIonCompilation();
4189 break;
4190 case JSJITCOMPILER_WATCHTOWER_MEGAMORPHIC:
4191 *valueOut = jit::JitOptions.enableWatchtowerMegamorphic ? 1 : 0;
4192 break;
4193 case JSJITCOMPILER_WASM_FOLD_OFFSETS:
4194 *valueOut = jit::JitOptions.wasmFoldOffsets ? 1 : 0;
4195 break;
4196 case JSJITCOMPILER_WASM_JIT_BASELINE:
4197 *valueOut = JS::ContextOptionsRef(cx).wasmBaseline() ? 1 : 0;
4198 break;
4199 case JSJITCOMPILER_WASM_JIT_OPTIMIZING:
4200 # ifdef ENABLE_WASM_CRANELIFT
4201 *valueOut = JS::ContextOptionsRef(cx).wasmCranelift() ? 1 : 0;
4202 # else
4203 *valueOut = JS::ContextOptionsRef(cx).wasmIon() ? 1 : 0;
4204 # endif
4205 break;
4206 # ifdef DEBUG
4207 case JSJITCOMPILER_FULL_DEBUG_CHECKS:
4208 *valueOut = jit::JitOptions.fullDebugChecks ? 1 : 0;
4209 break;
4210 # endif
4211 default:
4212 return false;
4213 }
4214 #else
4215 *valueOut = 0;
4216 #endif
4217 return true;
4218 }
4219
4220 /************************************************************************/
4221
4222 #if !defined(STATIC_EXPORTABLE_JS_API) && !defined(STATIC_JS_API) && \
4223 defined(XP_WIN)
4224
4225 # include "util/WindowsWrapper.h"
4226
4227 /*
4228 * Initialization routine for the JS DLL.
4229 */
DllMain(HINSTANCE hDLL,DWORD dwReason,LPVOID lpReserved)4230 BOOL WINAPI DllMain(HINSTANCE hDLL, DWORD dwReason, LPVOID lpReserved) {
4231 return TRUE;
4232 }
4233
4234 #endif
4235
JS_IndexToId(JSContext * cx,uint32_t index,MutableHandleId id)4236 JS_PUBLIC_API bool JS_IndexToId(JSContext* cx, uint32_t index,
4237 MutableHandleId id) {
4238 return IndexToId(cx, index, id);
4239 }
4240
JS_CharsToId(JSContext * cx,JS::TwoByteChars chars,MutableHandleId idp)4241 JS_PUBLIC_API bool JS_CharsToId(JSContext* cx, JS::TwoByteChars chars,
4242 MutableHandleId idp) {
4243 RootedAtom atom(cx, AtomizeChars(cx, chars.begin().get(), chars.length()));
4244 if (!atom) {
4245 return false;
4246 }
4247 #ifdef DEBUG
4248 MOZ_ASSERT(!atom->isIndex(), "API misuse: |chars| must not encode an index");
4249 #endif
4250 idp.set(AtomToId(atom));
4251 return true;
4252 }
4253
JS_IsIdentifier(JSContext * cx,HandleString str,bool * isIdentifier)4254 JS_PUBLIC_API bool JS_IsIdentifier(JSContext* cx, HandleString str,
4255 bool* isIdentifier) {
4256 cx->check(str);
4257
4258 JSLinearString* linearStr = str->ensureLinear(cx);
4259 if (!linearStr) {
4260 return false;
4261 }
4262
4263 *isIdentifier = js::frontend::IsIdentifier(linearStr);
4264 return true;
4265 }
4266
JS_IsIdentifier(const char16_t * chars,size_t length)4267 JS_PUBLIC_API bool JS_IsIdentifier(const char16_t* chars, size_t length) {
4268 return js::frontend::IsIdentifier(chars, length);
4269 }
4270
4271 namespace JS {
4272
reset()4273 void AutoFilename::reset() {
4274 if (ss_) {
4275 ss_->Release();
4276 ss_ = nullptr;
4277 }
4278 if (filename_.is<const char*>()) {
4279 filename_.as<const char*>() = nullptr;
4280 } else {
4281 filename_.as<UniqueChars>().reset();
4282 }
4283 }
4284
setScriptSource(js::ScriptSource * p)4285 void AutoFilename::setScriptSource(js::ScriptSource* p) {
4286 MOZ_ASSERT(!ss_);
4287 MOZ_ASSERT(!get());
4288 ss_ = p;
4289 if (p) {
4290 p->AddRef();
4291 setUnowned(p->filename());
4292 }
4293 }
4294
setUnowned(const char * filename)4295 void AutoFilename::setUnowned(const char* filename) {
4296 MOZ_ASSERT(!get());
4297 filename_.as<const char*>() = filename ? filename : "";
4298 }
4299
setOwned(UniqueChars && filename)4300 void AutoFilename::setOwned(UniqueChars&& filename) {
4301 MOZ_ASSERT(!get());
4302 filename_ = AsVariant(std::move(filename));
4303 }
4304
get() const4305 const char* AutoFilename::get() const {
4306 if (filename_.is<const char*>()) {
4307 return filename_.as<const char*>();
4308 }
4309 return filename_.as<UniqueChars>().get();
4310 }
4311
DescribeScriptedCaller(JSContext * cx,AutoFilename * filename,unsigned * lineno,unsigned * column)4312 JS_PUBLIC_API bool DescribeScriptedCaller(JSContext* cx, AutoFilename* filename,
4313 unsigned* lineno, unsigned* column) {
4314 if (filename) {
4315 filename->reset();
4316 }
4317 if (lineno) {
4318 *lineno = 0;
4319 }
4320 if (column) {
4321 *column = 0;
4322 }
4323
4324 if (!cx->compartment()) {
4325 return false;
4326 }
4327
4328 NonBuiltinFrameIter i(cx, cx->realm()->principals());
4329 if (i.done()) {
4330 return false;
4331 }
4332
4333 // If the caller is hidden, the embedding wants us to return false here so
4334 // that it can check its own stack (see HideScriptedCaller).
4335 if (i.activation()->scriptedCallerIsHidden()) {
4336 return false;
4337 }
4338
4339 if (filename) {
4340 if (i.isWasm()) {
4341 // For Wasm, copy out the filename, there is no script source.
4342 UniqueChars copy = DuplicateString(i.filename() ? i.filename() : "");
4343 if (!copy) {
4344 filename->setUnowned("out of memory");
4345 } else {
4346 filename->setOwned(std::move(copy));
4347 }
4348 } else {
4349 // All other frames have a script source to read the filename from.
4350 filename->setScriptSource(i.scriptSource());
4351 }
4352 }
4353
4354 if (lineno) {
4355 *lineno = i.computeLine(column);
4356 } else if (column) {
4357 i.computeLine(column);
4358 }
4359
4360 return true;
4361 }
4362
4363 // Fast path to get the activation and realm to use for GetScriptedCallerGlobal.
4364 // If this returns false, the fast path didn't work out and the caller has to
4365 // use the (much slower) NonBuiltinFrameIter path.
4366 //
4367 // The optimization here is that we skip Ion-inlined frames and only look at
4368 // 'outer' frames. That's fine because Ion doesn't inline cross-realm calls.
4369 // However, GetScriptedCallerGlobal has to skip self-hosted frames and Ion
4370 // can inline self-hosted scripts, so we have to be careful:
4371 //
4372 // * When we see a non-self-hosted outer script, it's possible we inlined
4373 // self-hosted scripts into it but that doesn't matter because these scripts
4374 // all have the same realm/global anyway.
4375 //
4376 // * When we see a self-hosted outer script, it's possible we inlined
4377 // non-self-hosted scripts into it, so we have to give up because in this
4378 // case, whether or not to skip the self-hosted frame (to the possibly
4379 // different-realm caller) requires the slow path to handle inlining. Baseline
4380 // and the interpreter don't inline so this only affects Ion.
GetScriptedCallerActivationRealmFast(JSContext * cx,Activation ** activation,Realm ** realm)4381 static bool GetScriptedCallerActivationRealmFast(JSContext* cx,
4382 Activation** activation,
4383 Realm** realm) {
4384 ActivationIterator activationIter(cx);
4385
4386 if (activationIter.done()) {
4387 *activation = nullptr;
4388 *realm = nullptr;
4389 return true;
4390 }
4391
4392 if (activationIter->isJit()) {
4393 jit::JitActivation* act = activationIter->asJit();
4394 JitFrameIter iter(act);
4395 while (true) {
4396 iter.skipNonScriptedJSFrames();
4397 if (iter.done()) {
4398 break;
4399 }
4400
4401 if (!iter.isSelfHostedIgnoringInlining()) {
4402 *activation = act;
4403 *realm = iter.realm();
4404 return true;
4405 }
4406
4407 if (iter.isJSJit() && iter.asJSJit().isIonScripted()) {
4408 // Ion might have inlined non-self-hosted scripts in this
4409 // self-hosted script.
4410 return false;
4411 }
4412
4413 ++iter;
4414 }
4415 } else if (activationIter->isInterpreter()) {
4416 InterpreterActivation* act = activationIter->asInterpreter();
4417 for (InterpreterFrameIterator iter(act); !iter.done(); ++iter) {
4418 if (!iter.frame()->script()->selfHosted()) {
4419 *activation = act;
4420 *realm = iter.frame()->script()->realm();
4421 return true;
4422 }
4423 }
4424 }
4425
4426 return false;
4427 }
4428
GetScriptedCallerGlobal(JSContext * cx)4429 JS_PUBLIC_API JSObject* GetScriptedCallerGlobal(JSContext* cx) {
4430 Activation* activation;
4431 Realm* realm;
4432 if (GetScriptedCallerActivationRealmFast(cx, &activation, &realm)) {
4433 if (!activation) {
4434 return nullptr;
4435 }
4436 } else {
4437 NonBuiltinFrameIter i(cx);
4438 if (i.done()) {
4439 return nullptr;
4440 }
4441 activation = i.activation();
4442 realm = i.realm();
4443 }
4444
4445 MOZ_ASSERT(realm->compartment() == activation->compartment());
4446
4447 // If the caller is hidden, the embedding wants us to return null here so
4448 // that it can check its own stack (see HideScriptedCaller).
4449 if (activation->scriptedCallerIsHidden()) {
4450 return nullptr;
4451 }
4452
4453 GlobalObject* global = realm->maybeGlobal();
4454
4455 // No one should be running code in a realm without any live objects, so
4456 // there should definitely be a live global.
4457 MOZ_ASSERT(global);
4458
4459 return global;
4460 }
4461
HideScriptedCaller(JSContext * cx)4462 JS_PUBLIC_API void HideScriptedCaller(JSContext* cx) {
4463 MOZ_ASSERT(cx);
4464
4465 // If there's no accessible activation on the stack, we'll return null from
4466 // DescribeScriptedCaller anyway, so there's no need to annotate anything.
4467 Activation* act = cx->activation();
4468 if (!act) {
4469 return;
4470 }
4471 act->hideScriptedCaller();
4472 }
4473
UnhideScriptedCaller(JSContext * cx)4474 JS_PUBLIC_API void UnhideScriptedCaller(JSContext* cx) {
4475 Activation* act = cx->activation();
4476 if (!act) {
4477 return;
4478 }
4479 act->unhideScriptedCaller();
4480 }
4481
4482 } /* namespace JS */
4483
4484 #ifdef JS_DEBUG
AssertArgumentsAreSane(JSContext * cx,HandleValue value)4485 JS_PUBLIC_API void JS::detail::AssertArgumentsAreSane(JSContext* cx,
4486 HandleValue value) {
4487 AssertHeapIsIdle();
4488 CHECK_THREAD(cx);
4489 cx->check(value);
4490 }
4491 #endif /* JS_DEBUG */
4492
FinishIncrementalEncoding(JSContext * cx,JS::HandleScript script,TranscodeBuffer & buffer)4493 JS_PUBLIC_API bool JS::FinishIncrementalEncoding(JSContext* cx,
4494 JS::HandleScript script,
4495 TranscodeBuffer& buffer) {
4496 if (!script) {
4497 return false;
4498 }
4499 if (!script->scriptSource()->xdrFinalizeEncoder(cx, buffer)) {
4500 return false;
4501 }
4502 return true;
4503 }
4504
IsWasmModuleObject(HandleObject obj)4505 bool JS::IsWasmModuleObject(HandleObject obj) {
4506 return obj->canUnwrapAs<WasmModuleObject>();
4507 }
4508
GetWasmModule(HandleObject obj)4509 JS_PUBLIC_API RefPtr<JS::WasmModule> JS::GetWasmModule(HandleObject obj) {
4510 MOZ_ASSERT(JS::IsWasmModuleObject(obj));
4511 WasmModuleObject& mobj = obj->unwrapAs<WasmModuleObject>();
4512 return const_cast<wasm::Module*>(&mobj.module());
4513 }
4514
DisableWasmHugeMemory()4515 bool JS::DisableWasmHugeMemory() { return wasm::DisableHugeMemory(); }
4516
SetProcessLargeAllocationFailureCallback(JS::LargeAllocationFailureCallback lafc)4517 JS_PUBLIC_API void JS::SetProcessLargeAllocationFailureCallback(
4518 JS::LargeAllocationFailureCallback lafc) {
4519 MOZ_ASSERT(!OnLargeAllocationFailure);
4520 OnLargeAllocationFailure = lafc;
4521 }
4522
SetOutOfMemoryCallback(JSContext * cx,OutOfMemoryCallback cb,void * data)4523 JS_PUBLIC_API void JS::SetOutOfMemoryCallback(JSContext* cx,
4524 OutOfMemoryCallback cb,
4525 void* data) {
4526 cx->runtime()->oomCallback = cb;
4527 cx->runtime()->oomCallbackData = data;
4528 }
4529
FirstSubsumedFrame(JSContext * cx,bool ignoreSelfHostedFrames)4530 JS::FirstSubsumedFrame::FirstSubsumedFrame(
4531 JSContext* cx, bool ignoreSelfHostedFrames /* = true */)
4532 : JS::FirstSubsumedFrame(cx, cx->realm()->principals(),
4533 ignoreSelfHostedFrames) {}
4534
CaptureCurrentStack(JSContext * cx,JS::MutableHandleObject stackp,JS::StackCapture && capture)4535 JS_PUBLIC_API bool JS::CaptureCurrentStack(
4536 JSContext* cx, JS::MutableHandleObject stackp,
4537 JS::StackCapture&& capture /* = JS::StackCapture(JS::AllFrames()) */) {
4538 AssertHeapIsIdle();
4539 CHECK_THREAD(cx);
4540 MOZ_RELEASE_ASSERT(cx->realm());
4541
4542 Realm* realm = cx->realm();
4543 Rooted<SavedFrame*> frame(cx);
4544 if (!realm->savedStacks().saveCurrentStack(cx, &frame, std::move(capture))) {
4545 return false;
4546 }
4547 stackp.set(frame.get());
4548 return true;
4549 }
4550
IsAsyncStackCaptureEnabledForRealm(JSContext * cx)4551 JS_PUBLIC_API bool JS::IsAsyncStackCaptureEnabledForRealm(JSContext* cx) {
4552 if (!cx->options().asyncStack()) {
4553 return false;
4554 }
4555
4556 return !cx->options().asyncStackCaptureDebuggeeOnly() ||
4557 cx->realm()->isDebuggee();
4558 }
4559
CopyAsyncStack(JSContext * cx,JS::HandleObject asyncStack,JS::HandleString asyncCause,JS::MutableHandleObject stackp,const Maybe<size_t> & maxFrameCount)4560 JS_PUBLIC_API bool JS::CopyAsyncStack(JSContext* cx,
4561 JS::HandleObject asyncStack,
4562 JS::HandleString asyncCause,
4563 JS::MutableHandleObject stackp,
4564 const Maybe<size_t>& maxFrameCount) {
4565 AssertHeapIsIdle();
4566 CHECK_THREAD(cx);
4567 MOZ_RELEASE_ASSERT(cx->realm());
4568
4569 js::AssertObjectIsSavedFrameOrWrapper(cx, asyncStack);
4570 Realm* realm = cx->realm();
4571 Rooted<SavedFrame*> frame(cx);
4572 if (!realm->savedStacks().copyAsyncStack(cx, asyncStack, asyncCause, &frame,
4573 maxFrameCount)) {
4574 return false;
4575 }
4576 stackp.set(frame.get());
4577 return true;
4578 }
4579
GetObjectZone(JSObject * obj)4580 JS_PUBLIC_API Zone* JS::GetObjectZone(JSObject* obj) { return obj->zone(); }
4581
GetNurseryCellZone(gc::Cell * cell)4582 JS_PUBLIC_API Zone* JS::GetNurseryCellZone(gc::Cell* cell) {
4583 return cell->nurseryZone();
4584 }
4585
GCThingTraceKind(void * thing)4586 JS_PUBLIC_API JS::TraceKind JS::GCThingTraceKind(void* thing) {
4587 MOZ_ASSERT(thing);
4588 return static_cast<js::gc::Cell*>(thing)->getTraceKind();
4589 }
4590
SetStackFormat(JSContext * cx,js::StackFormat format)4591 JS_PUBLIC_API void js::SetStackFormat(JSContext* cx, js::StackFormat format) {
4592 cx->runtime()->setStackFormat(format);
4593 }
4594
GetStackFormat(JSContext * cx)4595 JS_PUBLIC_API js::StackFormat js::GetStackFormat(JSContext* cx) {
4596 return cx->runtime()->stackFormat();
4597 }
4598
GetJSTimers(JSContext * cx)4599 JS_PUBLIC_API JS::JSTimers JS::GetJSTimers(JSContext* cx) {
4600 return cx->realm()->timers;
4601 }
4602
4603 namespace js {
4604
NoteIntentionalCrash()4605 JS_PUBLIC_API void NoteIntentionalCrash() {
4606 #ifdef __linux__
4607 static bool* addr =
4608 reinterpret_cast<bool*>(dlsym(RTLD_DEFAULT, "gBreakpadInjectorEnabled"));
4609 if (addr) {
4610 *addr = false;
4611 }
4612 #endif
4613 }
4614
4615 #ifdef DEBUG
4616 bool gSupportDifferentialTesting = false;
4617 #endif // DEBUG
4618
4619 } // namespace js
4620
4621 #ifdef DEBUG
4622
SetSupportDifferentialTesting(bool value)4623 JS_PUBLIC_API void JS::SetSupportDifferentialTesting(bool value) {
4624 js::gSupportDifferentialTesting = value;
4625 }
4626
4627 #endif // DEBUG
4628