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