Debian Codegraph @

js/src/vm/TypedArrayObject.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #ifndef vm_TypedArrayObject_h
8 #define vm_TypedArrayObject_h
9
10 #include "mozilla/Maybe.h"
11 #include "mozilla/TextUtils.h"
12
13 #include "gc/AllocKind.h"
14 #include "gc/MaybeRooted.h"
15 #include "js/Class.h"
16 #include "js/experimental/TypedData.h" // js::detail::TypedArrayLengthSlot
17 #include "js/ScalarType.h" // js::Scalar::Type
18 #include "vm/ArrayBufferObject.h"
19 #include "vm/ArrayBufferViewObject.h"
20 #include "vm/JSObject.h"
21 #include "vm/SharedArrayObject.h"
22
23 namespace js {
24
25 enum class ArraySortResult : uint32_t;
26
27 namespace jit {
28 class TrampolineNativeFrameLayout;
29 }
30
31 /*
32 * TypedArrayObject
33 *
34 * The non-templated base class for the specific typed implementations.
35 * This class holds all the member variables that are used by
36 * the subclasses.
37 */
38
39 class TypedArrayObject : public ArrayBufferViewObject {
40 public:
41 static_assert(js::detail::TypedArrayLengthSlot == LENGTH_SLOT,
42 "bad inlined constant in TypedData.h");
43 static_assert(js::detail::TypedArrayDataSlot == DATA_SLOT,
44 "bad inlined constant in TypedData.h");
45
46 static bool sameBuffer(Handle<TypedArrayObject*> a,
47 Handle<TypedArrayObject*> b) {
48 // Inline buffers.
49 if (!a->hasBuffer() || !b->hasBuffer()) {
50 return a.get() == b.get();
51 }
52
53 // Shared buffers.
54 if (a->isSharedMemory() && b->isSharedMemory()) {
55 return a->bufferShared()->globalID() == b->bufferShared()->globalID();
56 }
57
58 return a->bufferEither() == b->bufferEither();
59 }
60
61 static const JSClass anyClasses[2][Scalar::MaxTypedArrayViewType];
62 static constexpr const JSClass (
63 &fixedLengthClasses)[Scalar::MaxTypedArrayViewType] =
64 TypedArrayObject::anyClasses[0];
65 static constexpr const JSClass (
66 &resizableClasses)[Scalar::MaxTypedArrayViewType] =
67 TypedArrayObject::anyClasses[1];
68 static const JSClass protoClasses[Scalar::MaxTypedArrayViewType];
69 static const JSClass sharedTypedArrayPrototypeClass;
70
71 static const JSClass* protoClassForType(Scalar::Type type) {
72 MOZ_ASSERT(type < Scalar::MaxTypedArrayViewType);
73 return &protoClasses[type];
74 }
75
76 inline Scalar::Type type() const;
77 inline size_t bytesPerElement() const;
78
79 static bool ensureHasBuffer(JSContext* cx,
80 Handle<TypedArrayObject*> typedArray);
81
82 public:
83 /**
84 * Return the current length, or |Nothing| if the TypedArray is detached or
85 * out-of-bounds.
86 */
87 mozilla::Maybe<size_t> length() const {
88 return ArrayBufferViewObject::length();
89 }
90
91 /**
92 * Return the current byteLength, or |Nothing| if the TypedArray is detached
93 * or out-of-bounds.
94 */
95 mozilla::Maybe<size_t> byteLength() const {
96 return length().map(
97 [this](size_t value) { return value * bytesPerElement(); });
98 }
99
100 // Self-hosted TypedArraySubarray function needs to read [[ByteOffset]], even
101 // when it's currently out-of-bounds.
102 size_t byteOffsetMaybeOutOfBounds() const {
103 // dataPointerOffset() returns the [[ByteOffset]] spec value, except when
104 // the buffer is detached. (bug 1840991)
105 return ArrayBufferViewObject::dataPointerOffset();
106 }
107
108 template <AllowGC allowGC>
109 bool getElement(JSContext* cx, size_t index,
110 typename MaybeRooted<Value, allowGC>::MutableHandleType val);
111 bool getElementPure(size_t index, Value* vp);
112
113 /*
114 * Copy |length| elements from this typed array to vp. vp must point to rooted
115 * memory. |length| must not exceed the typed array's current length.
116 */
117 static bool getElements(JSContext* cx, Handle<TypedArrayObject*> tarray,
118 size_t length, Value* vp);
119
120 static bool GetTemplateObjectForNative(JSContext* cx, Native native,
121 const JS::HandleValueArray args,
122 MutableHandleObject res);
123
124 // Maximum allowed byte length for any typed array.
125 static constexpr size_t ByteLengthLimit = ArrayBufferObject::ByteLengthLimit;
126
127 static bool isOriginalLengthGetter(Native native);
128
129 static bool isOriginalByteOffsetGetter(Native native);
130
131 static bool isOriginalByteLengthGetter(Native native);
132
133 /* Accessors and functions */
134
135 static bool sort(JSContext* cx, unsigned argc, Value* vp);
136
137 bool convertValue(JSContext* cx, HandleValue v,
138 MutableHandleValue result) const;
139
140 /* Initialization bits */
141
142 static const JSFunctionSpec protoFunctions[];
143 static const JSPropertySpec protoAccessors[];
144 static const JSFunctionSpec staticFunctions[];
145 static const JSPropertySpec staticProperties[];
146 };
147
148 class FixedLengthTypedArrayObject : public TypedArrayObject {
149 public:
150 static constexpr size_t FIXED_DATA_START = RESERVED_SLOTS;
151
152 // For typed arrays which can store their data inline, the array buffer
153 // object is created lazily.
154 static constexpr uint32_t INLINE_BUFFER_LIMIT =
155 (NativeObject::MAX_FIXED_SLOTS - FIXED_DATA_START) * sizeof(Value);
156
157 inline gc::AllocKind allocKindForTenure() const;
158 static inline gc::AllocKind AllocKindForLazyBuffer(size_t nbytes);
159
160 size_t byteOffset() const {
161 return ArrayBufferViewObject::byteOffsetSlotValue();
162 }
163
164 size_t byteLength() const { return length() * bytesPerElement(); }
165
166 size_t length() const { return ArrayBufferViewObject::lengthSlotValue(); }
167
168 bool hasInlineElements() const;
169 void setInlineElements();
170 uint8_t* elementsRaw() const {
171 return maybePtrFromReservedSlot<uint8_t>(DATA_SLOT);
172 }
173 uint8_t* elements() const {
174 assertZeroLengthArrayData();
175 return elementsRaw();
176 }
177
178 #ifdef DEBUG
179 void assertZeroLengthArrayData() const;
180 #else
181 void assertZeroLengthArrayData() const {};
182 #endif
183
184 static void finalize(JS::GCContext* gcx, JSObject* obj);
185 static size_t objectMoved(JSObject* obj, JSObject* old);
186 };
187
188 class ResizableTypedArrayObject : public TypedArrayObject {
189 public:
190 static const uint8_t RESERVED_SLOTS = RESIZABLE_RESERVED_SLOTS;
191 };
192
193 extern TypedArrayObject* NewTypedArrayWithTemplateAndLength(
194 JSContext* cx, HandleObject templateObj, int32_t len);
195
196 extern TypedArrayObject* NewTypedArrayWithTemplateAndArray(
197 JSContext* cx, HandleObject templateObj, HandleObject array);
198
199 extern TypedArrayObject* NewTypedArrayWithTemplateAndBuffer(
200 JSContext* cx, HandleObject templateObj, HandleObject arrayBuffer,
201 HandleValue byteOffset, HandleValue length);
202
203 extern TypedArrayObject* NewUint8ArrayWithLength(
204 JSContext* cx, int32_t len, gc::Heap heap = gc::Heap::Default);
205
206 inline bool IsFixedLengthTypedArrayClass(const JSClass* clasp) {
207 return std::begin(TypedArrayObject::fixedLengthClasses) <= clasp &&
208 clasp < std::end(TypedArrayObject::fixedLengthClasses);
209 }
210
211 inline bool IsResizableTypedArrayClass(const JSClass* clasp) {
212 return std::begin(TypedArrayObject::resizableClasses) <= clasp &&
213 clasp < std::end(TypedArrayObject::resizableClasses);
214 }
215
216 inline bool IsTypedArrayClass(const JSClass* clasp) {
217 MOZ_ASSERT(std::end(TypedArrayObject::fixedLengthClasses) ==
218 std::begin(TypedArrayObject::resizableClasses),
219 "TypedArray classes are in contiguous memory");
220 return std::begin(TypedArrayObject::fixedLengthClasses) <= clasp &&
221 clasp < std::end(TypedArrayObject::resizableClasses);
222 }
223
224 inline Scalar::Type GetTypedArrayClassType(const JSClass* clasp) {
225 MOZ_ASSERT(IsTypedArrayClass(clasp));
226 if (clasp < std::end(TypedArrayObject::fixedLengthClasses)) {
227 return static_cast<Scalar::Type>(clasp -
228 &TypedArrayObject::fixedLengthClasses[0]);
229 }
230 return static_cast<Scalar::Type>(clasp -
231 &TypedArrayObject::resizableClasses[0]);
232 }
233
234 bool IsTypedArrayConstructor(const JSObject* obj);
235
236 bool IsTypedArrayConstructor(HandleValue v, Scalar::Type type);
237
238 JSNative TypedArrayConstructorNative(Scalar::Type type);
239
240 // In WebIDL terminology, a BufferSource is either an ArrayBuffer or a typed
241 // array view. In either case, extract the dataPointer/byteLength.
242 //
243 // If [AllowShared] is true, then the buffer may be backed by a shared array
244 // buffer.
245 // If [AllowResizable] is true, then the buffer may be backed by a resizable
246 // or growable array buffer.
247 bool IsBufferSource(JSContext* cx, JSObject* object, bool allowShared,
248 bool allowResizable, SharedMem<uint8_t*>* dataPointer,
249 size_t* byteLength);
250
251 inline Scalar::Type TypedArrayObject::type() const {
252 return GetTypedArrayClassType(getClass());
253 }
254
255 inline size_t TypedArrayObject::bytesPerElement() const {
256 return Scalar::byteSize(type());
257 }
258
259 // ES2020 draft rev a5375bdad264c8aa264d9c44f57408087761069e
260 // 7.1.16 CanonicalNumericIndexString
261 //
262 // Checks whether or not the string is a canonical numeric index string. If the
263 // string is a canonical numeric index which is not representable as a uint64_t,
264 // the returned index is UINT64_MAX.
265 template <typename CharT>
266 mozilla::Maybe<uint64_t> StringToTypedArrayIndex(mozilla::Range<const CharT> s);
267
268 // A string |s| is a TypedArray index (or: canonical numeric index string) iff
269 // |s| is "-0" or |SameValue(ToString(ToNumber(s)), s)| is true. So check for
270 // any characters which can start the string representation of a number,
271 // including "NaN" and "Infinity".
272 template <typename CharT>
273 inline bool CanStartTypedArrayIndex(CharT ch) {
274 return mozilla::IsAsciiDigit(ch) || ch == '-' || ch == 'N' || ch == 'I';
275 }
276
277 [[nodiscard]] inline mozilla::Maybe<uint64_t> ToTypedArrayIndex(jsid id) {
278 if (id.isInt()) {
279 int32_t i = id.toInt();
280 MOZ_ASSERT(i >= 0);
281 return mozilla::Some(i);
282 }
283
284 if (MOZ_UNLIKELY(!id.isString())) {
285 return mozilla::Nothing();
286 }
287
288 JS::AutoCheckCannotGC nogc;
289 JSAtom* atom = id.toAtom();
290
291 if (atom->empty() || !CanStartTypedArrayIndex(atom->latin1OrTwoByteChar(0))) {
292 return mozilla::Nothing();
293 }
294
295 if (atom->hasLatin1Chars()) {
296 mozilla::Range<const Latin1Char> chars = atom->latin1Range(nogc);
297 return StringToTypedArrayIndex(chars);
298 }
299
300 mozilla::Range<const char16_t> chars = atom->twoByteRange(nogc);
301 return StringToTypedArrayIndex(chars);
302 }
303
304 bool SetTypedArrayElement(JSContext* cx, Handle<TypedArrayObject*> obj,
305 uint64_t index, HandleValue v,
306 ObjectOpResult& result);
307
308 /*
309 * Implements [[DefineOwnProperty]] for TypedArrays when the property
310 * key is a TypedArray index.
311 */
312 bool DefineTypedArrayElement(JSContext* cx, Handle<TypedArrayObject*> obj,
313 uint64_t index, Handle<PropertyDescriptor> desc,
314 ObjectOpResult& result);
315
316 static inline constexpr unsigned TypedArrayShift(Scalar::Type viewType) {
317 switch (viewType) {
318 case Scalar::Int8:
319 case Scalar::Uint8:
320 case Scalar::Uint8Clamped:
321 return 0;
322 case Scalar::Int16:
323 case Scalar::Uint16:
324 case Scalar::Float16:
325 return 1;
326 case Scalar::Int32:
327 case Scalar::Uint32:
328 case Scalar::Float32:
329 return 2;
330 case Scalar::BigInt64:
331 case Scalar::BigUint64:
332 case Scalar::Int64:
333 case Scalar::Float64:
334 return 3;
335 default:
336 MOZ_CRASH("Unexpected array type");
337 }
338 }
339
340 static inline constexpr unsigned TypedArrayElemSize(Scalar::Type viewType) {
341 return 1u << TypedArrayShift(viewType);
342 }
343
344 extern ArraySortResult TypedArraySortFromJit(
345 JSContext* cx, jit::TrampolineNativeFrameLayout* frame);
346
347 } // namespace js
348
349 template <>
350 inline bool JSObject::is<js::TypedArrayObject>() const {
351 return js::IsTypedArrayClass(getClass());
352 }
353
354 template <>
355 inline bool JSObject::is<js::FixedLengthTypedArrayObject>() const {
356 return js::IsFixedLengthTypedArrayClass(getClass());
357 }
358
359 template <>
360 inline bool JSObject::is<js::ResizableTypedArrayObject>() const {
361 return js::IsResizableTypedArrayClass(getClass());
362 }
363
364 #endif /* vm_TypedArrayObject_h */