Debian Codegraph @

js/src/jit/VMFunctions.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 #include "jit/VMFunctions.h"
8
9 #include "mozilla/FloatingPoint.h"
10
11 #include "builtin/MapObject.h"
12 #include "builtin/String.h"
13 #include "gc/Cell.h"
14 #include "gc/GC.h"
15 #include "jit/arm/Simulator-arm.h"
16 #include "jit/AtomicOperations.h"
17 #include "jit/BaselineIC.h"
18 #include "jit/CalleeToken.h"
19 #include "jit/JitFrames.h"
20 #include "jit/JitRuntime.h"
21 #include "jit/mips64/Simulator-mips64.h"
22 #include "jit/Simulator.h"
23 #include "js/experimental/JitInfo.h"
24 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
25 #include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit
26 #include "js/friend/WindowProxy.h" // js::IsWindow
27 #include "js/Printf.h"
28 #include "js/TraceKind.h"
29 #include "proxy/ScriptedProxyHandler.h"
30 #include "util/Unicode.h"
31 #include "vm/ArrayObject.h"
32 #include "vm/Compartment.h"
33 #include "vm/DateObject.h"
34 #include "vm/Float16.h"
35 #include "vm/Interpreter.h"
36 #include "vm/JSAtomUtils.h" // AtomizeString
37 #include "vm/PlainObject.h" // js::PlainObject
38 #include "vm/SelfHosting.h"
39 #include "vm/StaticStrings.h"
40 #include "vm/TypedArrayObject.h"
41 #include "vm/TypeofEqOperand.h" // TypeofEqOperand
42 #include "vm/Watchtower.h"
43 #include "vm/WrapperObject.h"
44 #include "wasm/WasmGcObject.h"
45
46 #include "debugger/DebugAPI-inl.h"
47 #include "gc/StoreBuffer-inl.h"
48 #include "jit/BaselineFrame-inl.h"
49 #include "jit/VMFunctionList-inl.h"
50 #include "vm/Interpreter-inl.h"
51 #include "vm/JSAtomUtils-inl.h" // TypeName
52 #include "vm/JSContext-inl.h"
53 #include "vm/JSScript-inl.h"
54 #include "vm/NativeObject-inl.h"
55 #include "vm/PlainObject-inl.h" // js::CreateThis
56 #include "vm/StringObject-inl.h"
57
58 using namespace js;
59 using namespace js::jit;
60
61 namespace js {
62
63 class ArgumentsObject;
64 class NamedLambdaObject;
65 class AsyncFunctionGeneratorObject;
66 class RegExpObject;
67
68 namespace jit {
69
70 struct IonOsrTempData;
71
72 struct PopValues {
73 uint8_t numValues;
74 explicit constexpr PopValues(uint8_t numValues = 0) : numValues(numValues) {}
75 };
76
77 template <class>
78 struct ReturnTypeToDataType { /* Unexpected return type for a VMFunction. */
79 };
80 template <>
81 struct ReturnTypeToDataType<void> {
82 static const DataType result = Type_Void;
83 };
84 template <>
85 struct ReturnTypeToDataType<bool> {
86 static const DataType result = Type_Bool;
87 };
88 template <class T>
89 struct ReturnTypeToDataType<T*> {
90 // Assume by default that any pointer return types are cells.
91 static_assert(std::is_base_of_v<gc::Cell, T>);
92
93 static const DataType result = Type_Cell;
94 };
95
96 // Convert argument types to properties of the argument known by the jit.
97 template <class T>
98 struct TypeToArgProperties {
99 static const uint32_t result =
100 (sizeof(T) <= sizeof(void*) ? VMFunctionData::Word
101 : VMFunctionData::Double);
102 };
103 template <>
104 struct TypeToArgProperties<const Value&> {
105 static const uint32_t result =
106 TypeToArgProperties<Value>::result | VMFunctionData::ByRef;
107 };
108 template <>
109 struct TypeToArgProperties<HandleValue> {
110 static const uint32_t result =
111 TypeToArgProperties<Value>::result | VMFunctionData::ByRef;
112 };
113 template <>
114 struct TypeToArgProperties<MutableHandleValue> {
115 static const uint32_t result =
116 TypeToArgProperties<Value>::result | VMFunctionData::ByRef;
117 };
118 template <>
119 struct TypeToArgProperties<HandleId> {
120 static const uint32_t result =
121 TypeToArgProperties<jsid>::result | VMFunctionData::ByRef;
122 };
123 template <class T>
124 struct TypeToArgProperties<Handle<T*>> {
125 // Assume by default that any pointer handle types are cells.
126 static_assert(std::is_base_of_v<gc::Cell, T>);
127
128 static const uint32_t result =
129 TypeToArgProperties<T*>::result | VMFunctionData::ByRef;
130 };
131 template <class T>
132 struct TypeToArgProperties<Handle<T>> {
133 // Fail for Handle types that aren't specialized above.
134 };
135
136 // Convert argument type to whether or not it should be passed in a float
137 // register on platforms that have them, like x64.
138 template <class T>
139 struct TypeToPassInFloatReg {
140 static const uint32_t result = 0;
141 };
142 template <>
143 struct TypeToPassInFloatReg<double> {
144 static const uint32_t result = 1;
145 };
146
147 // Convert argument types to root types used by the gc, see TraceJitExitFrame.
148 template <class T>
149 struct TypeToRootType {
150 static const uint32_t result = VMFunctionData::RootNone;
151 };
152 template <>
153 struct TypeToRootType<HandleValue> {
154 static const uint32_t result = VMFunctionData::RootValue;
155 };
156 template <>
157 struct TypeToRootType<MutableHandleValue> {
158 static const uint32_t result = VMFunctionData::RootValue;
159 };
160 template <>
161 struct TypeToRootType<HandleId> {
162 static const uint32_t result = VMFunctionData::RootId;
163 };
164 template <class T>
165 struct TypeToRootType<Handle<T*>> {
166 // Assume by default that any pointer types are cells.
167 static_assert(std::is_base_of_v<gc::Cell, T>);
168
169 static constexpr uint32_t rootType() {
170 using JS::TraceKind;
171
172 switch (JS::MapTypeToTraceKind<T>::kind) {
173 case TraceKind::Object:
174 return VMFunctionData::RootObject;
175 case TraceKind::BigInt:
176 return VMFunctionData::RootBigInt;
177 case TraceKind::String:
178 return VMFunctionData::RootString;
179 case TraceKind::Shape:
180 case TraceKind::Script:
181 case TraceKind::Scope:
182 return VMFunctionData::RootCell;
183 case TraceKind::Symbol:
184 case TraceKind::BaseShape:
185 case TraceKind::Null:
186 case TraceKind::JitCode:
187 case TraceKind::RegExpShared:
188 case TraceKind::GetterSetter:
189 case TraceKind::PropMap:
190 case TraceKind::SmallBuffer:
191 MOZ_CRASH("Unexpected trace kind");
192 }
193 }
194
195 static constexpr uint32_t result = rootType();
196 };
197 template <class T>
198 struct TypeToRootType<Handle<T>> {
199 // Fail for Handle types that aren't specialized above.
200 };
201
202 template <class>
203 struct OutParamToDataType {
204 static const DataType result = Type_Void;
205 };
206 template <class T>
207 struct OutParamToDataType<const T*> {
208 // Const pointers can't be output parameters.
209 static const DataType result = Type_Void;
210 };
211 template <>
212 struct OutParamToDataType<uint64_t*> {
213 // Already used as an input type, so it can't be used as an output param.
214 static const DataType result = Type_Void;
215 };
216 template <>
217 struct OutParamToDataType<JSObject*> {
218 // Already used as an input type, so it can't be used as an output param.
219 static const DataType result = Type_Void;
220 };
221 template <>
222 struct OutParamToDataType<JSString*> {
223 // Already used as an input type, so it can't be used as an output param.
224 static const DataType result = Type_Void;
225 };
226 template <>
227 struct OutParamToDataType<BaselineFrame*> {
228 // Already used as an input type, so it can't be used as an output param.
229 static const DataType result = Type_Void;
230 };
231 template <>
232 struct OutParamToDataType<gc::AllocSite*> {
233 // Already used as an input type, so it can't be used as an output param.
234 static const DataType result = Type_Void;
235 };
236 template <>
237 struct OutParamToDataType<Value*> {
238 static const DataType result = Type_Value;
239 };
240 template <>
241 struct OutParamToDataType<int*> {
242 static const DataType result = Type_Int32;
243 };
244 template <>
245 struct OutParamToDataType<uint32_t*> {
246 static const DataType result = Type_Int32;
247 };
248 template <>
249 struct OutParamToDataType<bool*> {
250 static const DataType result = Type_Bool;
251 };
252 template <>
253 struct OutParamToDataType<double*> {
254 static const DataType result = Type_Double;
255 };
256 template <class T>
257 struct OutParamToDataType<T*> {
258 // Fail for pointer types that aren't specialized above.
259 };
260 template <class T>
261 struct OutParamToDataType<T**> {
262 static const DataType result = Type_Pointer;
263 };
264 template <class T>
265 struct OutParamToDataType<MutableHandle<T>> {
266 static const DataType result = Type_Handle;
267 };
268
269 template <class>
270 struct OutParamToRootType {
271 static const VMFunctionData::RootType result = VMFunctionData::RootNone;
272 };
273 template <>
274 struct OutParamToRootType<MutableHandleValue> {
275 static const VMFunctionData::RootType result = VMFunctionData::RootValue;
276 };
277 template <>
278 struct OutParamToRootType<MutableHandleObject> {
279 static const VMFunctionData::RootType result = VMFunctionData::RootObject;
280 };
281 template <>
282 struct OutParamToRootType<MutableHandleString> {
283 static const VMFunctionData::RootType result = VMFunctionData::RootString;
284 };
285 template <>
286 struct OutParamToRootType<MutableHandleBigInt> {
287 static const VMFunctionData::RootType result = VMFunctionData::RootBigInt;
288 };
289
290 // Construct a bit mask from a list of types. The mask is constructed as an OR
291 // of the mask produced for each argument. The result of each argument is
292 // shifted by its index, such that the result of the first argument is on the
293 // low bits of the mask, and the result of the last argument in part of the
294 // high bits of the mask.
295 template <template <typename> class Each, typename ResultType, size_t Shift,
296 typename... Args>
297 struct BitMask;
298
299 template <template <typename> class Each, typename ResultType, size_t Shift>
300 struct BitMask<Each, ResultType, Shift> {
301 static constexpr ResultType result = ResultType();
302 };
303
304 template <template <typename> class Each, typename ResultType, size_t Shift,
305 typename HeadType, typename... TailTypes>
306 struct BitMask<Each, ResultType, Shift, HeadType, TailTypes...> {
307 static_assert(ResultType(Each<HeadType>::result) < (1 << Shift),
308 "not enough bits reserved by the shift for individual results");
309 static_assert(sizeof...(TailTypes) < (8 * sizeof(ResultType) / Shift),
310 "not enough bits in the result type to store all bit masks");
311
312 static constexpr ResultType result =
313 ResultType(Each<HeadType>::result) |
314 (BitMask<Each, ResultType, Shift, TailTypes...>::result << Shift);
315 };
316
317 // Helper template to build the VMFunctionData for a function.
318 template <typename... Args>
319 struct VMFunctionDataHelper;
320
321 template <class R, typename... Args>
322 struct VMFunctionDataHelper<R (*)(JSContext*, Args...)>
323 : public VMFunctionData {
324 using Fun = R (*)(JSContext*, Args...);
325
326 static constexpr DataType returnType() {
327 return ReturnTypeToDataType<R>::result;
328 }
329 static constexpr DataType outParam() {
330 return OutParamToDataType<typename LastArg<Args...>::Type>::result;
331 }
332 static constexpr RootType outParamRootType() {
333 return OutParamToRootType<typename LastArg<Args...>::Type>::result;
334 }
335 static constexpr size_t NbArgs() { return sizeof...(Args); }
336 static constexpr size_t explicitArgs() {
337 return NbArgs() - (outParam() != Type_Void ? 1 : 0);
338 }
339 static constexpr uint32_t argumentProperties() {
340 return BitMask<TypeToArgProperties, uint32_t, 2, Args...>::result;
341 }
342 static constexpr uint32_t argumentPassedInFloatRegs() {
343 return BitMask<TypeToPassInFloatReg, uint32_t, 2, Args...>::result;
344 }
345 static constexpr uint64_t argumentRootTypes() {
346 return BitMask<TypeToRootType, uint64_t, 3, Args...>::result;
347 }
348 constexpr explicit VMFunctionDataHelper(const char* name)
349 : VMFunctionData(name, explicitArgs(), argumentProperties(),
350 argumentPassedInFloatRegs(), argumentRootTypes(),
351 outParam(), outParamRootType(), returnType(),
352 /* extraValuesToPop = */ 0) {}
353 constexpr explicit VMFunctionDataHelper(const char* name,
354 PopValues extraValuesToPop)
355 : VMFunctionData(name, explicitArgs(), argumentProperties(),
356 argumentPassedInFloatRegs(), argumentRootTypes(),
357 outParam(), outParamRootType(), returnType(),
358 extraValuesToPop.numValues) {}
359 };
360
361 // GCC warns when the signature does not have matching attributes (for example
362 // [[nodiscard]]). Squelch this warning to avoid a GCC-only footgun.
363 #if MOZ_IS_GCC
364 # pragma GCC diagnostic push
365 # pragma GCC diagnostic ignored "-Wignored-attributes"
366 #endif
367
368 // Generate VMFunctionData array.
369 static constexpr VMFunctionData vmFunctions[] = {
370 #define DEF_VMFUNCTION(name, fp, valuesToPop...) \
371 VMFunctionDataHelper<decltype(&fp)>(#name, PopValues(valuesToPop)),
372 VMFUNCTION_LIST(DEF_VMFUNCTION)
373 #undef DEF_VMFUNCTION
374 };
375
376 #if MOZ_IS_GCC
377 # pragma GCC diagnostic pop
378 #endif
379
380 // Generate arrays storing C++ function pointers. These pointers are not stored
381 // in VMFunctionData because there's no good way to cast them to void* in
382 // constexpr code. Compilers are smart enough to treat the const array below as
383 // constexpr.
384 #define DEF_VMFUNCTION(name, fp, ...) (void*)(fp),
385 static void* const vmFunctionTargets[] = {VMFUNCTION_LIST(DEF_VMFUNCTION)};
386 #undef DEF_VMFUNCTION
387
388 const VMFunctionData& GetVMFunction(VMFunctionId id) {
389 return vmFunctions[size_t(id)];
390 }
391
392 static DynFn GetVMFunctionTarget(VMFunctionId id) {
393 return DynFn{vmFunctionTargets[size_t(id)]};
394 }
395
396 size_t NumVMFunctions() { return size_t(VMFunctionId::Count); }
397
398 size_t VMFunctionData::sizeOfOutParamStackSlot() const {
399 switch (outParam) {
400 case Type_Value:
401 return sizeof(Value);
402
403 case Type_Pointer:
404 case Type_Int32:
405 case Type_Bool:
406 return sizeof(uintptr_t);
407
408 case Type_Double:
409 return sizeof(double);
410
411 case Type_Handle:
412 switch (outParamRootType) {
413 case RootNone:
414 MOZ_CRASH("Handle must have root type");
415 case RootObject:
416 case RootString:
417 case RootCell:
418 case RootBigInt:
419 case RootId:
420 return sizeof(uintptr_t);
421 case RootValue:
422 return sizeof(Value);
423 }
424 MOZ_CRASH("Invalid type");
425
426 case Type_Void:
427 return 0;
428
429 case Type_Cell:
430 MOZ_CRASH("Unexpected outparam type");
431 }
432
433 MOZ_CRASH("Invalid type");
434 }
435
436 bool JitRuntime::generateVMWrappers(JSContext* cx, MacroAssembler& masm,
437 PerfSpewerRangeRecorder& rangeRecorder) {
438 // Generate all VM function wrappers.
439
440 static constexpr size_t NumVMFunctions = size_t(VMFunctionId::Count);
441
442 if (!functionWrapperOffsets_.reserve(NumVMFunctions)) {
443 return false;
444 }
445
446 #ifdef DEBUG
447 const char* lastName = nullptr;
448 #endif
449
450 for (size_t i = 0; i < NumVMFunctions; i++) {
451 VMFunctionId id = VMFunctionId(i);
452 const VMFunctionData& fun = GetVMFunction(id);
453
454 #ifdef DEBUG
455 // Assert the list is sorted by name.
456 if (lastName) {
457 MOZ_ASSERT(strcmp(lastName, fun.name()) < 0,
458 "VM function list must be sorted by name");
459 }
460 lastName = fun.name();
461 #endif
462
463 JitSpew(JitSpew_Codegen, "# VM function wrapper (%s)", fun.name());
464
465 uint32_t offset;
466 if (!generateVMWrapper(cx, masm, id, fun, GetVMFunctionTarget(id),
467 &offset)) {
468 return false;
469 }
470 #if defined(JS_ION_PERF)
471 rangeRecorder.recordVMWrapperOffset(fun.name());
472 #else
473 rangeRecorder.recordOffset("Trampoline: VMWrapper");
474 #endif
475
476 MOZ_ASSERT(functionWrapperOffsets_.length() == size_t(id));
477 functionWrapperOffsets_.infallibleAppend(offset);
478 }
479
480 return true;
481 };
482
483 bool InvokeFunction(JSContext* cx, HandleObject obj, bool constructing,
484 bool ignoresReturnValue, uint32_t argc, Value* argv,
485 MutableHandleValue rval) {
486 RootedExternalValueArray argvRoot(cx, argc + 1 + constructing, argv);
487
488 // Data in the argument vector is arranged for a JIT -> JIT call.
489 RootedValue thisv(cx, argv[0]);
490 Value* argvWithoutThis = argv + 1;
491
492 RootedValue fval(cx, ObjectValue(*obj));
493 if (constructing) {
494 if (!IsConstructor(fval)) {
495 ReportValueError(cx, JSMSG_NOT_CONSTRUCTOR, JSDVG_IGNORE_STACK, fval,
496 nullptr);
497 return false;
498 }
499
500 ConstructArgs cargs(cx);
501 if (!cargs.init(cx, argc)) {
502 return false;
503 }
504
505 for (uint32_t i = 0; i < argc; i++) {
506 cargs[i].set(argvWithoutThis[i]);
507 }
508
509 RootedValue newTarget(cx, argvWithoutThis[argc]);
510
511 // See CreateThisFromIon for why this can be NullValue.
512 if (thisv.isNull()) {
513 thisv.setMagic(JS_IS_CONSTRUCTING);
514 }
515
516 // If |this| hasn't been created, or is JS_UNINITIALIZED_LEXICAL,
517 // we can use normal construction code without creating an extraneous
518 // object.
519 if (thisv.isMagic()) {
520 MOZ_ASSERT(thisv.whyMagic() == JS_IS_CONSTRUCTING ||
521 thisv.whyMagic() == JS_UNINITIALIZED_LEXICAL);
522
523 RootedObject obj(cx);
524 if (!Construct(cx, fval, cargs, newTarget, &obj)) {
525 return false;
526 }
527
528 rval.setObject(*obj);
529 return true;
530 }
531
532 // Otherwise the default |this| has already been created. We could
533 // almost perform a *call* at this point, but we'd break |new.target|
534 // in the function. So in this one weird case we call a one-off
535 // construction path that *won't* set |this| to JS_IS_CONSTRUCTING.
536 return InternalConstructWithProvidedThis(cx, fval, thisv, cargs, newTarget,
537 rval);
538 }
539
540 InvokeArgsMaybeIgnoresReturnValue args(cx);
541 if (!args.init(cx, argc, ignoresReturnValue)) {
542 return false;
543 }
544
545 for (size_t i = 0; i < argc; i++) {
546 args[i].set(argvWithoutThis[i]);
547 }
548
549 return Call(cx, fval, thisv, args, rval);
550 }
551
552 void* GetContextSensitiveInterpreterStub() {
553 return TlsContext.get()->runtime()->jitRuntime()->interpreterStub().value;
554 }
555
556 bool InvokeFromInterpreterStub(JSContext* cx,
557 InterpreterStubExitFrameLayout* frame) {
558 JitFrameLayout* jsFrame = frame->jsFrame();
559 CalleeToken token = jsFrame->calleeToken();
560
561 Value* argv = jsFrame->thisAndActualArgs();
562 uint32_t numActualArgs = jsFrame->numActualArgs();
563 bool constructing = CalleeTokenIsConstructing(token);
564 RootedFunction fun(cx, CalleeTokenToFunction(token));
565
566 // Ensure new.target immediately follows the actual arguments (the arguments
567 // rectifier added padding).
568 if (constructing && numActualArgs < fun->nargs()) {
569 argv[1 + numActualArgs] = argv[1 + fun->nargs()];
570 }
571
572 RootedValue rval(cx);
573 if (!InvokeFunction(cx, fun, constructing,
574 /* ignoresReturnValue = */ false, numActualArgs, argv,
575 &rval)) {
576 return false;
577 }
578
579 // Overwrite |this| with the return value.
580 argv[0] = rval;
581 return true;
582 }
583
584 static bool CheckOverRecursedImpl(JSContext* cx, size_t extra) {
585 // We just failed the jitStackLimit check. There are two possible reasons:
586 // 1) jitStackLimit was the real stack limit and we're over-recursed
587 // 2) jitStackLimit was set to JS::NativeStackLimitMin by
588 // JSContext::requestInterrupt and we need to call
589 // JSContext::handleInterrupt.
590
591 // This handles 1).
592 #ifdef JS_SIMULATOR
593 if (cx->simulator()->overRecursedWithExtra(extra)) {
594 ReportOverRecursed(cx);
595 return false;
596 }
597 #else
598 AutoCheckRecursionLimit recursion(cx);
599 if (!recursion.checkWithExtra(cx, extra)) {
600 return false;
601 }
602 #endif
603
604 // This handles 2).
605 gc::MaybeVerifyBarriers(cx);
606 return cx->handleInterrupt();
607 }
608
609 bool CheckOverRecursed(JSContext* cx) { return CheckOverRecursedImpl(cx, 0); }
610
611 bool CheckOverRecursedBaseline(JSContext* cx, BaselineFrame* frame) {
612 // The stack check in Baseline happens before pushing locals so we have to
613 // account for that by including script->nslots() in the C++ recursion check.
614 size_t extra = frame->script()->nslots() * sizeof(Value);
615 return CheckOverRecursedImpl(cx, extra);
616 }
617
618 bool MutatePrototype(JSContext* cx, Handle<PlainObject*> obj,
619 HandleValue value) {
620 if (!value.isObjectOrNull()) {
621 return true;
622 }
623
624 RootedObject newProto(cx, value.toObjectOrNull());
625 return SetPrototype(cx, obj, newProto);
626 }
627
628 template <EqualityKind Kind>
629 bool StringsEqual(JSContext* cx, HandleString lhs, HandleString rhs,
630 bool* res) {
631 JSLinearString* linearLhs = lhs->ensureLinear(cx);
632 if (!linearLhs) {
633 return false;
634 }
635 JSLinearString* linearRhs = rhs->ensureLinear(cx);
636 if (!linearRhs) {
637 return false;
638 }
639
640 *res = EqualChars(linearLhs, linearRhs);
641
642 if constexpr (Kind == EqualityKind::NotEqual) {
643 *res = !*res;
644 }
645 return true;
646 }
647
648 template bool StringsEqual<EqualityKind::Equal>(JSContext* cx, HandleString lhs,
649 HandleString rhs, bool* res);
650 template bool StringsEqual<EqualityKind::NotEqual>(JSContext* cx,
651 HandleString lhs,
652 HandleString rhs, bool* res);
653
654 template <ComparisonKind Kind>
655 bool StringsCompare(JSContext* cx, HandleString lhs, HandleString rhs,
656 bool* res) {
657 int32_t result;
658 if (!js::CompareStrings(cx, lhs, rhs, &result)) {
659 return false;
660 }
661 if (Kind == ComparisonKind::LessThan) {
662 *res = result < 0;
663 } else {
664 *res = result >= 0;
665 }
666 return true;
667 }
668
669 template bool StringsCompare<ComparisonKind::LessThan>(JSContext* cx,
670 HandleString lhs,
671 HandleString rhs,
672 bool* res);
673 template bool StringsCompare<ComparisonKind::GreaterThanOrEqual>(
674 JSContext* cx, HandleString lhs, HandleString rhs, bool* res);
675
676 JSString* ArrayJoin(JSContext* cx, HandleObject array, HandleString sep) {
677 JS::RootedValueArray<3> argv(cx);
678 argv[0].setUndefined();
679 argv[1].setObject(*array);
680 argv[2].setString(sep);
681 if (!js::array_join(cx, 1, argv.begin())) {
682 return nullptr;
683 }
684 return argv[0].toString();
685 }
686
687 bool SetArrayLength(JSContext* cx, HandleObject obj, HandleValue value,
688 bool strict) {
689 Handle<ArrayObject*> array = obj.as<ArrayObject>();
690
691 RootedId id(cx, NameToId(cx->names().length));
692 ObjectOpResult result;
693
694 // SetArrayLength is called by IC stubs for SetProp and SetElem on arrays'
695 // "length" property.
696 //
697 // ArraySetLength below coerces |value| before checking for length being
698 // writable, and in the case of illegal values, will throw RangeError even
699 // when "length" is not writable. This is incorrect observable behavior,
700 // as a regular [[Set]] operation will check for "length" being
701 // writable before attempting any assignment.
702 //
703 // So, perform ArraySetLength if and only if "length" is writable.
704 if (array->lengthIsWritable()) {
705 Rooted<PropertyDescriptor> desc(
706 cx, PropertyDescriptor::Data(value, JS::PropertyAttribute::Writable));
707 if (!ArraySetLength(cx, array, id, desc, result)) {
708 return false;
709 }
710 } else {
711 MOZ_ALWAYS_TRUE(result.fail(JSMSG_READ_ONLY));
712 }
713
714 return result.checkStrictModeError(cx, obj, id, strict);
715 }
716
717 bool CharCodeAt(JSContext* cx, HandleString str, int32_t index,
718 uint32_t* code) {
719 char16_t c;
720 if (!str->getChar(cx, index, &c)) {
721 return false;
722 }
723 *code = c;
724 return true;
725 }
726
727 bool CodePointAt(JSContext* cx, HandleString str, int32_t index,
728 uint32_t* code) {
729 char32_t codePoint;
730 if (!str->getCodePoint(cx, size_t(index), &codePoint)) {
731 return false;
732 }
733 *code = codePoint;
734 return true;
735 }
736
737 JSLinearString* StringFromCharCodeNoGC(JSContext* cx, int32_t code) {
738 AutoUnsafeCallWithABI unsafe;
739
740 char16_t c = char16_t(code);
741
742 if (StaticStrings::hasUnit(c)) {
743 return cx->staticStrings().getUnit(c);
744 }
745
746 return NewInlineString<NoGC>(cx, {c}, 1);
747 }
748
749 JSLinearString* LinearizeForCharAccessPure(JSString* str) {
750 AutoUnsafeCallWithABI unsafe;
751
752 // Should only be called on ropes.
753 MOZ_ASSERT(str->isRope());
754
755 // ensureLinear is intentionally called with a nullptr to avoid OOM reporting.
756 return str->ensureLinear(nullptr);
757 }
758
759 JSLinearString* LinearizeForCharAccess(JSContext* cx, JSString* str) {
760 // Should only be called on ropes.
761 MOZ_ASSERT(str->isRope());
762
763 return str->ensureLinear(cx);
764 }
765
766 template <typename CharT>
767 static size_t StringTrimStartIndex(mozilla::Range<CharT> chars) {
768 size_t begin = 0;
769 while (begin < chars.length() && unicode::IsSpace(chars[begin])) {
770 ++begin;
771 }
772 return begin;
773 }
774
775 template <typename CharT>
776 static size_t StringTrimEndIndex(mozilla::Range<CharT> chars, size_t begin) {
777 size_t end = chars.length();
778 while (end > begin && unicode::IsSpace(chars[end - 1])) {
779 --end;
780 }
781 return end;
782 }
783
784 int32_t StringTrimStartIndex(const JSString* str) {
785 AutoUnsafeCallWithABI unsafe;
786
787 MOZ_ASSERT(str->isLinear());
788
789 const auto* linear = &str->asLinear();
790
791 size_t begin;
792 if (linear->hasLatin1Chars()) {
793 JS::AutoCheckCannotGC nogc;
794 begin = StringTrimStartIndex(linear->latin1Range(nogc));
795 } else {
796 JS::AutoCheckCannotGC nogc;
797 begin = StringTrimStartIndex(linear->twoByteRange(nogc));
798 }
799 return int32_t(begin);
800 }
801
802 int32_t StringTrimEndIndex(const JSString* str, int32_t start) {
803 AutoUnsafeCallWithABI unsafe;
804
805 MOZ_ASSERT(str->isLinear());
806 MOZ_ASSERT(start >= 0 && size_t(start) <= str->length());
807
808 const auto* linear = &str->asLinear();
809
810 size_t end;
811 if (linear->hasLatin1Chars()) {
812 JS::AutoCheckCannotGC nogc;
813 end = StringTrimEndIndex(linear->latin1Range(nogc), size_t(start));
814 } else {
815 JS::AutoCheckCannotGC nogc;
816 end = StringTrimEndIndex(linear->twoByteRange(nogc), size_t(start));
817 }
818 return int32_t(end);
819 }
820
821 JSString* CharCodeToLowerCase(JSContext* cx, int32_t code) {
822 JSString* str = StringFromCharCode(cx, code);
823 if (!str) {
824 return nullptr;
825 }
826 return js::StringToLowerCase(cx, str);
827 }
828
829 JSString* CharCodeToUpperCase(JSContext* cx, int32_t code) {
830 JSString* str = StringFromCharCode(cx, code);
831 if (!str) {
832 return nullptr;
833 }
834 return js::StringToUpperCase(cx, str);
835 }
836
837 bool SetProperty(JSContext* cx, HandleObject obj, Handle<PropertyName*> name,
838 HandleValue value, bool strict, jsbytecode* pc) {
839 RootedId id(cx, NameToId(name));
840
841 RootedValue receiver(cx, ObjectValue(*obj));
842 ObjectOpResult result;
843 if (MOZ_LIKELY(!obj->getOpsSetProperty())) {
844 JSOp op = JSOp(*pc);
845 if (op == JSOp::SetName || op == JSOp::StrictSetName ||
846 op == JSOp::SetGName || op == JSOp::StrictSetGName) {
847 if (!NativeSetProperty<Unqualified>(cx, obj.as<NativeObject>(), id, value,
848 receiver, result)) {
849 return false;
850 }
851 } else {
852 if (!NativeSetProperty<Qualified>(cx, obj.as<NativeObject>(), id, value,
853 receiver, result)) {
854 return false;
855 }
856 }
857 } else {
858 if (!SetProperty(cx, obj, id, value, receiver, result)) {
859 return false;
860 }
861 }
862 return result.checkStrictModeError(cx, obj, id, strict);
863 }
864
865 bool InterruptCheck(JSContext* cx) {
866 gc::MaybeVerifyBarriers(cx);
867
868 return CheckForInterrupt(cx);
869 }
870
871 JSObject* NewStringObject(JSContext* cx, HandleString str) {
872 return StringObject::create(cx, str);
873 }
874
875 bool OperatorIn(JSContext* cx, HandleValue key, HandleObject obj, bool* out) {
876 RootedId id(cx);
877 return ToPropertyKey(cx, key, &id) && HasProperty(cx, obj, id, out);
878 }
879
880 bool GetIntrinsicValue(JSContext* cx, Handle<PropertyName*> name,
881 MutableHandleValue rval) {
882 return GlobalObject::getIntrinsicValue(cx, cx->global(), name, rval);
883 }
884
885 static uint32_t NumTraceableArgsForCreateThis(HandleFunction fun,
886 uint32_t argc) {
887 return argc + 1; // Add 1 for newTarget
888 }
889
890 bool CreateThisFromIC(JSContext* cx, HandleObject callee,
891 HandleObject newTarget, Value* argv, uint32_t argc,
892 MutableHandleValue rval) {
893 HandleFunction fun = callee.as<JSFunction>();
894 MOZ_ASSERT(fun->isInterpreted());
895 MOZ_ASSERT(fun->isConstructor());
896 MOZ_ASSERT(cx->realm() == fun->realm(),
897 "Realm switching happens before creating this");
898
899 RootedExternalValueArray args(cx, NumTraceableArgsForCreateThis(fun, argc),
900 argv);
901
902 // CreateThis expects rval to be this magic value.
903 rval.set(MagicValue(JS_IS_CONSTRUCTING));
904
905 if (!js::CreateThis(cx, fun, newTarget, GenericObject, rval)) {
906 return false;
907 }
908
909 MOZ_ASSERT_IF(rval.isObject(), fun->realm() == rval.toObject().nonCCWRealm());
910 return true;
911 }
912
913 bool CreateThisFromIon(JSContext* cx, HandleObject callee,
914 HandleObject newTarget, MutableHandleValue rval) {
915 // Return JS_IS_CONSTRUCTING for cases not supported by the inline call path.
916 rval.set(MagicValue(JS_IS_CONSTRUCTING));
917
918 if (!callee->is<JSFunction>()) {
919 return true;
920 }
921
922 HandleFunction fun = callee.as<JSFunction>();
923 if (!fun->isInterpreted() || !fun->isConstructor()) {
924 return true;
925 }
926
927 // If newTarget is not a function or is a function with a possibly-getter
928 // .prototype property, return NullValue to signal to LCallGeneric that it has
929 // to take the slow path. Note that we return NullValue instead of a
930 // MagicValue only because it's easier and faster to check for in JIT code
931 // (if we returned a MagicValue, JIT code would have to check both the type
932 // tag and the JSWhyMagic payload).
933 if (!fun->constructorNeedsUninitializedThis()) {
934 if (!newTarget->is<JSFunction>()) {
935 rval.setNull();
936 return true;
937 }
938 JSFunction* newTargetFun = &newTarget->as<JSFunction>();
939 if (!newTargetFun->hasNonConfigurablePrototypeDataProperty()) {
940 rval.setNull();
941 return true;
942 }
943 }
944
945 AutoRealm ar(cx, fun);
946 if (!js::CreateThis(cx, fun, newTarget, GenericObject, rval)) {
947 return false;
948 }
949
950 MOZ_ASSERT_IF(rval.isObject(), fun->realm() == rval.toObject().nonCCWRealm());
951 return true;
952 }
953
954 void PostWriteBarrier(JSRuntime* rt, js::gc::Cell* cell) {
955 AutoUnsafeCallWithABI unsafe;
956 rt->gc.storeBuffer().putWholeCellDontCheckLast(cell);
957 }
958
959 static const size_t MAX_WHOLE_CELL_BUFFER_SIZE = 4096;
960
961 void PostWriteElementBarrier(JSRuntime* rt, JSObject* obj, int32_t index) {
962 AutoUnsafeCallWithABI unsafe;
963
964 MOZ_ASSERT(!IsInsideNursery(obj));
965
966 NativeObject* nobj = &obj->as<NativeObject>();
967
968 MOZ_ASSERT(index >= 0);
969 MOZ_ASSERT(uint32_t(index) < nobj->getDenseInitializedLength());
970
971 if (gc::StoreBuffer::isInWholeCellBuffer(nobj)) {
972 return;
973 }
974
975 gc::StoreBuffer* sb = &rt->gc.storeBuffer();
976 if (nobj->getDenseInitializedLength() > MAX_WHOLE_CELL_BUFFER_SIZE ||
977 rt->hasZealMode(gc::ZealMode::ElementsBarrier)) {
978 sb->putSlot(nobj, HeapSlot::Element, nobj->unshiftedIndex(index), 1);
979 return;
980 }
981
982 sb->putWholeCell(obj);
983 }
984
985 void PostGlobalWriteBarrier(JSRuntime* rt, GlobalObject* obj) {
986 MOZ_ASSERT(obj->JSObject::is<GlobalObject>());
987
988 if (!obj->realm()->globalWriteBarriered) {
989 AutoUnsafeCallWithABI unsafe;
990 rt->gc.storeBuffer().putWholeCell(obj);
991 obj->realm()->globalWriteBarriered = 1;
992 }
993 }
994
995 bool GetInt32FromStringPure(JSContext* cx, JSString* str, int32_t* result) {
996 // We shouldn't GC here as this is called directly from IC code.
997 AutoUnsafeCallWithABI unsafe;
998
999 double d;
1000 if (!StringToNumberPure(cx, str, &d)) {
1001 return false;
1002 }
1003
1004 return mozilla::NumberIsInt32(d, result);
1005 }
1006
1007 int32_t GetIndexFromString(JSString* str) {
1008 // We shouldn't GC here as this is called directly from IC code.
1009 AutoUnsafeCallWithABI unsafe;
1010
1011 if (!str->isLinear()) {
1012 return -1;
1013 }
1014
1015 uint32_t index = UINT32_MAX; // Initialize this to appease Valgrind.
1016 if (!str->asLinear().isIndex(&index) || index > INT32_MAX) {
1017 return -1;
1018 }
1019
1020 return int32_t(index);
1021 }
1022
1023 JSObject* WrapObjectPure(JSContext* cx, JSObject* obj) {
1024 // IC code calls this directly so we shouldn't GC.
1025 AutoUnsafeCallWithABI unsafe;
1026
1027 MOZ_ASSERT(obj);
1028 MOZ_ASSERT(cx->compartment() != obj->compartment());
1029
1030 // From: Compartment::getNonWrapperObjectForCurrentCompartment
1031 // Note that if the object is same-compartment, but has been wrapped into a
1032 // different compartment, we need to unwrap it and return the bare same-
1033 // compartment object. Note again that windows are always wrapped by a
1034 // WindowProxy even when same-compartment so take care not to strip this
1035 // particular wrapper.
1036 obj = UncheckedUnwrap(obj, /* stopAtWindowProxy = */ true);
1037 if (cx->compartment() == obj->compartment()) {
1038 MOZ_ASSERT(!IsWindow(obj));
1039 JS::ExposeObjectToActiveJS(obj);
1040 return obj;
1041 }
1042
1043 // Try to Lookup an existing wrapper for this object. We assume that
1044 // if we can find such a wrapper, not calling preWrap is correct.
1045 if (ObjectWrapperMap::Ptr p = cx->compartment()->lookupWrapper(obj)) {
1046 JSObject* wrapped = p->value().get();
1047
1048 // Ensure the wrapper is still exposed.
1049 JS::ExposeObjectToActiveJS(wrapped);
1050 return wrapped;
1051 }
1052
1053 return nullptr;
1054 }
1055
1056 bool DebugPrologue(JSContext* cx, BaselineFrame* frame) {
1057 return DebugAPI::onEnterFrame(cx, frame);
1058 }
1059
1060 bool DebugEpilogueOnBaselineReturn(JSContext* cx, BaselineFrame* frame,
1061 const jsbytecode* pc) {
1062 if (!DebugEpilogue(cx, frame, pc, true)) {
1063 return false;
1064 }
1065
1066 return true;
1067 }
1068
1069 bool DebugEpilogue(JSContext* cx, BaselineFrame* frame, const jsbytecode* pc,
1070 bool ok) {
1071 // If DebugAPI::onLeaveFrame returns |true| we have to return the frame's
1072 // return value. If it returns |false|, the debugger threw an exception.
1073 // In both cases we have to pop debug scopes.
1074 ok = DebugAPI::onLeaveFrame(cx, frame, pc, ok);
1075
1076 // Unwind to the outermost environment.
1077 EnvironmentIter ei(cx, frame, pc);
1078 UnwindAllEnvironmentsInFrame(cx, ei);
1079
1080 if (!ok) {
1081 // Pop this frame by updating packedExitFP, so that the exception
1082 // handling code will start at the previous frame.
1083 JitFrameLayout* prefix = frame->framePrefix();
1084 EnsureUnwoundJitExitFrame(cx->activation()->asJit(), prefix);
1085 return false;
1086 }
1087
1088 return true;
1089 }
1090
1091 void FrameIsDebuggeeCheck(BaselineFrame* frame) {
1092 AutoUnsafeCallWithABI unsafe;
1093 if (frame->script()->isDebuggee()) {
1094 frame->setIsDebuggee();
1095 }
1096 }
1097
1098 JSObject* CreateGeneratorFromFrame(JSContext* cx, BaselineFrame* frame) {
1099 return AbstractGeneratorObject::createFromFrame(cx, frame);
1100 }
1101
1102 JSObject* CreateGenerator(JSContext* cx, HandleFunction callee,
1103 HandleScript script, HandleObject environmentChain,
1104 HandleObject args) {
1105 Rooted<ArgumentsObject*> argsObj(
1106 cx, args ? &args->as<ArgumentsObject>() : nullptr);
1107 return AbstractGeneratorObject::create(cx, callee, script, environmentChain,
1108 argsObj);
1109 }
1110
1111 bool NormalSuspend(JSContext* cx, HandleObject obj, BaselineFrame* frame,
1112 uint32_t frameSize, const jsbytecode* pc) {
1113 MOZ_ASSERT(JSOp(*pc) == JSOp::InitialYield || JSOp(*pc) == JSOp::Yield ||
1114 JSOp(*pc) == JSOp::Await);
1115
1116 // Minus one because we don't want to include the return value.
1117 uint32_t numSlots = frame->numValueSlots(frameSize) - 1;
1118 MOZ_ASSERT(numSlots >= frame->script()->nfixed());
1119 return AbstractGeneratorObject::suspend(cx, obj, frame, pc, numSlots);
1120 }
1121
1122 bool FinalSuspend(JSContext* cx, HandleObject obj, const jsbytecode* pc) {
1123 MOZ_ASSERT(JSOp(*pc) == JSOp::FinalYieldRval);
1124 AbstractGeneratorObject::finalSuspend(cx, obj);
1125 return true;
1126 }
1127
1128 bool InterpretResume(JSContext* cx, HandleObject obj, Value* stackValues,
1129 MutableHandleValue rval) {
1130 MOZ_ASSERT(obj->is<AbstractGeneratorObject>());
1131
1132 // The |stackValues| argument points to the JSOp::Resume operands on the
1133 // native stack. Because the stack grows down, these values are:
1134 //
1135 // [resumeKind, argument, generator, ..]
1136
1137 MOZ_ASSERT(stackValues[2].toObject() == *obj);
1138
1139 GeneratorResumeKind resumeKind = IntToResumeKind(stackValues[0].toInt32());
1140 JSAtom* kind = ResumeKindToAtom(cx, resumeKind);
1141
1142 FixedInvokeArgs<3> args(cx);
1143
1144 args[0].setObject(*obj);
1145 args[1].set(stackValues[1]);
1146 args[2].setString(kind);
1147
1148 return CallSelfHostedFunction(cx, cx->names().InterpretGeneratorResume,
1149 UndefinedHandleValue, args, rval);
1150 }
1151
1152 bool DebugAfterYield(JSContext* cx, BaselineFrame* frame) {
1153 // The BaselineFrame has just been constructed by JSOp::Resume in the
1154 // caller. We need to set its debuggee flag as necessary.
1155 //
1156 // If a breakpoint is set on JSOp::AfterYield, or stepping is enabled,
1157 // we may already have done this work. Don't fire onEnterFrame again.
1158 if (frame->script()->isDebuggee() && !frame->isDebuggee()) {
1159 frame->setIsDebuggee();
1160 return DebugAPI::onResumeFrame(cx, frame);
1161 }
1162
1163 return true;
1164 }
1165
1166 bool GeneratorThrowOrReturn(JSContext* cx, BaselineFrame* frame,
1167 Handle<AbstractGeneratorObject*> genObj,
1168 HandleValue arg, int32_t resumeKindArg) {
1169 GeneratorResumeKind resumeKind = IntToResumeKind(resumeKindArg);
1170 MOZ_ALWAYS_FALSE(
1171 js::GeneratorThrowOrReturn(cx, frame, genObj, arg, resumeKind));
1172 return false;
1173 }
1174
1175 bool GlobalDeclInstantiationFromIon(JSContext* cx, HandleScript script,
1176 const jsbytecode* pc) {
1177 MOZ_ASSERT(!script->hasNonSyntacticScope());
1178
1179 RootedObject envChain(cx, &cx->global()->lexicalEnvironment());
1180 GCThingIndex lastFun = GET_GCTHING_INDEX(pc);
1181
1182 return GlobalOrEvalDeclInstantiation(cx, envChain, script, lastFun);
1183 }
1184
1185 bool InitFunctionEnvironmentObjects(JSContext* cx, BaselineFrame* frame) {
1186 return frame->initFunctionEnvironmentObjects(cx);
1187 }
1188
1189 bool NewArgumentsObject(JSContext* cx, BaselineFrame* frame,
1190 MutableHandleValue res) {
1191 ArgumentsObject* obj = ArgumentsObject::createExpected(cx, frame);
1192 if (!obj) {
1193 return false;
1194 }
1195 res.setObject(*obj);
1196 return true;
1197 }
1198
1199 ArrayObject* NewArrayObjectEnsureDenseInitLength(JSContext* cx, int32_t count) {
1200 MOZ_ASSERT(count >= 0);
1201
1202 auto* array = NewDenseFullyAllocatedArray(cx, count);
1203 if (!array) {
1204 return nullptr;
1205 }
1206 array->ensureDenseInitializedLength(0, count);
1207
1208 return array;
1209 }
1210
1211 ArrayObject* InitRestParameter(JSContext* cx, uint32_t length, Value* rest,
1212 Handle<ArrayObject*> arrRes) {
1213 if (arrRes) {
1214 // Fast path: we managed to allocate the array inline; initialize the
1215 // elements.
1216 MOZ_ASSERT(arrRes->getDenseInitializedLength() == 0);
1217
1218 // We don't call this function if we can initialize the elements in JIT
1219 // code.
1220 MOZ_ASSERT(length > arrRes->getDenseCapacity());
1221
1222 if (!arrRes->growElements(cx, length)) {
1223 return nullptr;
1224 }
1225 arrRes->initDenseElements(rest, length);
1226 arrRes->setLengthToInitializedLength();
1227 return arrRes;
1228 }
1229
1230 return NewDenseCopiedArray(cx, length, rest);
1231 }
1232
1233 bool HandleDebugTrap(JSContext* cx, BaselineFrame* frame,
1234 const uint8_t* retAddr) {
1235 RootedScript script(cx, frame->script());
1236 jsbytecode* pc;
1237 if (frame->runningInInterpreter()) {
1238 pc = frame->interpreterPC();
1239 } else {
1240 BaselineScript* blScript = script->baselineScript();
1241 pc = blScript->retAddrEntryFromReturnAddress(retAddr).pc(script);
1242 }
1243
1244 // The Baseline Interpreter calls HandleDebugTrap for every op when the script
1245 // is in step mode or has breakpoints. The Baseline Compiler can toggle
1246 // breakpoints more granularly for specific bytecode PCs.
1247 if (frame->runningInInterpreter()) {
1248 MOZ_ASSERT(DebugAPI::hasAnyBreakpointsOrStepMode(script));
1249 } else {
1250 MOZ_ASSERT(DebugAPI::stepModeEnabled(script) ||
1251 DebugAPI::hasBreakpointsAt(script, pc));
1252 }
1253
1254 if (JSOp(*pc) == JSOp::AfterYield) {
1255 // JSOp::AfterYield will set the frame's debuggee flag and call the
1256 // onEnterFrame handler, but if we set a breakpoint there we have to do
1257 // it now.
1258 MOZ_ASSERT(!frame->isDebuggee());
1259
1260 if (!DebugAfterYield(cx, frame)) {
1261 return false;
1262 }
1263
1264 // If the frame is not a debuggee we're done. This can happen, for instance,
1265 // if the onEnterFrame hook called removeDebuggee.
1266 if (!frame->isDebuggee()) {
1267 return true;
1268 }
1269 }
1270
1271 MOZ_ASSERT(frame->isDebuggee());
1272
1273 if (DebugAPI::stepModeEnabled(script) && !DebugAPI::onSingleStep(cx)) {
1274 return false;
1275 }
1276
1277 if (DebugAPI::hasBreakpointsAt(script, pc) && !DebugAPI::onTrap(cx)) {
1278 return false;
1279 }
1280
1281 return true;
1282 }
1283
1284 bool OnDebuggerStatement(JSContext* cx, BaselineFrame* frame) {
1285 return DebugAPI::onDebuggerStatement(cx, frame);
1286 }
1287
1288 bool GlobalHasLiveOnDebuggerStatement(JSContext* cx) {
1289 AutoUnsafeCallWithABI unsafe;
1290 return cx->realm()->isDebuggee() &&
1291 DebugAPI::hasDebuggerStatementHook(cx->global());
1292 }
1293
1294 bool PushLexicalEnv(JSContext* cx, BaselineFrame* frame,
1295 Handle<LexicalScope*> scope) {
1296 return frame->pushLexicalEnvironment(cx, scope);
1297 }
1298
1299 bool DebugLeaveThenPopLexicalEnv(JSContext* cx, BaselineFrame* frame,
1300 const jsbytecode* pc) {
1301 MOZ_ALWAYS_TRUE(DebugLeaveLexicalEnv(cx, frame, pc));
1302 frame->popOffEnvironmentChain<ScopedLexicalEnvironmentObject>();
1303 return true;
1304 }
1305
1306 bool FreshenLexicalEnv(JSContext* cx, BaselineFrame* frame) {
1307 return frame->freshenLexicalEnvironment<false>(cx);
1308 }
1309
1310 bool DebuggeeFreshenLexicalEnv(JSContext* cx, BaselineFrame* frame,
1311 const jsbytecode* pc) {
1312 return frame->freshenLexicalEnvironment<true>(cx, pc);
1313 }
1314
1315 bool RecreateLexicalEnv(JSContext* cx, BaselineFrame* frame) {
1316 return frame->recreateLexicalEnvironment<false>(cx);
1317 }
1318
1319 bool DebuggeeRecreateLexicalEnv(JSContext* cx, BaselineFrame* frame,
1320 const jsbytecode* pc) {
1321 return frame->recreateLexicalEnvironment<true>(cx, pc);
1322 }
1323
1324 bool DebugLeaveLexicalEnv(JSContext* cx, BaselineFrame* frame,
1325 const jsbytecode* pc) {
1326 MOZ_ASSERT_IF(!frame->runningInInterpreter(),
1327 frame->script()->baselineScript()->hasDebugInstrumentation());
1328 if (cx->realm()->isDebuggee()) {
1329 DebugEnvironments::onPopLexical(cx, frame, pc);
1330 }
1331 return true;
1332 }
1333
1334 bool PushClassBodyEnv(JSContext* cx, BaselineFrame* frame,
1335 Handle<ClassBodyScope*> scope) {
1336 return frame->pushClassBodyEnvironment(cx, scope);
1337 }
1338
1339 bool PushVarEnv(JSContext* cx, BaselineFrame* frame, Handle<Scope*> scope) {
1340 return frame->pushVarEnvironment(cx, scope);
1341 }
1342
1343 bool EnterWith(JSContext* cx, BaselineFrame* frame, HandleValue val,
1344 Handle<WithScope*> templ) {
1345 return EnterWithOperation(cx, frame, val, templ);
1346 }
1347
1348 bool LeaveWith(JSContext* cx, BaselineFrame* frame) {
1349 if (MOZ_UNLIKELY(frame->isDebuggee())) {
1350 DebugEnvironments::onPopWith(frame);
1351 }
1352 frame->popOffEnvironmentChain<WithEnvironmentObject>();
1353 return true;
1354 }
1355
1356 bool InitBaselineFrameForOsr(BaselineFrame* frame,
1357 InterpreterFrame* interpFrame,
1358 uint32_t numStackValues) {
1359 return frame->initForOsr(interpFrame, numStackValues);
1360 }
1361
1362 JSString* StringReplace(JSContext* cx, HandleString string,
1363 HandleString pattern, HandleString repl) {
1364 MOZ_ASSERT(string);
1365 MOZ_ASSERT(pattern);
1366 MOZ_ASSERT(repl);
1367
1368 return str_replace_string_raw(cx, string, pattern, repl);
1369 }
1370
1371 void AssertValidBigIntPtr(JSContext* cx, JS::BigInt* bi) {
1372 AutoUnsafeCallWithABI unsafe;
1373 // FIXME: check runtime?
1374 MOZ_ASSERT(cx->zone() == bi->zone());
1375 MOZ_ASSERT(bi->isAligned());
1376 MOZ_ASSERT(bi->getAllocKind() == gc::AllocKind::BIGINT);
1377 }
1378
1379 void AssertValidObjectPtr(JSContext* cx, JSObject* obj) {
1380 AutoUnsafeCallWithABI unsafe;
1381 #ifdef DEBUG
1382 // Check what we can, so that we'll hopefully assert/crash if we get a
1383 // bogus object (pointer).
1384 MOZ_ASSERT(obj->compartment() == cx->compartment());
1385 MOZ_ASSERT(obj->zoneFromAnyThread() == cx->zone());
1386 MOZ_ASSERT(obj->runtimeFromMainThread() == cx->runtime());
1387
1388 if (obj->isTenured()) {
1389 MOZ_ASSERT(obj->isAligned());
1390 gc::AllocKind kind = obj->asTenured().getAllocKind();
1391 MOZ_ASSERT(gc::IsObjectAllocKind(kind));
1392 }
1393 #endif
1394 }
1395
1396 void AssertValidStringPtr(JSContext* cx, JSString* str) {
1397 AutoUnsafeCallWithABI unsafe;
1398 #ifdef DEBUG
1399 // We can't closely inspect strings from another runtime.
1400 if (str->runtimeFromAnyThread() != cx->runtime()) {
1401 MOZ_ASSERT(str->isPermanentAtom());
1402 return;
1403 }
1404
1405 if (str->isAtom()) {
1406 MOZ_ASSERT(str->zone()->isAtomsZone());
1407 } else {
1408 MOZ_ASSERT(str->zone() == cx->zone());
1409 }
1410
1411 MOZ_ASSERT(str->isAligned());
1412 MOZ_ASSERT(str->length() <= JSString::MAX_LENGTH);
1413
1414 gc::AllocKind kind = str->getAllocKind();
1415 if (str->isFatInline()) {
1416 if (str->isAtom()) {
1417 MOZ_ASSERT(kind == gc::AllocKind::FAT_INLINE_ATOM);
1418 } else {
1419 MOZ_ASSERT(kind == gc::AllocKind::FAT_INLINE_STRING);
1420 }
1421 } else if (str->isExternal()) {
1422 MOZ_ASSERT(kind == gc::AllocKind::EXTERNAL_STRING);
1423 } else if (str->isAtom()) {
1424 MOZ_ASSERT(kind == gc::AllocKind::ATOM);
1425 } else if (str->isLinear()) {
1426 MOZ_ASSERT(kind == gc::AllocKind::STRING ||
1427 kind == gc::AllocKind::FAT_INLINE_STRING);
1428 } else {
1429 MOZ_ASSERT(kind == gc::AllocKind::STRING);
1430 }
1431 #endif
1432 }
1433
1434 void AssertValidSymbolPtr(JSContext* cx, JS::Symbol* sym) {
1435 AutoUnsafeCallWithABI unsafe;
1436
1437 // We can't closely inspect symbols from another runtime.
1438 if (sym->runtimeFromAnyThread() != cx->runtime()) {
1439 MOZ_ASSERT(sym->isWellKnownSymbol());
1440 return;
1441 }
1442
1443 MOZ_ASSERT(sym->zone()->isAtomsZone());
1444 MOZ_ASSERT(sym->isAligned());
1445 if (JSAtom* desc = sym->description()) {
1446 AssertValidStringPtr(cx, desc);
1447 }
1448
1449 MOZ_ASSERT(sym->getAllocKind() == gc::AllocKind::SYMBOL);
1450 }
1451
1452 void AssertValidValue(JSContext* cx, Value* v) {
1453 AutoUnsafeCallWithABI unsafe;
1454 if (v->isObject()) {
1455 AssertValidObjectPtr(cx, &v->toObject());
1456 } else if (v->isString()) {
1457 AssertValidStringPtr(cx, v->toString());
1458 } else if (v->isSymbol()) {
1459 AssertValidSymbolPtr(cx, v->toSymbol());
1460 } else if (v->isBigInt()) {
1461 AssertValidBigIntPtr(cx, v->toBigInt());
1462 }
1463 }
1464
1465 bool ObjectIsCallable(JSObject* obj) {
1466 AutoUnsafeCallWithABI unsafe;
1467 return obj->isCallable();
1468 }
1469
1470 bool ObjectIsConstructor(JSObject* obj) {
1471 AutoUnsafeCallWithABI unsafe;
1472 return obj->isConstructor();
1473 }
1474
1475 JSObject* ObjectKeys(JSContext* cx, HandleObject obj) {
1476 JS::RootedValueArray<3> argv(cx);
1477 argv[0].setUndefined(); // rval
1478 argv[1].setUndefined(); // this
1479 argv[2].setObject(*obj); // arg0
1480 if (!js::obj_keys(cx, 1, argv.begin())) {
1481 return nullptr;
1482 }
1483 return argv[0].toObjectOrNull();
1484 }
1485
1486 bool ObjectKeysLength(JSContext* cx, HandleObject obj, int32_t* length) {
1487 MOZ_ASSERT(!obj->is<ProxyObject>());
1488 return js::obj_keys_length(cx, obj, *length);
1489 }
1490
1491 void JitValuePreWriteBarrier(JSRuntime* rt, Value* vp) {
1492 AutoUnsafeCallWithABI unsafe;
1493 MOZ_ASSERT(vp->isGCThing());
1494 MOZ_ASSERT(!vp->toGCThing()->isMarkedBlack());
1495 gc::ValuePreWriteBarrier(*vp);
1496 }
1497
1498 void JitStringPreWriteBarrier(JSRuntime* rt, JSString** stringp) {
1499 AutoUnsafeCallWithABI unsafe;
1500 MOZ_ASSERT(*stringp);
1501 MOZ_ASSERT(!(*stringp)->isMarkedBlack());
1502 gc::PreWriteBarrier(*stringp);
1503 }
1504
1505 void JitObjectPreWriteBarrier(JSRuntime* rt, JSObject** objp) {
1506 AutoUnsafeCallWithABI unsafe;
1507 MOZ_ASSERT(*objp);
1508 MOZ_ASSERT(!(*objp)->isMarkedBlack());
1509 gc::PreWriteBarrier(*objp);
1510 }
1511
1512 void JitShapePreWriteBarrier(JSRuntime* rt, Shape** shapep) {
1513 AutoUnsafeCallWithABI unsafe;
1514 MOZ_ASSERT(!(*shapep)->isMarkedBlack());
1515 gc::PreWriteBarrier(*shapep);
1516 }
1517
1518 void JitWasmAnyRefPreWriteBarrier(JSRuntime* rt, wasm::AnyRef* refp) {
1519 AutoUnsafeCallWithABI unsafe;
1520 MOZ_ASSERT(refp->isGCThing());
1521 MOZ_ASSERT(!(*refp).toGCThing()->isMarkedBlack());
1522 gc::WasmAnyRefPreWriteBarrier(*refp);
1523 }
1524
1525 bool ThrowRuntimeLexicalError(JSContext* cx, unsigned errorNumber) {
1526 ScriptFrameIter iter(cx);
1527 RootedScript script(cx, iter.script());
1528 ReportRuntimeLexicalError(cx, errorNumber, script, iter.pc());
1529 return false;
1530 }
1531
1532 bool ThrowBadDerivedReturnOrUninitializedThis(JSContext* cx, HandleValue v) {
1533 MOZ_ASSERT(!v.isObject());
1534 if (v.isUndefined()) {
1535 return js::ThrowUninitializedThis(cx);
1536 }
1537
1538 ReportValueError(cx, JSMSG_BAD_DERIVED_RETURN, JSDVG_IGNORE_STACK, v,
1539 nullptr);
1540 return false;
1541 }
1542
1543 bool BaselineGetFunctionThis(JSContext* cx, BaselineFrame* frame,
1544 MutableHandleValue res) {
1545 return GetFunctionThis(cx, frame, res);
1546 }
1547
1548 bool CallNativeGetter(JSContext* cx, HandleFunction callee,
1549 HandleValue receiver, MutableHandleValue result) {
1550 AutoRealm ar(cx, callee);
1551
1552 MOZ_ASSERT(callee->isNativeFun());
1553 JSNative natfun = callee->native();
1554
1555 JS::RootedValueArray<2> vp(cx);
1556 vp[0].setObject(*callee.get());
1557 vp[1].set(receiver);
1558
1559 if (!natfun(cx, 0, vp.begin())) {
1560 return false;
1561 }
1562
1563 result.set(vp[0]);
1564 return true;
1565 }
1566
1567 bool CallDOMGetter(JSContext* cx, const JSJitInfo* info, HandleObject obj,
1568 MutableHandleValue result) {
1569 MOZ_ASSERT(info->type() == JSJitInfo::Getter);
1570 MOZ_ASSERT(obj->is<NativeObject>());
1571 MOZ_ASSERT(obj->getClass()->isDOMClass());
1572 MOZ_ASSERT(obj->as<NativeObject>().numFixedSlots() > 0);
1573
1574 #ifdef DEBUG
1575 DOMInstanceClassHasProtoAtDepth instanceChecker =
1576 cx->runtime()->DOMcallbacks->instanceClassMatchesProto;
1577 MOZ_ASSERT(instanceChecker(obj->getClass(), info->protoID, info->depth));
1578 #endif
1579
1580 // Loading DOM_OBJECT_SLOT, which must be the first slot.
1581 JS::Value val = JS::GetReservedSlot(obj, 0);
1582 JSJitGetterOp getter = info->getter;
1583 return getter(cx, obj, val.toPrivate(), JSJitGetterCallArgs(result));
1584 }
1585
1586 bool CallNativeSetter(JSContext* cx, HandleFunction callee, HandleObject obj,
1587 HandleValue rhs) {
1588 AutoRealm ar(cx, callee);
1589
1590 MOZ_ASSERT(callee->isNativeFun());
1591 JSNative natfun = callee->native();
1592
1593 JS::RootedValueArray<3> vp(cx);
1594 vp[0].setObject(*callee.get());
1595 vp[1].setObject(*obj.get());
1596 vp[2].set(rhs);
1597
1598 return natfun(cx, 1, vp.begin());
1599 }
1600
1601 bool CallDOMSetter(JSContext* cx, const JSJitInfo* info, HandleObject obj,
1602 HandleValue value) {
1603 MOZ_ASSERT(info->type() == JSJitInfo::Setter);
1604 MOZ_ASSERT(obj->is<NativeObject>());
1605 MOZ_ASSERT(obj->getClass()->isDOMClass());
1606 MOZ_ASSERT(obj->as<NativeObject>().numFixedSlots() > 0);
1607
1608 #ifdef DEBUG
1609 DOMInstanceClassHasProtoAtDepth instanceChecker =
1610 cx->runtime()->DOMcallbacks->instanceClassMatchesProto;
1611 MOZ_ASSERT(instanceChecker(obj->getClass(), info->protoID, info->depth));
1612 #endif
1613
1614 // Loading DOM_OBJECT_SLOT, which must be the first slot.
1615 JS::Value val = JS::GetReservedSlot(obj, 0);
1616 JSJitSetterOp setter = info->setter;
1617
1618 RootedValue v(cx, value);
1619 return setter(cx, obj, val.toPrivate(), JSJitSetterCallArgs(&v));
1620 }
1621
1622 bool EqualStringsHelperPure(JSString* str1, JSString* str2) {
1623 // IC code calls this directly so we shouldn't GC.
1624 AutoUnsafeCallWithABI unsafe;
1625
1626 MOZ_ASSERT(str1->isAtom());
1627 MOZ_ASSERT(!str2->isAtom());
1628 MOZ_ASSERT(str1->length() == str2->length());
1629
1630 // ensureLinear is intentionally called with a nullptr to avoid OOM
1631 // reporting; if it fails, we will continue to the next stub.
1632 JSLinearString* str2Linear = str2->ensureLinear(nullptr);
1633 if (!str2Linear) {
1634 return false;
1635 }
1636
1637 return EqualChars(&str1->asLinear(), str2Linear);
1638 }
1639
1640 static bool MaybeTypedArrayIndexString(PropertyKey key) {
1641 MOZ_ASSERT(key.isAtom() || key.isSymbol());
1642
1643 if (MOZ_LIKELY(key.isAtom())) {
1644 JSAtom* str = key.toAtom();
1645 if (str->length() > 0) {
1646 // Only check the first character because we want this function to be
1647 // fast.
1648 return CanStartTypedArrayIndex(str->latin1OrTwoByteChar(0));
1649 }
1650 }
1651 return false;
1652 }
1653
1654 static void VerifyCacheEntry(JSContext* cx, NativeObject* obj, PropertyKey key,
1655 const MegamorphicCacheEntry& entry) {
1656 #ifdef DEBUG
1657 if (entry.isMissingProperty()) {
1658 NativeObject* pobj;
1659 PropertyResult prop;
1660 MOZ_ASSERT(LookupPropertyPure(cx, obj, key, &pobj, &prop));
1661 MOZ_ASSERT(prop.isNotFound());
1662 return;
1663 }
1664 if (entry.isMissingOwnProperty()) {
1665 MOZ_ASSERT(!obj->containsPure(key));
1666 return;
1667 }
1668 MOZ_ASSERT(entry.isDataProperty() || entry.isAccessorProperty());
1669 for (size_t i = 0, numHops = entry.numHops(); i < numHops; i++) {
1670 MOZ_ASSERT(!obj->containsPure(key));
1671 obj = &obj->staticPrototype()->as<NativeObject>();
1672 }
1673 mozilla::Maybe<PropertyInfo> prop = obj->lookupPure(key);
1674 MOZ_ASSERT(prop.isSome());
1675 MOZ_ASSERT_IF(entry.isDataProperty(), prop->isDataProperty());
1676 MOZ_ASSERT_IF(!entry.isDataProperty(), prop->isAccessorProperty());
1677 MOZ_ASSERT(obj->getTaggedSlotOffset(prop->slot()) == entry.slotOffset());
1678 #endif
1679 }
1680
1681 template <AllowGC allowGC>
1682 static MOZ_ALWAYS_INLINE bool MaybeGetNativePropertyAndWriteToCache(
1683 JSContext* cx, JSObject* obj, PropertyKey key, MegamorphicCacheEntry* entry,
1684 Value* vp) {
1685 MOZ_ASSERT(obj->is<NativeObject>());
1686 NativeObject* nobj = &obj->as<NativeObject>();
1687 Shape* receiverShape = obj->shape();
1688 MegamorphicCache& cache = cx->caches().megamorphicCache;
1689
1690 MOZ_ASSERT(entry);
1691
1692 size_t numHops = 0;
1693 while (true) {
1694 MOZ_ASSERT(!nobj->getOpsLookupProperty());
1695
1696 uint32_t index;
1697 if (PropMap* map = nobj->shape()->lookup(cx, key, &index)) {
1698 PropertyInfo prop = map->getPropertyInfo(index);
1699 if (prop.isDataProperty()) {
1700 TaggedSlotOffset offset = nobj->getTaggedSlotOffset(prop.slot());
1701 cache.initEntryForDataProperty(entry, receiverShape, key, numHops,
1702 offset);
1703 *vp = nobj->getSlot(prop.slot());
1704 return true;
1705 }
1706 if constexpr (allowGC) {
1707 // There's nothing fundamentally blocking us from supporting these,
1708 // it's just not a priority
1709 if (prop.isCustomDataProperty()) {
1710 return false;
1711 }
1712
1713 TaggedSlotOffset offset = nobj->getTaggedSlotOffset(prop.slot());
1714 MOZ_ASSERT(prop.isAccessorProperty());
1715 cache.initEntryForAccessorProperty(entry, receiverShape, key, numHops,
1716 offset);
1717 vp->setUndefined();
1718
1719 if (!nobj->hasGetter(prop)) {
1720 return true;
1721 }
1722
1723 RootedValue getter(cx, nobj->getGetterValue(prop));
1724 RootedValue receiver(cx, ObjectValue(*obj));
1725 RootedValue rootedValue(cx);
1726 if (js::CallGetter(cx, receiver, getter, &rootedValue)) {
1727 *vp = rootedValue;
1728 return true;
1729 }
1730 return false;
1731 } else {
1732 return false;
1733 }
1734 }
1735
1736 // Property not found. Watch out for Class hooks and TypedArrays.
1737 if (MOZ_UNLIKELY(!nobj->is<PlainObject>())) {
1738 if (ClassMayResolveId(cx->names(), nobj->getClass(), key, nobj)) {
1739 return false;
1740 }
1741
1742 // Don't skip past TypedArrayObjects if the key can be a TypedArray index.
1743 if (nobj->is<TypedArrayObject>()) {
1744 if (MaybeTypedArrayIndexString(key)) {
1745 return false;
1746 }
1747 }
1748 }
1749
1750 JSObject* proto = nobj->staticPrototype();
1751 if (!proto) {
1752 cache.initEntryForMissingProperty(entry, receiverShape, key);
1753 vp->setUndefined();
1754 return true;
1755 }
1756
1757 if (!proto->is<NativeObject>()) {
1758 return false;
1759 }
1760 nobj = &proto->as<NativeObject>();
1761 numHops++;
1762 }
1763 }
1764
1765 bool GetNativeDataPropertyPureWithCacheLookup(JSContext* cx, JSObject* obj,
1766 PropertyKey key,
1767 MegamorphicCacheEntry* entry,
1768 Value* vp) {
1769 AutoUnsafeCallWithABI unsafe;
1770
1771 // If we're on x86, we didn't have enough registers to populate this
1772 // directly in Baseline JITted code, so we do the lookup here.
1773 Shape* receiverShape = obj->shape();
1774 MegamorphicCache& cache = cx->caches().megamorphicCache;
1775
1776 if (cache.lookup(receiverShape, key, &entry)) {
1777 NativeObject* nobj = &obj->as<NativeObject>();
1778 VerifyCacheEntry(cx, nobj, key, *entry);
1779 if (entry->isDataProperty()) {
1780 for (size_t i = 0, numHops = entry->numHops(); i < numHops; i++) {
1781 nobj = &nobj->staticPrototype()->as<NativeObject>();
1782 }
1783 uint32_t offset = entry->slotOffset().offset();
1784 if (entry->slotOffset().isFixedSlot()) {
1785 size_t index = NativeObject::getFixedSlotIndexFromOffset(offset);
1786 *vp = nobj->getFixedSlot(index);
1787 } else {
1788 size_t index = NativeObject::getDynamicSlotIndexFromOffset(offset);
1789 *vp = nobj->getDynamicSlot(index);
1790 }
1791 return true;
1792 }
1793 if (entry->isMissingProperty()) {
1794 vp->setUndefined();
1795 return true;
1796 }
1797 if (entry->isAccessorProperty()) {
1798 return false;
1799 }
1800 MOZ_ASSERT(entry->isMissingOwnProperty());
1801 }
1802
1803 return MaybeGetNativePropertyAndWriteToCache<NoGC>(cx, obj, key, entry, vp);
1804 }
1805
1806 bool CheckProxyGetByValueResult(JSContext* cx, HandleObject obj,
1807 HandleValue idVal, HandleValue value,
1808 MutableHandleValue result) {
1809 MOZ_ASSERT(idVal.isString() || idVal.isSymbol());
1810 RootedId rootedId(cx);
1811 if (!PrimitiveValueToId<CanGC>(cx, idVal, &rootedId)) {
1812 return false;
1813 }
1814
1815 auto validation =
1816 ScriptedProxyHandler::checkGetTrapResult(cx, obj, rootedId, value);
1817 if (validation != ScriptedProxyHandler::GetTrapValidationResult::OK) {
1818 ScriptedProxyHandler::reportGetTrapValidationError(cx, rootedId,
1819 validation);
1820 return false;
1821 }
1822 result.set(value);
1823 return true;
1824 }
1825
1826 bool GetNativeDataPropertyPure(JSContext* cx, JSObject* obj, PropertyKey id,
1827 MegamorphicCacheEntry* entry, Value* vp) {
1828 AutoUnsafeCallWithABI unsafe;
1829 return MaybeGetNativePropertyAndWriteToCache<NoGC>(cx, obj, id, entry, vp);
1830 }
1831
1832 // Non-inlined implementation of ValueToAtomOrSymbolPure for less common types.
1833 static bool ValueToAtomOrSymbolSlow(JSContext* cx, const Value& keyVal,
1834 PropertyKey* key) {
1835 MOZ_ASSERT(!keyVal.isString());
1836 MOZ_ASSERT(!keyVal.isSymbol());
1837
1838 if (keyVal.isNull()) {
1839 *key = NameToId(cx->names().null);
1840 return true;
1841 }
1842 if (keyVal.isUndefined()) {
1843 *key = NameToId(cx->names().undefined);
1844 return true;
1845 }
1846 if (keyVal.isBoolean()) {
1847 *key =
1848 NameToId(keyVal.toBoolean() ? cx->names().true_ : cx->names().false_);
1849 return true;
1850 }
1851 if (keyVal.isNumber() && !IsNumberIndex(keyVal)) {
1852 JSAtom* atom = NumberToAtom(cx, keyVal.toNumber());
1853 if (!atom) {
1854 cx->recoverFromOutOfMemory();
1855 return false;
1856 }
1857 *key = PropertyKey::NonIntAtom(atom);
1858 return true;
1859 }
1860
1861 return false;
1862 }
1863
1864 static MOZ_ALWAYS_INLINE bool ValueToAtomOrSymbolPure(JSContext* cx,
1865 const Value& keyVal,
1866 PropertyKey* key) {
1867 if (MOZ_LIKELY(keyVal.isString())) {
1868 JSAtom* atom = AtomizeString(cx, keyVal.toString());
1869 if (!atom) {
1870 cx->recoverFromOutOfMemory();
1871 return false;
1872 }
1873
1874 // Watch out for integer ids because they may be stored in dense elements.
1875 static_assert(PropertyKey::IntMin == 0);
1876 static_assert(NativeObject::MAX_DENSE_ELEMENTS_COUNT < PropertyKey::IntMax,
1877 "All dense elements must have integer jsids");
1878 uint32_t index;
1879 if (MOZ_UNLIKELY(atom->isIndex(&index) && index <= PropertyKey::IntMax)) {
1880 return false;
1881 }
1882
1883 *key = PropertyKey::NonIntAtom(atom);
1884 return true;
1885 }
1886
1887 if (keyVal.isSymbol()) {
1888 *key = PropertyKey::Symbol(keyVal.toSymbol());
1889 return true;
1890 }
1891
1892 return ValueToAtomOrSymbolSlow(cx, keyVal, key);
1893 }
1894
1895 bool GetNativeDataPropertyByValuePure(JSContext* cx, JSObject* obj,
1896 MegamorphicCacheEntry* entry, Value* vp) {
1897 AutoUnsafeCallWithABI unsafe;
1898
1899 // vp[0] contains the key, result will be stored in vp[1].
1900 Value keyVal = vp[0];
1901 PropertyKey key;
1902 if (!ValueToAtomOrSymbolPure(cx, keyVal, &key)) {
1903 return false;
1904 }
1905
1906 Shape* receiverShape = obj->shape();
1907 MegamorphicCache& cache = cx->caches().megamorphicCache;
1908 if (!entry) {
1909 cache.lookup(receiverShape, key, &entry);
1910 }
1911
1912 Value* res = vp + 1;
1913 return MaybeGetNativePropertyAndWriteToCache<NoGC>(cx, obj, key, entry, res);
1914 }
1915
1916 bool GetPropertyCached(JSContext* cx, HandleObject obj, HandleId id,
1917 MegamorphicCacheEntry* entry,
1918 MutableHandleValue result) {
1919 if (entry->isMissingProperty()) {
1920 result.setUndefined();
1921 return true;
1922 }
1923
1924 MOZ_ASSERT(entry->isDataProperty() || entry->isAccessorProperty());
1925
1926 NativeObject* nobj = &obj->as<NativeObject>();
1927 for (size_t i = 0, numHops = entry->numHops(); i < numHops; i++) {
1928 nobj = &nobj->staticPrototype()->as<NativeObject>();
1929 }
1930
1931 uint32_t offset = entry->slotOffset().offset();
1932 if (entry->slotOffset().isFixedSlot()) {
1933 size_t index = NativeObject::getFixedSlotIndexFromOffset(offset);
1934 result.set(nobj->getFixedSlot(index));
1935 } else {
1936 size_t index = NativeObject::getDynamicSlotIndexFromOffset(offset);
1937 result.set(nobj->getDynamicSlot(index));
1938 }
1939
1940 // If it's a data property, we're done - otherwise we need to try to call the
1941 // getter
1942 if (entry->isDataProperty()) {
1943 return true;
1944 }
1945
1946 JSObject* getter = result.toGCThing()->as<GetterSetter>()->getter();
1947 if (getter) {
1948 RootedValue getterValue(cx, ObjectValue(*getter));
1949 RootedValue receiver(cx, ObjectValue(*obj));
1950 return js::CallGetter(cx, receiver, getterValue, result);
1951 }
1952 result.setUndefined();
1953 return true;
1954 }
1955
1956 bool GetPropMaybeCached(JSContext* cx, HandleObject obj, HandleId id,
1957 MegamorphicCacheEntry* entry,
1958 MutableHandleValue result) {
1959 if (obj->is<NativeObject>()) {
1960 // Look up the entry in the cache if we don't have it
1961 Shape* receiverShape = obj->shape();
1962 MegamorphicCache& cache = cx->caches().megamorphicCache;
1963 if (!entry) {
1964 cache.lookup(receiverShape, id, &entry);
1965 }
1966
1967 // If we hit it, load it from the cache. We can't though if it was a
1968 // MissingOwnProperty entry (added by the HasOwn handler), because we
1969 // need to look it up again to know if it's somewhere on the prototype
1970 // chain
1971 if (cache.isValidForLookup(*entry, receiverShape, id) &&
1972 !entry->isMissingOwnProperty()) {
1973 return GetPropertyCached(cx, obj, id, entry, result);
1974 }
1975
1976 if (MaybeGetNativePropertyAndWriteToCache<CanGC>(cx, obj.get(), id.get(),
1977 entry, &result.get())) {
1978 return true;
1979 }
1980
1981 // The getter call in MaybeGetNativePropertyAndWriteToCache can throw, so
1982 // we need to check for that specifically
1983 // XXX: I know this is unusual, but I'm not sure on the best approach here -
1984 // is this alright?
1985 if (JS_IsExceptionPending(cx)) {
1986 return false;
1987 }
1988 }
1989
1990 return GetProperty(cx, obj, obj, id, result);
1991 }
1992
1993 bool GetElemMaybeCached(JSContext* cx, HandleObject obj, HandleValue keyVal,
1994 MegamorphicCacheEntry* entry,
1995 MutableHandleValue result) {
1996 PropertyKey key;
1997 if (obj->is<NativeObject>() &&
1998 ValueToAtomOrSymbolPure(cx, keyVal.get(), &key)) {
1999 Shape* receiverShape = obj->shape();
2000 MegamorphicCache& cache = cx->caches().megamorphicCache;
2001 if (!entry) {
2002 cache.lookup(receiverShape, key, &entry);
2003 }
2004
2005 if (cache.isValidForLookup(*entry, receiverShape, key) &&
2006 !entry->isMissingOwnProperty()) {
2007 Rooted<PropertyKey> rkey(cx, key);
2008 return GetPropertyCached(cx, obj, rkey, entry, result);
2009 }
2010
2011 if (MaybeGetNativePropertyAndWriteToCache<CanGC>(cx, obj.get(), key, entry,
2012 &result.get())) {
2013 return true;
2014 }
2015
2016 // The getter call in MaybeGetNativePropertyAndWriteToCache can throw, so
2017 // we need to check for that specifically
2018 if (JS_IsExceptionPending(cx)) {
2019 return false;
2020 }
2021 }
2022
2023 RootedValue objVal(cx, ObjectValue(*obj));
2024 return GetObjectElementOperation(cx, JSOp::GetElem, obj, objVal, keyVal,
2025 result);
2026 }
2027
2028 bool ObjectHasGetterSetterPure(JSContext* cx, JSObject* objArg, jsid id,
2029 GetterSetter* getterSetter) {
2030 AutoUnsafeCallWithABI unsafe;
2031
2032 // Window objects may require outerizing (passing the WindowProxy to the
2033 // getter/setter), so we don't support them here.
2034 if (MOZ_UNLIKELY(!objArg->is<NativeObject>() || IsWindow(objArg))) {
2035 return false;
2036 }
2037
2038 NativeObject* nobj = &objArg->as<NativeObject>();
2039
2040 while (true) {
2041 uint32_t index;
2042 if (PropMap* map = nobj->shape()->lookup(cx, id, &index)) {
2043 PropertyInfo prop = map->getPropertyInfo(index);
2044 if (!prop.isAccessorProperty()) {
2045 return false;
2046 }
2047 GetterSetter* actualGetterSetter = nobj->getGetterSetter(prop);
2048 if (actualGetterSetter == getterSetter) {
2049 return true;
2050 }
2051 return (actualGetterSetter->getter() == getterSetter->getter() &&
2052 actualGetterSetter->setter() == getterSetter->setter());
2053 }
2054
2055 // Property not found. Watch out for Class hooks.
2056 if (!nobj->is<PlainObject>()) {
2057 if (ClassMayResolveId(cx->names(), nobj->getClass(), id, nobj)) {
2058 return false;
2059 }
2060 }
2061
2062 JSObject* proto = nobj->staticPrototype();
2063 if (!proto) {
2064 return false;
2065 }
2066
2067 if (!proto->is<NativeObject>()) {
2068 return false;
2069 }
2070 nobj = &proto->as<NativeObject>();
2071 }
2072 }
2073
2074 template <bool HasOwn>
2075 bool HasNativeDataPropertyPure(JSContext* cx, JSObject* obj,
2076 MegamorphicCacheEntry* entry, Value* vp) {
2077 AutoUnsafeCallWithABI unsafe;
2078
2079 // vp[0] contains the key, result will be stored in vp[1].
2080 Value keyVal = vp[0];
2081 PropertyKey key;
2082 if (!ValueToAtomOrSymbolPure(cx, keyVal, &key)) {
2083 return false;
2084 }
2085
2086 MegamorphicCache& cache = cx->caches().megamorphicCache;
2087 Shape* receiverShape = obj->shape();
2088 if (!entry) {
2089 if (cache.lookup(receiverShape, key, &entry)) {
2090 VerifyCacheEntry(cx, &obj->as<NativeObject>(), key, *entry);
2091 }
2092 }
2093
2094 size_t numHops = 0;
2095 do {
2096 if (MOZ_UNLIKELY(!obj->is<NativeObject>())) {
2097 return false;
2098 }
2099
2100 MOZ_ASSERT(!obj->getOpsLookupProperty());
2101
2102 NativeObject* nobj = &obj->as<NativeObject>();
2103 uint32_t index;
2104 if (PropMap* map = nobj->shape()->lookup(cx, key, &index)) {
2105 PropertyInfo prop = map->getPropertyInfo(index);
2106 if (prop.isDataProperty()) {
2107 TaggedSlotOffset offset = nobj->getTaggedSlotOffset(prop.slot());
2108 cache.initEntryForDataProperty(entry, receiverShape, key, numHops,
2109 offset);
2110 }
2111 vp[1].setBoolean(true);
2112 return true;
2113 }
2114
2115 // Property not found. Watch out for Class hooks and TypedArrays.
2116 if (MOZ_UNLIKELY(!obj->is<PlainObject>())) {
2117 // Fail if there's a resolve hook, unless the mayResolve hook tells us
2118 // the resolve hook won't define a property with this key.
2119 if (ClassMayResolveId(cx->names(), obj->getClass(), key, obj)) {
2120 return false;
2121 }
2122
2123 // Don't skip past TypedArrayObjects if the key can be a TypedArray
2124 // index.
2125 if (obj->is<TypedArrayObject>()) {
2126 if (MaybeTypedArrayIndexString(key)) {
2127 return false;
2128 }
2129 }
2130 }
2131
2132 // If implementing Object.hasOwnProperty, don't follow protochain.
2133 if constexpr (HasOwn) {
2134 break;
2135 }
2136
2137 // Get prototype. Objects that may allow dynamic prototypes are already
2138 // filtered out above.
2139 obj = obj->staticPrototype();
2140 numHops++;
2141 } while (obj);
2142
2143 // Missing property.
2144 if (entry) {
2145 if constexpr (HasOwn) {
2146 cache.initEntryForMissingOwnProperty(entry, receiverShape, key);
2147 } else {
2148 cache.initEntryForMissingProperty(entry, receiverShape, key);
2149 }
2150 }
2151 vp[1].setBoolean(false);
2152 return true;
2153 }
2154
2155 template bool HasNativeDataPropertyPure<true>(JSContext* cx, JSObject* obj,
2156 MegamorphicCacheEntry* entry,
2157 Value* vp);
2158
2159 template bool HasNativeDataPropertyPure<false>(JSContext* cx, JSObject* obj,
2160 MegamorphicCacheEntry* entry,
2161 Value* vp);
2162
2163 bool HasNativeElementPure(JSContext* cx, NativeObject* obj, int32_t index,
2164 Value* vp) {
2165 AutoUnsafeCallWithABI unsafe;
2166
2167 MOZ_ASSERT(obj->is<NativeObject>());
2168 MOZ_ASSERT(!obj->getOpsHasProperty());
2169 MOZ_ASSERT(!obj->getOpsLookupProperty());
2170 MOZ_ASSERT(!obj->getOpsGetOwnPropertyDescriptor());
2171
2172 if (MOZ_UNLIKELY(index < 0)) {
2173 return false;
2174 }
2175
2176 if (obj->containsDenseElement(index)) {
2177 vp[0].setBoolean(true);
2178 return true;
2179 }
2180
2181 PropertyKey key = PropertyKey::Int(index);
2182 uint32_t unused;
2183 if (obj->shape()->lookup(cx, key, &unused)) {
2184 vp[0].setBoolean(true);
2185 return true;
2186 }
2187
2188 // Fail if there's a resolve hook, unless the mayResolve hook tells
2189 // us the resolve hook won't define a property with this key.
2190 if (MOZ_UNLIKELY(ClassMayResolveId(cx->names(), obj->getClass(), key, obj))) {
2191 return false;
2192 }
2193 // TypedArrayObject are also native and contain indexed properties.
2194 if (MOZ_UNLIKELY(obj->is<TypedArrayObject>())) {
2195 size_t length = obj->as<TypedArrayObject>().length().valueOr(0);
2196 vp[0].setBoolean(uint32_t(index) < length);
2197 return true;
2198 }
2199
2200 vp[0].setBoolean(false);
2201 return true;
2202 }
2203
2204 // Fast path for setting/adding a plain object property. This is the common case
2205 // for megamorphic SetProp/SetElem.
2206 template <bool UseCache>
2207 static bool TryAddOrSetPlainObjectProperty(JSContext* cx,
2208 Handle<PlainObject*> obj,
2209 PropertyKey key, HandleValue value,
2210 bool* optimized) {
2211 MOZ_ASSERT(!*optimized);
2212
2213 Shape* receiverShape = obj->shape();
2214 MegamorphicSetPropCache& cache = *cx->caches().megamorphicSetPropCache;
2215
2216 #ifdef DEBUG
2217 if constexpr (UseCache) {
2218 MegamorphicSetPropCache::Entry* entry;
2219 if (cache.lookup(receiverShape, key, &entry)) {
2220 if (entry->afterShape() != nullptr) { // AddProp
2221 NativeObject* holder = nullptr;
2222 PropertyResult prop;
2223 MOZ_ASSERT(LookupPropertyPure(cx, obj, key, &holder, &prop));
2224 MOZ_ASSERT(obj != holder);
2225 MOZ_ASSERT_IF(prop.isFound(),
2226 prop.isNativeProperty() &&
2227 prop.propertyInfo().isDataProperty() &&
2228 prop.propertyInfo().writable());
2229 } else { // SetProp
2230 mozilla::Maybe<PropertyInfo> prop = obj->lookupPure(key);
2231 MOZ_ASSERT(prop.isSome());
2232 MOZ_ASSERT(prop->isDataProperty());
2233 MOZ_ASSERT(obj->getTaggedSlotOffset(prop->slot()) ==
2234 entry->slotOffset());
2235 }
2236 }
2237 }
2238 #endif
2239
2240 // Fast path for changing a data property.
2241 uint32_t index;
2242 if (PropMap* map = obj->shape()->lookup(cx, key, &index)) {
2243 PropertyInfo prop = map->getPropertyInfo(index);
2244 if (!prop.isDataProperty() || !prop.writable()) {
2245 return true;
2246 }
2247 bool watchesPropValue = Watchtower::watchesPropertyValueChange(obj);
2248 if (MOZ_UNLIKELY(watchesPropValue)) {
2249 Watchtower::watchPropertyValueChange<AllowGC::NoGC>(cx, obj, key, value,
2250 prop);
2251 }
2252 obj->setSlot(prop.slot(), value);
2253 *optimized = true;
2254
2255 if constexpr (UseCache) {
2256 // Don't add an entry to the MegamorphicSetPropCache if we need to invoke
2257 // the Watchtower hook for property value changes. The cache is used
2258 // directly from JIT code and we can't easily call into Watchtower from
2259 // there.
2260 if (!watchesPropValue) {
2261 TaggedSlotOffset offset = obj->getTaggedSlotOffset(prop.slot());
2262 cache.set(receiverShape, nullptr, key, offset, 0);
2263 }
2264 }
2265 return true;
2266 }
2267
2268 // Don't support "__proto__". This lets us take advantage of the
2269 // hasNonWritableOrAccessorPropExclProto optimization below.
2270 if (MOZ_UNLIKELY(!obj->isExtensible() || key.isAtom(cx->names().proto_))) {
2271 return true;
2272 }
2273
2274 // Ensure the proto chain contains only plain objects. Deoptimize for accessor
2275 // properties and non-writable data properties (we can't shadow non-writable
2276 // properties).
2277 JSObject* proto = obj->staticPrototype();
2278 while (proto) {
2279 if (!proto->is<PlainObject>()) {
2280 return true;
2281 }
2282 PlainObject* plainProto = &proto->as<PlainObject>();
2283 if (plainProto->hasNonWritableOrAccessorPropExclProto()) {
2284 uint32_t index;
2285 if (PropMap* map = plainProto->shape()->lookup(cx, key, &index)) {
2286 PropertyInfo prop = map->getPropertyInfo(index);
2287 if (!prop.isDataProperty() || !prop.writable()) {
2288 return true;
2289 }
2290 break;
2291 }
2292 }
2293 proto = plainProto->staticPrototype();
2294 }
2295
2296 #ifdef DEBUG
2297 // At this point either the property is missing or it's a writable data
2298 // property on the proto chain that we can shadow.
2299 {
2300 NativeObject* holder = nullptr;
2301 PropertyResult prop;
2302 MOZ_ASSERT(LookupPropertyPure(cx, obj, key, &holder, &prop));
2303 MOZ_ASSERT(obj != holder);
2304 MOZ_ASSERT_IF(prop.isFound(), prop.isNativeProperty() &&
2305 prop.propertyInfo().isDataProperty() &&
2306 prop.propertyInfo().writable());
2307 }
2308 #endif
2309
2310 *optimized = true;
2311 Rooted<PropertyKey> keyRoot(cx, key);
2312 Rooted<Shape*> receiverShapeRoot(cx, receiverShape);
2313 uint32_t resultSlot = 0;
2314 size_t numDynamic = obj->numDynamicSlots();
2315 bool res = AddDataPropertyToPlainObject(cx, obj, keyRoot, value, &resultSlot);
2316
2317 if constexpr (UseCache) {
2318 if (res && obj->shape()->isShared() &&
2319 resultSlot < SharedPropMap::MaxPropsForNonDictionary &&
2320 !Watchtower::watchesPropertyAdd(obj)) {
2321 TaggedSlotOffset offset = obj->getTaggedSlotOffset(resultSlot);
2322 uint32_t newCapacity = 0;
2323 if (!(resultSlot < obj->numFixedSlots() ||
2324 (resultSlot - obj->numFixedSlots()) < numDynamic)) {
2325 newCapacity = obj->numDynamicSlots();
2326 }
2327 cache.set(receiverShapeRoot, obj->shape(), keyRoot, offset, newCapacity);
2328 }
2329 }
2330
2331 return res;
2332 }
2333
2334 template <bool Cached>
2335 bool SetElementMegamorphic(JSContext* cx, HandleObject obj, HandleValue index,
2336 HandleValue value, bool strict) {
2337 if (obj->is<PlainObject>()) {
2338 PropertyKey key;
2339 if (ValueToAtomOrSymbolPure(cx, index, &key)) {
2340 bool optimized = false;
2341 if (!TryAddOrSetPlainObjectProperty<Cached>(cx, obj.as<PlainObject>(),
2342 key, value, &optimized)) {
2343 return false;
2344 }
2345 if (optimized) {
2346 return true;
2347 }
2348 }
2349 }
2350 Rooted<Value> receiver(cx, ObjectValue(*obj));
2351 return SetObjectElementWithReceiver(cx, obj, index, value, receiver, strict);
2352 }
2353
2354 template bool SetElementMegamorphic<false>(JSContext* cx, HandleObject obj,
2355 HandleValue index, HandleValue value,
2356 bool strict);
2357 template bool SetElementMegamorphic<true>(JSContext* cx, HandleObject obj,
2358 HandleValue index, HandleValue value,
2359 bool strict);
2360
2361 template <bool Cached>
2362 bool SetPropertyMegamorphic(JSContext* cx, HandleObject obj, HandleId id,
2363 HandleValue value, bool strict) {
2364 if (obj->is<PlainObject>()) {
2365 bool optimized = false;
2366 if (!TryAddOrSetPlainObjectProperty<Cached>(cx, obj.as<PlainObject>(), id,
2367 value, &optimized)) {
2368 return false;
2369 }
2370 if (optimized) {
2371 return true;
2372 }
2373 }
2374 Rooted<Value> receiver(cx, ObjectValue(*obj));
2375 ObjectOpResult result;
2376 return SetProperty(cx, obj, id, value, receiver, result) &&
2377 result.checkStrictModeError(cx, obj, id, strict);
2378 }
2379
2380 template bool SetPropertyMegamorphic<false>(JSContext* cx, HandleObject obj,
2381 HandleId id, HandleValue value,
2382 bool strict);
2383 template bool SetPropertyMegamorphic<true>(JSContext* cx, HandleObject obj,
2384 HandleId id, HandleValue value,
2385 bool strict);
2386
2387 void HandleCodeCoverageAtPC(BaselineFrame* frame, jsbytecode* pc) {
2388 AutoUnsafeCallWithABI unsafe(UnsafeABIStrictness::AllowPendingExceptions);
2389
2390 MOZ_ASSERT(frame->runningInInterpreter());
2391
2392 JSScript* script = frame->script();
2393 MOZ_ASSERT(pc == script->main() || BytecodeIsJumpTarget(JSOp(*pc)));
2394
2395 if (!script->hasScriptCounts()) {
2396 if (!script->realm()->collectCoverageForDebug()) {
2397 return;
2398 }
2399 JSContext* cx = script->runtimeFromMainThread()->mainContextFromOwnThread();
2400 AutoEnterOOMUnsafeRegion oomUnsafe;
2401 if (!script->initScriptCounts(cx)) {
2402 oomUnsafe.crash("initScriptCounts");
2403 }
2404 }
2405
2406 PCCounts* counts = script->maybeGetPCCounts(pc);
2407 MOZ_ASSERT(counts);
2408 counts->numExec()++;
2409 }
2410
2411 void HandleCodeCoverageAtPrologue(BaselineFrame* frame) {
2412 AutoUnsafeCallWithABI unsafe;
2413
2414 MOZ_ASSERT(frame->runningInInterpreter());
2415
2416 JSScript* script = frame->script();
2417 jsbytecode* main = script->main();
2418 if (!BytecodeIsJumpTarget(JSOp(*main))) {
2419 HandleCodeCoverageAtPC(frame, main);
2420 }
2421 }
2422
2423 JSString* TypeOfNameObject(JSObject* obj, JSRuntime* rt) {
2424 AutoUnsafeCallWithABI unsafe;
2425 JSType type = js::TypeOfObject(obj);
2426 return TypeName(type, *rt->commonNames);
2427 }
2428
2429 bool TypeOfEqObject(JSObject* obj, TypeofEqOperand operand) {
2430 AutoUnsafeCallWithABI unsafe;
2431 bool result = js::TypeOfObject(obj) == operand.type();
2432 if (operand.compareOp() == JSOp::Ne) {
2433 result = !result;
2434 }
2435 return result;
2436 }
2437
2438 bool GetPrototypeOf(JSContext* cx, HandleObject target,
2439 MutableHandleValue rval) {
2440 MOZ_ASSERT(target->hasDynamicPrototype());
2441
2442 RootedObject proto(cx);
2443 if (!GetPrototype(cx, target, &proto)) {
2444 return false;
2445 }
2446 rval.setObjectOrNull(proto);
2447 return true;
2448 }
2449
2450 static JSString* ConvertObjectToStringForConcat(JSContext* cx,
2451 HandleValue obj) {
2452 MOZ_ASSERT(obj.isObject());
2453 RootedValue rootedObj(cx, obj);
2454 if (!ToPrimitive(cx, &rootedObj)) {
2455 return nullptr;
2456 }
2457 return ToString<CanGC>(cx, rootedObj);
2458 }
2459
2460 bool DoConcatStringObject(JSContext* cx, HandleValue lhs, HandleValue rhs,
2461 MutableHandleValue res) {
2462 JSString* lstr = nullptr;
2463 JSString* rstr = nullptr;
2464
2465 if (lhs.isString()) {
2466 // Convert rhs first.
2467 MOZ_ASSERT(lhs.isString() && rhs.isObject());
2468 rstr = ConvertObjectToStringForConcat(cx, rhs);
2469 if (!rstr) {
2470 return false;
2471 }
2472
2473 // lhs is already string.
2474 lstr = lhs.toString();
2475 } else {
2476 MOZ_ASSERT(rhs.isString() && lhs.isObject());
2477 // Convert lhs first.
2478 lstr = ConvertObjectToStringForConcat(cx, lhs);
2479 if (!lstr) {
2480 return false;
2481 }
2482
2483 // rhs is already string.
2484 rstr = rhs.toString();
2485 }
2486
2487 JSString* str = ConcatStrings<NoGC>(cx, lstr, rstr);
2488 if (!str) {
2489 RootedString nlstr(cx, lstr), nrstr(cx, rstr);
2490 str = ConcatStrings<CanGC>(cx, nlstr, nrstr);
2491 if (!str) {
2492 return false;
2493 }
2494 }
2495
2496 res.setString(str);
2497 return true;
2498 }
2499
2500 bool IsPossiblyWrappedTypedArray(JSContext* cx, JSObject* obj, bool* result) {
2501 MOZ_ASSERT(obj->is<WrapperObject>(), "non-wrappers are handled in JIT code");
2502
2503 JSObject* unwrapped = CheckedUnwrapDynamic(obj, cx);
2504 if (!unwrapped) {
2505 ReportAccessDenied(cx);
2506 return false;
2507 }
2508
2509 *result = unwrapped->is<TypedArrayObject>();
2510 return true;
2511 }
2512
2513 // Called from CreateDependentString::generateFallback.
2514 void* AllocateDependentString(JSContext* cx) {
2515 AutoUnsafeCallWithABI unsafe;
2516 return cx->newCell<JSDependentString, NoGC>(js::gc::Heap::Default);
2517 }
2518 void* AllocateFatInlineString(JSContext* cx) {
2519 AutoUnsafeCallWithABI unsafe;
2520 return cx->newCell<JSFatInlineString, NoGC>(js::gc::Heap::Default);
2521 }
2522
2523 // Called to allocate a BigInt if inline allocation failed.
2524 void* AllocateBigIntNoGC(JSContext* cx, bool requestMinorGC) {
2525 AutoUnsafeCallWithABI unsafe;
2526
2527 if (requestMinorGC && cx->nursery().isEnabled()) {
2528 cx->nursery().requestMinorGC(JS::GCReason::OUT_OF_NURSERY);
2529 }
2530
2531 return cx->newCell<JS::BigInt, NoGC>(js::gc::Heap::Tenured);
2532 }
2533
2534 void AllocateAndInitTypedArrayBuffer(JSContext* cx, TypedArrayObject* obj,
2535 int32_t count) {
2536 AutoUnsafeCallWithABI unsafe;
2537
2538 // Initialize the data slot to UndefinedValue to signal to our JIT caller that
2539 // the allocation failed if the slot isn't overwritten below.
2540 obj->initFixedSlot(TypedArrayObject::DATA_SLOT, UndefinedValue());
2541
2542 // Negative numbers or zero will bail out to the slow path, which in turn will
2543 // raise an invalid argument exception or create a correct object with zero
2544 // elements.
2545 constexpr size_t byteLengthLimit = TypedArrayObject::ByteLengthLimit;
2546 if (count <= 0 || size_t(count) > byteLengthLimit / obj->bytesPerElement()) {
2547 obj->setFixedSlot(TypedArrayObject::LENGTH_SLOT, PrivateValue(size_t(0)));
2548 return;
2549 }
2550
2551 obj->setFixedSlot(TypedArrayObject::LENGTH_SLOT, PrivateValue(count));
2552
2553 size_t nbytes = size_t(count) * obj->bytesPerElement();
2554 MOZ_ASSERT(nbytes <= byteLengthLimit);
2555 nbytes = RoundUp(nbytes, sizeof(Value));
2556
2557 MOZ_ASSERT(!obj->isTenured());
2558 void* buf = cx->nursery().allocateZeroedBuffer(obj, nbytes,
2559 js::ArrayBufferContentsArena);
2560 if (buf) {
2561 InitReservedSlot(obj, TypedArrayObject::DATA_SLOT, buf, nbytes,
2562 MemoryUse::TypedArrayElements);
2563 }
2564 }
2565
2566 #ifdef JS_GC_PROBES
2567 void TraceCreateObject(JSObject* obj) {
2568 AutoUnsafeCallWithABI unsafe;
2569 js::gc::gcprobes::CreateObject(obj);
2570 }
2571 #endif
2572
2573 BigInt* CreateBigIntFromInt32(JSContext* cx, int32_t i32) {
2574 return js::BigInt::createFromInt64(cx, int64_t(i32));
2575 }
2576
2577 #if JS_BITS_PER_WORD == 32
2578 BigInt* CreateBigIntFromInt64(JSContext* cx, uint32_t low, uint32_t high) {
2579 uint64_t n = (static_cast<uint64_t>(high) << 32) + low;
2580 return js::BigInt::createFromInt64(cx, n);
2581 }
2582
2583 BigInt* CreateBigIntFromUint64(JSContext* cx, uint32_t low, uint32_t high) {
2584 uint64_t n = (static_cast<uint64_t>(high) << 32) + low;
2585 return js::BigInt::createFromUint64(cx, n);
2586 }
2587 #else
2588 BigInt* CreateBigIntFromInt64(JSContext* cx, uint64_t i64) {
2589 return js::BigInt::createFromInt64(cx, i64);
2590 }
2591
2592 BigInt* CreateBigIntFromUint64(JSContext* cx, uint64_t i64) {
2593 return js::BigInt::createFromUint64(cx, i64);
2594 }
2595 #endif
2596
2597 bool DoStringToInt64(JSContext* cx, HandleString str, uint64_t* res) {
2598 BigInt* bi;
2599 JS_TRY_VAR_OR_RETURN_FALSE(cx, bi, js::StringToBigInt(cx, str));
2600
2601 if (!bi) {
2602 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2603 JSMSG_BIGINT_INVALID_SYNTAX);
2604 return false;
2605 }
2606
2607 *res = js::BigInt::toUint64(bi);
2608 return true;
2609 }
2610
2611 template <EqualityKind Kind>
2612 bool BigIntEqual(BigInt* x, BigInt* y) {
2613 AutoUnsafeCallWithABI unsafe;
2614 bool res = BigInt::equal(x, y);
2615 if (Kind != EqualityKind::Equal) {
2616 res = !res;
2617 }
2618 return res;
2619 }
2620
2621 template bool BigIntEqual<EqualityKind::Equal>(BigInt* x, BigInt* y);
2622 template bool BigIntEqual<EqualityKind::NotEqual>(BigInt* x, BigInt* y);
2623
2624 template <ComparisonKind Kind>
2625 bool BigIntCompare(BigInt* x, BigInt* y) {
2626 AutoUnsafeCallWithABI unsafe;
2627 bool res = BigInt::lessThan(x, y);
2628 if (Kind != ComparisonKind::LessThan) {
2629 res = !res;
2630 }
2631 return res;
2632 }
2633
2634 template bool BigIntCompare<ComparisonKind::LessThan>(BigInt* x, BigInt* y);
2635 template bool BigIntCompare<ComparisonKind::GreaterThanOrEqual>(BigInt* x,
2636 BigInt* y);
2637
2638 template <EqualityKind Kind>
2639 bool BigIntNumberEqual(BigInt* x, double y) {
2640 AutoUnsafeCallWithABI unsafe;
2641 bool res = BigInt::equal(x, y);
2642 if (Kind != EqualityKind::Equal) {
2643 res = !res;
2644 }
2645 return res;
2646 }
2647
2648 template bool BigIntNumberEqual<EqualityKind::Equal>(BigInt* x, double y);
2649 template bool BigIntNumberEqual<EqualityKind::NotEqual>(BigInt* x, double y);
2650
2651 template <ComparisonKind Kind>
2652 bool BigIntNumberCompare(BigInt* x, double y) {
2653 AutoUnsafeCallWithABI unsafe;
2654 mozilla::Maybe<bool> res = BigInt::lessThan(x, y);
2655 if (Kind == ComparisonKind::LessThan) {
2656 return res.valueOr(false);
2657 }
2658 return !res.valueOr(true);
2659 }
2660
2661 template bool BigIntNumberCompare<ComparisonKind::LessThan>(BigInt* x,
2662 double y);
2663 template bool BigIntNumberCompare<ComparisonKind::GreaterThanOrEqual>(BigInt* x,
2664 double y);
2665
2666 template <ComparisonKind Kind>
2667 bool NumberBigIntCompare(double x, BigInt* y) {
2668 AutoUnsafeCallWithABI unsafe;
2669 mozilla::Maybe<bool> res = BigInt::lessThan(x, y);
2670 if (Kind == ComparisonKind::LessThan) {
2671 return res.valueOr(false);
2672 }
2673 return !res.valueOr(true);
2674 }
2675
2676 template bool NumberBigIntCompare<ComparisonKind::LessThan>(double x,
2677 BigInt* y);
2678 template bool NumberBigIntCompare<ComparisonKind::GreaterThanOrEqual>(
2679 double x, BigInt* y);
2680
2681 template <EqualityKind Kind>
2682 bool BigIntStringEqual(JSContext* cx, HandleBigInt x, HandleString y,
2683 bool* res) {
2684 JS_TRY_VAR_OR_RETURN_FALSE(cx, *res, BigInt::equal(cx, x, y));
2685 if (Kind != EqualityKind::Equal) {
2686 *res = !*res;
2687 }
2688 return true;
2689 }
2690
2691 template bool BigIntStringEqual<EqualityKind::Equal>(JSContext* cx,
2692 HandleBigInt x,
2693 HandleString y, bool* res);
2694 template bool BigIntStringEqual<EqualityKind::NotEqual>(JSContext* cx,
2695 HandleBigInt x,
2696 HandleString y,
2697 bool* res);
2698
2699 template <ComparisonKind Kind>
2700 bool BigIntStringCompare(JSContext* cx, HandleBigInt x, HandleString y,
2701 bool* res) {
2702 mozilla::Maybe<bool> result;
2703 if (!BigInt::lessThan(cx, x, y, result)) {
2704 return false;
2705 }
2706 if (Kind == ComparisonKind::LessThan) {
2707 *res = result.valueOr(false);
2708 } else {
2709 *res = !result.valueOr(true);
2710 }
2711 return true;
2712 }
2713
2714 template bool BigIntStringCompare<ComparisonKind::LessThan>(JSContext* cx,
2715 HandleBigInt x,
2716 HandleString y,
2717 bool* res);
2718 template bool BigIntStringCompare<ComparisonKind::GreaterThanOrEqual>(
2719 JSContext* cx, HandleBigInt x, HandleString y, bool* res);
2720
2721 template <ComparisonKind Kind>
2722 bool StringBigIntCompare(JSContext* cx, HandleString x, HandleBigInt y,
2723 bool* res) {
2724 mozilla::Maybe<bool> result;
2725 if (!BigInt::lessThan(cx, x, y, result)) {
2726 return false;
2727 }
2728 if (Kind == ComparisonKind::LessThan) {
2729 *res = result.valueOr(false);
2730 } else {
2731 *res = !result.valueOr(true);
2732 }
2733 return true;
2734 }
2735
2736 template bool StringBigIntCompare<ComparisonKind::LessThan>(JSContext* cx,
2737 HandleString x,
2738 HandleBigInt y,
2739 bool* res);
2740 template bool StringBigIntCompare<ComparisonKind::GreaterThanOrEqual>(
2741 JSContext* cx, HandleString x, HandleBigInt y, bool* res);
2742
2743 BigInt* BigIntAsIntN(JSContext* cx, HandleBigInt x, int32_t bits) {
2744 MOZ_ASSERT(bits >= 0);
2745 return BigInt::asIntN(cx, x, uint64_t(bits));
2746 }
2747
2748 BigInt* BigIntAsUintN(JSContext* cx, HandleBigInt x, int32_t bits) {
2749 MOZ_ASSERT(bits >= 0);
2750 return BigInt::asUintN(cx, x, uint64_t(bits));
2751 }
2752
2753 template <typename T>
2754 static int32_t AtomicsCompareExchange(TypedArrayObject* typedArray,
2755 size_t index, int32_t expected,
2756 int32_t replacement) {
2757 AutoUnsafeCallWithABI unsafe;
2758
2759 MOZ_ASSERT(!typedArray->hasDetachedBuffer());
2760 MOZ_ASSERT_IF(typedArray->hasResizableBuffer(), !typedArray->isOutOfBounds());
2761 MOZ_ASSERT(index < typedArray->length().valueOr(0));
2762
2763 SharedMem<T*> addr = typedArray->dataPointerEither().cast<T*>();
2764 return jit::AtomicOperations::compareExchangeSeqCst(addr + index, T(expected),
2765 T(replacement));
2766 }
2767
2768 AtomicsCompareExchangeFn AtomicsCompareExchange(Scalar::Type elementType) {
2769 switch (elementType) {
2770 case Scalar::Int8:
2771 return AtomicsCompareExchange<int8_t>;
2772 case Scalar::Uint8:
2773 return AtomicsCompareExchange<uint8_t>;
2774 case Scalar::Int16:
2775 return AtomicsCompareExchange<int16_t>;
2776 case Scalar::Uint16:
2777 return AtomicsCompareExchange<uint16_t>;
2778 case Scalar::Int32:
2779 return AtomicsCompareExchange<int32_t>;
2780 case Scalar::Uint32:
2781 return AtomicsCompareExchange<uint32_t>;
2782 default:
2783 MOZ_CRASH("Unexpected TypedArray type");
2784 }
2785 }
2786
2787 template <typename T>
2788 static int32_t AtomicsExchange(TypedArrayObject* typedArray, size_t index,
2789 int32_t value) {
2790 AutoUnsafeCallWithABI unsafe;
2791
2792 MOZ_ASSERT(!typedArray->hasDetachedBuffer());
2793 MOZ_ASSERT_IF(typedArray->hasResizableBuffer(), !typedArray->isOutOfBounds());
2794 MOZ_ASSERT(index < typedArray->length().valueOr(0));
2795
2796 SharedMem<T*> addr = typedArray->dataPointerEither().cast<T*>();
2797 return jit::AtomicOperations::exchangeSeqCst(addr + index, T(value));
2798 }
2799
2800 AtomicsReadWriteModifyFn AtomicsExchange(Scalar::Type elementType) {
2801 switch (elementType) {
2802 case Scalar::Int8:
2803 return AtomicsExchange<int8_t>;
2804 case Scalar::Uint8:
2805 return AtomicsExchange<uint8_t>;
2806 case Scalar::Int16:
2807 return AtomicsExchange<int16_t>;
2808 case Scalar::Uint16:
2809 return AtomicsExchange<uint16_t>;
2810 case Scalar::Int32:
2811 return AtomicsExchange<int32_t>;
2812 case Scalar::Uint32:
2813 return AtomicsExchange<uint32_t>;
2814 default:
2815 MOZ_CRASH("Unexpected TypedArray type");
2816 }
2817 }
2818
2819 template <typename T>
2820 static int32_t AtomicsAdd(TypedArrayObject* typedArray, size_t index,
2821 int32_t value) {
2822 AutoUnsafeCallWithABI unsafe;
2823
2824 MOZ_ASSERT(!typedArray->hasDetachedBuffer());
2825 MOZ_ASSERT_IF(typedArray->hasResizableBuffer(), !typedArray->isOutOfBounds());
2826 MOZ_ASSERT(index < typedArray->length().valueOr(0));
2827
2828 SharedMem<T*> addr = typedArray->dataPointerEither().cast<T*>();
2829 return jit::AtomicOperations::fetchAddSeqCst(addr + index, T(value));
2830 }
2831
2832 AtomicsReadWriteModifyFn AtomicsAdd(Scalar::Type elementType) {
2833 switch (elementType) {
2834 case Scalar::Int8:
2835 return AtomicsAdd<int8_t>;
2836 case Scalar::Uint8:
2837 return AtomicsAdd<uint8_t>;
2838 case Scalar::Int16:
2839 return AtomicsAdd<int16_t>;
2840 case Scalar::Uint16:
2841 return AtomicsAdd<uint16_t>;
2842 case Scalar::Int32:
2843 return AtomicsAdd<int32_t>;
2844 case Scalar::Uint32:
2845 return AtomicsAdd<uint32_t>;
2846 default:
2847 MOZ_CRASH("Unexpected TypedArray type");
2848 }
2849 }
2850
2851 template <typename T>
2852 static int32_t AtomicsSub(TypedArrayObject* typedArray, size_t index,
2853 int32_t value) {
2854 AutoUnsafeCallWithABI unsafe;
2855
2856 MOZ_ASSERT(!typedArray->hasDetachedBuffer());
2857 MOZ_ASSERT_IF(typedArray->hasResizableBuffer(), !typedArray->isOutOfBounds());
2858 MOZ_ASSERT(index < typedArray->length().valueOr(0));
2859
2860 SharedMem<T*> addr = typedArray->dataPointerEither().cast<T*>();
2861 return jit::AtomicOperations::fetchSubSeqCst(addr + index, T(value));
2862 }
2863
2864 AtomicsReadWriteModifyFn AtomicsSub(Scalar::Type elementType) {
2865 switch (elementType) {
2866 case Scalar::Int8:
2867 return AtomicsSub<int8_t>;
2868 case Scalar::Uint8:
2869 return AtomicsSub<uint8_t>;
2870 case Scalar::Int16:
2871 return AtomicsSub<int16_t>;
2872 case Scalar::Uint16:
2873 return AtomicsSub<uint16_t>;
2874 case Scalar::Int32:
2875 return AtomicsSub<int32_t>;
2876 case Scalar::Uint32:
2877 return AtomicsSub<uint32_t>;
2878 default:
2879 MOZ_CRASH("Unexpected TypedArray type");
2880 }
2881 }
2882
2883 template <typename T>
2884 static int32_t AtomicsAnd(TypedArrayObject* typedArray, size_t index,
2885 int32_t value) {
2886 AutoUnsafeCallWithABI unsafe;
2887
2888 MOZ_ASSERT(!typedArray->hasDetachedBuffer());
2889 MOZ_ASSERT_IF(typedArray->hasResizableBuffer(), !typedArray->isOutOfBounds());
2890 MOZ_ASSERT(index < typedArray->length().valueOr(0));
2891
2892 SharedMem<T*> addr = typedArray->dataPointerEither().cast<T*>();
2893 return jit::AtomicOperations::fetchAndSeqCst(addr + index, T(value));
2894 }
2895
2896 AtomicsReadWriteModifyFn AtomicsAnd(Scalar::Type elementType) {
2897 switch (elementType) {
2898 case Scalar::Int8:
2899 return AtomicsAnd<int8_t>;
2900 case Scalar::Uint8:
2901 return AtomicsAnd<uint8_t>;
2902 case Scalar::Int16:
2903 return AtomicsAnd<int16_t>;
2904 case Scalar::Uint16:
2905 return AtomicsAnd<uint16_t>;
2906 case Scalar::Int32:
2907 return AtomicsAnd<int32_t>;
2908 case Scalar::Uint32:
2909 return AtomicsAnd<uint32_t>;
2910 default:
2911 MOZ_CRASH("Unexpected TypedArray type");
2912 }
2913 }
2914
2915 template <typename T>
2916 static int32_t AtomicsOr(TypedArrayObject* typedArray, size_t index,
2917 int32_t value) {
2918 AutoUnsafeCallWithABI unsafe;
2919
2920 MOZ_ASSERT(!typedArray->hasDetachedBuffer());
2921 MOZ_ASSERT_IF(typedArray->hasResizableBuffer(), !typedArray->isOutOfBounds());
2922 MOZ_ASSERT(index < typedArray->length().valueOr(0));
2923
2924 SharedMem<T*> addr = typedArray->dataPointerEither().cast<T*>();
2925 return jit::AtomicOperations::fetchOrSeqCst(addr + index, T(value));
2926 }
2927
2928 AtomicsReadWriteModifyFn AtomicsOr(Scalar::Type elementType) {
2929 switch (elementType) {
2930 case Scalar::Int8:
2931 return AtomicsOr<int8_t>;
2932 case Scalar::Uint8:
2933 return AtomicsOr<uint8_t>;
2934 case Scalar::Int16:
2935 return AtomicsOr<int16_t>;
2936 case Scalar::Uint16:
2937 return AtomicsOr<uint16_t>;
2938 case Scalar::Int32:
2939 return AtomicsOr<int32_t>;
2940 case Scalar::Uint32:
2941 return AtomicsOr<uint32_t>;
2942 default:
2943 MOZ_CRASH("Unexpected TypedArray type");
2944 }
2945 }
2946
2947 template <typename T>
2948 static int32_t AtomicsXor(TypedArrayObject* typedArray, size_t index,
2949 int32_t value) {
2950 AutoUnsafeCallWithABI unsafe;
2951
2952 MOZ_ASSERT(!typedArray->hasDetachedBuffer());
2953 MOZ_ASSERT_IF(typedArray->hasResizableBuffer(), !typedArray->isOutOfBounds());
2954 MOZ_ASSERT(index < typedArray->length().valueOr(0));
2955
2956 SharedMem<T*> addr = typedArray->dataPointerEither().cast<T*>();
2957 return jit::AtomicOperations::fetchXorSeqCst(addr + index, T(value));
2958 }
2959
2960 AtomicsReadWriteModifyFn AtomicsXor(Scalar::Type elementType) {
2961 switch (elementType) {
2962 case Scalar::Int8:
2963 return AtomicsXor<int8_t>;
2964 case Scalar::Uint8:
2965 return AtomicsXor<uint8_t>;
2966 case Scalar::Int16:
2967 return AtomicsXor<int16_t>;
2968 case Scalar::Uint16:
2969 return AtomicsXor<uint16_t>;
2970 case Scalar::Int32:
2971 return AtomicsXor<int32_t>;
2972 case Scalar::Uint32:
2973 return AtomicsXor<uint32_t>;
2974 default:
2975 MOZ_CRASH("Unexpected TypedArray type");
2976 }
2977 }
2978
2979 template <typename AtomicOp, typename... Args>
2980 static BigInt* AtomicAccess64(JSContext* cx, TypedArrayObject* typedArray,
2981 size_t index, AtomicOp op, Args... args) {
2982 MOZ_ASSERT(Scalar::isBigIntType(typedArray->type()));
2983 MOZ_ASSERT(!typedArray->hasDetachedBuffer());
2984 MOZ_ASSERT_IF(typedArray->hasResizableBuffer(), !typedArray->isOutOfBounds());
2985 MOZ_ASSERT(index < typedArray->length().valueOr(0));
2986
2987 if (typedArray->type() == Scalar::BigInt64) {
2988 SharedMem<int64_t*> addr = typedArray->dataPointerEither().cast<int64_t*>();
2989 int64_t v = op(addr + index, BigInt::toInt64(args)...);
2990 return BigInt::createFromInt64(cx, v);
2991 }
2992
2993 SharedMem<uint64_t*> addr = typedArray->dataPointerEither().cast<uint64_t*>();
2994 uint64_t v = op(addr + index, BigInt::toUint64(args)...);
2995 return BigInt::createFromUint64(cx, v);
2996 }
2997
2998 template <typename AtomicOp, typename... Args>
2999 static auto AtomicAccess64(TypedArrayObject* typedArray, size_t index,
3000 AtomicOp op, Args... args) {
3001 MOZ_ASSERT(Scalar::isBigIntType(typedArray->type()));
3002 MOZ_ASSERT(!typedArray->hasDetachedBuffer());
3003 MOZ_ASSERT_IF(typedArray->hasResizableBuffer(), !typedArray->isOutOfBounds());
3004 MOZ_ASSERT(index < typedArray->length().valueOr(0));
3005
3006 if (typedArray->type() == Scalar::BigInt64) {
3007 SharedMem<int64_t*> addr = typedArray->dataPointerEither().cast<int64_t*>();
3008 return op(addr + index, BigInt::toInt64(args)...);
3009 }
3010
3011 SharedMem<uint64_t*> addr = typedArray->dataPointerEither().cast<uint64_t*>();
3012 return op(addr + index, BigInt::toUint64(args)...);
3013 }
3014
3015 BigInt* AtomicsLoad64(JSContext* cx, TypedArrayObject* typedArray,
3016 size_t index) {
3017 return AtomicAccess64(cx, typedArray, index, [](auto addr) {
3018 return jit::AtomicOperations::loadSeqCst(addr);
3019 });
3020 }
3021
3022 void AtomicsStore64(TypedArrayObject* typedArray, size_t index,
3023 const BigInt* value) {
3024 AutoUnsafeCallWithABI unsafe;
3025
3026 AtomicAccess64(
3027 typedArray, index,
3028 [](auto addr, auto val) {
3029 jit::AtomicOperations::storeSeqCst(addr, val);
3030 },
3031 value);
3032 }
3033
3034 BigInt* AtomicsCompareExchange64(JSContext* cx, TypedArrayObject* typedArray,
3035 size_t index, const BigInt* expected,
3036 const BigInt* replacement) {
3037 return AtomicAccess64(
3038 cx, typedArray, index,
3039 [](auto addr, auto oldval, auto newval) {
3040 return jit::AtomicOperations::compareExchangeSeqCst(addr, oldval,
3041 newval);
3042 },
3043 expected, replacement);
3044 }
3045
3046 BigInt* AtomicsExchange64(JSContext* cx, TypedArrayObject* typedArray,
3047 size_t index, const BigInt* value) {
3048 return AtomicAccess64(
3049 cx, typedArray, index,
3050 [](auto addr, auto val) {
3051 return jit::AtomicOperations::exchangeSeqCst(addr, val);
3052 },
3053 value);
3054 }
3055
3056 BigInt* AtomicsAdd64(JSContext* cx, TypedArrayObject* typedArray, size_t index,
3057 const BigInt* value) {
3058 return AtomicAccess64(
3059 cx, typedArray, index,
3060 [](auto addr, auto val) {
3061 return jit::AtomicOperations::fetchAddSeqCst(addr, val);
3062 },
3063 value);
3064 }
3065
3066 BigInt* AtomicsAnd64(JSContext* cx, TypedArrayObject* typedArray, size_t index,
3067 const BigInt* value) {
3068 return AtomicAccess64(
3069 cx, typedArray, index,
3070 [](auto addr, auto val) {
3071 return jit::AtomicOperations::fetchAndSeqCst(addr, val);
3072 },
3073 value);
3074 }
3075
3076 BigInt* AtomicsOr64(JSContext* cx, TypedArrayObject* typedArray, size_t index,
3077 const BigInt* value) {
3078 return AtomicAccess64(
3079 cx, typedArray, index,
3080 [](auto addr, auto val) {
3081 return jit::AtomicOperations::fetchOrSeqCst(addr, val);
3082 },
3083 value);
3084 }
3085
3086 BigInt* AtomicsSub64(JSContext* cx, TypedArrayObject* typedArray, size_t index,
3087 const BigInt* value) {
3088 return AtomicAccess64(
3089 cx, typedArray, index,
3090 [](auto addr, auto val) {
3091 return jit::AtomicOperations::fetchSubSeqCst(addr, val);
3092 },
3093 value);
3094 }
3095
3096 BigInt* AtomicsXor64(JSContext* cx, TypedArrayObject* typedArray, size_t index,
3097 const BigInt* value) {
3098 return AtomicAccess64(
3099 cx, typedArray, index,
3100 [](auto addr, auto val) {
3101 return jit::AtomicOperations::fetchXorSeqCst(addr, val);
3102 },
3103 value);
3104 }
3105
3106 float RoundFloat16ToFloat32(int32_t d) {
3107 AutoUnsafeCallWithABI unsafe;
3108 return static_cast<float>(js::float16{d});
3109 }
3110
3111 float RoundFloat16ToFloat32(float d) {
3112 AutoUnsafeCallWithABI unsafe;
3113 return static_cast<float>(js::float16{d});
3114 }
3115
3116 float RoundFloat16ToFloat32(double d) {
3117 AutoUnsafeCallWithABI unsafe;
3118 return static_cast<float>(js::float16{d});
3119 }
3120
3121 float Float16ToFloat32(int32_t value) {
3122 AutoUnsafeCallWithABI unsafe;
3123 return static_cast<float>(js::float16::fromRawBits(value));
3124 }
3125
3126 int32_t Float32ToFloat16(float value) {
3127 AutoUnsafeCallWithABI unsafe;
3128 return static_cast<int32_t>(js::float16{value}.toRawBits());
3129 }
3130
3131 void DateFillLocalTimeSlots(DateObject* dateObj) {
3132 AutoUnsafeCallWithABI unsafe;
3133 dateObj->fillLocalTimeSlots();
3134 }
3135
3136 JSAtom* AtomizeStringNoGC(JSContext* cx, JSString* str) {
3137 // IC code calls this directly so we shouldn't GC.
3138 AutoUnsafeCallWithABI unsafe;
3139
3140 JSAtom* atom = AtomizeString(cx, str);
3141 if (!atom) {
3142 cx->recoverFromOutOfMemory();
3143 return nullptr;
3144 }
3145
3146 return atom;
3147 }
3148
3149 bool SetObjectHas(JSContext* cx, Handle<SetObject*> obj, HandleValue key,
3150 bool* rval) {
3151 return obj->has(cx, key, rval);
3152 }
3153
3154 bool SetObjectDelete(JSContext* cx, Handle<SetObject*> obj, HandleValue key,
3155 bool* rval) {
3156 return obj->delete_(cx, key, rval);
3157 }
3158
3159 bool SetObjectAdd(JSContext* cx, Handle<SetObject*> obj, HandleValue key) {
3160 return obj->add(cx, key);
3161 }
3162
3163 bool SetObjectAddFromIC(JSContext* cx, Handle<SetObject*> obj, HandleValue key,
3164 MutableHandleValue rval) {
3165 if (!SetObjectAdd(cx, obj, key)) {
3166 return false;
3167 }
3168 rval.setObject(*obj);
3169 return true;
3170 }
3171
3172 bool MapObjectHas(JSContext* cx, Handle<MapObject*> obj, HandleValue key,
3173 bool* rval) {
3174 return obj->has(cx, key, rval);
3175 }
3176
3177 bool MapObjectGet(JSContext* cx, Handle<MapObject*> obj, HandleValue key,
3178 MutableHandleValue rval) {
3179 return obj->get(cx, key, rval);
3180 }
3181
3182 bool MapObjectDelete(JSContext* cx, Handle<MapObject*> obj, HandleValue key,
3183 bool* rval) {
3184 return obj->delete_(cx, key, rval);
3185 }
3186
3187 bool MapObjectSet(JSContext* cx, Handle<MapObject*> obj, HandleValue key,
3188 HandleValue val) {
3189 return obj->set(cx, key, val);
3190 }
3191
3192 bool MapObjectSetFromIC(JSContext* cx, Handle<MapObject*> obj, HandleValue key,
3193 HandleValue val, MutableHandleValue rval) {
3194 if (!MapObjectSet(cx, obj, key, val)) {
3195 return false;
3196 }
3197 rval.setObject(*obj);
3198 return true;
3199 }
3200
3201 #ifdef DEBUG
3202 template <class T>
3203 static mozilla::HashNumber HashValue(JSContext* cx, T* obj,
3204 const Value* value) {
3205 MOZ_ASSERT(obj->size() > 0);
3206
3207 HashableValue hashable;
3208 MOZ_ALWAYS_TRUE(hashable.setValue(cx, *value));
3209
3210 using Table = typename T::Table;
3211 return *Table(obj).hash(hashable);
3212 }
3213 #endif
3214
3215 void AssertSetObjectHash(JSContext* cx, SetObject* obj, const Value* value,
3216 mozilla::HashNumber actualHash) {
3217 AutoUnsafeCallWithABI unsafe;
3218
3219 MOZ_ASSERT(actualHash == HashValue(cx, obj, value));
3220 }
3221
3222 void AssertMapObjectHash(JSContext* cx, MapObject* obj, const Value* value,
3223 mozilla::HashNumber actualHash) {
3224 AutoUnsafeCallWithABI unsafe;
3225
3226 MOZ_ASSERT(actualHash == HashValue(cx, obj, value));
3227 }
3228
3229 void AssertPropertyLookup(NativeObject* obj, PropertyKey id, uint32_t slot) {
3230 AutoUnsafeCallWithABI unsafe;
3231 #ifdef DEBUG
3232 mozilla::Maybe<PropertyInfo> prop = obj->lookupPure(id);
3233 MOZ_ASSERT(prop.isSome());
3234 MOZ_ASSERT(prop->slot() == slot);
3235 #else
3236 MOZ_CRASH("This should only be called in debug builds.");
3237 #endif
3238 }
3239
3240 void AssumeUnreachable(const char* output) {
3241 MOZ_ReportAssertionFailure(output, __FILE__, __LINE__);
3242 }
3243
3244 void Printf0(const char* output) {
3245 AutoUnsafeCallWithABI unsafe;
3246
3247 // Use stderr instead of stdout because this is only used for debug
3248 // output. stderr is less likely to interfere with the program's normal
3249 // output, and it's always unbuffered.
3250 fprintf(stderr, "%s", output);
3251 }
3252
3253 void Printf1(const char* output, uintptr_t value) {
3254 AutoUnsafeCallWithABI unsafe;
3255 AutoEnterOOMUnsafeRegion oomUnsafe;
3256 js::UniqueChars line = JS_sprintf_append(nullptr, output, value);
3257 if (!line) {
3258 oomUnsafe.crash("OOM at masm.printf");
3259 }
3260 fprintf(stderr, "%s", line.get());
3261 }
3262
3263 } // namespace jit
3264 } // namespace js