Debian Codegraph @

js/src/jsapi.cpp

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