Debian Codegraph @

js/src/vm/TypedArrayObject.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 "vm/TypedArrayObject-inl.h"
8 #include "vm/TypedArrayObject.h"
9
10 #include "mozilla/Casting.h"
11 #include "mozilla/CheckedInt.h"
12 #include "mozilla/FloatingPoint.h"
13 #include "mozilla/IntegerTypeTraits.h"
14 #include "mozilla/Likely.h"
15 #include "mozilla/PodOperations.h"
16 #include "mozilla/ScopeExit.h"
17 #include "mozilla/SIMD.h"
18 #include "mozilla/TextUtils.h"
19
20 #include <algorithm>
21 #include <charconv>
22 #include <iterator>
23 #include <limits>
24 #include <numeric>
25 #include <string.h>
26 #include <string_view>
27 #if !defined(XP_WIN) && !defined(__wasi__)
28 # include <sys/mman.h>
29 #endif
30 #include <type_traits>
31
32 #include "jsnum.h"
33 #include "jstypes.h"
34
35 #include "builtin/Array.h"
36 #include "builtin/DataViewObject.h"
37 #include "gc/Barrier.h"
38 #include "gc/MaybeRooted.h"
39 #include "jit/InlinableNatives.h"
40 #include "jit/TrampolineNatives.h"
41 #include "js/Conversions.h"
42 #include "js/experimental/TypedData.h" // JS_GetArrayBufferViewType, JS_GetTypedArray{Length,ByteOffset,ByteLength}, JS_IsTypedArrayObject
43 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
44 #include "js/PropertySpec.h"
45 #include "js/ScalarType.h" // JS::Scalar::Type
46 #include "js/UniquePtr.h"
47 #include "js/Wrapper.h"
48 #include "util/DifferentialTesting.h"
49 #include "util/StringBuilder.h"
50 #include "util/Text.h"
51 #include "util/WindowsWrapper.h"
52 #include "vm/ArrayBufferObject.h"
53 #include "vm/Float16.h"
54 #include "vm/FunctionFlags.h" // js::FunctionFlags
55 #include "vm/GlobalObject.h"
56 #include "vm/Interpreter.h"
57 #include "vm/JSContext.h"
58 #include "vm/JSObject.h"
59 #include "vm/SelfHosting.h"
60 #include "vm/SharedMem.h"
61 #include "vm/Uint8Clamped.h"
62 #include "vm/WrapperObject.h"
63
64 #include "builtin/Sorting-inl.h"
65 #include "gc/Nursery-inl.h"
66 #include "vm/ArrayBufferObject-inl.h"
67 #include "vm/Compartment-inl.h"
68 #include "vm/GeckoProfiler-inl.h"
69 #include "vm/NativeObject-inl.h"
70
71 using namespace js;
72
73 using mozilla::IsAsciiDigit;
74
75 /*
76 * TypedArrayObject
77 *
78 * The non-templated base class for the specific typed implementations.
79 * This class holds all the member variables that are used by
80 * the subclasses.
81 */
82
83 bool TypedArrayObject::convertValue(JSContext* cx, HandleValue v,
84 MutableHandleValue result) const {
85 switch (type()) {
86 case Scalar::BigInt64:
87 case Scalar::BigUint64: {
88 BigInt* bi = ToBigInt(cx, v);
89 if (!bi) {
90 return false;
91 }
92 result.setBigInt(bi);
93 return true;
94 }
95 case Scalar::Int8:
96 case Scalar::Uint8:
97 case Scalar::Int16:
98 case Scalar::Uint16:
99 case Scalar::Int32:
100 case Scalar::Uint32:
101 case Scalar::Float16:
102 case Scalar::Float32:
103 case Scalar::Float64:
104 case Scalar::Uint8Clamped: {
105 double num;
106 if (!ToNumber(cx, v, &num)) {
107 return false;
108 }
109 result.setNumber(num);
110 return true;
111 }
112 case Scalar::MaxTypedArrayViewType:
113 case Scalar::Int64:
114 case Scalar::Simd128:
115 MOZ_CRASH("Unsupported TypedArray type");
116 }
117 MOZ_ASSERT_UNREACHABLE("Invalid scalar type");
118 return false;
119 }
120
121 static bool IsTypedArrayObject(HandleValue v) {
122 return v.isObject() && v.toObject().is<TypedArrayObject>();
123 }
124
125 static bool IsUint8ArrayObject(HandleValue v) {
126 return IsTypedArrayObject(v) &&
127 v.toObject().as<TypedArrayObject>().type() == Scalar::Uint8;
128 }
129
130 /* static */
131 bool TypedArrayObject::ensureHasBuffer(JSContext* cx,
132 Handle<TypedArrayObject*> typedArray) {
133 if (typedArray->hasBuffer()) {
134 return true;
135 }
136
137 MOZ_ASSERT(typedArray->is<FixedLengthTypedArrayObject>(),
138 "Resizable TypedArrays always use an ArrayBuffer");
139
140 Rooted<FixedLengthTypedArrayObject*> tarray(
141 cx, &typedArray->as<FixedLengthTypedArrayObject>());
142
143 size_t byteLength = tarray->byteLength();
144
145 AutoRealm ar(cx, tarray);
146 Rooted<ArrayBufferObject*> buffer(
147 cx, ArrayBufferObject::createZeroed(cx, tarray->byteLength()));
148 if (!buffer) {
149 return false;
150 }
151
152 buffer->pinLength(tarray->isLengthPinned());
153
154 // Attaching the first view to an array buffer is infallible.
155 MOZ_ALWAYS_TRUE(buffer->addView(cx, tarray));
156
157 // tarray is not shared, because if it were it would have a buffer.
158 memcpy(buffer->dataPointer(), tarray->dataPointerUnshared(), byteLength);
159
160 // If the object is in the nursery, the buffer will be freed by the next
161 // nursery GC. Free the data slot pointer if the object has no inline data.
162 size_t nbytes = RoundUp(byteLength, sizeof(Value));
163 Nursery& nursery = cx->nursery();
164 if (tarray->isTenured() && !tarray->hasInlineElements() &&
165 !nursery.isInside(tarray->elements())) {
166 js_free(tarray->elements());
167 RemoveCellMemory(tarray, nbytes, MemoryUse::TypedArrayElements);
168 }
169
170 tarray->setFixedSlot(TypedArrayObject::DATA_SLOT,
171 PrivateValue(buffer->dataPointer()));
172 tarray->setFixedSlot(TypedArrayObject::BUFFER_SLOT, ObjectValue(*buffer));
173
174 return true;
175 }
176
177 #ifdef DEBUG
178 void FixedLengthTypedArrayObject::assertZeroLengthArrayData() const {
179 if (length() == 0 && !hasBuffer()) {
180 uint8_t* end = fixedData(FixedLengthTypedArrayObject::FIXED_DATA_START);
181 MOZ_ASSERT(end[0] == ZeroLengthArrayData);
182 }
183 }
184 #endif
185
186 void FixedLengthTypedArrayObject::finalize(JS::GCContext* gcx, JSObject* obj) {
187 MOZ_ASSERT(!IsInsideNursery(obj));
188 auto* curObj = &obj->as<FixedLengthTypedArrayObject>();
189
190 // Template objects or discarded objects (which didn't have enough room
191 // for inner elements) don't have anything to free.
192 if (!curObj->elementsRaw()) {
193 return;
194 }
195
196 curObj->assertZeroLengthArrayData();
197
198 // Typed arrays with a buffer object do not need to be free'd
199 if (curObj->hasBuffer()) {
200 return;
201 }
202
203 // Free the data slot pointer if it does not point into the old JSObject.
204 if (!curObj->hasInlineElements()) {
205 size_t nbytes = RoundUp(curObj->byteLength(), sizeof(Value));
206 gcx->free_(obj, curObj->elements(), nbytes, MemoryUse::TypedArrayElements);
207 }
208 }
209
210 /* static */
211 size_t FixedLengthTypedArrayObject::objectMoved(JSObject* obj, JSObject* old) {
212 auto* newObj = &obj->as<FixedLengthTypedArrayObject>();
213 const auto* oldObj = &old->as<FixedLengthTypedArrayObject>();
214 MOZ_ASSERT(newObj->elementsRaw() == oldObj->elementsRaw());
215
216 // Typed arrays with a buffer object do not need an update.
217 if (oldObj->hasBuffer()) {
218 return 0;
219 }
220
221 if (!IsInsideNursery(old)) {
222 // Update the data slot pointer if it points to the old JSObject.
223 if (oldObj->hasInlineElements()) {
224 newObj->setInlineElements();
225 }
226
227 return 0;
228 }
229
230 void* buf = oldObj->elements();
231
232 // Discarded objects (which didn't have enough room for inner elements) don't
233 // have any data to move.
234 if (!buf) {
235 return 0;
236 }
237
238 Nursery& nursery = obj->runtimeFromMainThread()->gc.nursery();
239
240 // Determine if we can use inline data for the target array. If this is
241 // possible, the nursery will have picked an allocation size that is large
242 // enough.
243 size_t nbytes = oldObj->byteLength();
244 bool canUseDirectForward = nbytes >= sizeof(uintptr_t);
245
246 constexpr size_t headerSize = dataOffset() + sizeof(HeapSlot);
247
248 gc::AllocKind allocKind = oldObj->allocKindForTenure();
249 MOZ_ASSERT_IF(obj->isTenured(), obj->asTenured().getAllocKind() == allocKind);
250 MOZ_ASSERT_IF(nbytes == 0,
251 headerSize + sizeof(uint8_t) <= GetGCKindBytes(allocKind));
252
253 if (nursery.isInside(buf) &&
254 headerSize + nbytes <= GetGCKindBytes(allocKind)) {
255 MOZ_ASSERT(oldObj->hasInlineElements());
256 #ifdef DEBUG
257 if (nbytes == 0) {
258 uint8_t* output =
259 newObj->fixedData(FixedLengthTypedArrayObject::FIXED_DATA_START);
260 output[0] = ZeroLengthArrayData;
261 }
262 #endif
263 newObj->setInlineElements();
264 mozilla::PodCopy(newObj->elements(), oldObj->elements(), nbytes);
265
266 // Set a forwarding pointer for the element buffers in case they were
267 // preserved on the stack by Ion.
268 nursery.setForwardingPointerWhileTenuring(
269 oldObj->elements(), newObj->elements(), canUseDirectForward);
270
271 return 0;
272 }
273
274 // Non-inline allocations are rounded up.
275 nbytes = RoundUp(nbytes, sizeof(Value));
276
277 Nursery::WasBufferMoved result = nursery.maybeMoveBufferOnPromotion(
278 &buf, newObj, nbytes, nbytes, MemoryUse::TypedArrayElements,
279 ArrayBufferContentsArena);
280 if (result == Nursery::BufferMoved) {
281 newObj->setReservedSlot(DATA_SLOT, PrivateValue(buf));
282
283 // Set a forwarding pointer for the element buffers in case they were
284 // preserved on the stack by Ion.
285 nursery.setForwardingPointerWhileTenuring(
286 oldObj->elements(), newObj->elements(), canUseDirectForward);
287
288 return nbytes;
289 }
290
291 return 0;
292 }
293
294 bool FixedLengthTypedArrayObject::hasInlineElements() const {
295 return elements() ==
296 this->fixedData(FixedLengthTypedArrayObject::FIXED_DATA_START) &&
297 byteLength() <= FixedLengthTypedArrayObject::INLINE_BUFFER_LIMIT;
298 }
299
300 void FixedLengthTypedArrayObject::setInlineElements() {
301 char* dataSlot = reinterpret_cast<char*>(this) + dataOffset();
302 *reinterpret_cast<void**>(dataSlot) =
303 this->fixedData(FixedLengthTypedArrayObject::FIXED_DATA_START);
304 }
305
306 /* Helper clamped uint8_t type */
307
308 uint32_t js::ClampDoubleToUint8(const double x) {
309 // Not < so that NaN coerces to 0
310 if (!(x > 0)) {
311 return 0;
312 }
313
314 if (x >= 255) {
315 return 255;
316 }
317
318 // Convert with truncation.
319 uint8_t y = uint8_t(x);
320
321 // Now |y| is rounded toward zero. We want rounded to nearest, ties to even.
322 double r = x - double(y);
323
324 // It was a tie (since the difference is exactly 0.5). Round up if the number
325 // is odd.
326 if (r == 0.5) {
327 return y + (y & 1);
328 }
329
330 // Round up if truncation incorrectly rounded down.
331 return y + (r > 0.5);
332 }
333
334 static void ReportOutOfBounds(JSContext* cx, TypedArrayObject* typedArray) {
335 if (typedArray->hasDetachedBuffer()) {
336 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
337 JSMSG_TYPED_ARRAY_DETACHED);
338 } else {
339 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
340 JSMSG_TYPED_ARRAY_RESIZED_BOUNDS);
341 }
342 }
343
344 namespace {
345
346 template <class TypedArrayType>
347 static TypedArrayType* NewTypedArrayObject(JSContext* cx, const JSClass* clasp,
348 HandleObject proto,
349 gc::AllocKind allocKind,
350 gc::Heap heap) {
351 MOZ_ASSERT(proto);
352 allocKind = gc::GetFinalizedAllocKindForClass(allocKind, clasp);
353
354 static_assert(std::is_same_v<TypedArrayType, FixedLengthTypedArrayObject> ||
355 std::is_same_v<TypedArrayType, ResizableTypedArrayObject>);
356
357 // Fixed length typed arrays can store data inline so we only use fixed slots
358 // to cover the reserved slots, ignoring the AllocKind.
359 MOZ_ASSERT(ClassCanHaveFixedData(clasp));
360 constexpr size_t nfixed = TypedArrayType::RESERVED_SLOTS;
361 static_assert(nfixed <= NativeObject::MAX_FIXED_SLOTS);
362 static_assert(!std::is_same_v<TypedArrayType, FixedLengthTypedArrayObject> ||
363 nfixed == FixedLengthTypedArrayObject::FIXED_DATA_START);
364
365 Rooted<SharedShape*> shape(
366 cx,
367 SharedShape::getInitialShape(cx, clasp, cx->realm(), AsTaggedProto(proto),
368 nfixed, ObjectFlags()));
369 if (!shape) {
370 return nullptr;
371 }
372
373 return NativeObject::create<TypedArrayType>(cx, allocKind, heap, shape);
374 }
375
376 template <typename NativeType>
377 class FixedLengthTypedArrayObjectTemplate;
378
379 template <typename NativeType>
380 class ResizableTypedArrayObjectTemplate;
381
382 template <typename NativeType>
383 class TypedArrayObjectTemplate {
384 friend class js::TypedArrayObject;
385
386 using FixedLengthTypedArray = FixedLengthTypedArrayObjectTemplate<NativeType>;
387 using ResizableTypedArray = ResizableTypedArrayObjectTemplate<NativeType>;
388 using AutoLength = ArrayBufferViewObject::AutoLength;
389
390 static constexpr auto ByteLengthLimit = TypedArrayObject::ByteLengthLimit;
391 static constexpr auto INLINE_BUFFER_LIMIT =
392 FixedLengthTypedArrayObject::INLINE_BUFFER_LIMIT;
393
394 public:
395 static constexpr Scalar::Type ArrayTypeID() {
396 return TypeIDOfType<NativeType>::id;
397 }
398 static constexpr JSProtoKey protoKey() {
399 return TypeIDOfType<NativeType>::protoKey;
400 }
401
402 static constexpr size_t BYTES_PER_ELEMENT = sizeof(NativeType);
403
404 static JSObject* createPrototype(JSContext* cx, JSProtoKey key) {
405 Handle<GlobalObject*> global = cx->global();
406 RootedObject typedArrayProto(
407 cx, GlobalObject::getOrCreateTypedArrayPrototype(cx, global));
408 if (!typedArrayProto) {
409 return nullptr;
410 }
411
412 const JSClass* clasp = TypedArrayObject::protoClassForType(ArrayTypeID());
413 return GlobalObject::createBlankPrototypeInheriting(cx, clasp,
414 typedArrayProto);
415 }
416
417 static JSObject* createConstructor(JSContext* cx, JSProtoKey key) {
418 Handle<GlobalObject*> global = cx->global();
419 RootedFunction ctorProto(
420 cx, GlobalObject::getOrCreateTypedArrayConstructor(cx, global));
421 if (!ctorProto) {
422 return nullptr;
423 }
424
425 JSFunction* fun = NewFunctionWithProto(
426 cx, class_constructor, 3, FunctionFlags::NATIVE_CTOR, nullptr,
427 ClassName(key, cx), ctorProto, gc::AllocKind::FUNCTION, TenuredObject);
428
429 if (fun) {
430 fun->setJitInfo(&jit::JitInfo_TypedArrayConstructor);
431 }
432
433 return fun;
434 }
435
436 static bool convertValue(JSContext* cx, HandleValue v, NativeType* result);
437
438 static TypedArrayObject* makeTypedArrayWithTemplate(
439 JSContext* cx, TypedArrayObject* templateObj, HandleObject array) {
440 MOZ_ASSERT(!IsWrapper(array));
441 MOZ_ASSERT(!array->is<ArrayBufferObjectMaybeShared>());
442
443 return fromArray(cx, array);
444 }
445
446 static TypedArrayObject* makeTypedArrayWithTemplate(
447 JSContext* cx, TypedArrayObject* templateObj, HandleObject arrayBuffer,
448 HandleValue byteOffsetValue, HandleValue lengthValue) {
449 MOZ_ASSERT(!IsWrapper(arrayBuffer));
450 MOZ_ASSERT(arrayBuffer->is<ArrayBufferObjectMaybeShared>());
451
452 uint64_t byteOffset, length;
453 if (!byteOffsetAndLength(cx, byteOffsetValue, lengthValue, &byteOffset,
454 &length)) {
455 return nullptr;
456 }
457
458 return fromBufferSameCompartment(
459 cx, arrayBuffer.as<ArrayBufferObjectMaybeShared>(), byteOffset, length,
460 nullptr);
461 }
462
463 // ES2023 draft rev cf86f1cdc28e809170733d74ea64fd0f3dd79f78
464 // 23.2.5.1 TypedArray ( ...args )
465 static bool class_constructor(JSContext* cx, unsigned argc, Value* vp) {
466 AutoJSConstructorProfilerEntry pseudoFrame(cx, "[TypedArray]");
467 CallArgs args = CallArgsFromVp(argc, vp);
468
469 // Step 1.
470 if (!ThrowIfNotConstructing(cx, args, "typed array")) {
471 return false;
472 }
473
474 // Steps 2-6.
475 JSObject* obj = create(cx, args);
476 if (!obj) {
477 return false;
478 }
479 args.rval().setObject(*obj);
480 return true;
481 }
482
483 private:
484 static JSObject* create(JSContext* cx, const CallArgs& args) {
485 MOZ_ASSERT(args.isConstructing());
486
487 // Steps 5 and 6.c.
488 if (args.length() == 0 || !args[0].isObject()) {
489 // Step 6.c.ii.
490 uint64_t len;
491 if (!ToIndex(cx, args.get(0), JSMSG_BAD_ARRAY_LENGTH, &len)) {
492 return nullptr;
493 }
494
495 // Steps 5.a and 6.c.iii.
496 RootedObject proto(cx);
497 if (!GetPrototypeFromBuiltinConstructor(cx, args, protoKey(), &proto)) {
498 return nullptr;
499 }
500
501 return fromLength(cx, len, proto);
502 }
503
504 RootedObject dataObj(cx, &args[0].toObject());
505
506 // Step 6.b.i.
507 // 23.2.5.1.1 AllocateTypedArray, step 1.
508 RootedObject proto(cx);
509 if (!GetPrototypeFromBuiltinConstructor(cx, args, protoKey(), &proto)) {
510 return nullptr;
511 }
512
513 // Steps 6.b.ii and 6.b.iv.
514 if (!UncheckedUnwrap(dataObj)->is<ArrayBufferObjectMaybeShared>()) {
515 return fromArray(cx, dataObj, proto);
516 }
517
518 // Steps 6.b.iii.1-2.
519 // 23.2.5.1.3 InitializeTypedArrayFromArrayBuffer, steps 2 and 4.
520 uint64_t byteOffset, length;
521 if (!byteOffsetAndLength(cx, args.get(1), args.get(2), &byteOffset,
522 &length)) {
523 return nullptr;
524 }
525
526 // Step 6.b.iii.3.
527 if (dataObj->is<ArrayBufferObjectMaybeShared>()) {
528 auto buffer = dataObj.as<ArrayBufferObjectMaybeShared>();
529 return fromBufferSameCompartment(cx, buffer, byteOffset, length, proto);
530 }
531 return fromBufferWrapped(cx, dataObj, byteOffset, length, proto);
532 }
533
534 // ES2023 draft rev cf86f1cdc28e809170733d74ea64fd0f3dd79f78
535 // 23.2.5.1.3 InitializeTypedArrayFromArrayBuffer ( O, buffer, byteOffset,
536 // length ) Steps 2 and 4.
537 static bool byteOffsetAndLength(JSContext* cx, HandleValue byteOffsetValue,
538 HandleValue lengthValue, uint64_t* byteOffset,
539 uint64_t* length) {
540 // Step 2.
541 *byteOffset = 0;
542 if (!byteOffsetValue.isUndefined()) {
543 if (!ToIndex(cx, byteOffsetValue, byteOffset)) {
544 return false;
545 }
546
547 // Step 7.
548 if (*byteOffset % BYTES_PER_ELEMENT != 0) {
549 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
550 JSMSG_TYPED_ARRAY_CONSTRUCT_OFFSET_BOUNDS,
551 Scalar::name(ArrayTypeID()),
552 Scalar::byteSizeString(ArrayTypeID()));
553 return false;
554 }
555 }
556
557 // Step 4.
558 *length = UINT64_MAX;
559 if (!lengthValue.isUndefined()) {
560 if (!ToIndex(cx, lengthValue, length)) {
561 return false;
562 }
563 }
564
565 return true;
566 }
567
568 // ES2023 draft rev cf86f1cdc28e809170733d74ea64fd0f3dd79f78
569 // 23.2.5.1.3 InitializeTypedArrayFromArrayBuffer ( O, buffer, byteOffset,
570 // length ) Steps 5-8.
571 static bool computeAndCheckLength(
572 JSContext* cx, Handle<ArrayBufferObjectMaybeShared*> bufferMaybeUnwrapped,
573 uint64_t byteOffset, uint64_t lengthIndex, size_t* length,
574 AutoLength* autoLength) {
575 MOZ_ASSERT(byteOffset % BYTES_PER_ELEMENT == 0);
576 MOZ_ASSERT(byteOffset < uint64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT));
577 MOZ_ASSERT_IF(lengthIndex != UINT64_MAX,
578 lengthIndex < uint64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT));
579
580 // Step 5.
581 if (bufferMaybeUnwrapped->isDetached()) {
582 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
583 JSMSG_TYPED_ARRAY_DETACHED);
584 return false;
585 }
586
587 // Step 6.
588 size_t bufferByteLength = bufferMaybeUnwrapped->byteLength();
589 MOZ_ASSERT(bufferByteLength <= ByteLengthLimit);
590
591 size_t len;
592 if (lengthIndex == UINT64_MAX) {
593 // Check if |byteOffset| valid.
594 if (byteOffset > bufferByteLength) {
595 JS_ReportErrorNumberASCII(
596 cx, GetErrorMessage, nullptr,
597 JSMSG_TYPED_ARRAY_CONSTRUCT_OFFSET_LENGTH_BOUNDS,
598 Scalar::name(ArrayTypeID()));
599 return false;
600 }
601
602 // Resizable buffers without an explicit length are auto-length.
603 if (bufferMaybeUnwrapped->isResizable()) {
604 *length = 0;
605 *autoLength = AutoLength::Yes;
606 return true;
607 }
608
609 // Steps 7.a and 7.c.
610 if (bufferByteLength % BYTES_PER_ELEMENT != 0) {
611 // The given byte array doesn't map exactly to
612 // |BYTES_PER_ELEMENT * N|
613 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
614 JSMSG_TYPED_ARRAY_CONSTRUCT_OFFSET_MISALIGNED,
615 Scalar::name(ArrayTypeID()),
616 Scalar::byteSizeString(ArrayTypeID()));
617 return false;
618 }
619
620 // Step 7.b.
621 size_t newByteLength = bufferByteLength - size_t(byteOffset);
622 len = newByteLength / BYTES_PER_ELEMENT;
623 } else {
624 // Step 8.a.
625 uint64_t newByteLength = lengthIndex * BYTES_PER_ELEMENT;
626
627 // Step 8.b.
628 if (byteOffset + newByteLength > bufferByteLength) {
629 // |byteOffset + newByteLength| is too big for the arraybuffer
630 JS_ReportErrorNumberASCII(
631 cx, GetErrorMessage, nullptr,
632 JSMSG_TYPED_ARRAY_CONSTRUCT_ARRAY_LENGTH_BOUNDS,
633 Scalar::name(ArrayTypeID()));
634 return false;
635 }
636
637 len = size_t(lengthIndex);
638 }
639
640 MOZ_ASSERT(len <= ByteLengthLimit / BYTES_PER_ELEMENT);
641 *length = len;
642 *autoLength = AutoLength::No;
643 return true;
644 }
645
646 // ES2023 draft rev cf86f1cdc28e809170733d74ea64fd0f3dd79f78
647 // 23.2.5.1.3 InitializeTypedArrayFromArrayBuffer ( O, buffer, byteOffset,
648 // length ) Steps 5-13.
649 static TypedArrayObject* fromBufferSameCompartment(
650 JSContext* cx, Handle<ArrayBufferObjectMaybeShared*> buffer,
651 uint64_t byteOffset, uint64_t lengthIndex, HandleObject proto) {
652 cx->releaseCheck(buffer);
653 // Steps 5-8.
654 size_t length = 0;
655 auto autoLength = AutoLength::No;
656 if (!computeAndCheckLength(cx, buffer, byteOffset, lengthIndex, &length,
657 &autoLength)) {
658 return nullptr;
659 }
660
661 if (!buffer->isResizable()) {
662 // Steps 9-13.
663 return FixedLengthTypedArray::makeInstance(cx, buffer, byteOffset, length,
664 proto);
665 }
666
667 return ResizableTypedArray::makeInstance(cx, buffer, byteOffset, length,
668 autoLength, proto);
669 }
670
671 // Create a TypedArray object in another compartment.
672 //
673 // ES6 supports creating a TypedArray in global A (using global A's
674 // TypedArray constructor) backed by an ArrayBuffer created in global B.
675 //
676 // Our TypedArrayObject implementation doesn't support a TypedArray in
677 // compartment A backed by an ArrayBuffer in compartment B. So in this
678 // case, we create the TypedArray in B (!) and return a cross-compartment
679 // wrapper.
680 //
681 // Extra twist: the spec says the new TypedArray's [[Prototype]] must be
682 // A's TypedArray.prototype. So even though we're creating the TypedArray
683 // in B, its [[Prototype]] must be (a cross-compartment wrapper for) the
684 // TypedArray.prototype in A.
685 static JSObject* fromBufferWrapped(JSContext* cx, HandleObject bufobj,
686 uint64_t byteOffset, uint64_t lengthIndex,
687 HandleObject proto) {
688 JSObject* unwrapped = CheckedUnwrapStatic(bufobj);
689 if (!unwrapped) {
690 ReportAccessDenied(cx);
691 return nullptr;
692 }
693
694 if (!unwrapped->is<ArrayBufferObjectMaybeShared>()) {
695 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
696 JSMSG_TYPED_ARRAY_BAD_ARGS);
697 return nullptr;
698 }
699
700 Rooted<ArrayBufferObjectMaybeShared*> unwrappedBuffer(cx);
701 unwrappedBuffer = &unwrapped->as<ArrayBufferObjectMaybeShared>();
702
703 size_t length = 0;
704 auto autoLength = AutoLength::No;
705 if (!computeAndCheckLength(cx, unwrappedBuffer, byteOffset, lengthIndex,
706 &length, &autoLength)) {
707 return nullptr;
708 }
709
710 // Make sure to get the [[Prototype]] for the created typed array from
711 // this compartment.
712 RootedObject protoRoot(cx, proto);
713 if (!protoRoot) {
714 protoRoot = GlobalObject::getOrCreatePrototype(cx, protoKey());
715 if (!protoRoot) {
716 return nullptr;
717 }
718 }
719
720 RootedObject typedArray(cx);
721 {
722 JSAutoRealm ar(cx, unwrappedBuffer);
723
724 RootedObject wrappedProto(cx, protoRoot);
725 if (!cx->compartment()->wrap(cx, &wrappedProto)) {
726 return nullptr;
727 }
728
729 if (!unwrappedBuffer->isResizable()) {
730 typedArray = FixedLengthTypedArray::makeInstance(
731 cx, unwrappedBuffer, byteOffset, length, wrappedProto);
732 } else {
733 typedArray = ResizableTypedArray::makeInstance(
734 cx, unwrappedBuffer, byteOffset, length, autoLength, wrappedProto);
735 }
736 if (!typedArray) {
737 return nullptr;
738 }
739 }
740
741 if (!cx->compartment()->wrap(cx, &typedArray)) {
742 return nullptr;
743 }
744
745 return typedArray;
746 }
747
748 public:
749 static JSObject* fromBuffer(JSContext* cx, HandleObject bufobj,
750 size_t byteOffset, int64_t lengthInt) {
751 if (byteOffset % BYTES_PER_ELEMENT != 0) {
752 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
753 JSMSG_TYPED_ARRAY_CONSTRUCT_OFFSET_BOUNDS,
754 Scalar::name(ArrayTypeID()),
755 Scalar::byteSizeString(ArrayTypeID()));
756 return nullptr; // invalid byteOffset
757 }
758
759 uint64_t lengthIndex = lengthInt >= 0 ? uint64_t(lengthInt) : UINT64_MAX;
760 if (bufobj->is<ArrayBufferObjectMaybeShared>()) {
761 auto buffer = bufobj.as<ArrayBufferObjectMaybeShared>();
762 return fromBufferSameCompartment(cx, buffer, byteOffset, lengthIndex,
763 nullptr);
764 }
765 return fromBufferWrapped(cx, bufobj, byteOffset, lengthIndex, nullptr);
766 }
767
768 static bool maybeCreateArrayBuffer(JSContext* cx, uint64_t count,
769 MutableHandle<ArrayBufferObject*> buffer) {
770 if (count > ByteLengthLimit / BYTES_PER_ELEMENT) {
771 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
772 JSMSG_BAD_ARRAY_LENGTH);
773 return false;
774 }
775 size_t byteLength = count * BYTES_PER_ELEMENT;
776
777 MOZ_ASSERT(byteLength <= ByteLengthLimit);
778 static_assert(INLINE_BUFFER_LIMIT % BYTES_PER_ELEMENT == 0,
779 "ArrayBuffer inline storage shouldn't waste any space");
780
781 if (byteLength <= INLINE_BUFFER_LIMIT) {
782 // The array's data can be inline, and the buffer created lazily.
783 return true;
784 }
785
786 ArrayBufferObject* buf = ArrayBufferObject::createZeroed(cx, byteLength);
787 if (!buf) {
788 return false;
789 }
790
791 buffer.set(buf);
792 return true;
793 }
794
795 // ES2023 draft rev cf86f1cdc28e809170733d74ea64fd0f3dd79f78
796 // 23.2.5.1.1 AllocateTypedArray ( constructorName, newTarget, defaultProto [
797 // , length ] )
798 static TypedArrayObject* fromLength(JSContext* cx, uint64_t nelements,
799 HandleObject proto = nullptr,
800 gc::Heap heap = gc::Heap::Default) {
801 Rooted<ArrayBufferObject*> buffer(cx);
802 if (!maybeCreateArrayBuffer(cx, nelements, &buffer)) {
803 return nullptr;
804 }
805
806 return FixedLengthTypedArray::makeInstance(cx, buffer, 0, nelements, proto,
807 heap);
808 }
809
810 static TypedArrayObject* fromArray(JSContext* cx, HandleObject other,
811 HandleObject proto = nullptr);
812
813 static TypedArrayObject* fromTypedArray(JSContext* cx, HandleObject other,
814 bool isWrapped, HandleObject proto);
815
816 static TypedArrayObject* fromObject(JSContext* cx, HandleObject other,
817 HandleObject proto);
818
819 static const NativeType getIndex(TypedArrayObject* tarray, size_t index) {
820 MOZ_ASSERT(index < tarray->length().valueOr(0));
821 return jit::AtomicOperations::loadSafeWhenRacy(
822 tarray->dataPointerEither().cast<NativeType*>() + index);
823 }
824
825 static void setIndex(TypedArrayObject& tarray, size_t index, NativeType val) {
826 MOZ_ASSERT(index < tarray.length().valueOr(0));
827 jit::AtomicOperations::storeSafeWhenRacy(
828 tarray.dataPointerEither().cast<NativeType*>() + index, val);
829 }
830
831 static bool getElement(JSContext* cx, TypedArrayObject* tarray, size_t index,
832 MutableHandleValue val);
833 static bool getElementPure(TypedArrayObject* tarray, size_t index, Value* vp);
834
835 static bool setElement(JSContext* cx, Handle<TypedArrayObject*> obj,
836 uint64_t index, HandleValue v, ObjectOpResult& result);
837 };
838
839 template <typename NativeType>
840 class FixedLengthTypedArrayObjectTemplate
841 : public FixedLengthTypedArrayObject,
842 public TypedArrayObjectTemplate<NativeType> {
843 friend class js::TypedArrayObject;
844
845 using TypedArrayTemplate = TypedArrayObjectTemplate<NativeType>;
846
847 public:
848 using TypedArrayTemplate::ArrayTypeID;
849 using TypedArrayTemplate::BYTES_PER_ELEMENT;
850 using TypedArrayTemplate::protoKey;
851
852 static inline const JSClass* instanceClass() {
853 static_assert(ArrayTypeID() <
854 std::size(TypedArrayObject::fixedLengthClasses));
855 return &TypedArrayObject::fixedLengthClasses[ArrayTypeID()];
856 }
857
858 static FixedLengthTypedArrayObject* newBuiltinClassInstance(
859 JSContext* cx, gc::AllocKind allocKind, gc::Heap heap) {
860 RootedObject proto(cx, GlobalObject::getOrCreatePrototype(cx, protoKey()));
861 if (!proto) {
862 return nullptr;
863 }
864 return NewTypedArrayObject<FixedLengthTypedArrayObject>(
865 cx, instanceClass(), proto, allocKind, heap);
866 }
867
868 static FixedLengthTypedArrayObject* makeProtoInstance(
869 JSContext* cx, HandleObject proto, gc::AllocKind allocKind) {
870 MOZ_ASSERT(proto);
871 return NewTypedArrayObject<FixedLengthTypedArrayObject>(
872 cx, instanceClass(), proto, allocKind, gc::Heap::Default);
873 }
874
875 static FixedLengthTypedArrayObject* makeInstance(
876 JSContext* cx, Handle<ArrayBufferObjectMaybeShared*> buffer,
877 size_t byteOffset, size_t len, HandleObject proto,
878 gc::Heap heap = gc::Heap::Default) {
879 MOZ_ASSERT(len <= ByteLengthLimit / BYTES_PER_ELEMENT);
880
881 gc::AllocKind allocKind =
882 buffer ? gc::GetGCObjectKind(instanceClass())
883 : AllocKindForLazyBuffer(len * BYTES_PER_ELEMENT);
884
885 AutoSetNewObjectMetadata metadata(cx);
886 FixedLengthTypedArrayObject* obj;
887 if (proto) {
888 obj = makeProtoInstance(cx, proto, allocKind);
889 } else {
890 obj = newBuiltinClassInstance(cx, allocKind, heap);
891 }
892 if (!obj || !obj->init(cx, buffer, byteOffset, len, BYTES_PER_ELEMENT)) {
893 return nullptr;
894 }
895
896 return obj;
897 }
898
899 static FixedLengthTypedArrayObject* makeTemplateObject(JSContext* cx,
900 int32_t len) {
901 MOZ_ASSERT(len >= 0);
902 size_t nbytes;
903 MOZ_ALWAYS_TRUE(CalculateAllocSize<NativeType>(len, &nbytes));
904 bool fitsInline = nbytes <= INLINE_BUFFER_LIMIT;
905 gc::AllocKind allocKind = !fitsInline ? gc::GetGCObjectKind(instanceClass())
906 : AllocKindForLazyBuffer(nbytes);
907 MOZ_ASSERT(allocKind >= gc::GetGCObjectKind(instanceClass()));
908
909 AutoSetNewObjectMetadata metadata(cx);
910
911 auto* tarray = newBuiltinClassInstance(cx, allocKind, gc::Heap::Tenured);
912 if (!tarray) {
913 return nullptr;
914 }
915
916 initTypedArraySlots(tarray, len);
917
918 // Template objects don't need memory for their elements, since there
919 // won't be any elements to store.
920 MOZ_ASSERT(tarray->getReservedSlot(DATA_SLOT).isUndefined());
921
922 return tarray;
923 }
924
925 static void initTypedArraySlots(FixedLengthTypedArrayObject* tarray,
926 int32_t len) {
927 MOZ_ASSERT(len >= 0);
928 tarray->initFixedSlot(TypedArrayObject::BUFFER_SLOT, JS::FalseValue());
929 tarray->initFixedSlot(TypedArrayObject::LENGTH_SLOT, PrivateValue(len));
930 tarray->initFixedSlot(TypedArrayObject::BYTEOFFSET_SLOT,
931 PrivateValue(size_t(0)));
932
933 #ifdef DEBUG
934 if (len == 0) {
935 uint8_t* output =
936 tarray->fixedData(FixedLengthTypedArrayObject::FIXED_DATA_START);
937 output[0] = TypedArrayObject::ZeroLengthArrayData;
938 }
939 #endif
940 }
941
942 static void initTypedArrayData(FixedLengthTypedArrayObject* tarray, void* buf,
943 size_t nbytes, gc::AllocKind allocKind) {
944 if (buf) {
945 InitReservedSlot(tarray, TypedArrayObject::DATA_SLOT, buf, nbytes,
946 MemoryUse::TypedArrayElements);
947 } else {
948 #ifdef DEBUG
949 constexpr size_t dataOffset = ArrayBufferViewObject::dataOffset();
950 constexpr size_t offset = dataOffset + sizeof(HeapSlot);
951 MOZ_ASSERT(offset + nbytes <= GetGCKindBytes(allocKind));
952 #endif
953
954 void* data = tarray->fixedData(FIXED_DATA_START);
955 tarray->initReservedSlot(DATA_SLOT, PrivateValue(data));
956 memset(data, 0, nbytes);
957 }
958 }
959
960 static FixedLengthTypedArrayObject* makeTypedArrayWithTemplate(
961 JSContext* cx, TypedArrayObject* templateObj, int32_t len) {
962 if (len < 0 || size_t(len) > ByteLengthLimit / BYTES_PER_ELEMENT) {
963 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
964 JSMSG_BAD_ARRAY_LENGTH);
965 return nullptr;
966 }
967
968 size_t nbytes = size_t(len) * BYTES_PER_ELEMENT;
969 MOZ_ASSERT(nbytes <= ByteLengthLimit);
970
971 bool fitsInline = nbytes <= INLINE_BUFFER_LIMIT;
972
973 AutoSetNewObjectMetadata metadata(cx);
974
975 gc::AllocKind allocKind = !fitsInline ? gc::GetGCObjectKind(instanceClass())
976 : AllocKindForLazyBuffer(nbytes);
977 MOZ_ASSERT(templateObj->getClass() == instanceClass());
978
979 RootedObject proto(cx, templateObj->staticPrototype());
980 auto* obj = makeProtoInstance(cx, proto, allocKind);
981 if (!obj) {
982 return nullptr;
983 }
984
985 initTypedArraySlots(obj, len);
986
987 void* buf = nullptr;
988 if (!fitsInline) {
989 MOZ_ASSERT(len > 0);
990
991 nbytes = RoundUp(nbytes, sizeof(Value));
992 buf = cx->nursery().allocateZeroedBuffer(obj, nbytes,
993 js::ArrayBufferContentsArena);
994 if (!buf) {
995 ReportOutOfMemory(cx);
996 return nullptr;
997 }
998 }
999
1000 initTypedArrayData(obj, buf, nbytes, allocKind);
1001
1002 return obj;
1003 }
1004 };
1005
1006 template <typename NativeType>
1007 class ResizableTypedArrayObjectTemplate
1008 : public ResizableTypedArrayObject,
1009 public TypedArrayObjectTemplate<NativeType> {
1010 friend class js::TypedArrayObject;
1011
1012 using TypedArrayTemplate = TypedArrayObjectTemplate<NativeType>;
1013
1014 public:
1015 using TypedArrayTemplate::ArrayTypeID;
1016 using TypedArrayTemplate::BYTES_PER_ELEMENT;
1017 using TypedArrayTemplate::protoKey;
1018
1019 static inline const JSClass* instanceClass() {
1020 static_assert(ArrayTypeID() <
1021 std::size(TypedArrayObject::resizableClasses));
1022 return &TypedArrayObject::resizableClasses[ArrayTypeID()];
1023 }
1024
1025 static ResizableTypedArrayObject* newBuiltinClassInstance(
1026 JSContext* cx, gc::AllocKind allocKind, gc::Heap heap) {
1027 RootedObject proto(cx, GlobalObject::getOrCreatePrototype(cx, protoKey()));
1028 if (!proto) {
1029 return nullptr;
1030 }
1031 return NewTypedArrayObject<ResizableTypedArrayObject>(
1032 cx, instanceClass(), proto, allocKind, heap);
1033 }
1034
1035 static ResizableTypedArrayObject* makeProtoInstance(JSContext* cx,
1036 HandleObject proto,
1037 gc::AllocKind allocKind) {
1038 MOZ_ASSERT(proto);
1039 return NewTypedArrayObject<ResizableTypedArrayObject>(
1040 cx, instanceClass(), proto, allocKind, gc::Heap::Default);
1041 }
1042
1043 static ResizableTypedArrayObject* makeInstance(
1044 JSContext* cx, Handle<ArrayBufferObjectMaybeShared*> buffer,
1045 size_t byteOffset, size_t len, AutoLength autoLength,
1046 HandleObject proto) {
1047 MOZ_ASSERT(buffer);
1048 MOZ_ASSERT(buffer->isResizable());
1049 MOZ_ASSERT(!buffer->isDetached());
1050 MOZ_ASSERT(autoLength == AutoLength::No || len == 0,
1051 "length is zero for 'auto' length views");
1052 MOZ_ASSERT(len <= ByteLengthLimit / BYTES_PER_ELEMENT);
1053
1054 gc::AllocKind allocKind = gc::GetGCObjectKind(instanceClass());
1055
1056 AutoSetNewObjectMetadata metadata(cx);
1057 ResizableTypedArrayObject* obj;
1058 if (proto) {
1059 obj = makeProtoInstance(cx, proto, allocKind);
1060 } else {
1061 obj = newBuiltinClassInstance(cx, allocKind, gc::Heap::Default);
1062 }
1063 if (!obj || !obj->initResizable(cx, buffer, byteOffset, len,
1064 BYTES_PER_ELEMENT, autoLength)) {
1065 return nullptr;
1066 }
1067
1068 return obj;
1069 }
1070
1071 static ResizableTypedArrayObject* makeTemplateObject(JSContext* cx) {
1072 gc::AllocKind allocKind = gc::GetGCObjectKind(instanceClass());
1073
1074 AutoSetNewObjectMetadata metadata(cx);
1075
1076 auto* tarray = newBuiltinClassInstance(cx, allocKind, gc::Heap::Tenured);
1077 if (!tarray) {
1078 return nullptr;
1079 }
1080
1081 tarray->initFixedSlot(TypedArrayObject::BUFFER_SLOT, JS::FalseValue());
1082 tarray->initFixedSlot(TypedArrayObject::LENGTH_SLOT,
1083 PrivateValue(size_t(0)));
1084 tarray->initFixedSlot(TypedArrayObject::BYTEOFFSET_SLOT,
1085 PrivateValue(size_t(0)));
1086 tarray->initFixedSlot(AUTO_LENGTH_SLOT, BooleanValue(false));
1087 tarray->initFixedSlot(ResizableTypedArrayObject::INITIAL_LENGTH_SLOT,
1088 PrivateValue(size_t(0)));
1089 tarray->initFixedSlot(ResizableTypedArrayObject::INITIAL_BYTE_OFFSET_SLOT,
1090 PrivateValue(size_t(0)));
1091
1092 // Template objects don't need memory for their elements, since there
1093 // won't be any elements to store.
1094 MOZ_ASSERT(tarray->getReservedSlot(DATA_SLOT).isUndefined());
1095
1096 return tarray;
1097 }
1098 };
1099
1100 template <typename NativeType>
1101 bool TypedArrayObjectTemplate<NativeType>::convertValue(JSContext* cx,
1102 HandleValue v,
1103 NativeType* result) {
1104 double d;
1105 if (!ToNumber(cx, v, &d)) {
1106 return false;
1107 }
1108
1109 if (js::SupportDifferentialTesting()) {
1110 // See the comment in ElementSpecific::doubleToNative.
1111 d = JS::CanonicalizeNaN(d);
1112 }
1113
1114 // Assign based on characteristics of the destination type
1115 *result = ConvertNumber<NativeType>(d);
1116 return true;
1117 }
1118
1119 template <>
1120 bool TypedArrayObjectTemplate<int64_t>::convertValue(JSContext* cx,
1121 HandleValue v,
1122 int64_t* result) {
1123 JS_TRY_VAR_OR_RETURN_FALSE(cx, *result, ToBigInt64(cx, v));
1124 return true;
1125 }
1126
1127 template <>
1128 bool TypedArrayObjectTemplate<uint64_t>::convertValue(JSContext* cx,
1129 HandleValue v,
1130 uint64_t* result) {
1131 JS_TRY_VAR_OR_RETURN_FALSE(cx, *result, ToBigUint64(cx, v));
1132 return true;
1133 }
1134
1135 /**
1136 * 10.4.5.16 TypedArraySetElement ( O, index, value )
1137 *
1138 * ES2025 draft rev ac21460fedf4b926520b06c9820bdbebad596a8b
1139 */
1140 template <typename NativeType>
1141 /* static */ bool TypedArrayObjectTemplate<NativeType>::setElement(
1142 JSContext* cx, Handle<TypedArrayObject*> obj, uint64_t index, HandleValue v,
1143 ObjectOpResult& result) {
1144 // Steps 1-2.
1145 NativeType nativeValue;
1146 if (!convertValue(cx, v, &nativeValue)) {
1147 return false;
1148 }
1149
1150 // Step 3.
1151 if (index < obj->length().valueOr(0)) {
1152 MOZ_ASSERT(!obj->hasDetachedBuffer(),
1153 "detaching an array buffer sets the length to zero");
1154 TypedArrayObjectTemplate<NativeType>::setIndex(*obj, index, nativeValue);
1155 }
1156
1157 // Step 4.
1158 return result.succeed();
1159 }
1160
1161 } /* anonymous namespace */
1162
1163 TypedArrayObject* js::NewTypedArrayWithTemplateAndLength(
1164 JSContext* cx, HandleObject templateObj, int32_t len) {
1165 MOZ_ASSERT(templateObj->is<TypedArrayObject>());
1166 TypedArrayObject* tobj = &templateObj->as<TypedArrayObject>();
1167
1168 switch (tobj->type()) {
1169 #define CREATE_TYPED_ARRAY(_, T, N) \
1170 case Scalar::N: \
1171 return FixedLengthTypedArrayObjectTemplate<T>::makeTypedArrayWithTemplate( \
1172 cx, tobj, len);
1173 JS_FOR_EACH_TYPED_ARRAY(CREATE_TYPED_ARRAY)
1174 #undef CREATE_TYPED_ARRAY
1175 default:
1176 MOZ_CRASH("Unsupported TypedArray type");
1177 }
1178 }
1179
1180 TypedArrayObject* js::NewTypedArrayWithTemplateAndArray(
1181 JSContext* cx, HandleObject templateObj, HandleObject array) {
1182 MOZ_ASSERT(templateObj->is<TypedArrayObject>());
1183 TypedArrayObject* tobj = &templateObj->as<TypedArrayObject>();
1184
1185 switch (tobj->type()) {
1186 #define CREATE_TYPED_ARRAY(_, T, N) \
1187 case Scalar::N: \
1188 return TypedArrayObjectTemplate<T>::makeTypedArrayWithTemplate(cx, tobj, \
1189 array);
1190 JS_FOR_EACH_TYPED_ARRAY(CREATE_TYPED_ARRAY)
1191 #undef CREATE_TYPED_ARRAY
1192 default:
1193 MOZ_CRASH("Unsupported TypedArray type");
1194 }
1195 }
1196
1197 TypedArrayObject* js::NewTypedArrayWithTemplateAndBuffer(
1198 JSContext* cx, HandleObject templateObj, HandleObject arrayBuffer,
1199 HandleValue byteOffset, HandleValue length) {
1200 MOZ_ASSERT(templateObj->is<TypedArrayObject>());
1201 TypedArrayObject* tobj = &templateObj->as<TypedArrayObject>();
1202
1203 switch (tobj->type()) {
1204 #define CREATE_TYPED_ARRAY(_, T, N) \
1205 case Scalar::N: \
1206 return TypedArrayObjectTemplate<T>::makeTypedArrayWithTemplate( \
1207 cx, tobj, arrayBuffer, byteOffset, length);
1208 JS_FOR_EACH_TYPED_ARRAY(CREATE_TYPED_ARRAY)
1209 #undef CREATE_TYPED_ARRAY
1210 default:
1211 MOZ_CRASH("Unsupported TypedArray type");
1212 }
1213 }
1214
1215 TypedArrayObject* js::NewUint8ArrayWithLength(JSContext* cx, int32_t len,
1216 gc::Heap heap) {
1217 return TypedArrayObjectTemplate<uint8_t>::fromLength(cx, len, nullptr, heap);
1218 }
1219
1220 template <typename T>
1221 /* static */ TypedArrayObject* TypedArrayObjectTemplate<T>::fromArray(
1222 JSContext* cx, HandleObject other, HandleObject proto /* = nullptr */) {
1223 // Allow nullptr proto for FriendAPI methods, which don't care about
1224 // subclassing.
1225 if (other->is<TypedArrayObject>()) {
1226 return fromTypedArray(cx, other, /* wrapped= */ false, proto);
1227 }
1228
1229 if (other->is<WrapperObject>() &&
1230 UncheckedUnwrap(other)->is<TypedArrayObject>()) {
1231 return fromTypedArray(cx, other, /* wrapped= */ true, proto);
1232 }
1233
1234 return fromObject(cx, other, proto);
1235 }
1236
1237 // ES2023 draft rev cf86f1cdc28e809170733d74ea64fd0f3dd79f78
1238 // 23.2.5.1 TypedArray ( ...args )
1239 // 23.2.5.1.2 InitializeTypedArrayFromTypedArray ( O, srcArray )
1240 template <typename T>
1241 /* static */ TypedArrayObject* TypedArrayObjectTemplate<T>::fromTypedArray(
1242 JSContext* cx, HandleObject other, bool isWrapped, HandleObject proto) {
1243 MOZ_ASSERT_IF(!isWrapped, other->is<TypedArrayObject>());
1244 MOZ_ASSERT_IF(isWrapped, other->is<WrapperObject>() &&
1245 UncheckedUnwrap(other)->is<TypedArrayObject>());
1246
1247 Rooted<TypedArrayObject*> srcArray(cx);
1248 if (!isWrapped) {
1249 srcArray = &other->as<TypedArrayObject>();
1250 } else {
1251 srcArray = other->maybeUnwrapAs<TypedArrayObject>();
1252 if (!srcArray) {
1253 ReportAccessDenied(cx);
1254 return nullptr;
1255 }
1256 }
1257
1258 // InitializeTypedArrayFromTypedArray, step 1. (Skipped)
1259
1260 // InitializeTypedArrayFromTypedArray, step 2.
1261 auto srcLength = srcArray->length();
1262 if (!srcLength) {
1263 ReportOutOfBounds(cx, srcArray);
1264 return nullptr;
1265 }
1266
1267 // InitializeTypedArrayFromTypedArray, steps 3-7. (Skipped)
1268
1269 // InitializeTypedArrayFromTypedArray, step 8.
1270 size_t elementLength = *srcLength;
1271
1272 // InitializeTypedArrayFromTypedArray, step 9. (Skipped)
1273
1274 // InitializeTypedArrayFromTypedArray, step 10.a. (Partial)
1275 // InitializeTypedArrayFromTypedArray, step 11.a.
1276 Rooted<ArrayBufferObject*> buffer(cx);
1277 if (!maybeCreateArrayBuffer(cx, elementLength, &buffer)) {
1278 return nullptr;
1279 }
1280
1281 // InitializeTypedArrayFromTypedArray, step 11.b.
1282 if (Scalar::isBigIntType(ArrayTypeID()) !=
1283 Scalar::isBigIntType(srcArray->type())) {
1284 JS_ReportErrorNumberASCII(
1285 cx, GetErrorMessage, nullptr, JSMSG_TYPED_ARRAY_NOT_COMPATIBLE,
1286 srcArray->getClass()->name,
1287 TypedArrayObject::fixedLengthClasses[ArrayTypeID()].name);
1288 return nullptr;
1289 }
1290
1291 // Step 6.b.i.
1292 // InitializeTypedArrayFromTypedArray, steps 12-15.
1293 Rooted<TypedArrayObject*> obj(cx, FixedLengthTypedArray::makeInstance(
1294 cx, buffer, 0, elementLength, proto));
1295 if (!obj) {
1296 return nullptr;
1297 }
1298
1299 MOZ_RELEASE_ASSERT(!srcArray->hasDetachedBuffer());
1300
1301 // InitializeTypedArrayFromTypedArray, steps 10.a. (Remaining parts)
1302 // InitializeTypedArrayFromTypedArray, steps 11.c-f.
1303 MOZ_ASSERT(!obj->isSharedMemory());
1304 if (srcArray->isSharedMemory()) {
1305 if (!ElementSpecific<T, SharedOps>::setFromTypedArray(
1306 obj, elementLength, srcArray, elementLength, 0)) {
1307 MOZ_ASSERT_UNREACHABLE(
1308 "setFromTypedArray can only fail for overlapping buffers");
1309 return nullptr;
1310 }
1311 } else {
1312 if (!ElementSpecific<T, UnsharedOps>::setFromTypedArray(
1313 obj, elementLength, srcArray, elementLength, 0)) {
1314 MOZ_ASSERT_UNREACHABLE(
1315 "setFromTypedArray can only fail for overlapping buffers");
1316 return nullptr;
1317 }
1318 }
1319
1320 // Step 6.b.v.
1321 return obj;
1322 }
1323
1324 // ES2023 draft rev cf86f1cdc28e809170733d74ea64fd0f3dd79f78
1325 // 23.2.5.1 TypedArray ( ...args )
1326 // 23.2.5.1.4 InitializeTypedArrayFromList ( O, values )
1327 // 23.2.5.1.5 InitializeTypedArrayFromArrayLike ( O, arrayLike )
1328 template <typename T>
1329 /* static */ TypedArrayObject* TypedArrayObjectTemplate<T>::fromObject(
1330 JSContext* cx, HandleObject other, HandleObject proto) {
1331 // Steps 1-4 and 6.a (Already performed in caller).
1332
1333 // Steps 6.b.i (Allocation deferred until later).
1334
1335 // Steps 6.b.ii-iii. (Not applicable)
1336
1337 // Step 6.b.iv.
1338
1339 // Fast path when iterable is a packed array using the default iterator.
1340 if (IsArrayWithDefaultIterator<MustBePacked::Yes>(other, cx)) {
1341 // Steps 6.b.iv.2-3. (We don't need to call IterableToList for the fast
1342 // path).
1343 Handle<ArrayObject*> array = other.as<ArrayObject>();
1344
1345 // InitializeTypedArrayFromList, step 1.
1346 size_t len = array->getDenseInitializedLength();
1347
1348 // InitializeTypedArrayFromList, step 2.
1349 Rooted<ArrayBufferObject*> buffer(cx);
1350 if (!maybeCreateArrayBuffer(cx, len, &buffer)) {
1351 return nullptr;
1352 }
1353
1354 // Steps 6.b.i.
1355 Rooted<FixedLengthTypedArrayObject*> obj(
1356 cx, FixedLengthTypedArray::makeInstance(cx, buffer, 0, len, proto));
1357 if (!obj) {
1358 return nullptr;
1359 }
1360
1361 // InitializeTypedArrayFromList, steps 3-4.
1362 MOZ_ASSERT(!obj->isSharedMemory());
1363 if (!ElementSpecific<T, UnsharedOps>::initFromIterablePackedArray(cx, obj,
1364 array)) {
1365 return nullptr;
1366 }
1367
1368 // InitializeTypedArrayFromList, step 5. (The assertion isn't applicable for
1369 // the fast path).
1370
1371 // Step 6.b.v.
1372 return obj;
1373 }
1374
1375 // Step 6.b.iv.1 (Assertion; implicit in our implementation).
1376
1377 // Step 6.b.iv.2.
1378 RootedValue callee(cx);
1379 RootedId iteratorId(cx, PropertyKey::Symbol(cx->wellKnownSymbols().iterator));
1380 if (!GetProperty(cx, other, other, iteratorId, &callee)) {
1381 return nullptr;
1382 }
1383
1384 // Steps 6.b.iv.3-4.
1385 RootedObject arrayLike(cx);
1386 if (!callee.isNullOrUndefined()) {
1387 // Throw if other[Symbol.iterator] isn't callable.
1388 if (!callee.isObject() || !callee.toObject().isCallable()) {
1389 RootedValue otherVal(cx, ObjectValue(*other));
1390 UniqueChars bytes =
1391 DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, otherVal, nullptr);
1392 if (!bytes) {
1393 return nullptr;
1394 }
1395 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_NOT_ITERABLE,
1396 bytes.get());
1397 return nullptr;
1398 }
1399
1400 FixedInvokeArgs<2> args2(cx);
1401 args2[0].setObject(*other);
1402 args2[1].set(callee);
1403
1404 // Step 6.b.iv.3.a.
1405 RootedValue rval(cx);
1406 if (!CallSelfHostedFunction(cx, cx->names().IterableToList,
1407 UndefinedHandleValue, args2, &rval)) {
1408 return nullptr;
1409 }
1410
1411 // Step 6.b.iv.3.b (Implemented below).
1412 arrayLike = &rval.toObject();
1413 } else {
1414 // Step 4.a is an assertion: object is not an Iterator. Testing this is
1415 // literally the very last thing we did, so we don't assert here.
1416
1417 // Step 4.b (Implemented below).
1418 arrayLike = other;
1419 }
1420
1421 // We implement InitializeTypedArrayFromList in terms of
1422 // InitializeTypedArrayFromArrayLike.
1423
1424 // InitializeTypedArrayFromArrayLike, step 1.
1425 uint64_t len;
1426 if (!GetLengthProperty(cx, arrayLike, &len)) {
1427 return nullptr;
1428 }
1429
1430 // InitializeTypedArrayFromArrayLike, step 2.
1431 Rooted<ArrayBufferObject*> buffer(cx);
1432 if (!maybeCreateArrayBuffer(cx, len, &buffer)) {
1433 return nullptr;
1434 }
1435
1436 MOZ_ASSERT(len <= ByteLengthLimit / BYTES_PER_ELEMENT);
1437
1438 // Steps 6.b.i.
1439 Rooted<TypedArrayObject*> obj(
1440 cx, FixedLengthTypedArray::makeInstance(cx, buffer, 0, len, proto));
1441 if (!obj) {
1442 return nullptr;
1443 }
1444
1445 // InitializeTypedArrayFromArrayLike, steps 3-4.
1446 MOZ_ASSERT(!obj->isSharedMemory());
1447 if (!ElementSpecific<T, UnsharedOps>::setFromNonTypedArray(cx, obj, arrayLike,
1448 len)) {
1449 return nullptr;
1450 }
1451
1452 // Step 6.b.v.
1453 return obj;
1454 }
1455
1456 static bool TypedArrayConstructor(JSContext* cx, unsigned argc, Value* vp) {
1457 CallArgs args = CallArgsFromVp(argc, vp);
1458 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1459 JSMSG_TYPED_ARRAY_CALL_OR_CONSTRUCT,
1460 args.isConstructing() ? "construct" : "call");
1461 return false;
1462 }
1463
1464 template <typename T>
1465 static bool GetTemplateObjectForNative(JSContext* cx,
1466 const JS::HandleValueArray args,
1467 MutableHandleObject res) {
1468 if (args.length() == 0) {
1469 return true;
1470 }
1471
1472 HandleValue arg = args[0];
1473 if (arg.isInt32()) {
1474 uint32_t len = 0;
1475 if (arg.toInt32() >= 0) {
1476 len = arg.toInt32();
1477 }
1478
1479 size_t nbytes;
1480 if (!js::CalculateAllocSize<T>(len, &nbytes) ||
1481 nbytes > TypedArrayObject::ByteLengthLimit) {
1482 return true;
1483 }
1484
1485 res.set(
1486 FixedLengthTypedArrayObjectTemplate<T>::makeTemplateObject(cx, len));
1487 return !!res;
1488 }
1489
1490 if (!arg.isObject()) {
1491 return true;
1492 }
1493 auto* obj = &arg.toObject();
1494
1495 // We don't support wrappers, because of the complicated interaction between
1496 // wrapped ArrayBuffers and TypedArrays, see |fromBufferWrapped()|.
1497 if (IsWrapper(obj)) {
1498 return true;
1499 }
1500
1501 // We don't use the template's length in the object case, so we can create
1502 // the template typed array with an initial length of zero.
1503 uint32_t len = 0;
1504
1505 if (!obj->is<ArrayBufferObjectMaybeShared>() ||
1506 !obj->as<ArrayBufferObjectMaybeShared>().isResizable()) {
1507 res.set(
1508 FixedLengthTypedArrayObjectTemplate<T>::makeTemplateObject(cx, len));
1509 } else {
1510 res.set(ResizableTypedArrayObjectTemplate<T>::makeTemplateObject(cx));
1511 }
1512 return !!res;
1513 }
1514
1515 /* static */ bool TypedArrayObject::GetTemplateObjectForNative(
1516 JSContext* cx, Native native, const JS::HandleValueArray args,
1517 MutableHandleObject res) {
1518 MOZ_ASSERT(!res);
1519 #define CHECK_TYPED_ARRAY_CONSTRUCTOR(_, T, N) \
1520 if (native == &TypedArrayObjectTemplate<T>::class_constructor) { \
1521 return ::GetTemplateObjectForNative<T>(cx, args, res); \
1522 }
1523 JS_FOR_EACH_TYPED_ARRAY(CHECK_TYPED_ARRAY_CONSTRUCTOR)
1524 #undef CHECK_TYPED_ARRAY_CONSTRUCTOR
1525 return true;
1526 }
1527
1528 static bool LengthGetterImpl(JSContext* cx, const CallArgs& args) {
1529 auto* tarr = &args.thisv().toObject().as<TypedArrayObject>();
1530 args.rval().setNumber(tarr->length().valueOr(0));
1531 return true;
1532 }
1533
1534 static bool TypedArray_lengthGetter(JSContext* cx, unsigned argc, Value* vp) {
1535 CallArgs args = CallArgsFromVp(argc, vp);
1536 return CallNonGenericMethod<IsTypedArrayObject, LengthGetterImpl>(cx, args);
1537 }
1538
1539 static bool ByteOffsetGetterImpl(JSContext* cx, const CallArgs& args) {
1540 auto* tarr = &args.thisv().toObject().as<TypedArrayObject>();
1541 args.rval().setNumber(tarr->byteOffset().valueOr(0));
1542 return true;
1543 }
1544
1545 static bool TypedArray_byteOffsetGetter(JSContext* cx, unsigned argc,
1546 Value* vp) {
1547 CallArgs args = CallArgsFromVp(argc, vp);
1548 return CallNonGenericMethod<IsTypedArrayObject, ByteOffsetGetterImpl>(cx,
1549 args);
1550 }
1551
1552 static bool ByteLengthGetterImpl(JSContext* cx, const CallArgs& args) {
1553 auto* tarr = &args.thisv().toObject().as<TypedArrayObject>();
1554 args.rval().setNumber(tarr->byteLength().valueOr(0));
1555 return true;
1556 }
1557
1558 static bool TypedArray_byteLengthGetter(JSContext* cx, unsigned argc,
1559 Value* vp) {
1560 CallArgs args = CallArgsFromVp(argc, vp);
1561 return CallNonGenericMethod<IsTypedArrayObject, ByteLengthGetterImpl>(cx,
1562 args);
1563 }
1564
1565 static bool BufferGetterImpl(JSContext* cx, const CallArgs& args) {
1566 MOZ_ASSERT(IsTypedArrayObject(args.thisv()));
1567 Rooted<TypedArrayObject*> tarray(
1568 cx, &args.thisv().toObject().as<TypedArrayObject>());
1569 if (!TypedArrayObject::ensureHasBuffer(cx, tarray)) {
1570 return false;
1571 }
1572 args.rval().set(tarray->bufferValue());
1573 return true;
1574 }
1575
1576 static bool TypedArray_bufferGetter(JSContext* cx, unsigned argc, Value* vp) {
1577 CallArgs args = CallArgsFromVp(argc, vp);
1578 return CallNonGenericMethod<IsTypedArrayObject, BufferGetterImpl>(cx, args);
1579 }
1580
1581 // ES2019 draft rev fc9ecdcd74294d0ca3146d4b274e2a8e79565dc3
1582 // 22.2.3.32 get %TypedArray%.prototype [ @@toStringTag ]
1583 static bool TypedArray_toStringTagGetter(JSContext* cx, unsigned argc,
1584 Value* vp) {
1585 CallArgs args = CallArgsFromVp(argc, vp);
1586
1587 // Steps 1-2.
1588 if (!args.thisv().isObject()) {
1589 args.rval().setUndefined();
1590 return true;
1591 }
1592
1593 JSObject* obj = CheckedUnwrapStatic(&args.thisv().toObject());
1594 if (!obj) {
1595 ReportAccessDenied(cx);
1596 return false;
1597 }
1598
1599 // Step 3.
1600 if (!obj->is<TypedArrayObject>()) {
1601 args.rval().setUndefined();
1602 return true;
1603 }
1604
1605 // Steps 4-6.
1606 JSProtoKey protoKey = StandardProtoKeyOrNull(obj);
1607 MOZ_ASSERT(protoKey);
1608
1609 args.rval().setString(ClassName(protoKey, cx));
1610 return true;
1611 }
1612
1613 /* static */ const JSPropertySpec TypedArrayObject::protoAccessors[] = {
1614 JS_PSG("length", TypedArray_lengthGetter, 0),
1615 JS_PSG("buffer", TypedArray_bufferGetter, 0),
1616 JS_PSG("byteLength", TypedArray_byteLengthGetter, 0),
1617 JS_PSG("byteOffset", TypedArray_byteOffsetGetter, 0),
1618 JS_SYM_GET(toStringTag, TypedArray_toStringTagGetter, 0),
1619 JS_PS_END,
1620 };
1621
1622 template <typename T>
1623 static inline bool SetFromTypedArray(Handle<TypedArrayObject*> target,
1624 size_t targetLength,
1625 Handle<TypedArrayObject*> source,
1626 size_t sourceLength, size_t offset) {
1627 // WARNING: |source| may be an unwrapped typed array from a different
1628 // compartment. Proceed with caution!
1629
1630 if (target->isSharedMemory() || source->isSharedMemory()) {
1631 return ElementSpecific<T, SharedOps>::setFromTypedArray(
1632 target, targetLength, source, sourceLength, offset);
1633 }
1634 return ElementSpecific<T, UnsharedOps>::setFromTypedArray(
1635 target, targetLength, source, sourceLength, offset);
1636 }
1637
1638 template <typename T>
1639 static inline bool SetFromNonTypedArray(JSContext* cx,
1640 Handle<TypedArrayObject*> target,
1641 HandleObject source, size_t len,
1642 size_t offset) {
1643 MOZ_ASSERT(!source->is<TypedArrayObject>(), "use SetFromTypedArray");
1644
1645 if (target->isSharedMemory()) {
1646 return ElementSpecific<T, SharedOps>::setFromNonTypedArray(
1647 cx, target, source, len, offset);
1648 }
1649 return ElementSpecific<T, UnsharedOps>::setFromNonTypedArray(
1650 cx, target, source, len, offset);
1651 }
1652
1653 // ES2023 draft rev 22cc56ab08fcab92a865978c0aa5c6f1d8ce250f
1654 // 23.2.3.24.1 SetTypedArrayFromTypedArray ( target, targetOffset, source )
1655 static bool SetTypedArrayFromTypedArray(JSContext* cx,
1656 Handle<TypedArrayObject*> target,
1657 double targetOffset,
1658 size_t targetLength,
1659 Handle<TypedArrayObject*> source) {
1660 // WARNING: |source| may be an unwrapped typed array from a different
1661 // compartment. Proceed with caution!
1662
1663 MOZ_ASSERT(targetOffset >= 0);
1664
1665 // Steps 1-3. (Performed in caller.)
1666 MOZ_ASSERT(!target->hasDetachedBuffer());
1667
1668 // Steps 4-5.
1669 auto sourceLength = source->length();
1670 if (!sourceLength) {
1671 ReportOutOfBounds(cx, source);
1672 return false;
1673 }
1674
1675 // Steps 13-14 (Split into two checks to provide better error messages).
1676 if (targetOffset > targetLength) {
1677 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_INDEX);
1678 return false;
1679 }
1680
1681 // Step 14 (Cont'd).
1682 size_t offset = size_t(targetOffset);
1683 if (*sourceLength > targetLength - offset) {
1684 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1685 JSMSG_SOURCE_ARRAY_TOO_LONG);
1686 return false;
1687 }
1688
1689 // Step 15.
1690 if (Scalar::isBigIntType(target->type()) !=
1691 Scalar::isBigIntType(source->type())) {
1692 JS_ReportErrorNumberASCII(
1693 cx, GetErrorMessage, nullptr, JSMSG_TYPED_ARRAY_NOT_COMPATIBLE,
1694 source->getClass()->name, target->getClass()->name);
1695 return false;
1696 }
1697
1698 // Steps 6-12, 16-24.
1699 switch (target->type()) {
1700 #define SET_FROM_TYPED_ARRAY(_, T, N) \
1701 case Scalar::N: \
1702 if (!SetFromTypedArray<T>(target, targetLength, source, *sourceLength, \
1703 offset)) { \
1704 ReportOutOfMemory(cx); \
1705 return false; \
1706 } \
1707 break;
1708 JS_FOR_EACH_TYPED_ARRAY(SET_FROM_TYPED_ARRAY)
1709 #undef SET_FROM_TYPED_ARRAY
1710 default:
1711 MOZ_CRASH("Unsupported TypedArray type");
1712 }
1713
1714 return true;
1715 }
1716
1717 // ES2023 draft rev 22cc56ab08fcab92a865978c0aa5c6f1d8ce250f
1718 // 23.2.3.24.1 SetTypedArrayFromArrayLike ( target, targetOffset, source )
1719 static bool SetTypedArrayFromArrayLike(JSContext* cx,
1720 Handle<TypedArrayObject*> target,
1721 double targetOffset, size_t targetLength,
1722 HandleObject src) {
1723 MOZ_ASSERT(targetOffset >= 0);
1724
1725 // Steps 1-2. (Performed in caller.)
1726 MOZ_ASSERT(target->length().isSome());
1727
1728 // Steps 3-4. (Performed in caller.)
1729
1730 // Step 5.
1731 uint64_t srcLength;
1732 if (!GetLengthProperty(cx, src, &srcLength)) {
1733 return false;
1734 }
1735
1736 // Steps 6-7 (Split into two checks to provide better error messages).
1737 if (targetOffset > targetLength) {
1738 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_INDEX);
1739 return false;
1740 }
1741
1742 // Step 7 (Cont'd).
1743 size_t offset = size_t(targetOffset);
1744 if (srcLength > targetLength - offset) {
1745 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1746 JSMSG_SOURCE_ARRAY_TOO_LONG);
1747 return false;
1748 }
1749
1750 MOZ_ASSERT(srcLength <= targetLength);
1751
1752 // Steps 8-9.
1753 if (srcLength > 0) {
1754 switch (target->type()) {
1755 #define SET_FROM_NON_TYPED_ARRAY(_, T, N) \
1756 case Scalar::N: \
1757 if (!SetFromNonTypedArray<T>(cx, target, src, srcLength, offset)) \
1758 return false; \
1759 break;
1760 JS_FOR_EACH_TYPED_ARRAY(SET_FROM_NON_TYPED_ARRAY)
1761 #undef SET_FROM_NON_TYPED_ARRAY
1762 default:
1763 MOZ_CRASH("Unsupported TypedArray type");
1764 }
1765 }
1766
1767 // Step 10.
1768 return true;
1769 }
1770
1771 // ES2023 draft rev 22cc56ab08fcab92a865978c0aa5c6f1d8ce250f
1772 // 23.2.3.24 %TypedArray%.prototype.set ( source [ , offset ] )
1773 // 23.2.3.24.1 SetTypedArrayFromTypedArray ( target, targetOffset, source )
1774 // 23.2.3.24.2 SetTypedArrayFromArrayLike ( target, targetOffset, source )
1775 static bool TypedArray_set(JSContext* cx, const CallArgs& args) {
1776 MOZ_ASSERT(IsTypedArrayObject(args.thisv()));
1777
1778 // Steps 1-3 (Validation performed as part of CallNonGenericMethod).
1779 Rooted<TypedArrayObject*> target(
1780 cx, &args.thisv().toObject().as<TypedArrayObject>());
1781
1782 // Steps 4-5.
1783 double targetOffset = 0;
1784 if (args.length() > 1) {
1785 // Step 4.
1786 if (!ToInteger(cx, args[1], &targetOffset)) {
1787 return false;
1788 }
1789
1790 // Step 5.
1791 if (targetOffset < 0) {
1792 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_INDEX);
1793 return false;
1794 }
1795 }
1796
1797 // 23.2.3.24.1, steps 1-2.
1798 // 23.2.3.24.2, steps 1-2.
1799 auto targetLength = target->length();
1800 if (!targetLength) {
1801 ReportOutOfBounds(cx, target);
1802 return false;
1803 }
1804
1805 // 23.2.3.24.2, step 4. (23.2.3.24.1 only applies if args[0] is a typed
1806 // array, so it doesn't make a difference there to apply ToObject here.)
1807 RootedObject src(cx, ToObject(cx, args.get(0)));
1808 if (!src) {
1809 return false;
1810 }
1811
1812 Rooted<TypedArrayObject*> srcTypedArray(cx);
1813 {
1814 JSObject* obj = CheckedUnwrapStatic(src);
1815 if (!obj) {
1816 ReportAccessDenied(cx);
1817 return false;
1818 }
1819
1820 if (obj->is<TypedArrayObject>()) {
1821 srcTypedArray = &obj->as<TypedArrayObject>();
1822 }
1823 }
1824
1825 // Steps 6-7.
1826 if (srcTypedArray) {
1827 if (!SetTypedArrayFromTypedArray(cx, target, targetOffset, *targetLength,
1828 srcTypedArray)) {
1829 return false;
1830 }
1831 } else {
1832 if (!SetTypedArrayFromArrayLike(cx, target, targetOffset, *targetLength,
1833 src)) {
1834 return false;
1835 }
1836 }
1837
1838 // Step 8.
1839 args.rval().setUndefined();
1840 return true;
1841 }
1842
1843 static bool TypedArray_set(JSContext* cx, unsigned argc, Value* vp) {
1844 CallArgs args = CallArgsFromVp(argc, vp);
1845 return CallNonGenericMethod<IsTypedArrayObject, TypedArray_set>(cx, args);
1846 }
1847
1848 // ES2020 draft rev dc1e21c454bd316810be1c0e7af0131a2d7f38e9
1849 // 22.2.3.5 %TypedArray%.prototype.copyWithin ( target, start [ , end ] )
1850 static bool TypedArray_copyWithin(JSContext* cx, const CallArgs& args) {
1851 MOZ_ASSERT(IsTypedArrayObject(args.thisv()));
1852
1853 // Steps 1-2.
1854 Rooted<TypedArrayObject*> tarray(
1855 cx, &args.thisv().toObject().as<TypedArrayObject>());
1856
1857 auto arrayLength = tarray->length();
1858 if (!arrayLength) {
1859 ReportOutOfBounds(cx, tarray);
1860 return false;
1861 }
1862
1863 // Step 3.
1864 size_t len = *arrayLength;
1865
1866 // Steps 4-5.
1867 size_t to = 0;
1868 if (args.hasDefined(0)) {
1869 if (!ToIntegerIndex(cx, args[0], len, &to)) {
1870 return false;
1871 }
1872 }
1873
1874 // Steps 6-7.
1875 size_t from = 0;
1876 if (args.hasDefined(1)) {
1877 if (!ToIntegerIndex(cx, args[1], len, &from)) {
1878 return false;
1879 }
1880 }
1881
1882 // Steps 8-9.
1883 size_t final_ = len;
1884 if (args.hasDefined(2)) {
1885 if (!ToIntegerIndex(cx, args[2], len, &final_)) {
1886 return false;
1887 }
1888 }
1889
1890 // Step 10.
1891 MOZ_ASSERT(to <= len);
1892 size_t count;
1893 if (from <= final_) {
1894 count = std::min(final_ - from, len - to);
1895 } else {
1896 count = 0;
1897 }
1898
1899 // Step 11.
1900 //
1901 // Note that this copies elements effectively by memmove, *not* in
1902 // step 11's specified order. This is unobservable, even when the underlying
1903 // buffer is a SharedArrayBuffer instance, because the access is unordered and
1904 // therefore is allowed to have data races.
1905
1906 if (count == 0) {
1907 args.rval().setObject(*tarray);
1908 return true;
1909 }
1910
1911 // Reacquire the length because side-effects may have detached or resized the
1912 // array buffer.
1913 arrayLength = tarray->length();
1914 if (!arrayLength) {
1915 ReportOutOfBounds(cx, tarray);
1916 return false;
1917 }
1918
1919 // Recompute the bounds if the current length is smaller.
1920 if (*arrayLength < len) {
1921 MOZ_ASSERT(to + count <= len);
1922 MOZ_ASSERT(from + count <= len);
1923
1924 len = *arrayLength;
1925
1926 // Don't copy any bytes if either index is no longer in-bounds.
1927 if (to >= len || from >= len) {
1928 args.rval().setObject(*tarray);
1929 return true;
1930 }
1931
1932 // Restrict |count| to not copy any bytes after the end of the array.
1933 count = std::min(count, std::min(len - to, len - from));
1934 MOZ_ASSERT(count > 0);
1935 }
1936
1937 // Don't multiply by |tarray->bytesPerElement()| in case the compiler can't
1938 // strength-reduce multiplication by 1/2/4/8 into the equivalent shift.
1939 const size_t ElementShift = TypedArrayShift(tarray->type());
1940
1941 MOZ_ASSERT((SIZE_MAX >> ElementShift) > to);
1942 size_t byteDest = to << ElementShift;
1943
1944 MOZ_ASSERT((SIZE_MAX >> ElementShift) > from);
1945 size_t byteSrc = from << ElementShift;
1946
1947 MOZ_ASSERT((SIZE_MAX >> ElementShift) >= count);
1948 size_t byteSize = count << ElementShift;
1949
1950 #ifdef DEBUG
1951 {
1952 size_t viewByteLength = len << ElementShift;
1953 MOZ_ASSERT(byteSize <= viewByteLength);
1954 MOZ_ASSERT(byteDest < viewByteLength);
1955 MOZ_ASSERT(byteSrc < viewByteLength);
1956 MOZ_ASSERT(byteDest <= viewByteLength - byteSize);
1957 MOZ_ASSERT(byteSrc <= viewByteLength - byteSize);
1958 }
1959 #endif
1960
1961 if (tarray->isSharedMemory()) {
1962 auto data = SharedOps::extract(tarray).cast<uint8_t*>();
1963 SharedOps::memmove(data + byteDest, data + byteSrc, byteSize);
1964 } else {
1965 auto data = UnsharedOps::extract(tarray).cast<uint8_t*>();
1966 UnsharedOps::memmove(data + byteDest, data + byteSrc, byteSize);
1967 }
1968
1969 args.rval().setObject(*tarray);
1970 return true;
1971 }
1972
1973 static bool TypedArray_copyWithin(JSContext* cx, unsigned argc, Value* vp) {
1974 AutoJSMethodProfilerEntry pseudoFrame(cx, "[TypedArray].prototype",
1975 "copyWithin");
1976 CallArgs args = CallArgsFromVp(argc, vp);
1977 return CallNonGenericMethod<IsTypedArrayObject, TypedArray_copyWithin>(cx,
1978 args);
1979 }
1980
1981 template <typename ExternalType, typename NativeType>
1982 static bool TypedArrayJoinKernel(JSContext* cx,
1983 Handle<TypedArrayObject*> tarray, size_t len,
1984 Handle<JSLinearString*> sep,
1985 JSStringBuilder& sb) {
1986 // Steps 7-8.
1987 for (size_t k = 0; k < len; k++) {
1988 if (!CheckForInterrupt(cx)) {
1989 return false;
1990 }
1991
1992 // Step 8.a.
1993 if (k > 0 && sep->length() > 0 && !sb.append(sep)) {
1994 return false;
1995 }
1996
1997 // Step 8.b-c.
1998 auto element = TypedArrayObjectTemplate<NativeType>::getIndex(tarray, k);
1999 if constexpr (std::numeric_limits<NativeType>::is_integer) {
2000 // Plus one to include the largest number and plus one for the sign.
2001 constexpr size_t MaximumLength =
2002 std::numeric_limits<NativeType>::digits10 + 1 +
2003 std::numeric_limits<NativeType>::is_signed;
2004
2005 char str[MaximumLength] = {};
2006 auto result = std::to_chars(str, std::end(str),
2007 static_cast<ExternalType>(element), 10);
2008 MOZ_ASSERT(result.ec == std::errc());
2009
2010 size_t strlen = result.ptr - str;
2011 if (!sb.append(str, strlen)) {
2012 return false;
2013 }
2014 } else {
2015 ToCStringBuf cbuf;
2016 size_t strlen;
2017 char* str = NumberToCString(&cbuf, static_cast<double>(element), &strlen);
2018 if (!sb.append(str, strlen)) {
2019 return false;
2020 }
2021 }
2022 }
2023 return true;
2024 }
2025
2026 /**
2027 * %TypedArray%.prototype.join ( separator )
2028 *
2029 * ES2025 draft rev c4042979a7cdd96b663ffcc43aeee90af8d7a576
2030 */
2031 static bool TypedArray_join(JSContext* cx, const CallArgs& args) {
2032 MOZ_ASSERT(IsTypedArrayObject(args.thisv()));
2033
2034 // Steps 1-3.
2035 Rooted<TypedArrayObject*> tarray(
2036 cx, &args.thisv().toObject().as<TypedArrayObject>());
2037
2038 auto arrayLength = tarray->length();
2039 if (!arrayLength) {
2040 ReportOutOfBounds(cx, tarray);
2041 return false;
2042 }
2043 size_t len = *arrayLength;
2044
2045 // Steps 4-5.
2046 Rooted<JSLinearString*> sep(cx);
2047 if (args.hasDefined(0)) {
2048 JSString* s = ToString<CanGC>(cx, args[0]);
2049 if (!s) {
2050 return false;
2051 }
2052
2053 sep = s->ensureLinear(cx);
2054 if (!sep) {
2055 return false;
2056 }
2057 } else {
2058 sep = cx->names().comma_;
2059 }
2060
2061 // Steps 6-9 (When the length is zero, directly return the empty string).
2062 if (len == 0) {
2063 args.rval().setString(cx->emptyString());
2064 return true;
2065 }
2066
2067 // Step 6.
2068 JSStringBuilder sb(cx);
2069 if (sep->hasTwoByteChars() && !sb.ensureTwoByteChars()) {
2070 return false;
2071 }
2072
2073 // Reacquire the length because side-effects may have detached or resized the
2074 // array buffer.
2075 size_t actualLength = std::min(len, tarray->length().valueOr(0));
2076
2077 // The string representation of each element has at least one character.
2078 auto res = mozilla::CheckedInt<uint32_t>(actualLength);
2079
2080 // The separator will be added |length - 1| times, reserve space for that so
2081 // that we don't have to unnecessarily grow the buffer.
2082 size_t seplen = sep->length();
2083 if (seplen > 0) {
2084 if (len > UINT32_MAX) {
2085 ReportAllocationOverflow(cx);
2086 return false;
2087 }
2088 res += mozilla::CheckedInt<uint32_t>(seplen) * (uint32_t(len) - 1);
2089 }
2090 if (!res.isValid()) {
2091 ReportAllocationOverflow(cx);
2092 return false;
2093 }
2094 if (!sb.reserve(res.value())) {
2095 return false;
2096 }
2097
2098 switch (tarray->type()) {
2099 #define TYPED_ARRAY_JOIN(ExternalType, NativeType, Name) \
2100 case Scalar::Name: \
2101 if (!TypedArrayJoinKernel<ExternalType, NativeType>( \
2102 cx, tarray, actualLength, sep, sb)) { \
2103 return false; \
2104 } \
2105 break;
2106 JS_FOR_EACH_TYPED_ARRAY(TYPED_ARRAY_JOIN)
2107 #undef TYPED_ARRAY_JOIN
2108 default:
2109 MOZ_CRASH("Unsupported TypedArray type");
2110 }
2111
2112 for (size_t k = actualLength; k < len; k++) {
2113 if (!CheckForInterrupt(cx)) {
2114 return false;
2115 }
2116
2117 // Step 8.a.
2118 if (k > 0 && !sb.append(sep)) {
2119 return false;
2120 }
2121
2122 // Steps 8.b-c. (Not applicable)
2123 }
2124
2125 // Step 9.
2126 JSString* str = sb.finishString();
2127 if (!str) {
2128 return false;
2129 }
2130
2131 args.rval().setString(str);
2132 return true;
2133 }
2134
2135 /**
2136 * %TypedArray%.prototype.join ( separator )
2137 *
2138 * ES2025 draft rev c4042979a7cdd96b663ffcc43aeee90af8d7a576
2139 */
2140 static bool TypedArray_join(JSContext* cx, unsigned argc, Value* vp) {
2141 AutoJSMethodProfilerEntry pseudoFrame(cx, "[TypedArray].prototype", "join");
2142 CallArgs args = CallArgsFromVp(argc, vp);
2143 return CallNonGenericMethod<IsTypedArrayObject, TypedArray_join>(cx, args);
2144 }
2145
2146 template <typename Ops, typename NativeType>
2147 static int64_t TypedArrayIndexOfNaive(TypedArrayObject* tarray, size_t k,
2148 size_t len, NativeType searchElement) {
2149 MOZ_RELEASE_ASSERT(k < len);
2150 MOZ_RELEASE_ASSERT(len <= tarray->length().valueOr(0));
2151
2152 SharedMem<NativeType*> data =
2153 Ops::extract(tarray).template cast<NativeType*>();
2154 for (size_t i = k; i < len; i++) {
2155 NativeType element = Ops::load(data + i);
2156 if (element == searchElement) {
2157 return int64_t(i);
2158 }
2159 }
2160 return -1;
2161 }
2162
2163 template <typename NativeType>
2164 static int64_t TypedArrayIndexOfSIMD(TypedArrayObject* tarray, size_t k,
2165 size_t len, NativeType searchElement) {
2166 MOZ_RELEASE_ASSERT(k < len);
2167 MOZ_RELEASE_ASSERT(len <= tarray->length().valueOr(0));
2168
2169 if constexpr (sizeof(NativeType) == 1) {
2170 auto* data = UnsharedOps::extract(tarray).cast<char*>().unwrapUnshared();
2171 auto* ptr = mozilla::SIMD::memchr8(
2172 data + k, mozilla::BitwiseCast<char>(searchElement), len - k);
2173 if (!ptr) {
2174 return -1;
2175 }
2176 return int64_t(ptr - data);
2177 } else if constexpr (sizeof(NativeType) == 2) {
2178 auto* data =
2179 UnsharedOps::extract(tarray).cast<char16_t*>().unwrapUnshared();
2180 auto* ptr = mozilla::SIMD::memchr16(
2181 data + k, mozilla::BitwiseCast<char16_t>(searchElement), len - k);
2182 if (!ptr) {
2183 return -1;
2184 }
2185 return int64_t(ptr - data);
2186 } else if constexpr (sizeof(NativeType) == 4) {
2187 auto* data =
2188 UnsharedOps::extract(tarray).cast<uint32_t*>().unwrapUnshared();
2189 auto* ptr = mozilla::SIMD::memchr32(
2190 data + k, mozilla::BitwiseCast<uint32_t>(searchElement), len - k);
2191 if (!ptr) {
2192 return -1;
2193 }
2194 return int64_t(ptr - data);
2195 } else {
2196 static_assert(sizeof(NativeType) == 8);
2197
2198 auto* data =
2199 UnsharedOps::extract(tarray).cast<uint64_t*>().unwrapUnshared();
2200 auto* ptr = mozilla::SIMD::memchr64(
2201 data + k, mozilla::BitwiseCast<uint64_t>(searchElement), len - k);
2202 if (!ptr) {
2203 return -1;
2204 }
2205 return int64_t(ptr - data);
2206 }
2207 }
2208
2209 template <typename ExternalType, typename NativeType>
2210 static typename std::enable_if_t<!std::numeric_limits<NativeType>::is_integer,
2211 int64_t>
2212 TypedArrayIndexOf(TypedArrayObject* tarray, size_t k, size_t len,
2213 const Value& searchElement) {
2214 if (!searchElement.isNumber()) {
2215 return -1;
2216 }
2217
2218 double d = searchElement.toNumber();
2219 NativeType e = NativeType(d);
2220
2221 // Return early if the search element is not representable using |NativeType|
2222 // or if it's NaN.
2223 if (double(e) != d) {
2224 return -1;
2225 }
2226 MOZ_ASSERT(!std::isnan(d));
2227
2228 if (tarray->isSharedMemory()) {
2229 return TypedArrayIndexOfNaive<SharedOps>(tarray, k, len, e);
2230 }
2231 if (e == NativeType(0)) {
2232 // Can't use bitwise comparison when searching for ±0.
2233 return TypedArrayIndexOfNaive<UnsharedOps>(tarray, k, len, e);
2234 }
2235 return TypedArrayIndexOfSIMD(tarray, k, len, e);
2236 }
2237
2238 template <typename ExternalType, typename NativeType>
2239 static typename std::enable_if_t<std::numeric_limits<NativeType>::is_integer &&
2240 sizeof(NativeType) < 8,
2241 int64_t>
2242 TypedArrayIndexOf(TypedArrayObject* tarray, size_t k, size_t len,
2243 const Value& searchElement) {
2244 if (!searchElement.isNumber()) {
2245 return -1;
2246 }
2247
2248 int64_t d;
2249 if (searchElement.isInt32()) {
2250 d = searchElement.toInt32();
2251 } else {
2252 if (!mozilla::NumberEqualsInt64(searchElement.toDouble(), &d)) {
2253 return -1;
2254 }
2255 }
2256
2257 // Ensure search element is representable using |ExternalType|, which implies
2258 // it can be represented using |NativeType|.
2259 mozilla::CheckedInt<ExternalType> checked{d};
2260 if (!checked.isValid()) {
2261 return -1;
2262 }
2263 NativeType e = static_cast<NativeType>(checked.value());
2264
2265 if (tarray->isSharedMemory()) {
2266 return TypedArrayIndexOfNaive<SharedOps>(tarray, k, len, e);
2267 }
2268 return TypedArrayIndexOfSIMD(tarray, k, len, e);
2269 }
2270
2271 template <typename ExternalType, typename NativeType>
2272 static typename std::enable_if_t<std::is_same_v<NativeType, int64_t>, int64_t>
2273 TypedArrayIndexOf(TypedArrayObject* tarray, size_t k, size_t len,
2274 const Value& searchElement) {
2275 if (!searchElement.isBigInt()) {
2276 return -1;
2277 }
2278
2279 int64_t e;
2280 if (!BigInt::isInt64(searchElement.toBigInt(), &e)) {
2281 return -1;
2282 }
2283
2284 if (tarray->isSharedMemory()) {
2285 return TypedArrayIndexOfNaive<SharedOps>(tarray, k, len, e);
2286 }
2287 return TypedArrayIndexOfSIMD(tarray, k, len, e);
2288 }
2289
2290 template <typename ExternalType, typename NativeType>
2291 static typename std::enable_if_t<std::is_same_v<NativeType, uint64_t>, int64_t>
2292 TypedArrayIndexOf(TypedArrayObject* tarray, size_t k, size_t len,
2293 const Value& searchElement) {
2294 if (!searchElement.isBigInt()) {
2295 return -1;
2296 }
2297
2298 uint64_t e;
2299 if (!BigInt::isUint64(searchElement.toBigInt(), &e)) {
2300 return -1;
2301 }
2302
2303 if (tarray->isSharedMemory()) {
2304 return TypedArrayIndexOfNaive<SharedOps>(tarray, k, len, e);
2305 }
2306 return TypedArrayIndexOfSIMD(tarray, k, len, e);
2307 }
2308
2309 /**
2310 * %TypedArray%.prototype.indexOf ( searchElement [ , fromIndex ] )
2311 *
2312 * ES2025 draft rev c4042979a7cdd96b663ffcc43aeee90af8d7a576
2313 */
2314 static bool TypedArray_indexOf(JSContext* cx, const CallArgs& args) {
2315 MOZ_ASSERT(IsTypedArrayObject(args.thisv()));
2316
2317 // Steps 1-3.
2318 Rooted<TypedArrayObject*> tarray(
2319 cx, &args.thisv().toObject().as<TypedArrayObject>());
2320
2321 auto arrayLength = tarray->length();
2322 if (!arrayLength) {
2323 ReportOutOfBounds(cx, tarray);
2324 return false;
2325 }
2326 size_t len = *arrayLength;
2327
2328 // Step 4.
2329 if (len == 0) {
2330 args.rval().setInt32(-1);
2331 return true;
2332 }
2333
2334 // Steps 5-10.
2335 size_t k = 0;
2336 if (args.hasDefined(1)) {
2337 // Steps 5-6.
2338 if (!ToIntegerIndex(cx, args[1], len, &k)) {
2339 return false;
2340 }
2341
2342 // Reacquire the length because side-effects may have detached or resized
2343 // the array buffer.
2344 len = std::min(len, tarray->length().valueOr(0));
2345
2346 // Return early if |k| exceeds the current length.
2347 if (k >= len) {
2348 args.rval().setInt32(-1);
2349 return true;
2350 }
2351 }
2352 MOZ_ASSERT(k < len);
2353
2354 // Steps 11-12.
2355 int64_t result;
2356 switch (tarray->type()) {
2357 #define TYPED_ARRAY_INDEXOF(ExternalType, NativeType, Name) \
2358 case Scalar::Name: \
2359 result = TypedArrayIndexOf<ExternalType, NativeType>(tarray, k, len, \
2360 args.get(0)); \
2361 break;
2362 JS_FOR_EACH_TYPED_ARRAY(TYPED_ARRAY_INDEXOF)
2363 #undef TYPED_ARRAY_INDEXOF
2364 default:
2365 MOZ_CRASH("Unsupported TypedArray type");
2366 }
2367 MOZ_ASSERT_IF(result >= 0, uint64_t(result) < len);
2368 MOZ_ASSERT_IF(result < 0, result == -1);
2369
2370 args.rval().setNumber(result);
2371 return true;
2372 }
2373
2374 /**
2375 * %TypedArray%.prototype.indexOf ( searchElement [ , fromIndex ] )
2376 *
2377 * ES2025 draft rev c4042979a7cdd96b663ffcc43aeee90af8d7a576
2378 */
2379 static bool TypedArray_indexOf(JSContext* cx, unsigned argc, Value* vp) {
2380 AutoJSMethodProfilerEntry pseudoFrame(cx, "[TypedArray].prototype",
2381 "indexOf");
2382 CallArgs args = CallArgsFromVp(argc, vp);
2383 return CallNonGenericMethod<IsTypedArrayObject, TypedArray_indexOf>(cx, args);
2384 }
2385
2386 template <typename Ops, typename NativeType>
2387 static int64_t TypedArrayLastIndexOf(TypedArrayObject* tarray, size_t k,
2388 size_t len, NativeType searchElement) {
2389 MOZ_RELEASE_ASSERT(k < len);
2390 MOZ_RELEASE_ASSERT(len <= tarray->length().valueOr(0));
2391
2392 SharedMem<NativeType*> data =
2393 Ops::extract(tarray).template cast<NativeType*>();
2394 for (size_t i = k + 1; i > 0;) {
2395 NativeType element = Ops::load(data + --i);
2396 if (element == searchElement) {
2397 return int64_t(i);
2398 }
2399 }
2400 return -1;
2401 }
2402
2403 template <typename ExternalType, typename NativeType>
2404 static typename std::enable_if_t<!std::numeric_limits<NativeType>::is_integer,
2405 int64_t>
2406 TypedArrayLastIndexOf(TypedArrayObject* tarray, size_t k, size_t len,
2407 const Value& searchElement) {
2408 if (!searchElement.isNumber()) {
2409 return -1;
2410 }
2411
2412 double d = searchElement.toNumber();
2413 NativeType e = NativeType(d);
2414
2415 // Return early if the search element is not representable using |NativeType|
2416 // or if it's NaN.
2417 if (double(e) != d) {
2418 return -1;
2419 }
2420 MOZ_ASSERT(!std::isnan(d));
2421
2422 if (tarray->isSharedMemory()) {
2423 return TypedArrayLastIndexOf<SharedOps>(tarray, k, len, e);
2424 }
2425 return TypedArrayLastIndexOf<UnsharedOps>(tarray, k, len, e);
2426 }
2427
2428 template <typename ExternalType, typename NativeType>
2429 static typename std::enable_if_t<std::numeric_limits<NativeType>::is_integer &&
2430 sizeof(NativeType) < 8,
2431 int64_t>
2432 TypedArrayLastIndexOf(TypedArrayObject* tarray, size_t k, size_t len,
2433 const Value& searchElement) {
2434 if (!searchElement.isNumber()) {
2435 return -1;
2436 }
2437
2438 int64_t d;
2439 if (searchElement.isInt32()) {
2440 d = searchElement.toInt32();
2441 } else {
2442 if (!mozilla::NumberEqualsInt64(searchElement.toDouble(), &d)) {
2443 return -1;
2444 }
2445 }
2446
2447 // Ensure search element is representable using |ExternalType|, which implies
2448 // it can be represented using |NativeType|.
2449 mozilla::CheckedInt<ExternalType> checked{d};
2450 if (!checked.isValid()) {
2451 return -1;
2452 }
2453 NativeType e = static_cast<NativeType>(checked.value());
2454
2455 if (tarray->isSharedMemory()) {
2456 return TypedArrayLastIndexOf<SharedOps>(tarray, k, len, e);
2457 }
2458 return TypedArrayLastIndexOf<UnsharedOps>(tarray, k, len, e);
2459 }
2460
2461 template <typename ExternalType, typename NativeType>
2462 static typename std::enable_if_t<std::is_same_v<NativeType, int64_t>, int64_t>
2463 TypedArrayLastIndexOf(TypedArrayObject* tarray, size_t k, size_t len,
2464 const Value& searchElement) {
2465 if (!searchElement.isBigInt()) {
2466 return -1;
2467 }
2468
2469 int64_t e;
2470 if (!BigInt::isInt64(searchElement.toBigInt(), &e)) {
2471 return -1;
2472 }
2473
2474 if (tarray->isSharedMemory()) {
2475 return TypedArrayLastIndexOf<SharedOps>(tarray, k, len, e);
2476 }
2477 return TypedArrayLastIndexOf<UnsharedOps>(tarray, k, len, e);
2478 }
2479
2480 template <typename ExternalType, typename NativeType>
2481 static typename std::enable_if_t<std::is_same_v<NativeType, uint64_t>, int64_t>
2482 TypedArrayLastIndexOf(TypedArrayObject* tarray, size_t k, size_t len,
2483 const Value& searchElement) {
2484 if (!searchElement.isBigInt()) {
2485 return -1;
2486 }
2487
2488 uint64_t e;
2489 if (!BigInt::isUint64(searchElement.toBigInt(), &e)) {
2490 return -1;
2491 }
2492
2493 if (tarray->isSharedMemory()) {
2494 return TypedArrayLastIndexOf<SharedOps>(tarray, k, len, e);
2495 }
2496 return TypedArrayLastIndexOf<UnsharedOps>(tarray, k, len, e);
2497 }
2498
2499 /**
2500 * %TypedArray%.prototype.lastIndexOf ( searchElement [ , fromIndex ] )
2501 *
2502 * ES2025 draft rev c4042979a7cdd96b663ffcc43aeee90af8d7a576
2503 */
2504 static bool TypedArray_lastIndexOf(JSContext* cx, const CallArgs& args) {
2505 MOZ_ASSERT(IsTypedArrayObject(args.thisv()));
2506
2507 // Steps 1-3.
2508 Rooted<TypedArrayObject*> tarray(
2509 cx, &args.thisv().toObject().as<TypedArrayObject>());
2510
2511 auto arrayLength = tarray->length();
2512 if (!arrayLength) {
2513 ReportOutOfBounds(cx, tarray);
2514 return false;
2515 }
2516 size_t len = *arrayLength;
2517
2518 // Step 4.
2519 if (len == 0) {
2520 args.rval().setInt32(-1);
2521 return true;
2522 }
2523
2524 // Steps 5-8.
2525 size_t k = len - 1;
2526 if (args.length() > 1) {
2527 // Step 5.
2528 double fromIndex;
2529 if (!ToInteger(cx, args[1], &fromIndex)) {
2530 return false;
2531 }
2532
2533 // Steps 6-8.
2534 if (fromIndex >= 0) {
2535 k = size_t(std::min(fromIndex, double(len - 1)));
2536 } else {
2537 double d = double(len) + fromIndex;
2538 if (d < 0) {
2539 args.rval().setInt32(-1);
2540 return true;
2541 }
2542 k = size_t(d);
2543 }
2544 MOZ_ASSERT(k < len);
2545
2546 // Reacquire the length because side-effects may have detached or resized
2547 // the array buffer.
2548 size_t currentLength = tarray->length().valueOr(0);
2549
2550 // Restrict the search index and length if the new length is smaller.
2551 if (currentLength < len) {
2552 // Return early if the new length is zero.
2553 if (currentLength == 0) {
2554 args.rval().setInt32(-1);
2555 return true;
2556 }
2557
2558 // Otherwise just restrict |k| and |len| to the current length.
2559 k = std::min(k, currentLength - 1);
2560 len = currentLength;
2561 }
2562 }
2563 MOZ_ASSERT(k < len);
2564
2565 // Steps 9-10.
2566 int64_t result;
2567 switch (tarray->type()) {
2568 #define TYPED_ARRAY_LASTINDEXOF(ExternalType, NativeType, Name) \
2569 case Scalar::Name: \
2570 result = TypedArrayLastIndexOf<ExternalType, NativeType>(tarray, k, len, \
2571 args.get(0)); \
2572 break;
2573 JS_FOR_EACH_TYPED_ARRAY(TYPED_ARRAY_LASTINDEXOF)
2574 #undef TYPED_ARRAY_LASTINDEXOF
2575 default:
2576 MOZ_CRASH("Unsupported TypedArray type");
2577 }
2578 MOZ_ASSERT_IF(result >= 0, uint64_t(result) < len);
2579 MOZ_ASSERT_IF(result < 0, result == -1);
2580
2581 args.rval().setNumber(result);
2582 return true;
2583 }
2584
2585 /**
2586 * %TypedArray%.prototype.lastIndexOf ( searchElement [ , fromIndex ] )
2587 *
2588 * ES2025 draft rev c4042979a7cdd96b663ffcc43aeee90af8d7a576
2589 */
2590 static bool TypedArray_lastIndexOf(JSContext* cx, unsigned argc, Value* vp) {
2591 AutoJSMethodProfilerEntry pseudoFrame(cx, "[TypedArray].prototype",
2592 "lastIndexOf");
2593 CallArgs args = CallArgsFromVp(argc, vp);
2594 return CallNonGenericMethod<IsTypedArrayObject, TypedArray_lastIndexOf>(cx,
2595 args);
2596 }
2597
2598 template <typename T>
2599 static inline bool IsNaN(T num) {
2600 if constexpr (std::is_same_v<T, float16>) {
2601 return num != num;
2602 } else {
2603 // Static analysis complains when using self-comparison for built-in types,
2604 // so we have to use `std::isnan`.
2605 return std::isnan(num);
2606 }
2607 }
2608
2609 template <typename Ops, typename NativeType>
2610 static int64_t TypedArrayIncludesNaN(TypedArrayObject* tarray, size_t k,
2611 size_t len) {
2612 MOZ_RELEASE_ASSERT(k < len);
2613 MOZ_RELEASE_ASSERT(len <= tarray->length().valueOr(0));
2614
2615 SharedMem<NativeType*> data =
2616 Ops::extract(tarray).template cast<NativeType*>();
2617 for (size_t i = k; i < len; i++) {
2618 NativeType element = Ops::load(data + i);
2619 if (IsNaN(element)) {
2620 return int64_t(i);
2621 }
2622 }
2623 return -1;
2624 }
2625
2626 template <typename ExternalType, typename NativeType>
2627 static typename std::enable_if_t<!std::numeric_limits<NativeType>::is_integer,
2628 int64_t>
2629 TypedArrayIncludes(TypedArrayObject* tarray, size_t k, size_t len,
2630 const Value& searchElement) {
2631 if (searchElement.isDouble() && std::isnan(searchElement.toDouble())) {
2632 if (tarray->isSharedMemory()) {
2633 return TypedArrayIncludesNaN<SharedOps, NativeType>(tarray, k, len);
2634 }
2635 return TypedArrayIncludesNaN<UnsharedOps, NativeType>(tarray, k, len);
2636 }
2637
2638 // Delegate to TypedArrayIndexOf if not NaN.
2639 return TypedArrayIndexOf<ExternalType, NativeType>(tarray, k, len,
2640 searchElement);
2641 }
2642
2643 template <typename ExternalType, typename NativeType>
2644 static typename std::enable_if_t<std::numeric_limits<NativeType>::is_integer,
2645 int64_t>
2646 TypedArrayIncludes(TypedArrayObject* tarray, size_t k, size_t len,
2647 const Value& searchElement) {
2648 // Delegate to TypedArrayIndexOf for integer types.
2649 return TypedArrayIndexOf<ExternalType, NativeType>(tarray, k, len,
2650 searchElement);
2651 }
2652
2653 /**
2654 * %TypedArray%.prototype.includes ( searchElement [ , fromIndex ] )
2655 *
2656 * ES2025 draft rev c4042979a7cdd96b663ffcc43aeee90af8d7a576
2657 */
2658 static bool TypedArray_includes(JSContext* cx, const CallArgs& args) {
2659 MOZ_ASSERT(IsTypedArrayObject(args.thisv()));
2660
2661 // Steps 1-3.
2662 Rooted<TypedArrayObject*> tarray(
2663 cx, &args.thisv().toObject().as<TypedArrayObject>());
2664
2665 auto arrayLength = tarray->length();
2666 if (!arrayLength) {
2667 ReportOutOfBounds(cx, tarray);
2668 return false;
2669 }
2670 size_t len = *arrayLength;
2671
2672 // Step 4.
2673 if (len == 0) {
2674 args.rval().setBoolean(false);
2675 return true;
2676 }
2677
2678 // Steps 5-10.
2679 size_t k = 0;
2680 if (args.hasDefined(1)) {
2681 if (!ToIntegerIndex(cx, args[1], len, &k)) {
2682 return false;
2683 }
2684
2685 // Reacquire the length because side-effects may have detached or resized
2686 // the array buffer.
2687 size_t currentLength = tarray->length().valueOr(0);
2688
2689 // Contrary to `indexOf`, `includes` doesn't perform `HasProperty`, so we
2690 // have to handle the case when the current length is smaller than the
2691 // original length.
2692 if (currentLength < len) {
2693 // Accessing an element beyond the typed array length returns `undefined`,
2694 // so return `true` iff the search element is `undefined`.
2695 if (k < len && args[0].isUndefined()) {
2696 args.rval().setBoolean(true);
2697 return true;
2698 }
2699
2700 // Otherwise just restrict |len| to the current length.
2701 len = currentLength;
2702 }
2703
2704 // Return early if |k| exceeds the current length.
2705 if (k >= len) {
2706 args.rval().setBoolean(false);
2707 return true;
2708 }
2709 }
2710 MOZ_ASSERT(k < len);
2711
2712 // Steps 11-12.
2713 int64_t result;
2714 switch (tarray->type()) {
2715 #define TYPED_ARRAY_INCLUDES(ExternalType, NativeType, Name) \
2716 case Scalar::Name: \
2717 result = TypedArrayIncludes<ExternalType, NativeType>(tarray, k, len, \
2718 args.get(0)); \
2719 break;
2720 JS_FOR_EACH_TYPED_ARRAY(TYPED_ARRAY_INCLUDES)
2721 #undef TYPED_ARRAY_INCLUDES
2722 default:
2723 MOZ_CRASH("Unsupported TypedArray type");
2724 }
2725 MOZ_ASSERT_IF(result >= 0, uint64_t(result) < len);
2726 MOZ_ASSERT_IF(result < 0, result == -1);
2727
2728 args.rval().setBoolean(result >= 0);
2729 return true;
2730 }
2731
2732 /**
2733 * %TypedArray%.prototype.includes ( searchElement [ , fromIndex ] )
2734 *
2735 * ES2025 draft rev c4042979a7cdd96b663ffcc43aeee90af8d7a576
2736 */
2737 static bool TypedArray_includes(JSContext* cx, unsigned argc, Value* vp) {
2738 AutoJSMethodProfilerEntry pseudoFrame(cx, "[TypedArray].prototype",
2739 "includes");
2740 CallArgs args = CallArgsFromVp(argc, vp);
2741 return CallNonGenericMethod<IsTypedArrayObject, TypedArray_includes>(cx,
2742 args);
2743 }
2744
2745 template <typename Ops, typename NativeType>
2746 static void TypedArrayFill(TypedArrayObject* tarray, NativeType value,
2747 size_t startIndex, size_t endIndex) {
2748 MOZ_RELEASE_ASSERT(startIndex <= endIndex);
2749 MOZ_RELEASE_ASSERT(endIndex <= tarray->length().valueOr(0));
2750
2751 SharedMem<NativeType*> data =
2752 Ops::extract(tarray).template cast<NativeType*>();
2753 for (size_t i = startIndex; i < endIndex; i++) {
2754 Ops::store(data + i, value);
2755 }
2756 }
2757
2758 template <typename NativeType>
2759 static void TypedArrayFillStdMemset(TypedArrayObject* tarray, uint8_t value,
2760 size_t startIndex, size_t endIndex) {
2761 MOZ_RELEASE_ASSERT(startIndex <= endIndex);
2762 MOZ_RELEASE_ASSERT(endIndex <= tarray->length().valueOr(0));
2763
2764 SharedMem<uint8_t*> data = UnsharedOps::extract(tarray).cast<uint8_t*>();
2765 std::memset(data.unwrapUnshared() + startIndex * sizeof(NativeType), value,
2766 (endIndex - startIndex) * sizeof(NativeType));
2767 }
2768
2769 template <typename NativeType>
2770 static void TypedArrayFillAtomicMemset(TypedArrayObject* tarray, uint8_t value,
2771 size_t startIndex, size_t endIndex) {
2772 MOZ_RELEASE_ASSERT(startIndex <= endIndex);
2773 MOZ_RELEASE_ASSERT(endIndex <= tarray->length().valueOr(0));
2774
2775 SharedMem<uint8_t*> data = SharedOps::extract(tarray).cast<uint8_t*>();
2776 jit::AtomicOperations::memsetSafeWhenRacy(
2777 data + startIndex * sizeof(NativeType), value,
2778 (endIndex - startIndex) * sizeof(NativeType));
2779 }
2780
2781 template <typename NativeType>
2782 static NativeType ConvertToNativeType(const Value& value) {
2783 if constexpr (!std::numeric_limits<NativeType>::is_integer) {
2784 double d = value.toNumber();
2785
2786 if (js::SupportDifferentialTesting()) {
2787 // See the comment in ElementSpecific::doubleToNative.
2788 d = JS::CanonicalizeNaN(d);
2789 }
2790
2791 return ConvertNumber<NativeType>(d);
2792 } else if constexpr (std::is_same_v<NativeType, int64_t>) {
2793 return BigInt::toInt64(value.toBigInt());
2794 } else if constexpr (std::is_same_v<NativeType, uint64_t>) {
2795 return BigInt::toUint64(value.toBigInt());
2796 } else {
2797 return ConvertNumber<NativeType>(value.toNumber());
2798 }
2799 }
2800
2801 template <typename NativeType>
2802 static void TypedArrayFill(TypedArrayObject* tarray, const Value& value,
2803 size_t startIndex, size_t endIndex) {
2804 NativeType val = ConvertToNativeType<NativeType>(value);
2805
2806 using UnsignedT =
2807 typename mozilla::UnsignedStdintTypeForSize<sizeof(NativeType)>::Type;
2808 UnsignedT bits = mozilla::BitwiseCast<UnsignedT>(val);
2809
2810 // Duplicate the LSB to check if we can call memset.
2811 UnsignedT pattern;
2812 std::memset(&pattern, uint8_t(bits), sizeof(UnsignedT));
2813
2814 if (tarray->isSharedMemory()) {
2815 // To prevent teared writes, only use memset on shared memory when copying
2816 // single bytes.
2817 if (bits == pattern && sizeof(NativeType) == 1) {
2818 TypedArrayFillAtomicMemset<NativeType>(tarray, uint8_t(bits), startIndex,
2819 endIndex);
2820 } else {
2821 TypedArrayFill<SharedOps>(tarray, val, startIndex, endIndex);
2822 }
2823 } else {
2824 if (bits == pattern) {
2825 TypedArrayFillStdMemset<NativeType>(tarray, uint8_t(bits), startIndex,
2826 endIndex);
2827 } else {
2828 TypedArrayFill<UnsharedOps>(tarray, val, startIndex, endIndex);
2829 }
2830 }
2831 }
2832
2833 /**
2834 * %TypedArray%.prototype.fill ( value [ , start [ , end ] ] )
2835 *
2836 * ES2025 draft rev c4042979a7cdd96b663ffcc43aeee90af8d7a576
2837 */
2838 static bool TypedArray_fill(JSContext* cx, const CallArgs& args) {
2839 MOZ_ASSERT(IsTypedArrayObject(args.thisv()));
2840
2841 // Steps 1-3.
2842 Rooted<TypedArrayObject*> tarray(
2843 cx, &args.thisv().toObject().as<TypedArrayObject>());
2844
2845 auto arrayLength = tarray->length();
2846 if (!arrayLength) {
2847 ReportOutOfBounds(cx, tarray);
2848 return false;
2849 }
2850 size_t len = *arrayLength;
2851
2852 // Steps 4-5.
2853 Rooted<Value> value(cx);
2854 if (!tarray->convertValue(cx, args.get(0), &value)) {
2855 return false;
2856 }
2857
2858 // Steps 6-9
2859 size_t startIndex = 0;
2860 if (args.hasDefined(1)) {
2861 if (!ToIntegerIndex(cx, args[1], len, &startIndex)) {
2862 return false;
2863 }
2864 }
2865
2866 // Steps 10-13.
2867 size_t endIndex = len;
2868 if (args.hasDefined(2)) {
2869 if (!ToIntegerIndex(cx, args[2], len, &endIndex)) {
2870 return false;
2871 }
2872 }
2873
2874 // Steps 14-16.
2875 //
2876 // Reacquire the length because side-effects may have detached or resized
2877 // the array buffer.
2878 arrayLength = tarray->length();
2879 if (!arrayLength) {
2880 ReportOutOfBounds(cx, tarray);
2881 return false;
2882 }
2883 len = *arrayLength;
2884
2885 // Step 17.
2886 endIndex = std::min(endIndex, len);
2887
2888 // Steps 18-19.
2889 if (startIndex < endIndex) {
2890 switch (tarray->type()) {
2891 #define TYPED_ARRAY_FILL(_, NativeType, Name) \
2892 case Scalar::Name: \
2893 TypedArrayFill<NativeType>(tarray, value.get(), startIndex, endIndex); \
2894 break;
2895 JS_FOR_EACH_TYPED_ARRAY(TYPED_ARRAY_FILL)
2896 #undef TYPED_ARRAY_FILL
2897 default:
2898 MOZ_CRASH("Unsupported TypedArray type");
2899 }
2900 }
2901
2902 // Step 20.
2903 args.rval().setObject(*tarray);
2904 return true;
2905 }
2906
2907 /**
2908 * %TypedArray%.prototype.fill ( value [ , start [ , end ] ] )
2909 *
2910 * ES2025 draft rev c4042979a7cdd96b663ffcc43aeee90af8d7a576
2911 */
2912 static bool TypedArray_fill(JSContext* cx, unsigned argc, Value* vp) {
2913 AutoJSMethodProfilerEntry pseudoFrame(cx, "[TypedArray].prototype", "fill");
2914 CallArgs args = CallArgsFromVp(argc, vp);
2915 return CallNonGenericMethod<IsTypedArrayObject, TypedArray_fill>(cx, args);
2916 }
2917
2918 template <typename Ops, typename NativeType>
2919 static void TypedArrayReverse(TypedArrayObject* tarray, size_t len) {
2920 MOZ_RELEASE_ASSERT(len > 0);
2921 MOZ_RELEASE_ASSERT(len <= tarray->length().valueOr(0));
2922
2923 SharedMem<NativeType*> lower =
2924 Ops::extract(tarray).template cast<NativeType*>();
2925 SharedMem<NativeType*> upper = lower + (len - 1);
2926 for (; lower < upper; lower++, upper--) {
2927 NativeType lowerValue = Ops::load(lower);
2928 NativeType upperValue = Ops::load(upper);
2929
2930 Ops::store(lower, upperValue);
2931 Ops::store(upper, lowerValue);
2932 }
2933 }
2934
2935 template <typename NativeType>
2936 static void TypedArrayReverse(TypedArrayObject* tarray, size_t len) {
2937 if (tarray->isSharedMemory()) {
2938 TypedArrayReverse<SharedOps, NativeType>(tarray, len);
2939 } else {
2940 TypedArrayReverse<UnsharedOps, NativeType>(tarray, len);
2941 }
2942 }
2943
2944 /**
2945 * %TypedArray%.prototype.reverse ( )
2946 *
2947 * ES2025 draft rev c4042979a7cdd96b663ffcc43aeee90af8d7a576
2948 */
2949 static bool TypedArray_reverse(JSContext* cx, const CallArgs& args) {
2950 MOZ_ASSERT(IsTypedArrayObject(args.thisv()));
2951
2952 // Steps 1-3.
2953 Rooted<TypedArrayObject*> tarray(
2954 cx, &args.thisv().toObject().as<TypedArrayObject>());
2955
2956 auto arrayLength = tarray->length();
2957 if (!arrayLength) {
2958 ReportOutOfBounds(cx, tarray);
2959 return false;
2960 }
2961 size_t len = *arrayLength;
2962
2963 // Steps 4-6.
2964 if (len > 1) {
2965 switch (tarray->type()) {
2966 #define TYPED_ARRAY_REVERSE(_, NativeType, Name) \
2967 case Scalar::Name: \
2968 TypedArrayReverse<NativeType>(tarray, len); \
2969 break;
2970 JS_FOR_EACH_TYPED_ARRAY(TYPED_ARRAY_REVERSE)
2971 #undef TYPED_ARRAY_REVERSE
2972 default:
2973 MOZ_CRASH("Unsupported TypedArray type");
2974 }
2975 }
2976
2977 // Step 7.
2978 args.rval().setObject(*tarray);
2979 return true;
2980 }
2981
2982 /**
2983 * %TypedArray%.prototype.reverse ( )
2984 *
2985 * ES2025 draft rev c4042979a7cdd96b663ffcc43aeee90af8d7a576
2986 */
2987 static bool TypedArray_reverse(JSContext* cx, unsigned argc, Value* vp) {
2988 AutoJSMethodProfilerEntry pseudoFrame(cx, "[TypedArray].prototype",
2989 "reverse");
2990 CallArgs args = CallArgsFromVp(argc, vp);
2991 return CallNonGenericMethod<IsTypedArrayObject, TypedArray_reverse>(cx, args);
2992 }
2993
2994 /**
2995 * TypedArrayCreateSameType ( exemplar, argumentList )
2996 *
2997 * ES2025 draft rev c4042979a7cdd96b663ffcc43aeee90af8d7a576
2998 */
2999 static TypedArrayObject* TypedArrayCreateSameType(
3000 JSContext* cx, Handle<TypedArrayObject*> exemplar, size_t length) {
3001 switch (exemplar->type()) {
3002 #define TYPED_ARRAY_CREATE(_, NativeType, Name) \
3003 case Scalar::Name: \
3004 return TypedArrayObjectTemplate<NativeType>::fromLength(cx, length);
3005 JS_FOR_EACH_TYPED_ARRAY(TYPED_ARRAY_CREATE)
3006 #undef TYPED_ARRAY_CREATE
3007 default:
3008 MOZ_CRASH("Unsupported TypedArray type");
3009 }
3010 }
3011
3012 template <typename NativeType>
3013 static void TypedArrayCopyElements(TypedArrayObject* source,
3014 TypedArrayObject* target, size_t length) {
3015 MOZ_ASSERT(source->type() == target->type());
3016 MOZ_ASSERT(!target->isSharedMemory());
3017 MOZ_ASSERT(length > 0);
3018 MOZ_RELEASE_ASSERT(length <= source->length().valueOr(0));
3019 MOZ_RELEASE_ASSERT(length <= target->length().valueOr(0));
3020
3021 auto dest = UnsharedOps::extract(target).cast<NativeType*>();
3022 if (source->isSharedMemory()) {
3023 auto src = SharedOps::extract(source).cast<NativeType*>();
3024 SharedOps::podCopy(dest, src, length);
3025 } else {
3026 auto src = UnsharedOps::extract(source).cast<NativeType*>();
3027 UnsharedOps::podCopy(dest, src, length);
3028 }
3029 }
3030
3031 static void TypedArrayCopyElements(TypedArrayObject* source,
3032 TypedArrayObject* target, size_t length) {
3033 switch (source->type()) {
3034 #define TYPED_ARRAY_COPY_ELEMENTS(_, NativeType, Name) \
3035 case Scalar::Name: \
3036 return TypedArrayCopyElements<NativeType>(source, target, length);
3037 JS_FOR_EACH_TYPED_ARRAY(TYPED_ARRAY_COPY_ELEMENTS)
3038 #undef TYPED_ARRAY_COPY_ELEMENTS
3039 default:
3040 MOZ_CRASH("Unsupported TypedArray type");
3041 }
3042 }
3043
3044 /**
3045 * %TypedArray%.prototype.toReversed ( )
3046 *
3047 * ES2025 draft rev c4042979a7cdd96b663ffcc43aeee90af8d7a576
3048 */
3049 static bool TypedArray_toReversed(JSContext* cx, const CallArgs& args) {
3050 MOZ_ASSERT(IsTypedArrayObject(args.thisv()));
3051
3052 // Steps 1-3.
3053 Rooted<TypedArrayObject*> tarray(
3054 cx, &args.thisv().toObject().as<TypedArrayObject>());
3055
3056 auto arrayLength = tarray->length();
3057 if (!arrayLength) {
3058 ReportOutOfBounds(cx, tarray);
3059 return false;
3060 }
3061 size_t length = *arrayLength;
3062
3063 // Step 4.
3064 TypedArrayObject* result = TypedArrayCreateSameType(cx, tarray, length);
3065 if (!result) {
3066 return false;
3067 }
3068
3069 // Steps 5-6.
3070 if (length > 0) {
3071 TypedArrayCopyElements(tarray, result, length);
3072
3073 switch (result->type()) {
3074 #define TYPED_ARRAY_TOREVERSED(_, NativeType, Name) \
3075 case Scalar::Name: \
3076 TypedArrayReverse<UnsharedOps, NativeType>(result, length); \
3077 break;
3078 JS_FOR_EACH_TYPED_ARRAY(TYPED_ARRAY_TOREVERSED)
3079 #undef TYPED_ARRAY_TOREVERSED
3080 default:
3081 MOZ_CRASH("Unsupported TypedArray type");
3082 }
3083 }
3084
3085 // Step 7.
3086 args.rval().setObject(*result);
3087 return true;
3088 }
3089
3090 /**
3091 * %TypedArray%.prototype.toReversed ( )
3092 *
3093 * ES2025 draft rev c4042979a7cdd96b663ffcc43aeee90af8d7a576
3094 */
3095 static bool TypedArray_toReversed(JSContext* cx, unsigned argc, Value* vp) {
3096 AutoJSMethodProfilerEntry pseudoFrame(cx, "[TypedArray].prototype",
3097 "toReversed");
3098 CallArgs args = CallArgsFromVp(argc, vp);
3099 return CallNonGenericMethod<IsTypedArrayObject, TypedArray_toReversed>(cx,
3100 args);
3101 }
3102
3103 template <typename Ops, typename NativeType>
3104 static void TypedArraySetElement(TypedArrayObject* tarray, size_t index,
3105 const Value& value) {
3106 MOZ_RELEASE_ASSERT(index < tarray->length().valueOr(0));
3107
3108 NativeType val = ConvertToNativeType<NativeType>(value);
3109
3110 SharedMem<NativeType*> data =
3111 Ops::extract(tarray).template cast<NativeType*>();
3112 Ops::store(data + index, val);
3113 }
3114
3115 /**
3116 * %TypedArray%.prototype.with ( index, value )
3117 *
3118 * ES2025 draft rev c4042979a7cdd96b663ffcc43aeee90af8d7a576
3119 */
3120 static bool TypedArray_with(JSContext* cx, const CallArgs& args) {
3121 MOZ_ASSERT(IsTypedArrayObject(args.thisv()));
3122
3123 // Steps 1-3.
3124 Rooted<TypedArrayObject*> tarray(
3125 cx, &args.thisv().toObject().as<TypedArrayObject>());
3126
3127 auto arrayLength = tarray->length();
3128 if (!arrayLength) {
3129 ReportOutOfBounds(cx, tarray);
3130 return false;
3131 }
3132 size_t len = *arrayLength;
3133
3134 // Step 4.
3135 double relativeIndex;
3136 if (!ToInteger(cx, args.get(0), &relativeIndex)) {
3137 return false;
3138 }
3139
3140 // Steps 5-6.
3141 double actualIndex;
3142 if (relativeIndex >= 0) {
3143 actualIndex = relativeIndex;
3144 } else {
3145 actualIndex = double(len) + relativeIndex;
3146 }
3147
3148 // Steps 7-8.
3149 Rooted<Value> value(cx);
3150 if (!tarray->convertValue(cx, args.get(1), &value)) {
3151 return false;
3152 }
3153
3154 // Reacquire the length because side-effects may have detached or resized
3155 // the array buffer.
3156 size_t currentLength = tarray->length().valueOr(0);
3157
3158 // Step 9. (Inlined IsValidIntegerIndex)
3159 if (actualIndex < 0 || actualIndex >= double(currentLength)) {
3160 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_INDEX);
3161 return false;
3162 }
3163 MOZ_ASSERT(currentLength > 0);
3164
3165 // Step 10.
3166 Rooted<TypedArrayObject*> result(cx,
3167 TypedArrayCreateSameType(cx, tarray, len));
3168 if (!result) {
3169 return false;
3170 }
3171
3172 // Steps 11-12.
3173 if (len > 0) {
3174 // Start with copying all elements from |tarray|.
3175 TypedArrayCopyElements(tarray, result, std::min(len, currentLength));
3176
3177 // Set the replacement value.
3178 if (actualIndex < double(len)) {
3179 switch (result->type()) {
3180 #define TYPED_ARRAY_SET_ELEMENT(_, NativeType, Name) \
3181 case Scalar::Name: \
3182 TypedArraySetElement<UnsharedOps, NativeType>(result, size_t(actualIndex), \
3183 value); \
3184 break;
3185 JS_FOR_EACH_TYPED_ARRAY(TYPED_ARRAY_SET_ELEMENT)
3186 #undef TYPED_ARRAY_SET_ELEMENT
3187 default:
3188 MOZ_CRASH("Unsupported TypedArray type");
3189 }
3190 }
3191
3192 // Fill the remaining elements with `undefined`.
3193 if (currentLength < len) {
3194 if (!result->convertValue(cx, UndefinedHandleValue, &value)) {
3195 return false;
3196 }
3197
3198 switch (result->type()) {
3199 #define TYPED_ARRAY_FILL(_, NativeType, Name) \
3200 case Scalar::Name: \
3201 TypedArrayFill<NativeType>(result, value.get(), currentLength, len); \
3202 break;
3203 JS_FOR_EACH_TYPED_ARRAY(TYPED_ARRAY_FILL)
3204 #undef TYPED_ARRAY_FILL
3205 default:
3206 MOZ_CRASH("Unsupported TypedArray type");
3207 }
3208 }
3209 }
3210
3211 // Step 13.
3212 args.rval().setObject(*result);
3213 return true;
3214 }
3215
3216 /**
3217 * %TypedArray%.prototype.with ( index, value )
3218 *
3219 * ES2025 draft rev c4042979a7cdd96b663ffcc43aeee90af8d7a576
3220 */
3221 static bool TypedArray_with(JSContext* cx, unsigned argc, Value* vp) {
3222 AutoJSMethodProfilerEntry pseudoFrame(cx, "[TypedArray].prototype", "with");
3223 CallArgs args = CallArgsFromVp(argc, vp);
3224 return CallNonGenericMethod<IsTypedArrayObject, TypedArray_with>(cx, args);
3225 }
3226
3227 // Byte vector with large enough inline storage to allow constructing small
3228 // typed arrays without extra heap allocations.
3229 using ByteVector =
3230 js::Vector<uint8_t, FixedLengthTypedArrayObject::INLINE_BUFFER_LIMIT>;
3231
3232 class ByteSink final {
3233 ByteVector& bytes_;
3234
3235 public:
3236 explicit ByteSink(ByteVector& bytes) : bytes_(bytes) {
3237 MOZ_ASSERT(bytes.empty());
3238 }
3239
3240 constexpr bool canAppend(size_t n = 1) const { return true; }
3241
3242 template <typename... Args>
3243 bool append(Args... args) {
3244 if (!bytes_.reserve(bytes_.length() + sizeof...(args))) {
3245 return false;
3246 }
3247 (bytes_.infallibleAppend(args), ...);
3248 return true;
3249 }
3250 };
3251
3252 class TypedArraySink final {
3253 Handle<TypedArrayObject*> typedArray_;
3254 size_t maxLength_;
3255 size_t index_ = 0;
3256
3257 public:
3258 TypedArraySink(Handle<TypedArrayObject*> typedArray, size_t maxLength)
3259 : typedArray_(typedArray), maxLength_(maxLength) {
3260 MOZ_ASSERT(typedArray->type() == Scalar::Uint8);
3261
3262 // The underlying buffer must neither be detached nor shrunk. (It may have
3263 // been grown when it's a growable shared buffer and a concurrent thread
3264 // resized the buffer.)
3265 MOZ_ASSERT(!typedArray->hasDetachedBuffer());
3266 MOZ_ASSERT(typedArray->length().valueOr(0) >= maxLength);
3267 }
3268
3269 size_t written() const { return index_; }
3270
3271 bool canAppend(size_t n = 1) const { return maxLength_ - index_ >= n; }
3272
3273 template <typename... Args>
3274 bool append(Args... args) {
3275 MOZ_ASSERT(canAppend(sizeof...(args)));
3276 (TypedArrayObjectTemplate<uint8_t>::setIndex(*typedArray_, index_++, args),
3277 ...);
3278 return true;
3279 }
3280 };
3281
3282 static UniqueChars QuoteString(JSContext* cx, char16_t ch) {
3283 Sprinter sprinter(cx);
3284 if (!sprinter.init()) {
3285 return nullptr;
3286 }
3287
3288 StringEscape esc{};
3289 js::EscapePrinter ep(sprinter, esc);
3290 ep.putChar(ch);
3291
3292 return sprinter.release();
3293 }
3294
3295 /**
3296 * FromHex ( string [ , maxLength ] )
3297 *
3298 * https://tc39.es/proposal-arraybuffer-base64/spec/#sec-fromhex
3299 */
3300 template <class Sink>
3301 static bool FromHex(JSContext* cx, Handle<JSString*> string, Sink& sink,
3302 size_t* readLength) {
3303 // Step 1. (Not applicable in our implementation.)
3304
3305 // Step 2.
3306 size_t length = string->length();
3307
3308 // Step 3.
3309 if (length % 2 != 0) {
3310 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3311 JSMSG_TYPED_ARRAY_BAD_HEX_STRING_LENGTH);
3312 return false;
3313 }
3314
3315 JSLinearString* linear = string->ensureLinear(cx);
3316 if (!linear) {
3317 return false;
3318 }
3319
3320 // Step 4. (Not applicable in our implementation.)
3321
3322 // Step 5.
3323 size_t index = 0;
3324
3325 // Step 6.
3326 while (index < length && sink.canAppend()) {
3327 // Step 6.a.
3328 char16_t c0 = linear->latin1OrTwoByteChar(index);
3329 char16_t c1 = linear->latin1OrTwoByteChar(index + 1);
3330
3331 // Step 6.b.
3332 if (MOZ_UNLIKELY(!mozilla::IsAsciiHexDigit(c0) ||
3333 !mozilla::IsAsciiHexDigit(c1))) {
3334 char16_t ch = !mozilla::IsAsciiHexDigit(c0) ? c0 : c1;
3335 if (auto str = QuoteString(cx, ch)) {
3336 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3337 JSMSG_TYPED_ARRAY_BAD_HEX_DIGIT, str.get());
3338 }
3339 return false;
3340 }
3341
3342 // Step 6.c.
3343 index += 2;
3344
3345 // Step 6.d.
3346 uint8_t byte = (mozilla::AsciiAlphanumericToNumber(c0) << 4) +
3347 mozilla::AsciiAlphanumericToNumber(c1);
3348
3349 // Step 6.e.
3350 if (!sink.append(byte)) {
3351 return false;
3352 }
3353 }
3354
3355 // Step 7.
3356 *readLength = index;
3357 return true;
3358 }
3359
3360 namespace Base64 {
3361 static constexpr uint8_t InvalidChar = UINT8_MAX;
3362
3363 static constexpr auto DecodeTable(const char (&alphabet)[65]) {
3364 std::array<uint8_t, 128> result = {};
3365
3366 // Initialize all elements to InvalidChar.
3367 for (auto& e : result) {
3368 e = InvalidChar;
3369 }
3370
3371 // Map the base64 characters to their values.
3372 for (uint8_t i = 0; i < 64; ++i) {
3373 result[alphabet[i]] = i;
3374 }
3375
3376 return result;
3377 }
3378 } // namespace Base64
3379
3380 namespace Base64::Encode {
3381 static constexpr const char Base64[] =
3382 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3383 static_assert(std::char_traits<char>::length(Base64) == 64);
3384
3385 static constexpr const char Base64Url[] =
3386 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
3387 static_assert(std::char_traits<char>::length(Base64Url) == 64);
3388 } // namespace Base64::Encode
3389
3390 namespace Base64::Decode {
3391 static constexpr auto Base64 = DecodeTable(Base64::Encode::Base64);
3392 static_assert(Base64.size() == 128,
3393 "128 elements to allow access through ASCII characters");
3394
3395 static constexpr auto Base64Url = DecodeTable(Base64::Encode::Base64Url);
3396 static_assert(Base64Url.size() == 128,
3397 "128 elements to allow access through ASCII characters");
3398 } // namespace Base64::Decode
3399
3400 enum class Alphabet {
3401 /**
3402 * Standard base64 alphabet.
3403 */
3404 Base64,
3405
3406 /**
3407 * URL and filename safe base64 alphabet.
3408 */
3409 Base64Url,
3410 };
3411
3412 enum class LastChunkHandling {
3413 /**
3414 * Allow partial chunks at the end of the input.
3415 */
3416 Loose,
3417
3418 /**
3419 * Disallow partial chunks at the end of the input.
3420 */
3421 Strict,
3422
3423 /**
3424 * Stop before partial chunks at the end of the input.
3425 */
3426 StopBeforePartial,
3427 };
3428
3429 /**
3430 * FromBase64 ( string, alphabet, lastChunkHandling [ , maxLength ] )
3431 *
3432 * https://tc39.es/proposal-arraybuffer-base64/spec/#sec-frombase64
3433 */
3434 template <class Sink>
3435 static bool FromBase64(JSContext* cx, Handle<JSString*> string,
3436 Alphabet alphabet, LastChunkHandling lastChunkHandling,
3437 Sink& sink, size_t* readLength) {
3438 // Steps 1-2. (Not applicable in our implementation.)
3439
3440 // Step 3.
3441 if (!sink.canAppend()) {
3442 *readLength = 0;
3443 return true;
3444 }
3445
3446 JSLinearString* linear = string->ensureLinear(cx);
3447 if (!linear) {
3448 return false;
3449 }
3450
3451 // DecodeBase64Chunk ( chunk [ , throwOnExtraBits ] )
3452 //
3453 // Encode a complete base64 chunk.
3454 auto decodeChunk = [&](uint32_t chunk) {
3455 MOZ_ASSERT(chunk <= 0xffffff);
3456 return sink.append(chunk >> 16, chunk >> 8, chunk);
3457 };
3458
3459 // DecodeBase64Chunk ( chunk [ , throwOnExtraBits ] )
3460 //
3461 // Encode a three element partial base64 chunk.
3462 auto decodeChunk3 = [&](uint32_t chunk, bool throwOnExtraBits) {
3463 MOZ_ASSERT(chunk <= 0x3ffff);
3464
3465 if (throwOnExtraBits && (chunk & 0x3) != 0) {
3466 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3467 JSMSG_TYPED_ARRAY_EXTRA_BASE64_BITS);
3468 return false;
3469 }
3470 return sink.append(chunk >> 10, chunk >> 2);
3471 };
3472
3473 // DecodeBase64Chunk ( chunk [ , throwOnExtraBits ] )
3474 //
3475 // Encode a two element partial base64 chunk.
3476 auto decodeChunk2 = [&](uint32_t chunk, bool throwOnExtraBits) {
3477 MOZ_ASSERT(chunk <= 0xfff);
3478
3479 if (throwOnExtraBits && (chunk & 0xf) != 0) {
3480 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3481 JSMSG_TYPED_ARRAY_EXTRA_BASE64_BITS);
3482 return false;
3483 }
3484 return sink.append(chunk >> 4);
3485 };
3486
3487 // DecodeBase64Chunk ( chunk [ , throwOnExtraBits ] )
3488 //
3489 // Encode a partial base64 chunk.
3490 auto decodePartialChunk = [&](uint32_t chunk, uint32_t chunkLength,
3491 bool throwOnExtraBits = false) {
3492 MOZ_ASSERT(chunkLength == 2 || chunkLength == 3);
3493 return chunkLength == 2 ? decodeChunk2(chunk, throwOnExtraBits)
3494 : decodeChunk3(chunk, throwOnExtraBits);
3495 };
3496
3497 // Step 4.
3498 //
3499 // String index after the last fully read base64 chunk.
3500 size_t read = 0;
3501
3502 // Step 5. (Not applicable in our implementation.)
3503
3504 // Step 6.
3505 //
3506 // Current base64 chunk, a uint24 number.
3507 uint32_t chunk = 0;
3508
3509 // Step 7.
3510 //
3511 // Current base64 chunk length, in the range [0..4].
3512 size_t chunkLength = 0;
3513
3514 // Step 8.
3515 //
3516 // Current string index.
3517 size_t index = 0;
3518
3519 // Step 9.
3520 size_t length = linear->length();
3521
3522 const auto& decode = alphabet == Alphabet::Base64 ? Base64::Decode::Base64
3523 : Base64::Decode::Base64Url;
3524
3525 // Step 10.
3526 for (; index < length; index++) {
3527 // Step 10.c. (Reordered)
3528 char16_t ch = linear->latin1OrTwoByteChar(index);
3529
3530 // Step 10.a.
3531 if (mozilla::IsAsciiWhitespace(ch)) {
3532 continue;
3533 }
3534
3535 // Step 10.b. (Moved out of loop.)
3536
3537 // Step 10.d. (Performed in for-loop step.)
3538
3539 // Step 10.e.
3540 if (ch == '=') {
3541 break;
3542 }
3543
3544 // Steps 10.f-g.
3545 uint8_t value = Base64::InvalidChar;
3546 if (mozilla::IsAscii(ch)) {
3547 value = decode[ch];
3548 }
3549 if (MOZ_UNLIKELY(value == Base64::InvalidChar)) {
3550 if (auto str = QuoteString(cx, ch)) {
3551 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3552 JSMSG_TYPED_ARRAY_BAD_BASE64_CHAR, str.get());
3553 }
3554 return false;
3555 }
3556
3557 // Step 10.h. (Not applicable in our implementation.)
3558
3559 // Step 10.i.
3560 if (chunkLength > 1 && !sink.canAppend(chunkLength)) {
3561 *readLength = read;
3562 return true;
3563 }
3564
3565 // Step 10.j.
3566 chunk = (chunk << 6) | value;
3567
3568 // Step 10.k.
3569 chunkLength += 1;
3570
3571 // Step 10.l.
3572 if (chunkLength == 4) {
3573 // Step 10.l.i.
3574 if (!decodeChunk(chunk)) {
3575 return false;
3576 }
3577
3578 // Step 10.l.ii.
3579 chunk = 0;
3580
3581 // Step 10.l.iii.
3582 chunkLength = 0;
3583
3584 // Step 10.l.iv.
3585 //
3586 // NB: Add +1 to include the |index| update from step 10.d.
3587 read = index + 1;
3588
3589 // Step 10.l.v.
3590 if (!sink.canAppend()) {
3591 *readLength = read;
3592 return true;
3593 }
3594 }
3595 }
3596
3597 // Step 10.b.
3598 if (index == length) {
3599 // Step 10.b.i.
3600 if (chunkLength > 0) {
3601 // Step 10.b.i.1.
3602 if (lastChunkHandling == LastChunkHandling::StopBeforePartial) {
3603 *readLength = read;
3604 return true;
3605 }
3606
3607 // Steps 10.b.i.2-3.
3608 if (lastChunkHandling == LastChunkHandling::Loose) {
3609 // Step 10.b.i.2.a.
3610 if (chunkLength == 1) {
3611 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3612 JSMSG_TYPED_ARRAY_BAD_INCOMPLETE_CHUNK);
3613 return false;
3614 }
3615 MOZ_ASSERT(chunkLength == 2 || chunkLength == 3);
3616
3617 // Step 10.b.i.2.b.
3618 if (!decodePartialChunk(chunk, chunkLength)) {
3619 return false;
3620 }
3621 } else {
3622 // Step 10.b.i.3.a.
3623 MOZ_ASSERT(lastChunkHandling == LastChunkHandling::Strict);
3624
3625 // Step 10.b.i.3.b.
3626 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3627 JSMSG_TYPED_ARRAY_BAD_INCOMPLETE_CHUNK);
3628 return false;
3629 }
3630 }
3631
3632 // Step 10.b.ii.
3633 *readLength = length;
3634 return true;
3635 }
3636
3637 // Step 10.e.
3638 MOZ_ASSERT(index < length);
3639 MOZ_ASSERT(linear->latin1OrTwoByteChar(index) == '=');
3640
3641 // Step 10.e.i.
3642 if (chunkLength < 2) {
3643 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3644 JSMSG_TYPED_ARRAY_BAD_INCOMPLETE_CHUNK);
3645 return false;
3646 }
3647 MOZ_ASSERT(chunkLength == 2 || chunkLength == 3);
3648
3649 // Step 10.e.ii. (Inlined SkipAsciiWhitespace)
3650 while (++index < length) {
3651 char16_t ch = linear->latin1OrTwoByteChar(index);
3652 if (!mozilla::IsAsciiWhitespace(ch)) {
3653 break;
3654 }
3655 }
3656
3657 // Step 10.e.iii.
3658 if (chunkLength == 2) {
3659 // Step 10.e.iii.1.
3660 if (index == length) {
3661 // Step 10.e.iii.1.a.
3662 if (lastChunkHandling == LastChunkHandling::StopBeforePartial) {
3663 *readLength = read;
3664 return true;
3665 }
3666
3667 // Step 10.e.iii.1.b.
3668 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3669 JSMSG_TYPED_ARRAY_MISSING_BASE64_PADDING);
3670 return false;
3671 }
3672
3673 // Step 10.e.iii.2.
3674 char16_t ch = linear->latin1OrTwoByteChar(index);
3675
3676 // Step 10.e.iii.3.
3677 if (ch == '=') {
3678 // Step 10.e.iii.3.a. (Inlined SkipAsciiWhitespace)
3679 while (++index < length) {
3680 char16_t ch = linear->latin1OrTwoByteChar(index);
3681 if (!mozilla::IsAsciiWhitespace(ch)) {
3682 break;
3683 }
3684 }
3685 }
3686 }
3687
3688 // Step 10.e.iv.
3689 if (index < length) {
3690 char16_t ch = linear->latin1OrTwoByteChar(index);
3691 if (auto str = QuoteString(cx, ch)) {
3692 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3693 JSMSG_TYPED_ARRAY_BAD_BASE64_AFTER_PADDING,
3694 str.get());
3695 }
3696 return false;
3697 }
3698
3699 // Steps 10.e.v-vi.
3700 bool throwOnExtraBits = lastChunkHandling == LastChunkHandling::Strict;
3701
3702 // Step 10.e.vii.
3703 if (!decodePartialChunk(chunk, chunkLength, throwOnExtraBits)) {
3704 return false;
3705 }
3706
3707 // Step 10.e.viii.
3708 *readLength = length;
3709 return true;
3710 }
3711
3712 /**
3713 * Uint8Array.fromBase64 ( string [ , options ] )
3714 * Uint8Array.prototype.setFromBase64 ( string [ , options ] )
3715 * Uint8Array.prototype.toBase64 ( [ options ] )
3716 *
3717 * Helper to retrieve the "alphabet" option.
3718 */
3719 static bool GetAlphabetOption(JSContext* cx, Handle<JSObject*> options,
3720 Alphabet* result) {
3721 Rooted<Value> value(cx);
3722 if (!GetProperty(cx, options, options, cx->names().alphabet, &value)) {
3723 return false;
3724 }
3725
3726 if (value.isUndefined()) {
3727 *result = Alphabet::Base64;
3728 return true;
3729 }
3730
3731 if (!value.isString()) {
3732 return ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_IGNORE_STACK,
3733 value, nullptr, "not a string");
3734 }
3735
3736 auto* linear = value.toString()->ensureLinear(cx);
3737 if (!linear) {
3738 return false;
3739 }
3740
3741 if (StringEqualsAscii(linear, "base64")) {
3742 *result = Alphabet::Base64;
3743 return true;
3744 }
3745
3746 if (StringEqualsAscii(linear, "base64url")) {
3747 *result = Alphabet::Base64Url;
3748 return true;
3749 }
3750
3751 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3752 JSMSG_TYPED_ARRAY_BAD_BASE64_ALPHABET);
3753 return false;
3754 }
3755
3756 /**
3757 * Uint8Array.fromBase64 ( string [ , options ] )
3758 * Uint8Array.prototype.setFromBase64 ( string [ , options ] )
3759 *
3760 * Helper to retrieve the "lastChunkHandling" option.
3761 */
3762 static bool GetLastChunkHandlingOption(JSContext* cx, Handle<JSObject*> options,
3763 LastChunkHandling* result) {
3764 Rooted<Value> value(cx);
3765 if (!GetProperty(cx, options, options, cx->names().lastChunkHandling,
3766 &value)) {
3767 return false;
3768 }
3769
3770 if (value.isUndefined()) {
3771 *result = LastChunkHandling::Loose;
3772 return true;
3773 }
3774
3775 if (!value.isString()) {
3776 return ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_IGNORE_STACK,
3777 value, nullptr, "not a string");
3778 }
3779
3780 auto* linear = value.toString()->ensureLinear(cx);
3781 if (!linear) {
3782 return false;
3783 }
3784
3785 if (StringEqualsAscii(linear, "loose")) {
3786 *result = LastChunkHandling::Loose;
3787 return true;
3788 }
3789
3790 if (StringEqualsAscii(linear, "strict")) {
3791 *result = LastChunkHandling::Strict;
3792 return true;
3793 }
3794
3795 if (StringEqualsAscii(linear, "stop-before-partial")) {
3796 *result = LastChunkHandling::StopBeforePartial;
3797 return true;
3798 }
3799
3800 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3801 JSMSG_TYPED_ARRAY_BAD_BASE64_LAST_CHUNK_HANDLING);
3802 return false;
3803 }
3804
3805 enum class OmitPadding : bool { No, Yes };
3806
3807 /**
3808 * Uint8Array.prototype.toBase64 ( [ options ] )
3809 *
3810 * Helper to retrieve the "omitPadding" option.
3811 */
3812 static bool GetOmitPaddingOption(JSContext* cx, Handle<JSObject*> options,
3813 OmitPadding* result) {
3814 Rooted<Value> value(cx);
3815 if (!GetProperty(cx, options, options, cx->names().omitPadding, &value)) {
3816 return false;
3817 }
3818
3819 *result = static_cast<OmitPadding>(JS::ToBoolean(value));
3820 return true;
3821 }
3822
3823 /**
3824 * Uint8Array.fromBase64 ( string [ , options ] )
3825 *
3826 * https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.frombase64
3827 */
3828 static bool uint8array_fromBase64(JSContext* cx, unsigned argc, Value* vp) {
3829 CallArgs args = CallArgsFromVp(argc, vp);
3830
3831 // Step 1.
3832 if (!args.get(0).isString()) {
3833 return ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK,
3834 args.get(0), nullptr, "not a string");
3835 }
3836 Rooted<JSString*> string(cx, args[0].toString());
3837
3838 // Steps 2-9.
3839 auto alphabet = Alphabet::Base64;
3840 auto lastChunkHandling = LastChunkHandling::Loose;
3841 if (args.hasDefined(1)) {
3842 // Step 2. (Inlined GetOptionsObject)
3843 Rooted<JSObject*> options(
3844 cx, RequireObjectArg(cx, "options", "fromBase64", args[1]));
3845 if (!options) {
3846 return false;
3847 }
3848
3849 // Steps 3-6.
3850 if (!GetAlphabetOption(cx, options, &alphabet)) {
3851 return false;
3852 }
3853
3854 // Steps 7-9.
3855 if (!GetLastChunkHandlingOption(cx, options, &lastChunkHandling)) {
3856 return false;
3857 }
3858 }
3859
3860 // Step 10.
3861 ByteVector bytes(cx);
3862 ByteSink sink{bytes};
3863 size_t unusedReadLength;
3864 if (!FromBase64(cx, string, alphabet, lastChunkHandling, sink,
3865 &unusedReadLength)) {
3866 return false;
3867 }
3868
3869 // Step 11.
3870 size_t resultLength = bytes.length();
3871
3872 // Step 12.
3873 auto* tarray =
3874 TypedArrayObjectTemplate<uint8_t>::fromLength(cx, resultLength);
3875 if (!tarray) {
3876 return false;
3877 }
3878
3879 // Step 13.
3880 auto target = SharedMem<uint8_t*>::unshared(tarray->dataPointerUnshared());
3881 auto source = SharedMem<uint8_t*>::unshared(bytes.begin());
3882 UnsharedOps::podCopy(target, source, resultLength);
3883
3884 // Step 14.
3885 args.rval().setObject(*tarray);
3886 return true;
3887 }
3888
3889 /**
3890 * Uint8Array.fromHex ( string )
3891 *
3892 * https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.fromhex
3893 */
3894 static bool uint8array_fromHex(JSContext* cx, unsigned argc, Value* vp) {
3895 CallArgs args = CallArgsFromVp(argc, vp);
3896
3897 // Step 1.
3898 if (!args.get(0).isString()) {
3899 return ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK,
3900 args.get(0), nullptr, "not a string");
3901 }
3902 Rooted<JSString*> string(cx, args[0].toString());
3903
3904 // Step 2.
3905 ByteVector bytes(cx);
3906 ByteSink sink{bytes};
3907 size_t unusedReadLength;
3908 if (!FromHex(cx, string, sink, &unusedReadLength)) {
3909 return false;
3910 }
3911
3912 // Step 3.
3913 size_t resultLength = bytes.length();
3914
3915 // Step 4.
3916 auto* tarray =
3917 TypedArrayObjectTemplate<uint8_t>::fromLength(cx, resultLength);
3918 if (!tarray) {
3919 return false;
3920 }
3921
3922 // Step 5.
3923 auto target = SharedMem<uint8_t*>::unshared(tarray->dataPointerUnshared());
3924 auto source = SharedMem<uint8_t*>::unshared(bytes.begin());
3925 UnsharedOps::podCopy(target, source, resultLength);
3926
3927 // Step 6.
3928 args.rval().setObject(*tarray);
3929 return true;
3930 }
3931
3932 /**
3933 * Uint8Array.prototype.setFromBase64 ( string [ , options ] )
3934 *
3935 * https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.prototype.setfrombase64
3936 */
3937 static bool uint8array_setFromBase64(JSContext* cx, const CallArgs& args) {
3938 Rooted<TypedArrayObject*> tarray(
3939 cx, &args.thisv().toObject().as<TypedArrayObject>());
3940
3941 // Step 3.
3942 if (!args.get(0).isString()) {
3943 return ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK,
3944 args.get(0), nullptr, "not a string");
3945 }
3946 Rooted<JSString*> string(cx, args[0].toString());
3947
3948 // Steps 4-11.
3949 auto alphabet = Alphabet::Base64;
3950 auto lastChunkHandling = LastChunkHandling::Loose;
3951 if (args.hasDefined(1)) {
3952 // Step 2. (Inlined GetOptionsObject)
3953 Rooted<JSObject*> options(
3954 cx, RequireObjectArg(cx, "options", "setFromBase64", args[1]));
3955 if (!options) {
3956 return false;
3957 }
3958
3959 // Steps 3-6.
3960 if (!GetAlphabetOption(cx, options, &alphabet)) {
3961 return false;
3962 }
3963
3964 // Steps 7-9.
3965 if (!GetLastChunkHandlingOption(cx, options, &lastChunkHandling)) {
3966 return false;
3967 }
3968 }
3969
3970 // Steps 12-14.
3971 auto length = tarray->length();
3972 if (!length) {
3973 ReportOutOfBounds(cx, tarray);
3974 return false;
3975 }
3976
3977 // Steps 15-17.
3978 ByteVector bytes(cx);
3979 TypedArraySink sink{tarray, *length};
3980 size_t readLength;
3981 if (!FromBase64(cx, string, alphabet, lastChunkHandling, sink, &readLength)) {
3982 return false;
3983 }
3984
3985 // Step 18.
3986 size_t written = sink.written();
3987
3988 // Steps 19-21. (Not applicable in our implementation.)
3989
3990 // Step 22.
3991 Rooted<PlainObject*> result(cx, NewPlainObject(cx));
3992 if (!result) {
3993 return false;
3994 }
3995
3996 // Step 23.
3997 Rooted<Value> readValue(cx, NumberValue(readLength));
3998 if (!DefineDataProperty(cx, result, cx->names().read, readValue)) {
3999 return false;
4000 }
4001
4002 // Step 24.
4003 Rooted<Value> writtenValue(cx, NumberValue(written));
4004 if (!DefineDataProperty(cx, result, cx->names().written, writtenValue)) {
4005 return false;
4006 }
4007
4008 // Step 25.
4009 args.rval().setObject(*result);
4010 return true;
4011 }
4012
4013 /**
4014 * Uint8Array.prototype.setFromBase64 ( string [ , options ] )
4015 *
4016 * https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.prototype.setfrombase64
4017 */
4018 static bool uint8array_setFromBase64(JSContext* cx, unsigned argc, Value* vp) {
4019 CallArgs args = CallArgsFromVp(argc, vp);
4020
4021 // Steps 1-2.
4022 return CallNonGenericMethod<IsUint8ArrayObject, uint8array_setFromBase64>(
4023 cx, args);
4024 }
4025
4026 /**
4027 * Uint8Array.prototype.setFromHex ( string )
4028 *
4029 * https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.prototype.setfromhex
4030 */
4031 static bool uint8array_setFromHex(JSContext* cx, const CallArgs& args) {
4032 Rooted<TypedArrayObject*> tarray(
4033 cx, &args.thisv().toObject().as<TypedArrayObject>());
4034
4035 // Step 3.
4036 if (!args.get(0).isString()) {
4037 return ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK,
4038 args.get(0), nullptr, "not a string");
4039 }
4040 Rooted<JSString*> string(cx, args[0].toString());
4041
4042 // Steps 4-6.
4043 auto length = tarray->length();
4044 if (!length) {
4045 ReportOutOfBounds(cx, tarray);
4046 return false;
4047 }
4048
4049 // Steps 7-9.
4050 TypedArraySink sink{tarray, *length};
4051 size_t readLength;
4052 if (!FromHex(cx, string, sink, &readLength)) {
4053 return false;
4054 }
4055
4056 // Step 10.
4057 size_t written = sink.written();
4058
4059 // Steps 11-13. (Not applicable in our implementation.)
4060
4061 // Step 14.
4062 Rooted<PlainObject*> result(cx, NewPlainObject(cx));
4063 if (!result) {
4064 return false;
4065 }
4066
4067 // Step 15.
4068 Rooted<Value> readValue(cx, NumberValue(readLength));
4069 if (!DefineDataProperty(cx, result, cx->names().read, readValue)) {
4070 return false;
4071 }
4072
4073 // Step 16.
4074 Rooted<Value> writtenValue(cx, NumberValue(written));
4075 if (!DefineDataProperty(cx, result, cx->names().written, writtenValue)) {
4076 return false;
4077 }
4078
4079 // Step 17.
4080 args.rval().setObject(*result);
4081 return true;
4082 }
4083
4084 /**
4085 * Uint8Array.prototype.setFromHex ( string )
4086 *
4087 * https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.prototype.setfromhex
4088 */
4089 static bool uint8array_setFromHex(JSContext* cx, unsigned argc, Value* vp) {
4090 CallArgs args = CallArgsFromVp(argc, vp);
4091
4092 // Steps 1-2.
4093 return CallNonGenericMethod<IsUint8ArrayObject, uint8array_setFromHex>(cx,
4094 args);
4095 }
4096
4097 /**
4098 * Uint8Array.prototype.toBase64 ( [ options ] )
4099 *
4100 * https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.prototype.tobase64
4101 */
4102 static bool uint8array_toBase64(JSContext* cx, const CallArgs& args) {
4103 Rooted<TypedArrayObject*> tarray(
4104 cx, &args.thisv().toObject().as<TypedArrayObject>());
4105
4106 // Steps 3-7.
4107 auto alphabet = Alphabet::Base64;
4108 auto omitPadding = OmitPadding::No;
4109 if (args.hasDefined(0)) {
4110 // Step 3. (Inlined GetOptionsObject)
4111 Rooted<JSObject*> options(
4112 cx, RequireObjectArg(cx, "options", "toBase64", args[0]));
4113 if (!options) {
4114 return false;
4115 }
4116
4117 // Steps 4-6.
4118 if (!GetAlphabetOption(cx, options, &alphabet)) {
4119 return false;
4120 }
4121
4122 // Step 7.
4123 if (!GetOmitPaddingOption(cx, options, &omitPadding)) {
4124 return false;
4125 }
4126 }
4127
4128 // Step 8. (Partial)
4129 auto length = tarray->length();
4130 if (!length) {
4131 ReportOutOfBounds(cx, tarray);
4132 return false;
4133 }
4134
4135 // Compute the output string length. Three input bytes are encoded as four
4136 // characters, so the output length is ⌈length × 4/3⌉. When omitting padding,
4137 // the output length is length + ⌈length / 3⌉.
4138 auto outLength = mozilla::CheckedInt<size_t>{*length};
4139 outLength += 2;
4140 outLength /= 3;
4141 if (omitPadding == OmitPadding::No) {
4142 outLength *= 4;
4143 } else {
4144 outLength += *length;
4145 }
4146 if (!outLength.isValid() || outLength.value() > JSString::MAX_LENGTH) {
4147 ReportAllocationOverflow(cx);
4148 return false;
4149 }
4150
4151 JSStringBuilder sb(cx);
4152 if (!sb.reserve(outLength.value())) {
4153 return false;
4154 }
4155
4156 // Steps 9-10.
4157 const auto& base64Chars = alphabet == Alphabet::Base64
4158 ? Base64::Encode::Base64
4159 : Base64::Encode::Base64Url;
4160
4161 auto encode = [&base64Chars](uint32_t value) {
4162 return base64Chars[value & 0x3f];
4163 };
4164
4165 // Our implementation directly converts the bytes to their string
4166 // representation instead of first collecting them into an intermediate list.
4167 auto data = tarray->dataPointerEither().cast<uint8_t*>();
4168 auto toRead = *length;
4169 for (; toRead >= 3; toRead -= 3) {
4170 // Combine three input bytes into a single uint24 value.
4171 auto byte0 = jit::AtomicOperations::loadSafeWhenRacy(data++);
4172 auto byte1 = jit::AtomicOperations::loadSafeWhenRacy(data++);
4173 auto byte2 = jit::AtomicOperations::loadSafeWhenRacy(data++);
4174 auto u24 = (uint32_t(byte0) << 16) | (uint32_t(byte1) << 8) | byte2;
4175
4176 // Encode the uint24 value as base64.
4177 sb.infallibleAppend(encode(u24 >> 18));
4178 sb.infallibleAppend(encode(u24 >> 12));
4179 sb.infallibleAppend(encode(u24 >> 6));
4180 sb.infallibleAppend(encode(u24 >> 0));
4181 }
4182
4183 // Trailing two and one element bytes are optionally padded with '='.
4184 if (toRead == 2) {
4185 // Combine two input bytes into a single uint24 value.
4186 auto byte0 = jit::AtomicOperations::loadSafeWhenRacy(data++);
4187 auto byte1 = jit::AtomicOperations::loadSafeWhenRacy(data++);
4188 auto u24 = (uint32_t(byte0) << 16) | (uint32_t(byte1) << 8);
4189
4190 // Encode the uint24 value as base64, optionally including padding.
4191 sb.infallibleAppend(encode(u24 >> 18));
4192 sb.infallibleAppend(encode(u24 >> 12));
4193 sb.infallibleAppend(encode(u24 >> 6));
4194 if (omitPadding == OmitPadding::No) {
4195 sb.infallibleAppend('=');
4196 }
4197 } else if (toRead == 1) {
4198 // Combine one input byte into a single uint24 value.
4199 auto byte0 = jit::AtomicOperations::loadSafeWhenRacy(data++);
4200 auto u24 = uint32_t(byte0) << 16;
4201
4202 // Encode the uint24 value as base64, optionally including padding.
4203 sb.infallibleAppend(encode(u24 >> 18));
4204 sb.infallibleAppend(encode(u24 >> 12));
4205 if (omitPadding == OmitPadding::No) {
4206 sb.infallibleAppend('=');
4207 sb.infallibleAppend('=');
4208 }
4209 } else {
4210 MOZ_ASSERT(toRead == 0);
4211 }
4212
4213 MOZ_ASSERT(sb.length() == outLength.value(), "all characters were written");
4214
4215 // Step 11.
4216 auto* str = sb.finishString();
4217 if (!str) {
4218 return false;
4219 }
4220
4221 args.rval().setString(str);
4222 return true;
4223 }
4224
4225 /**
4226 * Uint8Array.prototype.toBase64 ( [ options ] )
4227 *
4228 * https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.prototype.tobase64
4229 */
4230 static bool uint8array_toBase64(JSContext* cx, unsigned argc, Value* vp) {
4231 CallArgs args = CallArgsFromVp(argc, vp);
4232
4233 // Steps 1-2.
4234 return CallNonGenericMethod<IsUint8ArrayObject, uint8array_toBase64>(cx,
4235 args);
4236 }
4237
4238 /**
4239 * Uint8Array.prototype.toHex ( )
4240 *
4241 * https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.prototype.tohex
4242 */
4243 static bool uint8array_toHex(JSContext* cx, const CallArgs& args) {
4244 Rooted<TypedArrayObject*> tarray(
4245 cx, &args.thisv().toObject().as<TypedArrayObject>());
4246
4247 // Step 3. (Partial)
4248 auto length = tarray->length();
4249 if (!length) {
4250 ReportOutOfBounds(cx, tarray);
4251 return false;
4252 }
4253
4254 // |length| is limited by |ByteLengthLimit|, which ensures that multiplying it
4255 // by two won't overflow.
4256 static_assert(TypedArrayObject::ByteLengthLimit <=
4257 std::numeric_limits<size_t>::max() / 2);
4258 MOZ_ASSERT(*length <= TypedArrayObject::ByteLengthLimit);
4259
4260 // Compute the output string length. Each byte is encoded as two characters,
4261 // so the output length is exactly twice as large as |length|.
4262 size_t outLength = *length * 2;
4263 if (outLength > JSString::MAX_LENGTH) {
4264 ReportAllocationOverflow(cx);
4265 return false;
4266 }
4267
4268 // Step 4.
4269 JSStringBuilder sb(cx);
4270 if (!sb.reserve(outLength)) {
4271 return false;
4272 }
4273
4274 // NB: Lower case hex digits.
4275 static constexpr char HexDigits[] = "0123456789abcdef";
4276 static_assert(std::char_traits<char>::length(HexDigits) == 16);
4277
4278 // Steps 3 and 5.
4279 //
4280 // Our implementation directly converts the bytes to their string
4281 // representation instead of first collecting them into an intermediate list.
4282 auto data = tarray->dataPointerEither().cast<uint8_t*>();
4283 for (size_t index = 0; index < *length; index++) {
4284 auto byte = jit::AtomicOperations::loadSafeWhenRacy(data + index);
4285
4286 sb.infallibleAppend(HexDigits[byte >> 4]);
4287 sb.infallibleAppend(HexDigits[byte & 0xf]);
4288 }
4289
4290 MOZ_ASSERT(sb.length() == outLength, "all characters were written");
4291
4292 // Step 6.
4293 auto* str = sb.finishString();
4294 if (!str) {
4295 return false;
4296 }
4297
4298 args.rval().setString(str);
4299 return true;
4300 }
4301
4302 /**
4303 * Uint8Array.prototype.toHex ( )
4304 *
4305 * https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.prototype.tohex
4306 */
4307 static bool uint8array_toHex(JSContext* cx, unsigned argc, Value* vp) {
4308 CallArgs args = CallArgsFromVp(argc, vp);
4309
4310 // Steps 1-2.
4311 return CallNonGenericMethod<IsUint8ArrayObject, uint8array_toHex>(cx, args);
4312 }
4313
4314 /* static */ const JSFunctionSpec TypedArrayObject::protoFunctions[] = {
4315 JS_SELF_HOSTED_FN("subarray", "TypedArraySubarray", 2, 0),
4316 JS_FN("set", TypedArray_set, 1, 0),
4317 JS_FN("copyWithin", TypedArray_copyWithin, 2, 0),
4318 JS_SELF_HOSTED_FN("every", "TypedArrayEvery", 1, 0),
4319 JS_FN("fill", TypedArray_fill, 1, 0),
4320 JS_SELF_HOSTED_FN("filter", "TypedArrayFilter", 1, 0),
4321 JS_SELF_HOSTED_FN("find", "TypedArrayFind", 1, 0),
4322 JS_SELF_HOSTED_FN("findIndex", "TypedArrayFindIndex", 1, 0),
4323 JS_SELF_HOSTED_FN("findLast", "TypedArrayFindLast", 1, 0),
4324 JS_SELF_HOSTED_FN("findLastIndex", "TypedArrayFindLastIndex", 1, 0),
4325 JS_SELF_HOSTED_FN("forEach", "TypedArrayForEach", 1, 0),
4326 JS_FN("indexOf", TypedArray_indexOf, 1, 0),
4327 JS_FN("join", TypedArray_join, 1, 0),
4328 JS_FN("lastIndexOf", TypedArray_lastIndexOf, 1, 0),
4329 JS_SELF_HOSTED_FN("map", "TypedArrayMap", 1, 0),
4330 JS_SELF_HOSTED_FN("reduce", "TypedArrayReduce", 1, 0),
4331 JS_SELF_HOSTED_FN("reduceRight", "TypedArrayReduceRight", 1, 0),
4332 JS_FN("reverse", TypedArray_reverse, 0, 0),
4333 JS_SELF_HOSTED_FN("slice", "TypedArraySlice", 2, 0),
4334 JS_SELF_HOSTED_FN("some", "TypedArraySome", 1, 0),
4335 JS_TRAMPOLINE_FN("sort", TypedArrayObject::sort, 1, 0, TypedArraySort),
4336 JS_SELF_HOSTED_FN("entries", "TypedArrayEntries", 0, 0),
4337 JS_SELF_HOSTED_FN("keys", "TypedArrayKeys", 0, 0),
4338 JS_SELF_HOSTED_FN("values", "$TypedArrayValues", 0, 0),
4339 JS_SELF_HOSTED_SYM_FN(iterator, "$TypedArrayValues", 0, 0),
4340 JS_FN("includes", TypedArray_includes, 1, 0),
4341 JS_SELF_HOSTED_FN("toString", "ArrayToString", 0, 0),
4342 JS_SELF_HOSTED_FN("toLocaleString", "TypedArrayToLocaleString", 2, 0),
4343 JS_SELF_HOSTED_FN("at", "TypedArrayAt", 1, 0),
4344 JS_FN("toReversed", TypedArray_toReversed, 0, 0),
4345 JS_SELF_HOSTED_FN("toSorted", "TypedArrayToSorted", 1, 0),
4346 JS_FN("with", TypedArray_with, 2, 0),
4347 JS_FS_END,
4348 };
4349
4350 /* static */ const JSFunctionSpec TypedArrayObject::staticFunctions[] = {
4351 JS_SELF_HOSTED_FN("from", "TypedArrayStaticFrom", 3, 0),
4352 JS_SELF_HOSTED_FN("of", "TypedArrayStaticOf", 0, 0),
4353 JS_FS_END,
4354 };
4355
4356 /* static */ const JSPropertySpec TypedArrayObject::staticProperties[] = {
4357 JS_SELF_HOSTED_SYM_GET(species, "$TypedArraySpecies", 0),
4358 JS_PS_END,
4359 };
4360
4361 static JSObject* CreateSharedTypedArrayPrototype(JSContext* cx,
4362 JSProtoKey key) {
4363 return GlobalObject::createBlankPrototype(
4364 cx, cx->global(), &TypedArrayObject::sharedTypedArrayPrototypeClass);
4365 }
4366
4367 static const ClassSpec TypedArrayObjectSharedTypedArrayPrototypeClassSpec = {
4368 GenericCreateConstructor<TypedArrayConstructor, 0, gc::AllocKind::FUNCTION>,
4369 CreateSharedTypedArrayPrototype,
4370 TypedArrayObject::staticFunctions,
4371 TypedArrayObject::staticProperties,
4372 TypedArrayObject::protoFunctions,
4373 TypedArrayObject::protoAccessors,
4374 nullptr,
4375 ClassSpec::DontDefineConstructor,
4376 };
4377
4378 /* static */ const JSClass TypedArrayObject::sharedTypedArrayPrototypeClass = {
4379 "TypedArrayPrototype",
4380 JSCLASS_HAS_CACHED_PROTO(JSProto_TypedArray),
4381 JS_NULL_CLASS_OPS,
4382 &TypedArrayObjectSharedTypedArrayPrototypeClassSpec,
4383 };
4384
4385 namespace {
4386
4387 // This default implementation is only valid for integer types less
4388 // than 32-bits in size.
4389 template <typename NativeType>
4390 bool TypedArrayObjectTemplate<NativeType>::getElementPure(
4391 TypedArrayObject* tarray, size_t index, Value* vp) {
4392 static_assert(sizeof(NativeType) < 4,
4393 "this method must only handle NativeType values that are "
4394 "always exact int32_t values");
4395
4396 *vp = Int32Value(getIndex(tarray, index));
4397 return true;
4398 }
4399
4400 // We need to specialize for floats and other integer types.
4401 template <>
4402 bool TypedArrayObjectTemplate<int32_t>::getElementPure(TypedArrayObject* tarray,
4403 size_t index,
4404 Value* vp) {
4405 *vp = Int32Value(getIndex(tarray, index));
4406 return true;
4407 }
4408
4409 template <>
4410 bool TypedArrayObjectTemplate<uint32_t>::getElementPure(
4411 TypedArrayObject* tarray, size_t index, Value* vp) {
4412 uint32_t val = getIndex(tarray, index);
4413 *vp = NumberValue(val);
4414 return true;
4415 }
4416
4417 template <>
4418 bool TypedArrayObjectTemplate<float16>::getElementPure(TypedArrayObject* tarray,
4419 size_t index,
4420 Value* vp) {
4421 float16 f16 = getIndex(tarray, index);
4422 /*
4423 * Doubles in typed arrays could be typed-punned arrays of integers. This
4424 * could allow user code to break the engine-wide invariant that only
4425 * canonical nans are stored into jsvals, which means user code could
4426 * confuse the engine into interpreting a double-typed jsval as an
4427 * object-typed jsval.
4428 *
4429 * This could be removed for platforms/compilers known to convert a 32-bit
4430 * non-canonical nan to a 64-bit canonical nan.
4431 */
4432 *vp = JS::CanonicalizedDoubleValue(static_cast<double>(f16));
4433 return true;
4434 }
4435
4436 template <>
4437 bool TypedArrayObjectTemplate<float>::getElementPure(TypedArrayObject* tarray,
4438 size_t index, Value* vp) {
4439 float val = getIndex(tarray, index);
4440 double dval = val;
4441
4442 /*
4443 * Doubles in typed arrays could be typed-punned arrays of integers. This
4444 * could allow user code to break the engine-wide invariant that only
4445 * canonical nans are stored into jsvals, which means user code could
4446 * confuse the engine into interpreting a double-typed jsval as an
4447 * object-typed jsval.
4448 *
4449 * This could be removed for platforms/compilers known to convert a 32-bit
4450 * non-canonical nan to a 64-bit canonical nan.
4451 */
4452 *vp = JS::CanonicalizedDoubleValue(dval);
4453 return true;
4454 }
4455
4456 template <>
4457 bool TypedArrayObjectTemplate<double>::getElementPure(TypedArrayObject* tarray,
4458 size_t index, Value* vp) {
4459 double val = getIndex(tarray, index);
4460
4461 /*
4462 * Doubles in typed arrays could be typed-punned arrays of integers. This
4463 * could allow user code to break the engine-wide invariant that only
4464 * canonical nans are stored into jsvals, which means user code could
4465 * confuse the engine into interpreting a double-typed jsval as an
4466 * object-typed jsval.
4467 */
4468 *vp = JS::CanonicalizedDoubleValue(val);
4469 return true;
4470 }
4471
4472 template <>
4473 bool TypedArrayObjectTemplate<int64_t>::getElementPure(TypedArrayObject* tarray,
4474 size_t index,
4475 Value* vp) {
4476 return false;
4477 }
4478
4479 template <>
4480 bool TypedArrayObjectTemplate<uint64_t>::getElementPure(
4481 TypedArrayObject* tarray, size_t index, Value* vp) {
4482 return false;
4483 }
4484 } /* anonymous namespace */
4485
4486 namespace {
4487
4488 template <typename NativeType>
4489 bool TypedArrayObjectTemplate<NativeType>::getElement(JSContext* cx,
4490 TypedArrayObject* tarray,
4491 size_t index,
4492 MutableHandleValue val) {
4493 MOZ_ALWAYS_TRUE(getElementPure(tarray, index, val.address()));
4494 return true;
4495 }
4496
4497 template <>
4498 bool TypedArrayObjectTemplate<int64_t>::getElement(JSContext* cx,
4499 TypedArrayObject* tarray,
4500 size_t index,
4501 MutableHandleValue val) {
4502 int64_t n = getIndex(tarray, index);
4503 BigInt* res = BigInt::createFromInt64(cx, n);
4504 if (!res) {
4505 return false;
4506 }
4507 val.setBigInt(res);
4508 return true;
4509 }
4510
4511 template <>
4512 bool TypedArrayObjectTemplate<uint64_t>::getElement(JSContext* cx,
4513 TypedArrayObject* tarray,
4514 size_t index,
4515 MutableHandleValue val) {
4516 uint64_t n = getIndex(tarray, index);
4517 BigInt* res = BigInt::createFromUint64(cx, n);
4518 if (!res) {
4519 return false;
4520 }
4521 val.setBigInt(res);
4522 return true;
4523 }
4524 } /* anonymous namespace */
4525
4526 namespace js {
4527
4528 template <>
4529 bool TypedArrayObject::getElement<CanGC>(JSContext* cx, size_t index,
4530 MutableHandleValue val) {
4531 switch (type()) {
4532 #define GET_ELEMENT(_, T, N) \
4533 case Scalar::N: \
4534 return TypedArrayObjectTemplate<T>::getElement(cx, this, index, val);
4535 JS_FOR_EACH_TYPED_ARRAY(GET_ELEMENT)
4536 #undef GET_ELEMENT
4537 case Scalar::MaxTypedArrayViewType:
4538 case Scalar::Int64:
4539 case Scalar::Simd128:
4540 break;
4541 }
4542
4543 MOZ_CRASH("Unknown TypedArray type");
4544 }
4545
4546 template <>
4547 bool TypedArrayObject::getElement<NoGC>(
4548 JSContext* cx, size_t index,
4549 typename MaybeRooted<Value, NoGC>::MutableHandleType vp) {
4550 return getElementPure(index, vp.address());
4551 }
4552
4553 } // namespace js
4554
4555 bool TypedArrayObject::getElementPure(size_t index, Value* vp) {
4556 switch (type()) {
4557 #define GET_ELEMENT_PURE(_, T, N) \
4558 case Scalar::N: \
4559 return TypedArrayObjectTemplate<T>::getElementPure(this, index, vp);
4560 JS_FOR_EACH_TYPED_ARRAY(GET_ELEMENT_PURE)
4561 #undef GET_ELEMENT
4562 case Scalar::MaxTypedArrayViewType:
4563 case Scalar::Int64:
4564 case Scalar::Simd128:
4565 break;
4566 }
4567
4568 MOZ_CRASH("Unknown TypedArray type");
4569 }
4570
4571 /* static */
4572 bool TypedArrayObject::getElements(JSContext* cx,
4573 Handle<TypedArrayObject*> tarray,
4574 size_t length, Value* vp) {
4575 MOZ_ASSERT(length <= tarray->length().valueOr(0));
4576 MOZ_ASSERT_IF(length > 0, !tarray->hasDetachedBuffer());
4577
4578 switch (tarray->type()) {
4579 #define GET_ELEMENTS(_, T, N) \
4580 case Scalar::N: \
4581 for (size_t i = 0; i < length; ++i, ++vp) { \
4582 if (!TypedArrayObjectTemplate<T>::getElement( \
4583 cx, tarray, i, MutableHandleValue::fromMarkedLocation(vp))) { \
4584 return false; \
4585 } \
4586 } \
4587 return true;
4588 JS_FOR_EACH_TYPED_ARRAY(GET_ELEMENTS)
4589 #undef GET_ELEMENTS
4590 case Scalar::MaxTypedArrayViewType:
4591 case Scalar::Int64:
4592 case Scalar::Simd128:
4593 break;
4594 }
4595
4596 MOZ_CRASH("Unknown TypedArray type");
4597 }
4598
4599 /***
4600 *** JS impl
4601 ***/
4602
4603 /*
4604 * TypedArrayObject boilerplate
4605 */
4606
4607 static const JSClassOps TypedArrayClassOps = {
4608 nullptr, // addProperty
4609 nullptr, // delProperty
4610 nullptr, // enumerate
4611 nullptr, // newEnumerate
4612 nullptr, // resolve
4613 nullptr, // mayResolve
4614 FixedLengthTypedArrayObject::finalize, // finalize
4615 nullptr, // call
4616 nullptr, // construct
4617 ArrayBufferViewObject::trace, // trace
4618 };
4619
4620 static const JSClassOps ResizableTypedArrayClassOps = {
4621 nullptr, // addProperty
4622 nullptr, // delProperty
4623 nullptr, // enumerate
4624 nullptr, // newEnumerate
4625 nullptr, // resolve
4626 nullptr, // mayResolve
4627 nullptr, // finalize
4628 nullptr, // call
4629 nullptr, // construct
4630 ArrayBufferViewObject::trace, // trace
4631 };
4632
4633 static const ClassExtension TypedArrayClassExtension = {
4634 FixedLengthTypedArrayObject::objectMoved, // objectMovedOp
4635 };
4636
4637 static const JSPropertySpec
4638 static_prototype_properties[Scalar::MaxTypedArrayViewType][2] = {
4639 #define IMPL_TYPED_ARRAY_PROPERTIES(ExternalType, NativeType, Name) \
4640 { \
4641 JS_INT32_PS("BYTES_PER_ELEMENT", \
4642 TypedArrayObjectTemplate<NativeType>::BYTES_PER_ELEMENT, \
4643 JSPROP_READONLY | JSPROP_PERMANENT), \
4644 JS_PS_END, \
4645 },
4646
4647 JS_FOR_EACH_TYPED_ARRAY(IMPL_TYPED_ARRAY_PROPERTIES)
4648 #undef IMPL_TYPED_ARRAY_PROPERTIES
4649 };
4650
4651 static const JSFunctionSpec uint8array_static_methods[] = {
4652 JS_FN("fromBase64", uint8array_fromBase64, 1, 0),
4653 JS_FN("fromHex", uint8array_fromHex, 1, 0),
4654 JS_FS_END,
4655 };
4656
4657 static const JSFunctionSpec uint8array_methods[] = {
4658 JS_FN("setFromBase64", uint8array_setFromBase64, 1, 0),
4659 JS_FN("setFromHex", uint8array_setFromHex, 1, 0),
4660 JS_FN("toBase64", uint8array_toBase64, 0, 0),
4661 JS_FN("toHex", uint8array_toHex, 0, 0),
4662 JS_FS_END,
4663 };
4664
4665 static constexpr const JSFunctionSpec* TypedArrayStaticMethods(
4666 Scalar::Type type) {
4667 if (type == Scalar::Uint8) {
4668 return uint8array_static_methods;
4669 }
4670 return nullptr;
4671 }
4672
4673 static constexpr const JSFunctionSpec* TypedArrayMethods(Scalar::Type type) {
4674 if (type == Scalar::Uint8) {
4675 return uint8array_methods;
4676 }
4677 return nullptr;
4678 }
4679
4680 static const ClassSpec
4681 TypedArrayObjectClassSpecs[Scalar::MaxTypedArrayViewType] = {
4682 #define IMPL_TYPED_ARRAY_CLASS_SPEC(ExternalType, NativeType, Name) \
4683 { \
4684 TypedArrayObjectTemplate<NativeType>::createConstructor, \
4685 TypedArrayObjectTemplate<NativeType>::createPrototype, \
4686 TypedArrayStaticMethods(Scalar::Type::Name), \
4687 static_prototype_properties[Scalar::Type::Name], \
4688 TypedArrayMethods(Scalar::Type::Name), \
4689 static_prototype_properties[Scalar::Type::Name], \
4690 nullptr, \
4691 JSProto_TypedArray, \
4692 },
4693
4694 JS_FOR_EACH_TYPED_ARRAY(IMPL_TYPED_ARRAY_CLASS_SPEC)
4695 #undef IMPL_TYPED_ARRAY_CLASS_SPEC
4696 };
4697
4698 // Class definitions for fixed length and resizable typed arrays. Stored into a
4699 // 2-dimensional array to ensure the classes are in contiguous memory.
4700 const JSClass TypedArrayObject::anyClasses[2][Scalar::MaxTypedArrayViewType] = {
4701 // Class definitions for fixed length typed arrays.
4702 {
4703 #define IMPL_TYPED_ARRAY_CLASS(ExternalType, NativeType, Name) \
4704 { \
4705 #Name "Array", \
4706 JSCLASS_HAS_RESERVED_SLOTS(TypedArrayObject::RESERVED_SLOTS) | \
4707 JSCLASS_HAS_CACHED_PROTO(JSProto_##Name##Array) | \
4708 JSCLASS_DELAY_METADATA_BUILDER | JSCLASS_SKIP_NURSERY_FINALIZE | \
4709 JSCLASS_BACKGROUND_FINALIZE, \
4710 &TypedArrayClassOps, \
4711 &TypedArrayObjectClassSpecs[Scalar::Type::Name], \
4712 &TypedArrayClassExtension, \
4713 },
4714
4715 JS_FOR_EACH_TYPED_ARRAY(IMPL_TYPED_ARRAY_CLASS)
4716 #undef IMPL_TYPED_ARRAY_CLASS
4717 },
4718
4719 // Class definitions for resizable typed arrays.
4720 {
4721 #define IMPL_TYPED_ARRAY_CLASS(ExternalType, NativeType, Name) \
4722 { \
4723 #Name "Array", \
4724 JSCLASS_HAS_RESERVED_SLOTS(ResizableTypedArrayObject::RESERVED_SLOTS) | \
4725 JSCLASS_HAS_CACHED_PROTO(JSProto_##Name##Array) | \
4726 JSCLASS_DELAY_METADATA_BUILDER, \
4727 &ResizableTypedArrayClassOps, \
4728 &TypedArrayObjectClassSpecs[Scalar::Type::Name], \
4729 JS_NULL_CLASS_EXT, \
4730 },
4731
4732 JS_FOR_EACH_TYPED_ARRAY(IMPL_TYPED_ARRAY_CLASS)
4733 #undef IMPL_TYPED_ARRAY_CLASS
4734 },
4735 };
4736
4737 // The various typed array prototypes are supposed to 1) be normal objects,
4738 // 2) stringify to "[object <name of constructor>]", and 3) (Gecko-specific)
4739 // be xrayable. The first and second requirements mandate (in the absence of
4740 // @@toStringTag) a custom class. The third requirement mandates that each
4741 // prototype's class have the relevant typed array's cached JSProtoKey in them.
4742 // Thus we need one class with cached prototype per kind of typed array, with a
4743 // delegated ClassSpec.
4744 //
4745 // Actually ({}).toString.call(Uint8Array.prototype) should throw, because
4746 // Uint8Array.prototype lacks the the typed array internal slots. (Same as
4747 // with %TypedArray%.prototype.) It's not clear this is desirable (see
4748 // above), but it's what we've always done, so keep doing it till we
4749 // implement @@toStringTag or ES6 changes.
4750 const JSClass TypedArrayObject::protoClasses[Scalar::MaxTypedArrayViewType] = {
4751 #define IMPL_TYPED_ARRAY_PROTO_CLASS(ExternalType, NativeType, Name) \
4752 { \
4753 #Name "Array.prototype", \
4754 JSCLASS_HAS_CACHED_PROTO(JSProto_##Name##Array), \
4755 JS_NULL_CLASS_OPS, \
4756 &TypedArrayObjectClassSpecs[Scalar::Type::Name], \
4757 },
4758
4759 JS_FOR_EACH_TYPED_ARRAY(IMPL_TYPED_ARRAY_PROTO_CLASS)
4760 #undef IMPL_TYPED_ARRAY_PROTO_CLASS
4761 };
4762
4763 /* static */
4764 bool TypedArrayObject::isOriginalLengthGetter(Native native) {
4765 return native == TypedArray_lengthGetter;
4766 }
4767
4768 /* static */
4769 bool TypedArrayObject::isOriginalByteOffsetGetter(Native native) {
4770 return native == TypedArray_byteOffsetGetter;
4771 }
4772
4773 /* static */
4774 bool TypedArrayObject::isOriginalByteLengthGetter(Native native) {
4775 return native == TypedArray_byteLengthGetter;
4776 }
4777
4778 bool js::IsTypedArrayConstructor(const JSObject* obj) {
4779 #define CHECK_TYPED_ARRAY_CONSTRUCTOR(_, T, N) \
4780 if (IsNativeFunction(obj, TypedArrayObjectTemplate<T>::class_constructor)) { \
4781 return true; \
4782 }
4783 JS_FOR_EACH_TYPED_ARRAY(CHECK_TYPED_ARRAY_CONSTRUCTOR)
4784 #undef CHECK_TYPED_ARRAY_CONSTRUCTOR
4785 return false;
4786 }
4787
4788 bool js::IsTypedArrayConstructor(HandleValue v, Scalar::Type type) {
4789 return IsNativeFunction(v, TypedArrayConstructorNative(type));
4790 }
4791
4792 JSNative js::TypedArrayConstructorNative(Scalar::Type type) {
4793 #define TYPED_ARRAY_CONSTRUCTOR_NATIVE(_, T, N) \
4794 if (type == Scalar::N) { \
4795 return TypedArrayObjectTemplate<T>::class_constructor; \
4796 }
4797 JS_FOR_EACH_TYPED_ARRAY(TYPED_ARRAY_CONSTRUCTOR_NATIVE)
4798 #undef TYPED_ARRAY_CONSTRUCTOR_NATIVE
4799
4800 MOZ_CRASH("unexpected typed array type");
4801 }
4802
4803 bool js::IsBufferSource(JSContext* cx, JSObject* object, bool allowShared,
4804 bool allowResizable, SharedMem<uint8_t*>* dataPointer,
4805 size_t* byteLength) {
4806 if (object->is<TypedArrayObject>()) {
4807 Rooted<TypedArrayObject*> view(cx, &object->as<TypedArrayObject>());
4808 if (!allowShared && view->isSharedMemory()) {
4809 return false;
4810 }
4811 if (!allowResizable && JS::IsResizableArrayBufferView(object)) {
4812 return false;
4813 }
4814 // Ensure the pointer we pass out won't move as long as you properly root
4815 // it. This is only needed for non-shared memory.
4816 if (!view->isSharedMemory() &&
4817 !ArrayBufferViewObject::ensureNonInline(cx, view)) {
4818 return false;
4819 }
4820 *dataPointer = view->dataPointerEither().cast<uint8_t*>();
4821 *byteLength = view->byteLength().valueOr(0);
4822 return true;
4823 }
4824
4825 if (object->is<DataViewObject>()) {
4826 Rooted<DataViewObject*> view(cx, &object->as<DataViewObject>());
4827 if (!allowShared && view->isSharedMemory()) {
4828 return false;
4829 }
4830 if (!allowResizable && JS::IsResizableArrayBufferView(object)) {
4831 return false;
4832 }
4833 // Ensure the pointer we pass out won't move as long as you properly root
4834 // it. This is only needed for non-shared memory.
4835 if (!view->isSharedMemory() &&
4836 !ArrayBufferViewObject::ensureNonInline(cx, view)) {
4837 return false;
4838 }
4839 *dataPointer = view->dataPointerEither().cast<uint8_t*>();
4840 *byteLength = view->byteLength().valueOr(0);
4841 return true;
4842 }
4843
4844 if (object->is<ArrayBufferObject>()) {
4845 Rooted<ArrayBufferObject*> buffer(cx, &object->as<ArrayBufferObject>());
4846 if (!allowResizable && buffer->isResizable()) {
4847 return false;
4848 }
4849 // Ensure the pointer we pass out won't move as long as you properly root
4850 // it.
4851 if (!ArrayBufferObject::ensureNonInline(cx, buffer)) {
4852 return false;
4853 }
4854 *dataPointer = buffer->dataPointerEither();
4855 *byteLength = buffer->byteLength();
4856 return true;
4857 }
4858
4859 if (allowShared && object->is<SharedArrayBufferObject>()) {
4860 SharedArrayBufferObject& buffer = object->as<SharedArrayBufferObject>();
4861 if (!allowResizable && buffer.isResizable()) {
4862 return false;
4863 }
4864 // This will always be locked and out of line.
4865 *dataPointer = buffer.dataPointerShared();
4866 *byteLength = buffer.byteLength();
4867 return true;
4868 }
4869
4870 return false;
4871 }
4872
4873 template <typename CharT>
4874 static inline bool StringIsInfinity(mozilla::Range<const CharT> s) {
4875 static constexpr std::string_view Infinity = "Infinity";
4876
4877 // Compilers optimize this to one |cmp| instruction on x64 resp. two for x86,
4878 // when the input is a Latin-1 string, because the string "Infinity" is
4879 // exactly eight characters long, so it can be represented as a single uint64
4880 // value.
4881 return s.length() == Infinity.length() &&
4882 EqualChars(s.begin().get(), Infinity.data(), Infinity.length());
4883 }
4884
4885 template <typename CharT>
4886 static inline bool StringIsNaN(mozilla::Range<const CharT> s) {
4887 static constexpr std::string_view NaN = "NaN";
4888
4889 // "NaN" is not as nicely optimizable as "Infinity", but oh well.
4890 return s.length() == NaN.length() &&
4891 EqualChars(s.begin().get(), NaN.data(), NaN.length());
4892 }
4893
4894 template <typename CharT>
4895 static mozilla::Maybe<uint64_t> StringToTypedArrayIndexSlow(
4896 mozilla::Range<const CharT> s) {
4897 const mozilla::RangedPtr<const CharT> start = s.begin();
4898 const mozilla::RangedPtr<const CharT> end = s.end();
4899
4900 const CharT* actualEnd;
4901 double result = js_strtod(start.get(), end.get(), &actualEnd);
4902
4903 // The complete string must have been parsed.
4904 if (actualEnd != end.get()) {
4905 return mozilla::Nothing();
4906 }
4907
4908 // Now convert it back to a string.
4909 ToCStringBuf cbuf;
4910 size_t cstrlen;
4911 const char* cstr = js::NumberToCString(&cbuf, result, &cstrlen);
4912 MOZ_ASSERT(cstr);
4913
4914 // Both strings must be equal for a canonical numeric index string.
4915 if (s.length() != cstrlen || !EqualChars(start.get(), cstr, cstrlen)) {
4916 return mozilla::Nothing();
4917 }
4918
4919 // Directly perform IsInteger() check and encode negative and non-integer
4920 // indices as OOB.
4921 // See 9.4.5.2 [[HasProperty]], steps 3.b.iii and 3.b.v.
4922 // See 9.4.5.3 [[DefineOwnProperty]], steps 3.b.i and 3.b.iii.
4923 // See 9.4.5.8 IntegerIndexedElementGet, steps 5 and 8.
4924 // See 9.4.5.9 IntegerIndexedElementSet, steps 6 and 9.
4925 if (result < 0 || !IsInteger(result)) {
4926 return mozilla::Some(UINT64_MAX);
4927 }
4928
4929 // Anything equals-or-larger than 2^53 is definitely OOB, encode it
4930 // accordingly so that the cast to uint64_t is well defined.
4931 if (result >= DOUBLE_INTEGRAL_PRECISION_LIMIT) {
4932 return mozilla::Some(UINT64_MAX);
4933 }
4934
4935 // The string is an actual canonical numeric index.
4936 return mozilla::Some(result);
4937 }
4938
4939 template <typename CharT>
4940 mozilla::Maybe<uint64_t> js::StringToTypedArrayIndex(
4941 mozilla::Range<const CharT> s) {
4942 mozilla::RangedPtr<const CharT> cp = s.begin();
4943 const mozilla::RangedPtr<const CharT> end = s.end();
4944
4945 MOZ_ASSERT(cp < end, "caller must check for empty strings");
4946
4947 bool negative = false;
4948 if (*cp == '-') {
4949 negative = true;
4950 if (++cp == end) {
4951 return mozilla::Nothing();
4952 }
4953 }
4954
4955 if (!IsAsciiDigit(*cp)) {
4956 // Check for "NaN", "Infinity", or "-Infinity".
4957 if ((!negative && StringIsNaN<CharT>({cp, end})) ||
4958 StringIsInfinity<CharT>({cp, end})) {
4959 return mozilla::Some(UINT64_MAX);
4960 }
4961 return mozilla::Nothing();
4962 }
4963
4964 uint32_t digit = AsciiDigitToNumber(*cp++);
4965
4966 // Don't allow leading zeros.
4967 if (digit == 0 && cp != end) {
4968 // The string may be of the form "0.xyz". The exponent form isn't possible
4969 // when the string starts with "0".
4970 if (*cp == '.') {
4971 return StringToTypedArrayIndexSlow(s);
4972 }
4973 return mozilla::Nothing();
4974 }
4975
4976 uint64_t index = digit;
4977
4978 for (; cp < end; cp++) {
4979 if (!IsAsciiDigit(*cp)) {
4980 // Take the slow path when the string has fractional parts or an exponent.
4981 if (*cp == '.' || *cp == 'e') {
4982 return StringToTypedArrayIndexSlow(s);
4983 }
4984 return mozilla::Nothing();
4985 }
4986
4987 digit = AsciiDigitToNumber(*cp);
4988
4989 static_assert(
4990 uint64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT) < (UINT64_MAX - 10) / 10,
4991 "2^53 is way below UINT64_MAX, so |10 * index + digit| can't overflow");
4992
4993 index = 10 * index + digit;
4994
4995 // Also take the slow path when the string is larger-or-equals 2^53.
4996 if (index >= uint64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT)) {
4997 return StringToTypedArrayIndexSlow(s);
4998 }
4999 }
5000
5001 if (negative) {
5002 return mozilla::Some(UINT64_MAX);
5003 }
5004 return mozilla::Some(index);
5005 }
5006
5007 template mozilla::Maybe<uint64_t> js::StringToTypedArrayIndex(
5008 mozilla::Range<const char16_t> s);
5009
5010 template mozilla::Maybe<uint64_t> js::StringToTypedArrayIndex(
5011 mozilla::Range<const Latin1Char> s);
5012
5013 bool js::SetTypedArrayElement(JSContext* cx, Handle<TypedArrayObject*> obj,
5014 uint64_t index, HandleValue v,
5015 ObjectOpResult& result) {
5016 switch (obj->type()) {
5017 #define SET_TYPED_ARRAY_ELEMENT(_, T, N) \
5018 case Scalar::N: \
5019 return TypedArrayObjectTemplate<T>::setElement(cx, obj, index, v, result);
5020 JS_FOR_EACH_TYPED_ARRAY(SET_TYPED_ARRAY_ELEMENT)
5021 #undef SET_TYPED_ARRAY_ELEMENT
5022 case Scalar::MaxTypedArrayViewType:
5023 case Scalar::Int64:
5024 case Scalar::Simd128:
5025 break;
5026 }
5027
5028 MOZ_CRASH("Unsupported TypedArray type");
5029 }
5030
5031 // ES2025 draft rev ac21460fedf4b926520b06c9820bdbebad596a8b
5032 // 10.4.5.3 [[DefineOwnProperty]], step 1.b.
5033 bool js::DefineTypedArrayElement(JSContext* cx, Handle<TypedArrayObject*> obj,
5034 uint64_t index,
5035 Handle<PropertyDescriptor> desc,
5036 ObjectOpResult& result) {
5037 // These are all substeps of 1.b.
5038
5039 // Step i.
5040 if (index >= obj->length().valueOr(0)) {
5041 if (obj->hasDetachedBuffer()) {
5042 return result.fail(JSMSG_TYPED_ARRAY_DETACHED);
5043 }
5044 return result.fail(JSMSG_DEFINE_BAD_INDEX);
5045 }
5046
5047 // Step ii.
5048 if (desc.hasConfigurable() && !desc.configurable()) {
5049 return result.fail(JSMSG_CANT_REDEFINE_PROP);
5050 }
5051
5052 // Step iii.
5053 if (desc.hasEnumerable() && !desc.enumerable()) {
5054 return result.fail(JSMSG_CANT_REDEFINE_PROP);
5055 }
5056
5057 // Step iv.
5058 if (desc.isAccessorDescriptor()) {
5059 return result.fail(JSMSG_CANT_REDEFINE_PROP);
5060 }
5061
5062 // Step v.
5063 if (desc.hasWritable() && !desc.writable()) {
5064 return result.fail(JSMSG_CANT_REDEFINE_PROP);
5065 }
5066
5067 // Step vi.
5068 if (desc.hasValue()) {
5069 return SetTypedArrayElement(cx, obj, index, desc.value(), result);
5070 }
5071
5072 // Step vii.
5073 return result.succeed();
5074 }
5075
5076 template <typename T, typename U>
5077 static constexpr typename std::enable_if_t<
5078 std::numeric_limits<T>::is_integer && !std::numeric_limits<T>::is_signed, U>
5079 UnsignedSortValue(U val) {
5080 return val;
5081 }
5082
5083 template <typename T, typename U>
5084 static constexpr typename std::enable_if_t<
5085 std::numeric_limits<T>::is_integer && std::numeric_limits<T>::is_signed, U>
5086 UnsignedSortValue(U val) {
5087 // Flip sign bit.
5088 return val ^ static_cast<U>(std::numeric_limits<T>::min());
5089 }
5090
5091 template <typename T, typename UnsignedT>
5092 static constexpr
5093 typename std::enable_if_t<!std::numeric_limits<T>::is_integer, UnsignedT>
5094 UnsignedSortValue(UnsignedT val) {
5095 // Flip sign bit for positive numbers; flip all bits for negative numbers,
5096 // except negative NaNs.
5097 using FloatingPoint = mozilla::FloatingPoint<T>;
5098 static_assert(std::is_same_v<typename FloatingPoint::Bits, UnsignedT>,
5099 "FloatingPoint::Bits matches the unsigned int representation");
5100
5101 // FF80'0000 is negative infinity, (FF80'0000, FFFF'FFFF] are all NaNs with
5102 // the sign-bit set (and the equivalent holds for double and float16 values).
5103 // So any value larger than negative infinity is a negative NaN.
5104 constexpr UnsignedT NegativeInfinity = mozilla::InfinityBits<T, 1>::value;
5105 if (val > NegativeInfinity) {
5106 return val;
5107 }
5108 if (val & FloatingPoint::kSignBit) {
5109 return ~val;
5110 }
5111 return val ^ FloatingPoint::kSignBit;
5112 }
5113
5114 template <typename T, typename U>
5115 static constexpr
5116 typename std::enable_if_t<std::numeric_limits<T>::is_integer, U>
5117 ToCountingSortKey(U val) {
5118 return UnsignedSortValue<T, U>(val);
5119 }
5120
5121 template <typename T, typename U>
5122 static constexpr
5123 typename std::enable_if_t<std::numeric_limits<T>::is_integer, U>
5124 FromCountingSortKey(U val) {
5125 // ToCountingSortKey for integers is a self-inverse function.
5126 return ToCountingSortKey<T, U>(val);
5127 }
5128
5129 /**
5130 * UnsignedSortValue for floating point values isn't reversible, so we use a
5131 * different implementation for counting sort to keep NaN payloads unmodified
5132 * for consistency with TypedArrayRadixSort and TypedArrayStdSort.
5133 *
5134 * Mapping overview:
5135 * - Largest -NaN = FFFF -> FFFF
5136 * - Smallest -NaN = FC01 -> FC01
5137 * - Negative infinity = FC00 -> 0000
5138 * - Negative zero = 8000 -> 7C00
5139 * - Positive zero = 0000 -> 7C01
5140 * - Positive infinity = 7C00 -> F801
5141 * - Smallest +NaN = 7C01 -> F802
5142 * - Largest +NaN = 7FFF -> FC00
5143 */
5144 template <typename T, typename U>
5145 static constexpr typename std::enable_if_t<std::is_same_v<T, js::float16>, U>
5146 ToCountingSortKey(U val) {
5147 using FloatingPoint = mozilla::FloatingPoint<T>;
5148 static_assert(std::is_same_v<typename FloatingPoint::Bits, U>,
5149 "FloatingPoint::Bits matches the unsigned int representation");
5150
5151 constexpr U PositiveInfinity = mozilla::InfinityBits<T, 0>::value;
5152 constexpr U NegativeInfinity = mozilla::InfinityBits<T, 1>::value;
5153
5154 // Any value larger than negative infinity is a negative NaN. Place those at
5155 // the very end.
5156 if (val > NegativeInfinity) {
5157 return val;
5158 }
5159
5160 // Map negative values, starting at negative infinity which is mapped to zero.
5161 if (val & FloatingPoint::kSignBit) {
5162 return NegativeInfinity - val;
5163 }
5164
5165 // Map positive values right after the last negative value (negative zero).
5166 return val + (PositiveInfinity + 1);
5167 }
5168
5169 /**
5170 * Reverse the mapping from ToCountingSortKey.
5171 */
5172 template <typename T, typename U>
5173 static constexpr typename std::enable_if_t<std::is_same_v<T, js::float16>, U>
5174 FromCountingSortKey(U val) {
5175 using FloatingPoint = mozilla::FloatingPoint<T>;
5176 static_assert(std::is_same_v<typename FloatingPoint::Bits, U>,
5177 "FloatingPoint::Bits matches the unsigned int representation");
5178
5179 constexpr U PositiveInfinity = mozilla::InfinityBits<T, 0>::value;
5180 constexpr U NegativeInfinity = mozilla::InfinityBits<T, 1>::value;
5181
5182 // Negative NaN are unchanged.
5183 if (val > NegativeInfinity) {
5184 return val;
5185 }
5186
5187 // Any value larger than 0x7C00 was a positive number, including positive NaN.
5188 if (val > PositiveInfinity) {
5189 return val - (PositiveInfinity + 1);
5190 }
5191
5192 // Any other value was a negative number, excluding negative NaN.
5193 return NegativeInfinity - val;
5194 }
5195
5196 template <typename T>
5197 static typename std::enable_if_t<std::numeric_limits<T>::is_integer>
5198 TypedArrayStdSort(SharedMem<void*> data, size_t length) {
5199 T* unwrapped = data.cast<T*>().unwrapUnshared();
5200 std::sort(unwrapped, unwrapped + length);
5201 }
5202
5203 template <typename T>
5204 static typename std::enable_if_t<!std::numeric_limits<T>::is_integer>
5205 TypedArrayStdSort(SharedMem<void*> data, size_t length) {
5206 // Sort on the unsigned representation for performance reasons.
5207 using UnsignedT =
5208 typename mozilla::UnsignedStdintTypeForSize<sizeof(T)>::Type;
5209 UnsignedT* unwrapped = data.cast<UnsignedT*>().unwrapUnshared();
5210 std::sort(unwrapped, unwrapped + length, [](UnsignedT x, UnsignedT y) {
5211 constexpr auto SortValue = UnsignedSortValue<T, UnsignedT>;
5212 return SortValue(x) < SortValue(y);
5213 });
5214 }
5215
5216 template <typename T, typename Ops>
5217 static typename std::enable_if_t<std::is_same_v<Ops, UnsharedOps>, bool>
5218 TypedArrayStdSort(JSContext* cx, TypedArrayObject* typedArray, size_t length) {
5219 TypedArrayStdSort<T>(typedArray->dataPointerEither(), length);
5220 return true;
5221 }
5222
5223 template <typename T, typename Ops>
5224 static typename std::enable_if_t<std::is_same_v<Ops, SharedOps>, bool>
5225 TypedArrayStdSort(JSContext* cx, TypedArrayObject* typedArray, size_t length) {
5226 // Always create a copy when sorting shared memory backed typed arrays to
5227 // ensure concurrent write accesses doesn't lead to UB when calling std::sort.
5228 auto ptr = cx->make_pod_array<T>(length);
5229 if (!ptr) {
5230 return false;
5231 }
5232 SharedMem<T*> unshared = SharedMem<T*>::unshared(ptr.get());
5233 SharedMem<T*> data = typedArray->dataPointerShared().cast<T*>();
5234
5235 Ops::podCopy(unshared, data, length);
5236
5237 TypedArrayStdSort<T>(unshared.template cast<void*>(), length);
5238
5239 Ops::podCopy(data, unshared, length);
5240
5241 return true;
5242 }
5243
5244 template <typename T, typename Ops>
5245 static bool TypedArrayCountingSort(JSContext* cx, TypedArrayObject* typedArray,
5246 size_t length) {
5247 // Determined by performance testing.
5248 if (length <= 64) {
5249 return TypedArrayStdSort<T, Ops>(cx, typedArray, length);
5250 }
5251
5252 // Map signed values onto the unsigned range when storing in buffer.
5253 using UnsignedT =
5254 typename mozilla::UnsignedStdintTypeForSize<sizeof(T)>::Type;
5255
5256 constexpr size_t InlineStorage = sizeof(T) == 1 ? 256 : 0;
5257 Vector<size_t, InlineStorage> buffer(cx);
5258 if (!buffer.resize(size_t(std::numeric_limits<UnsignedT>::max()) + 1)) {
5259 return false;
5260 }
5261
5262 SharedMem<UnsignedT*> data =
5263 typedArray->dataPointerEither().cast<UnsignedT*>();
5264
5265 // Populate the buffer.
5266 for (size_t i = 0; i < length; i++) {
5267 UnsignedT val = ToCountingSortKey<T, UnsignedT>(Ops::load(data + i));
5268 buffer[val]++;
5269 }
5270
5271 // Traverse the buffer in order and write back elements to array.
5272 UnsignedT val = UnsignedT(-1); // intentional overflow on first increment
5273 for (size_t i = 0; i < length;) {
5274 size_t j;
5275 do {
5276 j = buffer[++val];
5277 } while (j == 0);
5278
5279 // Invariant: sum(buffer[val:]) == length-i
5280 MOZ_ASSERT(j <= length - i);
5281
5282 for (; j > 0; j--) {
5283 Ops::store(data + i++, FromCountingSortKey<T, UnsignedT>(val));
5284 }
5285 }
5286
5287 return true;
5288 }
5289
5290 template <typename T, typename U, typename Ops>
5291 static void SortByColumn(SharedMem<U*> data, size_t length, SharedMem<U*> aux,
5292 uint8_t col) {
5293 static_assert(std::is_unsigned_v<U>, "SortByColumn sorts on unsigned values");
5294 static_assert(std::is_same_v<Ops, UnsharedOps>,
5295 "SortByColumn only works on unshared data");
5296
5297 // |counts| is used to compute the starting index position for each key.
5298 // Letting counts[0] always be 0, simplifies the transform step below.
5299 // Example:
5300 //
5301 // Computing frequency counts for the input [1 2 1] gives:
5302 // 0 1 2 3 ... (keys)
5303 // 0 0 2 1 (frequencies)
5304 //
5305 // Transforming frequencies to indexes gives:
5306 // 0 1 2 3 ... (keys)
5307 // 0 0 2 3 (indexes)
5308
5309 constexpr size_t R = 256;
5310
5311 // Initialize all entries to zero.
5312 size_t counts[R + 1] = {};
5313
5314 const auto ByteAtCol = [col](U x) {
5315 U y = UnsignedSortValue<T, U>(x);
5316 return static_cast<uint8_t>(y >> (col * 8));
5317 };
5318
5319 // Compute frequency counts.
5320 for (size_t i = 0; i < length; i++) {
5321 U val = Ops::load(data + i);
5322 uint8_t b = ByteAtCol(val);
5323 counts[b + 1]++;
5324 }
5325
5326 // Transform counts to indices.
5327 std::partial_sum(std::begin(counts), std::end(counts), std::begin(counts));
5328
5329 // Distribute
5330 for (size_t i = 0; i < length; i++) {
5331 U val = Ops::load(data + i);
5332 uint8_t b = ByteAtCol(val);
5333 size_t j = counts[b]++;
5334 MOZ_ASSERT(j < length,
5335 "index is in bounds when |data| can't be modified concurrently");
5336 UnsharedOps::store(aux + j, val);
5337 }
5338
5339 // Copy back
5340 Ops::podCopy(data, aux, length);
5341 }
5342
5343 template <typename T, typename Ops>
5344 static bool TypedArrayRadixSort(JSContext* cx, TypedArrayObject* typedArray,
5345 size_t length) {
5346 // Determined by performance testing.
5347 constexpr size_t StdSortMinCutoff = sizeof(T) == 2 ? 64 : 256;
5348
5349 // Radix sort uses O(n) additional space, limit this space to 64 MB.
5350 constexpr size_t StdSortMaxCutoff = (64 * 1024 * 1024) / sizeof(T);
5351
5352 if constexpr (sizeof(T) == 2) {
5353 // Radix sort uses |n * sizeof(T)| additional space, whereas counting sort
5354 // uses |65536 * sizeof(size_t)| additional space. When the additional
5355 // space needed for radix sort exceeds the space needed for counting sort,
5356 // switch over to counting sort.
5357 //
5358 // It's faster to switch slightly earlier, so subtract a constant from the
5359 // exact value. This constant (2048) was determined by performance testing.
5360 constexpr size_t CountingSortMaxCutoff =
5361 65536 * (sizeof(size_t) / sizeof(T)) - 2048;
5362 static_assert(CountingSortMaxCutoff < StdSortMaxCutoff);
5363
5364 if (length >= CountingSortMaxCutoff) {
5365 return TypedArrayCountingSort<T, Ops>(cx, typedArray, length);
5366 }
5367 }
5368
5369 if (length <= StdSortMinCutoff || length >= StdSortMaxCutoff) {
5370 return TypedArrayStdSort<T, Ops>(cx, typedArray, length);
5371 }
5372
5373 using UnsignedT =
5374 typename mozilla::UnsignedStdintTypeForSize<sizeof(T)>::Type;
5375
5376 auto ptr = cx->make_zeroed_pod_array<UnsignedT>(length);
5377 if (!ptr) {
5378 return false;
5379 }
5380 SharedMem<UnsignedT*> aux = SharedMem<UnsignedT*>::unshared(ptr.get());
5381
5382 SharedMem<UnsignedT*> data =
5383 typedArray->dataPointerEither().cast<UnsignedT*>();
5384
5385 // Always create a copy when sorting shared memory backed typed arrays to
5386 // ensure concurrent write accesses don't lead to computing bad indices.
5387 SharedMem<UnsignedT*> unshared;
5388 SharedMem<UnsignedT*> shared;
5389 UniquePtr<UnsignedT[], JS::FreePolicy> ptrUnshared;
5390 if constexpr (std::is_same_v<Ops, SharedOps>) {
5391 ptrUnshared = cx->make_pod_array<UnsignedT>(length);
5392 if (!ptrUnshared) {
5393 return false;
5394 }
5395 unshared = SharedMem<UnsignedT*>::unshared(ptrUnshared.get());
5396 shared = data;
5397
5398 Ops::podCopy(unshared, shared, length);
5399
5400 data = unshared;
5401 }
5402
5403 for (uint8_t col = 0; col < sizeof(UnsignedT); col++) {
5404 SortByColumn<T, UnsignedT, UnsharedOps>(data, length, aux, col);
5405 }
5406
5407 if constexpr (std::is_same_v<Ops, SharedOps>) {
5408 Ops::podCopy(shared, unshared, length);
5409 }
5410
5411 return true;
5412 }
5413
5414 using TypedArraySortFn = bool (*)(JSContext*, TypedArrayObject*, size_t length);
5415
5416 template <typename T, typename Ops>
5417 static constexpr typename std::enable_if_t<sizeof(T) == 1, TypedArraySortFn>
5418 TypedArraySort() {
5419 return TypedArrayCountingSort<T, Ops>;
5420 }
5421
5422 template <typename T, typename Ops>
5423 static constexpr typename std::enable_if_t<sizeof(T) == 2 || sizeof(T) == 4,
5424 TypedArraySortFn>
5425 TypedArraySort() {
5426 return TypedArrayRadixSort<T, Ops>;
5427 }
5428
5429 template <typename T, typename Ops>
5430 static constexpr typename std::enable_if_t<sizeof(T) == 8, TypedArraySortFn>
5431 TypedArraySort() {
5432 return TypedArrayStdSort<T, Ops>;
5433 }
5434
5435 static bool TypedArraySortWithoutComparator(JSContext* cx,
5436 TypedArrayObject* typedArray,
5437 size_t len) {
5438 bool isShared = typedArray->isSharedMemory();
5439 switch (typedArray->type()) {
5440 #define SORT(_, T, N) \
5441 case Scalar::N: \
5442 if (isShared) { \
5443 if (!TypedArraySort<T, SharedOps>()(cx, typedArray, len)) { \
5444 return false; \
5445 } \
5446 } else { \
5447 if (!TypedArraySort<T, UnsharedOps>()(cx, typedArray, len)) { \
5448 return false; \
5449 } \
5450 } \
5451 break;
5452 JS_FOR_EACH_TYPED_ARRAY(SORT)
5453 #undef SORT
5454 default:
5455 MOZ_CRASH("Unsupported TypedArray type");
5456 }
5457 return true;
5458 }
5459
5460 static MOZ_ALWAYS_INLINE bool TypedArraySortPrologue(JSContext* cx,
5461 Handle<Value> thisv,
5462 Handle<Value> comparefn,
5463 ArraySortData* d,
5464 bool* done) {
5465 // https://tc39.es/ecma262/#sec-%typedarray%.prototype.sort
5466 // 23.2.3.29 %TypedArray%.prototype.sort ( comparefn )
5467
5468 // Step 1.
5469 if (MOZ_UNLIKELY(!comparefn.isUndefined() && !IsCallable(comparefn))) {
5470 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5471 JSMSG_BAD_TYPEDARRAY_SORT_ARG);
5472 return false;
5473 }
5474
5475 // Steps 2-3.
5476 Rooted<TypedArrayObject*> tarrayUnwrapped(
5477 cx, UnwrapAndTypeCheckValue<TypedArrayObject>(cx, thisv, [cx, &thisv]() {
5478 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
5479 JSMSG_INCOMPATIBLE_METHOD, "sort", "method",
5480 InformalValueTypeName(thisv));
5481 }));
5482 if (!tarrayUnwrapped) {
5483 return false;
5484 }
5485 auto arrayLength = tarrayUnwrapped->length();
5486 if (!arrayLength) {
5487 ReportOutOfBounds(cx, tarrayUnwrapped);
5488 return false;
5489 }
5490
5491 // Step 4.
5492 size_t len = *arrayLength;
5493
5494 // Arrays with less than two elements remain unchanged when sorted.
5495 if (len <= 1) {
5496 d->setReturnValue(&thisv.toObject());
5497 *done = true;
5498 return true;
5499 }
5500
5501 // Fast path for sorting without a comparator.
5502 if (comparefn.isUndefined()) {
5503 if (!TypedArraySortWithoutComparator(cx, tarrayUnwrapped, len)) {
5504 return false;
5505 }
5506 d->setReturnValue(&thisv.toObject());
5507 *done = true;
5508 return true;
5509 }
5510
5511 // Ensure length * 2 (used below) doesn't overflow UINT32_MAX.
5512 if (MOZ_UNLIKELY(len > UINT32_MAX / 2)) {
5513 ReportAllocationOverflow(cx);
5514 return false;
5515 }
5516
5517 // Merge sort requires extra scratch space.
5518 bool needsScratchSpace = len > ArraySortData::InsertionSortMaxLength;
5519
5520 Rooted<ArraySortData::ValueVector> vec(cx);
5521 if (MOZ_UNLIKELY(!vec.resize(needsScratchSpace ? (2 * len) : len))) {
5522 ReportOutOfMemory(cx);
5523 return false;
5524 }
5525
5526 // Copy elements to JS Value vector.
5527 if (!TypedArrayObject::getElements(cx, tarrayUnwrapped, len, vec.begin())) {
5528 return false;
5529 }
5530
5531 d->init(&thisv.toObject(), &comparefn.toObject(), std::move(vec.get()), len,
5532 len);
5533
5534 // Continue in ArraySortData::sortTypedArrayWithComparator.
5535 MOZ_ASSERT(!*done);
5536 return true;
5537 }
5538
5539 // Copies sorted elements back to the typed array.
5540 template <typename T, typename Ops>
5541 static void StoreSortedElements(TypedArrayObject* tarray, Value* elements,
5542 size_t len) {
5543 SharedMem<T*> data = tarray->dataPointerEither().cast<T*>();
5544 for (size_t i = 0; i < len; i++) {
5545 T val;
5546 if constexpr (!std::numeric_limits<T>::is_integer) {
5547 val = elements[i].toDouble();
5548 } else if constexpr (std::is_same_v<T, int64_t>) {
5549 val = BigInt::toInt64(elements[i].toBigInt());
5550 } else if constexpr (std::is_same_v<T, uint64_t>) {
5551 val = BigInt::toUint64(elements[i].toBigInt());
5552 } else if constexpr (std::is_same_v<T, uint32_t>) {
5553 val = uint32_t(elements[i].toNumber());
5554 } else {
5555 val = elements[i].toInt32();
5556 }
5557 Ops::store(data + i, val);
5558 }
5559 }
5560
5561 // static
5562 ArraySortResult ArraySortData::sortTypedArrayWithComparator(ArraySortData* d) {
5563 ArraySortResult result =
5564 sortWithComparatorShared<ArraySortKind::TypedArray>(d);
5565 if (result != ArraySortResult::Done) {
5566 return result;
5567 }
5568
5569 // Copy sorted elements to the typed array.
5570 JSContext* cx = d->cx();
5571 Rooted<TypedArrayObject*> tarrayUnwrapped(
5572 cx, UnwrapAndDowncastObject<TypedArrayObject>(cx, d->obj_));
5573 if (MOZ_UNLIKELY(!tarrayUnwrapped)) {
5574 return ArraySortResult::Failure;
5575 }
5576
5577 auto length = tarrayUnwrapped->length();
5578 if (MOZ_LIKELY(length)) {
5579 size_t len = std::min<size_t>(*length, d->denseLen);
5580 Value* elements = d->list;
5581 bool isShared = tarrayUnwrapped->isSharedMemory();
5582 switch (tarrayUnwrapped->type()) {
5583 #define SORT(_, T, N) \
5584 case Scalar::N: \
5585 if (isShared) { \
5586 StoreSortedElements<T, SharedOps>(tarrayUnwrapped, elements, len); \
5587 } else { \
5588 StoreSortedElements<T, UnsharedOps>(tarrayUnwrapped, elements, len); \
5589 } \
5590 break;
5591 JS_FOR_EACH_TYPED_ARRAY(SORT)
5592 #undef SORT
5593 default:
5594 MOZ_CRASH("Unsupported TypedArray type");
5595 }
5596 }
5597
5598 d->freeMallocData();
5599 d->setReturnValue(d->obj_);
5600 return ArraySortResult::Done;
5601 }
5602
5603 // https://tc39.es/ecma262/#sec-%typedarray%.prototype.sort
5604 // 23.2.3.29 %TypedArray%.prototype.sort ( comparefn )
5605 // static
5606 bool TypedArrayObject::sort(JSContext* cx, unsigned argc, Value* vp) {
5607 AutoJSMethodProfilerEntry pseudoFrame(cx, "[TypedArray].prototype", "sort");
5608 CallArgs args = CallArgsFromVp(argc, vp);
5609
5610 // If we have a comparator argument, use the JIT trampoline implementation
5611 // instead. This avoids a performance cliff (especially with large arrays)
5612 // because C++ => JIT calls are much slower than Trampoline => JIT calls.
5613 if (args.hasDefined(0) && jit::IsBaselineInterpreterEnabled()) {
5614 return CallTrampolineNativeJitCode(
5615 cx, jit::TrampolineNative::TypedArraySort, args);
5616 }
5617
5618 Rooted<ArraySortData> data(cx, cx);
5619
5620 // On all return paths other than ArraySortData::sortTypedArrayWithComparator
5621 // returning Done, we call freeMallocData to not fail debug assertions. This
5622 // matches the JIT trampoline where we can't rely on C++ destructors.
5623 auto freeData =
5624 mozilla::MakeScopeExit([&]() { data.get().freeMallocData(); });
5625
5626 bool done = false;
5627 if (!TypedArraySortPrologue(cx, args.thisv(), args.get(0), data.address(),
5628 &done)) {
5629 return false;
5630 }
5631 if (done) {
5632 args.rval().set(data.get().returnValue());
5633 return true;
5634 }
5635
5636 FixedInvokeArgs<2> callArgs(cx);
5637 Rooted<Value> rval(cx);
5638
5639 while (true) {
5640 ArraySortResult res =
5641 ArraySortData::sortTypedArrayWithComparator(data.address());
5642 switch (res) {
5643 case ArraySortResult::Failure:
5644 return false;
5645
5646 case ArraySortResult::Done:
5647 freeData.release();
5648 args.rval().set(data.get().returnValue());
5649 return true;
5650
5651 case ArraySortResult::CallJS:
5652 case ArraySortResult::CallJSSameRealmNoRectifier:
5653 MOZ_ASSERT(data.get().comparatorThisValue().isUndefined());
5654 MOZ_ASSERT(&args[0].toObject() == data.get().comparator());
5655 callArgs[0].set(data.get().comparatorArg(0));
5656 callArgs[1].set(data.get().comparatorArg(1));
5657 if (!js::Call(cx, args[0], UndefinedHandleValue, callArgs, &rval)) {
5658 return false;
5659 }
5660 data.get().setComparatorReturnValue(rval);
5661 break;
5662 }
5663 }
5664 }
5665
5666 ArraySortResult js::TypedArraySortFromJit(
5667 JSContext* cx, jit::TrampolineNativeFrameLayout* frame) {
5668 AutoJSMethodProfilerEntry pseudoFrame(cx, "[TypedArray].prototype", "sort");
5669 // Initialize the ArraySortData class stored in the trampoline frame.
5670 void* dataUninit = frame->getFrameData<ArraySortData>();
5671 auto* data = new (dataUninit) ArraySortData(cx);
5672
5673 Rooted<Value> thisv(cx, frame->thisv());
5674 Rooted<Value> comparefn(cx);
5675 if (frame->numActualArgs() > 0) {
5676 comparefn = frame->actualArgs()[0];
5677 }
5678
5679 bool done = false;
5680 if (!TypedArraySortPrologue(cx, thisv, comparefn, data, &done)) {
5681 return ArraySortResult::Failure;
5682 }
5683 if (done) {
5684 data->freeMallocData();
5685 return ArraySortResult::Done;
5686 }
5687
5688 return ArraySortData::sortTypedArrayWithComparator(data);
5689 }
5690
5691 /* JS Public API */
5692
5693 #define IMPL_TYPED_ARRAY_JSAPI_CONSTRUCTORS(ExternalType, NativeType, Name) \
5694 JS_PUBLIC_API JSObject* JS_New##Name##Array(JSContext* cx, \
5695 size_t nelements) { \
5696 return TypedArrayObjectTemplate<NativeType>::fromLength(cx, nelements); \
5697 } \
5698 \
5699 JS_PUBLIC_API JSObject* JS_New##Name##ArrayFromArray(JSContext* cx, \
5700 HandleObject other) { \
5701 return TypedArrayObjectTemplate<NativeType>::fromArray(cx, other); \
5702 } \
5703 \
5704 JS_PUBLIC_API JSObject* JS_New##Name##ArrayWithBuffer( \
5705 JSContext* cx, HandleObject arrayBuffer, size_t byteOffset, \
5706 int64_t length) { \
5707 return TypedArrayObjectTemplate<NativeType>::fromBuffer( \
5708 cx, arrayBuffer, byteOffset, length); \
5709 } \
5710 \
5711 JS_PUBLIC_API JSObject* js::Unwrap##Name##Array(JSObject* obj) { \
5712 obj = obj->maybeUnwrapIf<TypedArrayObject>(); \
5713 if (!obj) { \
5714 return nullptr; \
5715 } \
5716 const JSClass* clasp = obj->getClass(); \
5717 if (clasp != FixedLengthTypedArrayObjectTemplate< \
5718 NativeType>::instanceClass() && \
5719 clasp != \
5720 ResizableTypedArrayObjectTemplate<NativeType>::instanceClass()) { \
5721 return nullptr; \
5722 } \
5723 return obj; \
5724 } \
5725 \
5726 JS_PUBLIC_API ExternalType* JS_Get##Name##ArrayLengthAndData( \
5727 JSObject* obj, size_t* length, bool* isSharedMemory, \
5728 const JS::AutoRequireNoGC& nogc) { \
5729 TypedArrayObject* tarr = obj->maybeUnwrapAs<TypedArrayObject>(); \
5730 if (!tarr) { \
5731 return nullptr; \
5732 } \
5733 mozilla::Span<ExternalType> span = \
5734 JS::TypedArray<JS::Scalar::Name>::fromObject(tarr).getData( \
5735 isSharedMemory, nogc); \
5736 *length = span.Length(); \
5737 return span.data(); \
5738 } \
5739 \
5740 JS_PUBLIC_API ExternalType* JS_Get##Name##ArrayData( \
5741 JSObject* obj, bool* isSharedMemory, const JS::AutoRequireNoGC& nogc) { \
5742 size_t length; \
5743 return JS_Get##Name##ArrayLengthAndData(obj, &length, isSharedMemory, \
5744 nogc); \
5745 } \
5746 JS_PUBLIC_API JSObject* JS_GetObjectAs##Name##Array( \
5747 JSObject* obj, size_t* length, bool* isShared, ExternalType** data) { \
5748 obj = js::Unwrap##Name##Array(obj); \
5749 if (!obj) { \
5750 return nullptr; \
5751 } \
5752 TypedArrayObject* tarr = &obj->as<TypedArrayObject>(); \
5753 *length = tarr->length().valueOr(0); \
5754 *isShared = tarr->isSharedMemory(); \
5755 *data = static_cast<ExternalType*>(tarr->dataPointerEither().unwrap( \
5756 /*safe - caller sees isShared flag*/)); \
5757 return obj; \
5758 }
5759
5760 JS_FOR_EACH_TYPED_ARRAY(IMPL_TYPED_ARRAY_JSAPI_CONSTRUCTORS)
5761 #undef IMPL_TYPED_ARRAY_JSAPI_CONSTRUCTORS
5762
5763 JS_PUBLIC_API bool JS_IsTypedArrayObject(JSObject* obj) {
5764 return obj->canUnwrapAs<TypedArrayObject>();
5765 }
5766
5767 JS_PUBLIC_API size_t JS_GetTypedArrayLength(JSObject* obj) {
5768 TypedArrayObject* tarr = obj->maybeUnwrapAs<TypedArrayObject>();
5769 if (!tarr) {
5770 return 0;
5771 }
5772 return tarr->length().valueOr(0);
5773 }
5774
5775 JS_PUBLIC_API size_t JS_GetTypedArrayByteOffset(JSObject* obj) {
5776 TypedArrayObject* tarr = obj->maybeUnwrapAs<TypedArrayObject>();
5777 if (!tarr) {
5778 return 0;
5779 }
5780 return tarr->byteOffset().valueOr(0);
5781 }
5782
5783 JS_PUBLIC_API size_t JS_GetTypedArrayByteLength(JSObject* obj) {
5784 TypedArrayObject* tarr = obj->maybeUnwrapAs<TypedArrayObject>();
5785 if (!tarr) {
5786 return 0;
5787 }
5788 return tarr->byteLength().valueOr(0);
5789 }
5790
5791 JS_PUBLIC_API bool JS_GetTypedArraySharedness(JSObject* obj) {
5792 TypedArrayObject* tarr = obj->maybeUnwrapAs<TypedArrayObject>();
5793 if (!tarr) {
5794 return false;
5795 }
5796 return tarr->isSharedMemory();
5797 }
5798
5799 JS_PUBLIC_API JS::Scalar::Type JS_GetArrayBufferViewType(JSObject* obj) {
5800 ArrayBufferViewObject* view = obj->maybeUnwrapAs<ArrayBufferViewObject>();
5801 if (!view) {
5802 return Scalar::MaxTypedArrayViewType;
5803 }
5804
5805 if (view->is<TypedArrayObject>()) {
5806 return view->as<TypedArrayObject>().type();
5807 }
5808 if (view->is<DataViewObject>()) {
5809 return Scalar::MaxTypedArrayViewType;
5810 }
5811 MOZ_CRASH("invalid ArrayBufferView type");
5812 }
5813
5814 JS_PUBLIC_API size_t JS_MaxMovableTypedArraySize() {
5815 return FixedLengthTypedArrayObject::INLINE_BUFFER_LIMIT;
5816 }
5817
5818 namespace JS {
5819
5820 const JSClass* const TypedArray_base::fixedLengthClasses =
5821 TypedArrayObject::fixedLengthClasses;
5822 const JSClass* const TypedArray_base::resizableClasses =
5823 TypedArrayObject::resizableClasses;
5824
5825 #define INSTANTIATE(ExternalType, NativeType, Name) \
5826 template class TypedArray<JS::Scalar::Name>;
5827 JS_FOR_EACH_TYPED_ARRAY(INSTANTIATE)
5828 #undef INSTANTIATE
5829
5830 JS::ArrayBufferOrView JS::ArrayBufferOrView::unwrap(JSObject* maybeWrapped) {
5831 if (!maybeWrapped) {
5832 return JS::ArrayBufferOrView(nullptr);
5833 }
5834 auto* ab = maybeWrapped->maybeUnwrapIf<ArrayBufferObjectMaybeShared>();
5835 if (ab) {
5836 return ArrayBufferOrView::fromObject(ab);
5837 }
5838
5839 return ArrayBufferView::unwrap(maybeWrapped);
5840 }
5841
5842 bool JS::ArrayBufferOrView::isDetached() const {
5843 MOZ_ASSERT(obj);
5844 if (obj->is<ArrayBufferObjectMaybeShared>()) {
5845 return obj->as<ArrayBufferObjectMaybeShared>().isDetached();
5846 } else {
5847 return obj->as<ArrayBufferViewObject>().hasDetachedBuffer();
5848 }
5849 }
5850
5851 bool JS::ArrayBufferOrView::isResizable() const {
5852 MOZ_ASSERT(obj);
5853 if (obj->is<ArrayBufferObjectMaybeShared>()) {
5854 return obj->as<ArrayBufferObjectMaybeShared>().isResizable();
5855 } else {
5856 return obj->as<ArrayBufferViewObject>().hasResizableBuffer();
5857 }
5858 }
5859
5860 JS::TypedArray_base JS::TypedArray_base::fromObject(JSObject* unwrapped) {
5861 if (unwrapped && unwrapped->is<TypedArrayObject>()) {
5862 return TypedArray_base(unwrapped);
5863 }
5864 return TypedArray_base(nullptr);
5865 }
5866
5867 // Template getData function for TypedArrays, implemented here because
5868 // it requires internal APIs.
5869 template <JS::Scalar::Type EType>
5870 typename mozilla::Span<typename TypedArray<EType>::DataType>
5871 TypedArray<EType>::getData(bool* isSharedMemory, const AutoRequireNoGC&) {
5872 using ExternalType = TypedArray<EType>::DataType;
5873 if (!obj) {
5874 return nullptr;
5875 }
5876 TypedArrayObject* tarr = &obj->as<TypedArrayObject>();
5877 MOZ_ASSERT(tarr);
5878 *isSharedMemory = tarr->isSharedMemory();
5879 return {static_cast<ExternalType*>(tarr->dataPointerEither().unwrap(
5880 /*safe - caller sees isShared*/)),
5881 tarr->length().valueOr(0)};
5882 };
5883
5884 // Force the method defined above to actually be instantianted in this
5885 // compilation unit and emitted into the object file, since otherwise a binary
5886 // could include the header file and emit an undefined symbol that would not be
5887 // satisfied by the linker. (This happens with opt gtest, at least. In a DEBUG
5888 // build, the header contains a call to this function so it will always be
5889 // emitted.)
5890 #define INSTANTIATE_GET_DATA(a, b, Name) \
5891 template mozilla::Span<typename TypedArray<JS::Scalar::Name>::DataType> \
5892 TypedArray<JS::Scalar::Name>::getData(bool* isSharedMemory, \
5893 const AutoRequireNoGC&);
5894 JS_FOR_EACH_TYPED_ARRAY(INSTANTIATE_GET_DATA)
5895 #undef INSTANTIATE_GET_DATA
5896
5897 } /* namespace JS */