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