Debian Codegraph @

js/src/vm/TypedArrayObject-inl.h

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 #ifndef vm_TypedArrayObject_inl_h
8 #define vm_TypedArrayObject_inl_h
9
10 /* Utilities and common inline code for TypedArray */
11
12 #include "vm/TypedArrayObject.h"
13
14 #include "mozilla/Assertions.h"
15 #include "mozilla/Compiler.h"
16 #include "mozilla/FloatingPoint.h"
17
18 #include <algorithm>
19 #include <type_traits>
20
21 #include "jsnum.h"
22
23 #include "gc/Zone.h"
24 #include "jit/AtomicOperations.h"
25 #include "js/Conversions.h"
26 #include "js/ScalarType.h" // js::Scalar::Type
27 #include "js/Value.h"
28 #include "util/DifferentialTesting.h"
29 #include "util/Memory.h"
30 #include "vm/ArrayObject.h"
31 #include "vm/BigIntType.h"
32 #include "vm/Float16.h"
33 #include "vm/NativeObject.h"
34 #include "vm/Uint8Clamped.h"
35
36 #include "gc/ObjectKind-inl.h"
37 #include "vm/NativeObject-inl.h"
38 #include "vm/ObjectOperations-inl.h"
39
40 namespace js {
41
42 // Use static_assert in compilers which support CWG2518. In all other cases
43 // fall back to MOZ_CRASH.
44 //
45 // https://cplusplus.github.io/CWG/issues/2518.html
46 #if defined(__clang__)
47 # if (__clang_major__ >= 17)
48 # define STATIC_ASSERT_IN_UNEVALUATED_CONTEXT 1
49 # else
50 # define STATIC_ASSERT_IN_UNEVALUATED_CONTEXT 0
51 # endif
52 #elif MOZ_IS_GCC
53 # if MOZ_GCC_VERSION_AT_LEAST(13, 1, 0)
54 # define STATIC_ASSERT_IN_UNEVALUATED_CONTEXT 1
55 # else
56 # define STATIC_ASSERT_IN_UNEVALUATED_CONTEXT 0
57 # endif
58 #else
59 # define STATIC_ASSERT_IN_UNEVALUATED_CONTEXT 0
60 #endif
61
62 template <typename T>
63 inline auto ToFloatingPoint(T value) {
64 static_assert(!std::numeric_limits<T>::is_integer);
65
66 if constexpr (std::is_floating_point_v<T>) {
67 return value;
68 } else {
69 return static_cast<double>(value);
70 }
71 }
72
73 template <typename To, typename From>
74 inline To ConvertNumber(From src) {
75 if constexpr (!std::numeric_limits<From>::is_integer) {
76 if constexpr (std::is_same_v<From, To>) {
77 return src;
78 } else if constexpr (!std::numeric_limits<To>::is_integer) {
79 return static_cast<To>(ToFloatingPoint(src));
80 } else if constexpr (std::is_same_v<int8_t, To>) {
81 return JS::ToInt8(ToFloatingPoint(src));
82 } else if constexpr (std::is_same_v<uint8_t, To>) {
83 return JS::ToUint8(ToFloatingPoint(src));
84 } else if constexpr (std::is_same_v<uint8_clamped, To>) {
85 return uint8_clamped(ToFloatingPoint(src));
86 } else if constexpr (std::is_same_v<int16_t, To>) {
87 return JS::ToInt16(ToFloatingPoint(src));
88 } else if constexpr (std::is_same_v<uint16_t, To>) {
89 return JS::ToUint16(ToFloatingPoint(src));
90 } else if constexpr (std::is_same_v<int32_t, To>) {
91 return JS::ToInt32(ToFloatingPoint(src));
92 } else if constexpr (std::is_same_v<uint32_t, To>) {
93 return JS::ToUint32(ToFloatingPoint(src));
94 } else {
95 #if STATIC_ASSERT_IN_UNEVALUATED_CONTEXT
96 static_assert(false,
97 "conversion from floating point to int should have been "
98 "handled by specializations above");
99 #else
100 MOZ_CRASH(
101 "conversion from floating point to int should have been "
102 "handled by specializations above");
103 #endif
104 }
105 } else {
106 return static_cast<To>(src);
107 }
108 }
109
110 #undef STATIC_ASSERT_IN_UNEVALUATED_CONTEXT
111
112 template <typename NativeType>
113 struct TypeIDOfType;
114 template <>
115 struct TypeIDOfType<int8_t> {
116 static const Scalar::Type id = Scalar::Int8;
117 static const JSProtoKey protoKey = JSProto_Int8Array;
118 };
119 template <>
120 struct TypeIDOfType<uint8_t> {
121 static const Scalar::Type id = Scalar::Uint8;
122 static const JSProtoKey protoKey = JSProto_Uint8Array;
123 };
124 template <>
125 struct TypeIDOfType<int16_t> {
126 static const Scalar::Type id = Scalar::Int16;
127 static const JSProtoKey protoKey = JSProto_Int16Array;
128 };
129 template <>
130 struct TypeIDOfType<uint16_t> {
131 static const Scalar::Type id = Scalar::Uint16;
132 static const JSProtoKey protoKey = JSProto_Uint16Array;
133 };
134 template <>
135 struct TypeIDOfType<int32_t> {
136 static const Scalar::Type id = Scalar::Int32;
137 static const JSProtoKey protoKey = JSProto_Int32Array;
138 };
139 template <>
140 struct TypeIDOfType<uint32_t> {
141 static const Scalar::Type id = Scalar::Uint32;
142 static const JSProtoKey protoKey = JSProto_Uint32Array;
143 };
144 template <>
145 struct TypeIDOfType<int64_t> {
146 static const Scalar::Type id = Scalar::BigInt64;
147 static const JSProtoKey protoKey = JSProto_BigInt64Array;
148 };
149 template <>
150 struct TypeIDOfType<uint64_t> {
151 static const Scalar::Type id = Scalar::BigUint64;
152 static const JSProtoKey protoKey = JSProto_BigUint64Array;
153 };
154 template <>
155 struct TypeIDOfType<float16> {
156 static const Scalar::Type id = Scalar::Float16;
157 static const JSProtoKey protoKey = JSProto_Float16Array;
158 };
159 template <>
160 struct TypeIDOfType<float> {
161 static const Scalar::Type id = Scalar::Float32;
162 static const JSProtoKey protoKey = JSProto_Float32Array;
163 };
164 template <>
165 struct TypeIDOfType<double> {
166 static const Scalar::Type id = Scalar::Float64;
167 static const JSProtoKey protoKey = JSProto_Float64Array;
168 };
169 template <>
170 struct TypeIDOfType<uint8_clamped> {
171 static const Scalar::Type id = Scalar::Uint8Clamped;
172 static const JSProtoKey protoKey = JSProto_Uint8ClampedArray;
173 };
174
175 class SharedOps {
176 public:
177 template <typename T>
178 static T load(SharedMem<T*> addr) {
179 return js::jit::AtomicOperations::loadSafeWhenRacy(addr);
180 }
181
182 template <typename T>
183 static void store(SharedMem<T*> addr, T value) {
184 js::jit::AtomicOperations::storeSafeWhenRacy(addr, value);
185 }
186
187 template <typename T>
188 static void memcpy(SharedMem<T*> dest, SharedMem<T*> src, size_t size) {
189 js::jit::AtomicOperations::memcpySafeWhenRacy(dest, src, size);
190 }
191
192 template <typename T>
193 static void memmove(SharedMem<T*> dest, SharedMem<T*> src, size_t size) {
194 js::jit::AtomicOperations::memmoveSafeWhenRacy(dest, src, size);
195 }
196
197 template <typename T>
198 static void podCopy(SharedMem<T*> dest, SharedMem<T*> src, size_t nelem) {
199 js::jit::AtomicOperations::podCopySafeWhenRacy(dest, src, nelem);
200 }
201
202 template <typename T>
203 static void podMove(SharedMem<T*> dest, SharedMem<T*> src, size_t nelem) {
204 js::jit::AtomicOperations::podMoveSafeWhenRacy(dest, src, nelem);
205 }
206
207 static SharedMem<void*> extract(TypedArrayObject* obj) {
208 return obj->dataPointerEither();
209 }
210 };
211
212 class UnsharedOps {
213 public:
214 template <typename T>
215 static T load(SharedMem<T*> addr) {
216 return *addr.unwrapUnshared();
217 }
218
219 template <typename T>
220 static void store(SharedMem<T*> addr, T value) {
221 *addr.unwrapUnshared() = value;
222 }
223
224 template <typename T>
225 static void memcpy(SharedMem<T*> dest, SharedMem<T*> src, size_t size) {
226 ::memcpy(dest.unwrapUnshared(), src.unwrapUnshared(), size);
227 }
228
229 template <typename T>
230 static void memmove(SharedMem<T*> dest, SharedMem<T*> src, size_t size) {
231 ::memmove(dest.unwrapUnshared(), src.unwrapUnshared(), size);
232 }
233
234 template <typename T>
235 static void podCopy(SharedMem<T*> dest, SharedMem<T*> src, size_t nelem) {
236 // std::copy_n better matches the argument values/types of this
237 // function, but as noted below it allows the input/output ranges to
238 // overlap. std::copy does not, so use it so the compiler has extra
239 // ability to optimize.
240 const auto* first = src.unwrapUnshared();
241 const auto* last = first + nelem;
242 auto* result = dest.unwrapUnshared();
243 std::copy(first, last, result);
244 }
245
246 template <typename T>
247 static void podMove(SharedMem<T*> dest, SharedMem<T*> src, size_t n) {
248 // std::copy_n copies from |src| to |dest| starting from |src|, so
249 // input/output ranges *may* permissibly overlap, as this function
250 // allows.
251 const auto* start = src.unwrapUnshared();
252 auto* result = dest.unwrapUnshared();
253 std::copy_n(start, n, result);
254 }
255
256 static SharedMem<void*> extract(TypedArrayObject* obj) {
257 return SharedMem<void*>::unshared(obj->dataPointerUnshared());
258 }
259 };
260
261 /**
262 * Check if |targetType| and |sourceType| have compatible bit-level
263 * representations to allow bitwise copying.
264 */
265 constexpr bool CanUseBitwiseCopy(Scalar::Type targetType,
266 Scalar::Type sourceType) {
267 switch (targetType) {
268 case Scalar::Int8:
269 case Scalar::Uint8:
270 return sourceType == Scalar::Int8 || sourceType == Scalar::Uint8 ||
271 sourceType == Scalar::Uint8Clamped;
272
273 case Scalar::Uint8Clamped:
274 return sourceType == Scalar::Uint8 || sourceType == Scalar::Uint8Clamped;
275
276 case Scalar::Int16:
277 case Scalar::Uint16:
278 return sourceType == Scalar::Int16 || sourceType == Scalar::Uint16;
279
280 case Scalar::Int32:
281 case Scalar::Uint32:
282 return sourceType == Scalar::Int32 || sourceType == Scalar::Uint32;
283
284 case Scalar::Float16:
285 return sourceType == Scalar::Float16;
286
287 case Scalar::Float32:
288 return sourceType == Scalar::Float32;
289
290 case Scalar::Float64:
291 return sourceType == Scalar::Float64;
292
293 case Scalar::BigInt64:
294 case Scalar::BigUint64:
295 return sourceType == Scalar::BigInt64 || sourceType == Scalar::BigUint64;
296
297 case Scalar::MaxTypedArrayViewType:
298 case Scalar::Int64:
299 case Scalar::Simd128:
300 // GCC8 doesn't like MOZ_CRASH in constexpr functions, so we can't use it
301 // here to catch invalid typed array types.
302 break;
303 }
304 return false;
305 }
306
307 template <typename T, typename Ops>
308 class ElementSpecific {
309 static constexpr bool canUseBitwiseCopy(Scalar::Type sourceType) {
310 return CanUseBitwiseCopy(TypeIDOfType<T>::id, sourceType);
311 }
312
313 template <typename From>
314 static inline constexpr bool canCopyBitwise =
315 canUseBitwiseCopy(TypeIDOfType<From>::id);
316
317 template <typename From, typename LoadOps = Ops>
318 static typename std::enable_if_t<!canCopyBitwise<From>> store(
319 SharedMem<T*> dest, SharedMem<void*> data, size_t count) {
320 SharedMem<From*> src = data.cast<From*>();
321 for (size_t i = 0; i < count; ++i) {
322 Ops::store(dest++, ConvertNumber<T>(LoadOps::load(src++)));
323 }
324 }
325
326 template <typename From, typename LoadOps = Ops>
327 static typename std::enable_if_t<canCopyBitwise<From>> store(
328 SharedMem<T*> dest, SharedMem<void*> data, size_t count) {
329 MOZ_ASSERT_UNREACHABLE("caller handles bitwise copies");
330 }
331
332 template <typename LoadOps = Ops, typename U = T>
333 static typename std::enable_if_t<!std::is_same_v<U, int64_t> &&
334 !std::is_same_v<U, uint64_t>>
335 storeTo(SharedMem<T*> dest, Scalar::Type type, SharedMem<void*> data,
336 size_t count) {
337 static_assert(std::is_same_v<T, U>,
338 "template parameter U only used to disable this declaration");
339 switch (type) {
340 case Scalar::Int8: {
341 store<int8_t, LoadOps>(dest, data, count);
342 break;
343 }
344 case Scalar::Uint8:
345 case Scalar::Uint8Clamped: {
346 store<uint8_t, LoadOps>(dest, data, count);
347 break;
348 }
349 case Scalar::Int16: {
350 store<int16_t, LoadOps>(dest, data, count);
351 break;
352 }
353 case Scalar::Uint16: {
354 store<uint16_t, LoadOps>(dest, data, count);
355 break;
356 }
357 case Scalar::Int32: {
358 store<int32_t, LoadOps>(dest, data, count);
359 break;
360 }
361 case Scalar::Uint32: {
362 store<uint32_t, LoadOps>(dest, data, count);
363 break;
364 }
365 case Scalar::Float16: {
366 store<float16, LoadOps>(dest, data, count);
367 break;
368 }
369 case Scalar::Float32: {
370 store<float, LoadOps>(dest, data, count);
371 break;
372 }
373 case Scalar::Float64: {
374 store<double, LoadOps>(dest, data, count);
375 break;
376 }
377 case Scalar::BigInt64:
378 case Scalar::BigUint64:
379 MOZ_FALLTHROUGH_ASSERT("unexpected int64/uint64 typed array");
380 default:
381 MOZ_CRASH("setFromTypedArray with a typed array with bogus type");
382 }
383 }
384
385 template <typename LoadOps = Ops, typename U = T>
386 static typename std::enable_if_t<std::is_same_v<U, int64_t> ||
387 std::is_same_v<U, uint64_t>>
388 storeTo(SharedMem<T*> dest, Scalar::Type type, SharedMem<void*> data,
389 size_t count) {
390 static_assert(std::is_same_v<T, U>,
391 "template parameter U only used to disable this declaration");
392 MOZ_ASSERT_UNREACHABLE("caller handles int64<>uint64 bitwise copies");
393 }
394
395 public:
396 /*
397 * Copy |source|'s elements into |target|, starting at |target[offset]|.
398 * Act as if the assignments occurred from a fresh copy of |source|, in
399 * case the two memory ranges overlap.
400 */
401 static bool setFromTypedArray(Handle<TypedArrayObject*> target,
402 size_t targetLength,
403 Handle<TypedArrayObject*> source,
404 size_t sourceLength, size_t offset) {
405 // WARNING: |source| may be an unwrapped typed array from a different
406 // compartment. Proceed with caution!
407
408 MOZ_ASSERT(TypeIDOfType<T>::id == target->type(),
409 "calling wrong setFromTypedArray specialization");
410 MOZ_ASSERT(Scalar::isBigIntType(target->type()) ==
411 Scalar::isBigIntType(source->type()),
412 "can't convert between BigInt and Number");
413 MOZ_ASSERT(!target->hasDetachedBuffer(), "target isn't detached");
414 MOZ_ASSERT(!source->hasDetachedBuffer(), "source isn't detached");
415 MOZ_ASSERT(*target->length() >= targetLength, "target isn't shrunk");
416 MOZ_ASSERT(*source->length() >= sourceLength, "source isn't shrunk");
417
418 MOZ_ASSERT(offset <= targetLength);
419 MOZ_ASSERT(sourceLength <= targetLength - offset);
420
421 // Return early when copying no elements.
422 //
423 // Note: `SharedMem::cast` asserts the memory is properly aligned. Non-zero
424 // memory is correctly aligned, this is statically asserted below. Zero
425 // memory can have a different alignment, so we have to return early.
426 if (sourceLength == 0) {
427 return true;
428 }
429
430 if (TypedArrayObject::sameBuffer(target, source)) {
431 return setFromOverlappingTypedArray(target, targetLength, source,
432 sourceLength, offset);
433 }
434
435 // `malloc` returns memory at least as strictly aligned as for max_align_t
436 // and the alignment of max_align_t is a multiple of the size of `T`,
437 // so `SharedMem::cast` will be called with properly aligned memory.
438 static_assert(alignof(std::max_align_t) % sizeof(T) == 0);
439
440 SharedMem<T*> dest = Ops::extract(target).template cast<T*>() + offset;
441 SharedMem<void*> data = Ops::extract(source);
442
443 if (canUseBitwiseCopy(source->type())) {
444 Ops::podCopy(dest, data.template cast<T*>(), sourceLength);
445 } else {
446 storeTo(dest, source->type(), data, sourceLength);
447 }
448
449 return true;
450 }
451
452 /*
453 * Copy |source[0]| to |source[len]| (exclusive) elements into the typed
454 * array |target|, starting at index |offset|. |source| must not be a
455 * typed array.
456 */
457 static bool setFromNonTypedArray(JSContext* cx,
458 Handle<TypedArrayObject*> target,
459 HandleObject source, size_t len,
460 size_t offset = 0) {
461 MOZ_ASSERT(target->type() == TypeIDOfType<T>::id,
462 "target type and NativeType must match");
463 MOZ_ASSERT(!source->is<TypedArrayObject>(),
464 "use setFromTypedArray instead of this method");
465 MOZ_ASSERT_IF(target->hasDetachedBuffer(), target->length().isNothing());
466
467 size_t i = 0;
468 if (source->is<NativeObject>()) {
469 size_t targetLength = target->length().valueOr(0);
470 if (offset <= targetLength && len <= targetLength - offset) {
471 // Attempt fast-path infallible conversion of dense elements up to
472 // the first potentially side-effectful lookup or conversion.
473 size_t bound = std::min<size_t>(
474 source->as<NativeObject>().getDenseInitializedLength(), len);
475
476 SharedMem<T*> dest = Ops::extract(target).template cast<T*>() + offset;
477
478 MOZ_ASSERT(!canConvertInfallibly(MagicValue(JS_ELEMENTS_HOLE)),
479 "the following loop must abort on holes");
480
481 const Value* srcValues = source->as<NativeObject>().getDenseElements();
482 for (; i < bound; i++) {
483 if (!canConvertInfallibly(srcValues[i])) {
484 break;
485 }
486 Ops::store(dest + i, infallibleValueToNative(srcValues[i]));
487 }
488 if (i == len) {
489 return true;
490 }
491 }
492 }
493
494 // Convert and copy any remaining elements generically.
495 RootedValue v(cx);
496 for (; i < len; i++) {
497 if constexpr (sizeof(i) == sizeof(uint32_t)) {
498 if (!GetElement(cx, source, source, uint32_t(i), &v)) {
499 return false;
500 }
501 } else {
502 if (!GetElementLargeIndex(cx, source, source, i, &v)) {
503 return false;
504 }
505 }
506
507 T n;
508 if (!valueToNative(cx, v, &n)) {
509 return false;
510 }
511
512 // Ignore out-of-bounds writes, but still execute getElement/valueToNative
513 // because of observable side-effects.
514 if (offset + i >= target->length().valueOr(0)) {
515 continue;
516 }
517
518 MOZ_ASSERT(!target->hasDetachedBuffer());
519
520 // Compute every iteration in case getElement/valueToNative
521 // detaches the underlying array buffer or GC moves the data.
522 SharedMem<T*> dest =
523 Ops::extract(target).template cast<T*>() + offset + i;
524 Ops::store(dest, n);
525 }
526
527 return true;
528 }
529
530 /*
531 * Copy |source| into the typed array |target|.
532 */
533 static bool initFromIterablePackedArray(
534 JSContext* cx, Handle<FixedLengthTypedArrayObject*> target,
535 Handle<ArrayObject*> source) {
536 MOZ_ASSERT(target->type() == TypeIDOfType<T>::id,
537 "target type and NativeType must match");
538 MOZ_ASSERT(!target->hasDetachedBuffer(), "target isn't detached");
539 MOZ_ASSERT(IsPackedArray(source), "source array must be packed");
540 MOZ_ASSERT(source->getDenseInitializedLength() <= target->length());
541
542 size_t len = source->getDenseInitializedLength();
543 size_t i = 0;
544
545 // Attempt fast-path infallible conversion of dense elements up to the
546 // first potentially side-effectful conversion.
547
548 SharedMem<T*> dest = Ops::extract(target).template cast<T*>();
549
550 const Value* srcValues = source->getDenseElements();
551 for (; i < len; i++) {
552 if (!canConvertInfallibly(srcValues[i])) {
553 break;
554 }
555 Ops::store(dest + i, infallibleValueToNative(srcValues[i]));
556 }
557 if (i == len) {
558 return true;
559 }
560
561 // Convert any remaining elements by first collecting them into a
562 // temporary list, and then copying them into the typed array.
563 RootedValueVector values(cx);
564 if (!values.append(srcValues + i, len - i)) {
565 return false;
566 }
567
568 RootedValue v(cx);
569 for (size_t j = 0; j < values.length(); i++, j++) {
570 v = values[j];
571
572 T n;
573 if (!valueToNative(cx, v, &n)) {
574 return false;
575 }
576
577 // |target| is a newly allocated typed array and not yet visible to
578 // content script, so valueToNative can't detach the underlying
579 // buffer.
580 MOZ_ASSERT(i < target->length());
581
582 // Compute every iteration in case GC moves the data.
583 SharedMem<T*> newDest = Ops::extract(target).template cast<T*>();
584 Ops::store(newDest + i, n);
585 }
586
587 return true;
588 }
589
590 private:
591 static bool setFromOverlappingTypedArray(Handle<TypedArrayObject*> target,
592 size_t targetLength,
593 Handle<TypedArrayObject*> source,
594 size_t sourceLength, size_t offset) {
595 // WARNING: |source| may be an unwrapped typed array from a different
596 // compartment. Proceed with caution!
597
598 MOZ_ASSERT(TypeIDOfType<T>::id == target->type(),
599 "calling wrong setFromTypedArray specialization");
600 MOZ_ASSERT(Scalar::isBigIntType(target->type()) ==
601 Scalar::isBigIntType(source->type()),
602 "can't convert between BigInt and Number");
603 MOZ_ASSERT(!target->hasDetachedBuffer(), "target isn't detached");
604 MOZ_ASSERT(!source->hasDetachedBuffer(), "source isn't detached");
605 MOZ_ASSERT(*target->length() >= targetLength, "target isn't shrunk");
606 MOZ_ASSERT(*source->length() >= sourceLength, "source isn't shrunk");
607 MOZ_ASSERT(TypedArrayObject::sameBuffer(target, source),
608 "the provided arrays don't actually overlap, so it's "
609 "undesirable to use this method");
610
611 MOZ_ASSERT(offset <= targetLength);
612 MOZ_ASSERT(sourceLength <= targetLength - offset);
613
614 SharedMem<T*> dest = Ops::extract(target).template cast<T*>() + offset;
615 size_t len = sourceLength;
616
617 if (canUseBitwiseCopy(source->type())) {
618 SharedMem<T*> src = Ops::extract(source).template cast<T*>();
619 Ops::podMove(dest, src, len);
620 return true;
621 }
622
623 // Copy |source| because it overlaps the target elements being set.
624 size_t sourceByteLen = len * source->bytesPerElement();
625 auto temp = target->zone()->template make_pod_array<uint8_t>(sourceByteLen);
626 if (!temp) {
627 return false;
628 }
629
630 auto data = SharedMem<void*>::unshared(temp.get());
631 Ops::memcpy(data, Ops::extract(source), sourceByteLen);
632
633 storeTo<UnsharedOps>(dest, source->type(), data, len);
634
635 return true;
636 }
637
638 static bool canConvertInfallibly(const Value& v) {
639 if (std::is_same_v<T, int64_t> || std::is_same_v<T, uint64_t>) {
640 // Numbers, Null, Undefined, and Symbols throw a TypeError. Strings may
641 // OOM and Objects may have side-effects.
642 return v.isBigInt() || v.isBoolean();
643 }
644 // BigInts and Symbols throw a TypeError. Strings may OOM and Objects may
645 // have side-effects.
646 return v.isNumber() || v.isBoolean() || v.isNull() || v.isUndefined();
647 }
648
649 static T infallibleValueToNative(const Value& v) {
650 if constexpr (std::is_same_v<T, int64_t>) {
651 if (v.isBigInt()) {
652 return T(BigInt::toInt64(v.toBigInt()));
653 }
654 return T(v.toBoolean());
655 } else if constexpr (std::is_same_v<T, uint64_t>) {
656 if (v.isBigInt()) {
657 return T(BigInt::toUint64(v.toBigInt()));
658 }
659 return T(v.toBoolean());
660 } else {
661 if (v.isInt32()) {
662 return T(v.toInt32());
663 }
664 if (v.isDouble()) {
665 return doubleToNative(v.toDouble());
666 }
667 if (v.isBoolean()) {
668 return T(v.toBoolean());
669 }
670 if (v.isNull()) {
671 return T(0);
672 }
673
674 MOZ_ASSERT(v.isUndefined());
675 return !std::numeric_limits<T>::is_integer ? T(JS::GenericNaN()) : T(0);
676 }
677 }
678
679 static bool valueToNative(JSContext* cx, HandleValue v, T* result) {
680 MOZ_ASSERT(!v.isMagic());
681
682 if (MOZ_LIKELY(canConvertInfallibly(v))) {
683 *result = infallibleValueToNative(v);
684 return true;
685 }
686
687 if constexpr (std::is_same_v<T, int64_t>) {
688 JS_TRY_VAR_OR_RETURN_FALSE(cx, *result, ToBigInt64(cx, v));
689 } else if constexpr (std::is_same_v<T, uint64_t>) {
690 JS_TRY_VAR_OR_RETURN_FALSE(cx, *result, ToBigUint64(cx, v));
691 } else {
692 MOZ_ASSERT(v.isString() || v.isObject() || v.isSymbol() || v.isBigInt());
693
694 double d;
695 if (!(v.isString() ? StringToNumber(cx, v.toString(), &d)
696 : ToNumber(cx, v, &d))) {
697 return false;
698 }
699 *result = doubleToNative(d);
700 }
701 return true;
702 }
703
704 static T doubleToNative(double d) {
705 if constexpr (!std::numeric_limits<T>::is_integer) {
706 // The JS spec doesn't distinguish among different NaN values, and
707 // it deliberately doesn't specify the bit pattern written to a
708 // typed array when NaN is written into it. This bit-pattern
709 // inconsistency could confuse differential testing, so always
710 // canonicalize NaN values in differential testing.
711 if (js::SupportDifferentialTesting()) {
712 d = JS::CanonicalizeNaN(d);
713 }
714 }
715 return ConvertNumber<T>(d);
716 }
717 };
718
719 inline gc::AllocKind js::FixedLengthTypedArrayObject::allocKindForTenure()
720 const {
721 // Fixed length typed arrays in the nursery may have a lazily allocated
722 // buffer. Make sure there is room for the array's fixed data when moving the
723 // array.
724
725 using namespace js::gc;
726
727 if (hasBuffer()) {
728 return NativeObject::allocKindForTenure();
729 }
730
731 AllocKind allocKind;
732 if (hasInlineElements()) {
733 allocKind = AllocKindForLazyBuffer(byteLength());
734 } else {
735 allocKind = GetGCObjectKind(getClass());
736 }
737
738 MOZ_ASSERT(GetObjectFinalizeKind(getClass()) == gc::FinalizeKind::Background);
739 return GetFinalizedAllocKind(allocKind, gc::FinalizeKind::Background);
740 }
741
742 /* static */ gc::AllocKind
743 js::FixedLengthTypedArrayObject::AllocKindForLazyBuffer(size_t nbytes) {
744 MOZ_ASSERT(nbytes <= INLINE_BUFFER_LIMIT);
745 if (nbytes == 0) {
746 nbytes += sizeof(uint8_t);
747 }
748 size_t dataSlots = AlignBytes(nbytes, sizeof(Value)) / sizeof(Value);
749 MOZ_ASSERT(nbytes <= dataSlots * sizeof(Value));
750 return gc::GetGCObjectKind(FIXED_DATA_START + dataSlots);
751 }
752
753 } // namespace js
754
755 #endif // vm_TypedArrayObject_inl_h