-
Notifications
You must be signed in to change notification settings - Fork 54
/
TypedArrayObject.cpp
2573 lines (2179 loc) · 85.7 KB
/
TypedArrayObject.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "vm/TypedArrayObject-inl.h"
#include "vm/TypedArrayObject.h"
#include "mozilla/Alignment.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/FloatingPoint.h"
#include "mozilla/PodOperations.h"
#include "mozilla/TextUtils.h"
#include <string.h>
#ifndef XP_WIN
# include <sys/mman.h>
#endif
#include "jsapi.h"
#include "jsnum.h"
#include "jstypes.h"
#include "jsutil.h"
#include "builtin/Array.h"
#include "builtin/DataViewObject.h"
#include "builtin/TypedObjectConstants.h"
#include "gc/Barrier.h"
#include "gc/Marking.h"
#include "jit/InlinableNatives.h"
#include "js/Conversions.h"
#include "js/PropertySpec.h"
#include "js/UniquePtr.h"
#include "js/Wrapper.h"
#include "util/Windows.h"
#include "vm/ArrayBufferObject.h"
#include "vm/GlobalObject.h"
#include "vm/Interpreter.h"
#include "vm/JSContext.h"
#include "vm/JSObject.h"
#include "vm/PIC.h"
#include "vm/SelfHosting.h"
#include "vm/SharedMem.h"
#include "vm/WrapperObject.h"
#include "gc/Nursery-inl.h"
#include "gc/StoreBuffer-inl.h"
#include "vm/ArrayBufferObject-inl.h"
#include "vm/JSAtom-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/Shape-inl.h"
using namespace js;
using JS::CanonicalizeNaN;
using JS::ToInt32;
using JS::ToUint32;
using mozilla::CheckedUint32;
using mozilla::IsAsciiDigit;
/*
* TypedArrayObject
*
* The non-templated base class for the specific typed implementations.
* This class holds all the member variables that are used by
* the subclasses.
*/
bool TypedArrayObject::convertForSideEffect(JSContext* cx,
HandleValue v) const {
switch (type()) {
case Scalar::BigInt64:
case Scalar::BigUint64: {
return ToBigInt(cx, v) != nullptr;
}
case Scalar::Int8:
case Scalar::Uint8:
case Scalar::Int16:
case Scalar::Uint16:
case Scalar::Int32:
case Scalar::Uint32:
case Scalar::Float32:
case Scalar::Float64:
case Scalar::Uint8Clamped: {
double ignore;
return ToNumber(cx, v, &ignore);
}
case Scalar::MaxTypedArrayViewType:
case Scalar::Int64:
MOZ_CRASH("Unsupported TypedArray type");
}
MOZ_ASSERT_UNREACHABLE("Invalid scalar type");
return false;
}
/* static */
bool TypedArrayObject::is(HandleValue v) {
return v.isObject() && v.toObject().is<TypedArrayObject>();
}
/* static */
bool TypedArrayObject::ensureHasBuffer(JSContext* cx,
Handle<TypedArrayObject*> tarray) {
if (tarray->hasBuffer()) {
return true;
}
AutoRealm ar(cx, tarray);
Rooted<ArrayBufferObject*> buffer(
cx, ArrayBufferObject::createZeroed(cx, tarray->byteLength()));
if (!buffer) {
return false;
}
// Attaching the first view to an array buffer is infallible.
MOZ_ALWAYS_TRUE(buffer->addView(cx, tarray));
// tarray is not shared, because if it were it would have a buffer.
memcpy(buffer->dataPointer(), tarray->dataPointerUnshared(),
tarray->byteLength());
// If the object is in the nursery, the buffer will be freed by the next
// nursery GC. Free the data slot pointer if the object has no inline data.
size_t nbytes = JS_ROUNDUP(tarray->byteLength(), sizeof(Value));
Nursery& nursery = cx->nursery();
if (tarray->isTenured() && !tarray->hasInlineElements() &&
!nursery.isInside(tarray->elements())) {
js_free(tarray->elements());
RemoveCellMemory(tarray, nbytes, MemoryUse::TypedArrayElements);
}
tarray->setPrivate(buffer->dataPointer());
tarray->setFixedSlot(TypedArrayObject::BUFFER_SLOT, ObjectValue(*buffer));
// Notify compiled jit code that the base pointer has moved.
MarkObjectStateChange(cx, tarray);
return true;
}
#ifdef DEBUG
void TypedArrayObject::assertZeroLengthArrayData() const {
if (length() == 0 && !hasBuffer()) {
uint8_t* end = fixedData(TypedArrayObject::FIXED_DATA_START);
MOZ_ASSERT(end[0] == ZeroLengthArrayData);
}
}
#endif
void TypedArrayObject::finalize(FreeOp* fop, JSObject* obj) {
MOZ_ASSERT(!IsInsideNursery(obj));
TypedArrayObject* curObj = &obj->as<TypedArrayObject>();
// Template objects or discarded objects (which didn't have enough room
// for inner elements) don't have anything to free.
if (!curObj->elementsRaw()) {
return;
}
curObj->assertZeroLengthArrayData();
// Typed arrays with a buffer object do not need to be free'd
if (curObj->hasBuffer()) {
return;
}
// Free the data slot pointer if it does not point into the old JSObject.
if (!curObj->hasInlineElements()) {
size_t nbytes = JS_ROUNDUP(curObj->byteLength(), sizeof(Value));
fop->free_(obj, curObj->elements(), nbytes, MemoryUse::TypedArrayElements);
}
}
/* static */
size_t TypedArrayObject::objectMoved(JSObject* obj, JSObject* old) {
TypedArrayObject* newObj = &obj->as<TypedArrayObject>();
const TypedArrayObject* oldObj = &old->as<TypedArrayObject>();
MOZ_ASSERT(newObj->elementsRaw() == oldObj->elementsRaw());
MOZ_ASSERT(obj->isTenured());
// Typed arrays with a buffer object do not need an update.
if (oldObj->hasBuffer()) {
return 0;
}
if (!IsInsideNursery(old)) {
// Update the data slot pointer if it points to the old JSObject.
if (oldObj->hasInlineElements()) {
newObj->setInlineElements();
}
return 0;
}
void* buf = oldObj->elements();
// Discarded objects (which didn't have enough room for inner elements) don't
// have any data to move.
if (!buf) {
return 0;
}
Nursery& nursery = obj->runtimeFromMainThread()->gc.nursery();
if (!nursery.isInside(buf)) {
nursery.removeMallocedBuffer(buf);
size_t nbytes = JS_ROUNDUP(newObj->byteLength(), sizeof(Value));
AddCellMemory(newObj, nbytes, MemoryUse::TypedArrayElements);
return 0;
}
// Determine if we can use inline data for the target array. If this is
// possible, the nursery will have picked an allocation size that is large
// enough.
size_t nbytes = oldObj->byteLength();
constexpr size_t headerSize = dataOffset() + sizeof(HeapSlot);
// See AllocKindForLazyBuffer.
gc::AllocKind newAllocKind = obj->asTenured().getAllocKind();
MOZ_ASSERT_IF(nbytes == 0,
headerSize + sizeof(uint8_t) <= GetGCKindBytes(newAllocKind));
if (headerSize + nbytes <= GetGCKindBytes(newAllocKind)) {
MOZ_ASSERT(oldObj->hasInlineElements());
#ifdef DEBUG
if (nbytes == 0) {
uint8_t* output = newObj->fixedData(TypedArrayObject::FIXED_DATA_START);
output[0] = ZeroLengthArrayData;
}
#endif
newObj->setInlineElements();
} else {
MOZ_ASSERT(!oldObj->hasInlineElements());
MOZ_ASSERT((CheckedUint32(nbytes) + sizeof(Value)).isValid(),
"JS_ROUNDUP must not overflow");
AutoEnterOOMUnsafeRegion oomUnsafe;
nbytes = JS_ROUNDUP(nbytes, sizeof(Value));
void* data = newObj->zone()->pod_malloc<uint8_t>(
nbytes, js::ArrayBufferContentsArena);
if (!data) {
oomUnsafe.crash(
"Failed to allocate typed array elements while tenuring.");
}
MOZ_ASSERT(!nursery.isInside(data));
InitObjectPrivate(newObj, data, nbytes, MemoryUse::TypedArrayElements);
}
mozilla::PodCopy(newObj->elements(), oldObj->elements(), nbytes);
// Set a forwarding pointer for the element buffers in case they were
// preserved on the stack by Ion.
nursery.setForwardingPointerWhileTenuring(
oldObj->elements(), newObj->elements(),
/* direct = */ nbytes >= sizeof(uintptr_t));
return newObj->hasInlineElements() ? 0 : nbytes;
}
bool TypedArrayObject::hasInlineElements() const {
return elements() == this->fixedData(TypedArrayObject::FIXED_DATA_START) &&
byteLength() <= TypedArrayObject::INLINE_BUFFER_LIMIT;
}
void TypedArrayObject::setInlineElements() {
char* dataSlot = reinterpret_cast<char*>(this) + this->dataOffset();
*reinterpret_cast<void**>(dataSlot) =
this->fixedData(TypedArrayObject::FIXED_DATA_START);
}
/* Helper clamped uint8_t type */
uint32_t JS_FASTCALL js::ClampDoubleToUint8(const double x) {
// Not < so that NaN coerces to 0
if (!(x >= 0)) {
return 0;
}
if (x > 255) {
return 255;
}
double toTruncate = x + 0.5;
uint8_t y = uint8_t(toTruncate);
/*
* now val is rounded to nearest, ties rounded up. We want
* rounded to nearest ties to even, so check whether we had a
* tie.
*/
if (y == toTruncate) {
/*
* It was a tie (since adding 0.5 gave us the exact integer
* we want). Since we rounded up, we either already have an
* even number or we have an odd number but the number we
* want is one less. So just unconditionally masking out the
* ones bit should do the trick to get us the value we
* want.
*/
return y & ~1;
}
return y;
}
namespace {
enum class SpeciesConstructorOverride { None, ArrayBuffer };
enum class CreateSingleton { No, Yes };
template <typename NativeType>
class TypedArrayObjectTemplate : public TypedArrayObject {
friend class TypedArrayObject;
public:
static constexpr Scalar::Type ArrayTypeID() {
return TypeIDOfType<NativeType>::id;
}
static constexpr JSProtoKey protoKey() {
return TypeIDOfType<NativeType>::protoKey;
}
static constexpr bool ArrayTypeIsUnsigned() {
return TypeIsUnsigned<NativeType>();
}
static constexpr bool ArrayTypeIsFloatingPoint() {
return TypeIsFloatingPoint<NativeType>();
}
static constexpr size_t BYTES_PER_ELEMENT = sizeof(NativeType);
static JSObject* createPrototype(JSContext* cx, JSProtoKey key) {
Handle<GlobalObject*> global = cx->global();
RootedObject typedArrayProto(
cx, GlobalObject::getOrCreateTypedArrayPrototype(cx, global));
if (!typedArrayProto) {
return nullptr;
}
const Class* clasp = TypedArrayObject::protoClassForType(ArrayTypeID());
return GlobalObject::createBlankPrototypeInheriting(cx, clasp,
typedArrayProto);
}
static JSObject* createConstructor(JSContext* cx, JSProtoKey key) {
Handle<GlobalObject*> global = cx->global();
RootedFunction ctorProto(
cx, GlobalObject::getOrCreateTypedArrayConstructor(cx, global));
if (!ctorProto) {
return nullptr;
}
JSFunction* fun =
NewFunctionWithProto(cx, class_constructor, 3, JSFunction::NATIVE_CTOR,
nullptr, ClassName(key, cx), ctorProto,
gc::AllocKind::FUNCTION, SingletonObject);
if (fun) {
fun->setJitInfo(&jit::JitInfo_TypedArrayConstructor);
}
return fun;
}
static inline const Class* instanceClass() {
return TypedArrayObject::classForType(ArrayTypeID());
}
static bool is(HandleValue v) {
return v.isObject() && v.toObject().hasClass(instanceClass());
}
static bool convertValue(JSContext* cx, HandleValue v, NativeType* result);
static TypedArrayObject* newBuiltinClassInstance(JSContext* cx,
gc::AllocKind allocKind,
NewObjectKind newKind) {
JSObject* obj =
NewBuiltinClassInstance(cx, instanceClass(), allocKind, newKind);
return obj ? &obj->as<TypedArrayObject>() : nullptr;
}
static TypedArrayObject* makeProtoInstance(JSContext* cx, HandleObject proto,
gc::AllocKind allocKind) {
MOZ_ASSERT(proto);
JSObject* obj =
NewObjectWithGivenProto(cx, instanceClass(), proto, allocKind);
return obj ? &obj->as<TypedArrayObject>() : nullptr;
}
static TypedArrayObject* makeTypedInstance(JSContext* cx,
CreateSingleton createSingleton,
HandleObjectGroup group,
gc::AllocKind allocKind) {
if (createSingleton == CreateSingleton::Yes) {
MOZ_ASSERT(!group);
return newBuiltinClassInstance(cx, allocKind, SingletonObject);
}
if (group) {
MOZ_ASSERT(group->clasp() == instanceClass());
NewObjectKind newKind = GenericObject;
{
AutoSweepObjectGroup sweep(group);
if (group->shouldPreTenure(sweep)) {
newKind = TenuredObject;
}
}
return NewObjectWithGroup<TypedArrayObject>(cx, group, allocKind,
newKind);
}
jsbytecode* pc;
RootedScript script(cx, cx->currentScript(&pc));
Rooted<TypedArrayObject*> obj(
cx, newBuiltinClassInstance(cx, allocKind, GenericObject));
if (!obj) {
return nullptr;
}
if (script && !ObjectGroup::setAllocationSiteObjectGroup(
cx, script, pc, obj, /* singleton = */ false)) {
return nullptr;
}
return obj;
}
static TypedArrayObject* makeInstance(
JSContext* cx, Handle<ArrayBufferObjectMaybeShared*> buffer,
CreateSingleton createSingleton, uint32_t byteOffset, uint32_t len,
HandleObject proto, HandleObjectGroup group = nullptr) {
MOZ_ASSERT(len < INT32_MAX / BYTES_PER_ELEMENT);
gc::AllocKind allocKind =
buffer ? gc::GetGCObjectKind(instanceClass())
: AllocKindForLazyBuffer(len * BYTES_PER_ELEMENT);
// Subclassing mandates that we hand in the proto every time. Most of
// the time, though, that [[Prototype]] will not be interesting. If
// it isn't, we can do some more TI optimizations.
RootedObject checkProto(cx);
if (proto) {
checkProto = GlobalObject::getOrCreatePrototype(cx, protoKey());
if (!checkProto) {
return nullptr;
}
}
AutoSetNewObjectMetadata metadata(cx);
Rooted<TypedArrayObject*> obj(cx);
if (proto && proto != checkProto) {
MOZ_ASSERT(!group);
obj = makeProtoInstance(cx, proto, allocKind);
} else {
obj = makeTypedInstance(cx, createSingleton, group, allocKind);
}
if (!obj || !obj->init(cx, buffer, byteOffset, len, BYTES_PER_ELEMENT)) {
return nullptr;
}
return obj;
}
static TypedArrayObject* makeTemplateObject(JSContext* cx, int32_t len) {
MOZ_ASSERT(len >= 0);
size_t nbytes;
MOZ_ALWAYS_TRUE(CalculateAllocSize<NativeType>(len, &nbytes));
MOZ_ASSERT(nbytes < TypedArrayObject::SINGLETON_BYTE_LENGTH);
bool fitsInline = nbytes <= INLINE_BUFFER_LIMIT;
gc::AllocKind allocKind = !fitsInline ? gc::GetGCObjectKind(instanceClass())
: AllocKindForLazyBuffer(nbytes);
MOZ_ASSERT(allocKind >= gc::GetGCObjectKind(instanceClass()));
AutoSetNewObjectMetadata metadata(cx);
jsbytecode* pc;
RootedScript script(cx, cx->currentScript(&pc));
Rooted<TypedArrayObject*> tarray(
cx, newBuiltinClassInstance(cx, allocKind, TenuredObject));
if (!tarray) {
return nullptr;
}
initTypedArraySlots(tarray, len);
// Template objects do not need memory for its elements, since there
// won't be any elements to store. Therefore, we set the pointer to
// nullptr and avoid allocating memory that will never be used.
tarray->initPrivate(nullptr);
if (script && !ObjectGroup::setAllocationSiteObjectGroup(
cx, script, pc, tarray, /* singleton = */ false)) {
return nullptr;
}
return tarray;
}
static void initTypedArraySlots(TypedArrayObject* tarray, int32_t len) {
MOZ_ASSERT(len >= 0);
tarray->initFixedSlot(TypedArrayObject::BUFFER_SLOT, NullValue());
tarray->initFixedSlot(TypedArrayObject::LENGTH_SLOT, Int32Value(len));
tarray->initFixedSlot(TypedArrayObject::BYTEOFFSET_SLOT, Int32Value(0));
// Verify that the private slot is at the expected place.
MOZ_ASSERT(tarray->numFixedSlots() == TypedArrayObject::DATA_SLOT);
#ifdef DEBUG
if (len == 0) {
uint8_t* output = tarray->fixedData(TypedArrayObject::FIXED_DATA_START);
output[0] = TypedArrayObject::ZeroLengthArrayData;
}
#endif
}
static void initTypedArrayData(TypedArrayObject* tarray, void* buf,
size_t nbytes, gc::AllocKind allocKind) {
if (buf) {
InitObjectPrivate(tarray, buf, nbytes, MemoryUse::TypedArrayElements);
} else {
#ifdef DEBUG
constexpr size_t dataOffset = TypedArrayObject::dataOffset();
constexpr size_t offset = dataOffset + sizeof(HeapSlot);
MOZ_ASSERT(offset + nbytes <= GetGCKindBytes(allocKind));
#endif
void* data = tarray->fixedData(FIXED_DATA_START);
tarray->initPrivate(data);
memset(data, 0, nbytes);
}
}
static TypedArrayObject* makeTypedArrayWithTemplate(
JSContext* cx, TypedArrayObject* templateObj, int32_t len) {
if (len < 0 || uint32_t(len) >= INT32_MAX / BYTES_PER_ELEMENT) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_BAD_ARRAY_LENGTH);
return nullptr;
}
size_t nbytes = len * BYTES_PER_ELEMENT;
bool fitsInline = nbytes <= INLINE_BUFFER_LIMIT;
AutoSetNewObjectMetadata metadata(cx);
gc::AllocKind allocKind = !fitsInline ? gc::GetGCObjectKind(instanceClass())
: AllocKindForLazyBuffer(nbytes);
RootedObjectGroup group(cx, templateObj->group());
MOZ_ASSERT(group->clasp() == instanceClass());
TypedArrayObject* obj =
NewObjectWithGroup<TypedArrayObject>(cx, group, allocKind);
if (!obj) {
return nullptr;
}
initTypedArraySlots(obj, len);
void* buf = nullptr;
if (!fitsInline) {
MOZ_ASSERT(len > 0);
MOZ_ASSERT((CheckedUint32(nbytes) + sizeof(Value)).isValid(),
"JS_ROUNDUP must not overflow");
nbytes = JS_ROUNDUP(nbytes, sizeof(Value));
buf = cx->nursery().allocateZeroedBuffer(obj, nbytes,
js::ArrayBufferContentsArena);
if (!buf) {
ReportOutOfMemory(cx);
return nullptr;
}
}
initTypedArrayData(obj, buf, nbytes, allocKind);
return obj;
}
static TypedArrayObject* makeTypedArrayWithTemplate(
JSContext* cx, TypedArrayObject* templateObj, HandleObject array) {
MOZ_ASSERT(!IsWrapper(array));
MOZ_ASSERT(!array->is<ArrayBufferObjectMaybeShared>());
RootedObjectGroup group(cx, templateObj->group());
return fromArray(cx, array, nullptr, group);
}
static TypedArrayObject* makeTypedArrayWithTemplate(
JSContext* cx, TypedArrayObject* templateObj, HandleObject arrayBuffer,
HandleValue byteOffsetValue, HandleValue lengthValue) {
MOZ_ASSERT(!IsWrapper(arrayBuffer));
MOZ_ASSERT(arrayBuffer->is<ArrayBufferObjectMaybeShared>());
RootedObjectGroup group(cx, templateObj->group());
uint64_t byteOffset, length;
if (!byteOffsetAndLength(cx, byteOffsetValue, lengthValue, &byteOffset,
&length)) {
return nullptr;
}
return fromBufferSameCompartment(
cx, arrayBuffer.as<ArrayBufferObjectMaybeShared>(), byteOffset, length,
nullptr, group);
}
// ES2018 draft rev 8340bf9a8427ea81bb0d1459471afbcc91d18add
// 22.2.4.1 TypedArray ( )
// 22.2.4.2 TypedArray ( length )
// 22.2.4.3 TypedArray ( typedArray )
// 22.2.4.4 TypedArray ( object )
// 22.2.4.5 TypedArray ( buffer [ , byteOffset [ , length ] ] )
static bool class_constructor(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
// Step 1 (22.2.4.1) or 2 (22.2.4.2-5).
if (!ThrowIfNotConstructing(cx, args, "typed array")) {
return false;
}
JSObject* obj = create(cx, args);
if (!obj) {
return false;
}
args.rval().setObject(*obj);
return true;
}
private:
static JSObject* create(JSContext* cx, const CallArgs& args) {
MOZ_ASSERT(args.isConstructing());
// 22.2.4.1 TypedArray ( )
// 22.2.4.2 TypedArray ( length )
if (args.length() == 0 || !args[0].isObject()) {
// 22.2.4.2, step 3.
uint64_t len;
if (!ToIndex(cx, args.get(0), JSMSG_BAD_ARRAY_LENGTH, &len)) {
return nullptr;
}
// 22.2.4.1, step 3 and 22.2.4.2, step 5.
// 22.2.4.2.1 AllocateTypedArray, step 1.
RootedObject proto(cx);
if (!GetPrototypeFromBuiltinConstructor(cx, args, protoKey(), &proto)) {
return nullptr;
}
return fromLength(cx, len, proto);
}
RootedObject dataObj(cx, &args[0].toObject());
// 22.2.4.{3,4,5}, step 4.
// 22.2.4.2.1 AllocateTypedArray, step 1.
RootedObject proto(cx);
if (!GetPrototypeFromBuiltinConstructor(cx, args, protoKey(), &proto)) {
return nullptr;
}
// 22.2.4.3 TypedArray ( typedArray )
// 22.2.4.4 TypedArray ( object )
if (!UncheckedUnwrap(dataObj)->is<ArrayBufferObjectMaybeShared>()) {
return fromArray(cx, dataObj, proto);
}
// 22.2.4.5 TypedArray ( buffer [ , byteOffset [ , length ] ] )
uint64_t byteOffset, length;
if (!byteOffsetAndLength(cx, args.get(1), args.get(2), &byteOffset,
&length)) {
return nullptr;
}
// Steps 9-17.
if (dataObj->is<ArrayBufferObjectMaybeShared>()) {
HandleArrayBufferObjectMaybeShared buffer =
dataObj.as<ArrayBufferObjectMaybeShared>();
return fromBufferSameCompartment(cx, buffer, byteOffset, length, proto);
}
return fromBufferWrapped(cx, dataObj, byteOffset, length, proto);
}
// ES2018 draft rev 8340bf9a8427ea81bb0d1459471afbcc91d18add
// 22.2.4.5 TypedArray ( buffer [ , byteOffset [ , length ] ] )
// Steps 6-8.
static bool byteOffsetAndLength(JSContext* cx, HandleValue byteOffsetValue,
HandleValue lengthValue, uint64_t* byteOffset,
uint64_t* length) {
*byteOffset = 0;
if (!byteOffsetValue.isUndefined()) {
// Step 6.
if (!ToIndex(cx, byteOffsetValue, byteOffset)) {
return false;
}
// Step 7.
if (*byteOffset % BYTES_PER_ELEMENT != 0) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_TYPED_ARRAY_CONSTRUCT_BOUNDS);
return false;
}
}
*length = UINT64_MAX;
if (!lengthValue.isUndefined()) {
// Step 8.a.
if (!ToIndex(cx, lengthValue, length)) {
return false;
}
}
return true;
}
// ES2018 draft rev 8340bf9a8427ea81bb0d1459471afbcc91d18add
// 22.2.4.5 TypedArray ( buffer [ , byteOffset [ , length ] ] )
// Steps 9-12.
static bool computeAndCheckLength(
JSContext* cx, HandleArrayBufferObjectMaybeShared bufferMaybeUnwrapped,
uint64_t byteOffset, uint64_t lengthIndex, uint32_t* length) {
MOZ_ASSERT(byteOffset % BYTES_PER_ELEMENT == 0);
MOZ_ASSERT(byteOffset < uint64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT));
MOZ_ASSERT_IF(lengthIndex != UINT64_MAX,
lengthIndex < uint64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT));
// Step 9.
if (bufferMaybeUnwrapped->isDetached()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_TYPED_ARRAY_DETACHED);
return false;
}
// Step 10.
uint32_t bufferByteLength = bufferMaybeUnwrapped->byteLength();
uint32_t len;
if (lengthIndex == UINT64_MAX) {
// Steps 11.a, 11.c.
if (bufferByteLength % BYTES_PER_ELEMENT != 0 ||
byteOffset > bufferByteLength) {
// The given byte array doesn't map exactly to
// |BYTES_PER_ELEMENT * N| or |byteOffset| is invalid.
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_TYPED_ARRAY_CONSTRUCT_BOUNDS);
return false;
}
// Step 11.b.
uint32_t newByteLength = bufferByteLength - uint32_t(byteOffset);
len = newByteLength / BYTES_PER_ELEMENT;
} else {
// Step 12.a.
uint64_t newByteLength = lengthIndex * BYTES_PER_ELEMENT;
// Step 12.b.
if (byteOffset + newByteLength > bufferByteLength) {
// |byteOffset + newByteLength| is too big for the arraybuffer
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_TYPED_ARRAY_CONSTRUCT_BOUNDS);
return false;
}
len = uint32_t(lengthIndex);
}
// ArrayBuffer is too large for TypedArrays:
// Standalone ArrayBuffers can hold up to INT32_MAX bytes, whereas
// buffers in TypedArrays must have less than or equal to
// |INT32_MAX - BYTES_PER_ELEMENT - INT32_MAX % BYTES_PER_ELEMENT|
// bytes.
if (len >= INT32_MAX / BYTES_PER_ELEMENT) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_TYPED_ARRAY_CONSTRUCT_BOUNDS);
return false;
}
MOZ_ASSERT(byteOffset <= UINT32_MAX);
*length = len;
return true;
}
// ES2018 draft rev 8340bf9a8427ea81bb0d1459471afbcc91d18add
// 22.2.4.5 TypedArray ( buffer [ , byteOffset [ , length ] ] )
// Steps 9-17.
static TypedArrayObject* fromBufferSameCompartment(
JSContext* cx, HandleArrayBufferObjectMaybeShared buffer,
uint64_t byteOffset, uint64_t lengthIndex, HandleObject proto,
HandleObjectGroup group = nullptr) {
// Steps 9-12.
uint32_t length;
if (!computeAndCheckLength(cx, buffer, byteOffset, lengthIndex, &length)) {
return nullptr;
}
CreateSingleton createSingleton = CreateSingleton::No;
if (!group &&
length * BYTES_PER_ELEMENT >= TypedArrayObject::SINGLETON_BYTE_LENGTH) {
createSingleton = CreateSingleton::Yes;
}
// Steps 13-17.
return makeInstance(cx, buffer, createSingleton, uint32_t(byteOffset),
length, proto, group);
}
// Create a TypedArray object in another compartment.
//
// ES6 supports creating a TypedArray in global A (using global A's
// TypedArray constructor) backed by an ArrayBuffer created in global B.
//
// Our TypedArrayObject implementation doesn't support a TypedArray in
// compartment A backed by an ArrayBuffer in compartment B. So in this
// case, we create the TypedArray in B (!) and return a cross-compartment
// wrapper.
//
// Extra twist: the spec says the new TypedArray's [[Prototype]] must be
// A's TypedArray.prototype. So even though we're creating the TypedArray
// in B, its [[Prototype]] must be (a cross-compartment wrapper for) the
// TypedArray.prototype in A.
static JSObject* fromBufferWrapped(JSContext* cx, HandleObject bufobj,
uint64_t byteOffset, uint64_t lengthIndex,
HandleObject proto) {
JSObject* unwrapped = CheckedUnwrapStatic(bufobj);
if (!unwrapped) {
ReportAccessDenied(cx);
return nullptr;
}
if (!unwrapped->is<ArrayBufferObjectMaybeShared>()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_TYPED_ARRAY_BAD_ARGS);
return nullptr;
}
RootedArrayBufferObjectMaybeShared unwrappedBuffer(cx);
unwrappedBuffer = &unwrapped->as<ArrayBufferObjectMaybeShared>();
uint32_t length;
if (!computeAndCheckLength(cx, unwrappedBuffer, byteOffset, lengthIndex,
&length)) {
return nullptr;
}
// Make sure to get the [[Prototype]] for the created typed array from
// this compartment.
RootedObject protoRoot(cx, proto);
if (!protoRoot) {
protoRoot = GlobalObject::getOrCreatePrototype(cx, protoKey());
if (!protoRoot) {
return nullptr;
}
}
RootedObject typedArray(cx);
{
JSAutoRealm ar(cx, unwrappedBuffer);
RootedObject wrappedProto(cx, protoRoot);
if (!cx->compartment()->wrap(cx, &wrappedProto)) {
return nullptr;
}
typedArray = makeInstance(cx, unwrappedBuffer, CreateSingleton::No,
uint32_t(byteOffset), length, wrappedProto);
if (!typedArray) {
return nullptr;
}
}
if (!cx->compartment()->wrap(cx, &typedArray)) {
return nullptr;
}
return typedArray;
}
public:
static JSObject* fromBuffer(JSContext* cx, HandleObject bufobj,
uint32_t byteOffset, int32_t lengthInt) {
if (byteOffset % BYTES_PER_ELEMENT != 0) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_TYPED_ARRAY_CONSTRUCT_BOUNDS);
return nullptr; // invalid byteOffset
}
uint64_t lengthIndex = lengthInt >= 0 ? uint64_t(lengthInt) : UINT64_MAX;
if (bufobj->is<ArrayBufferObjectMaybeShared>()) {
HandleArrayBufferObjectMaybeShared buffer =
bufobj.as<ArrayBufferObjectMaybeShared>();
return fromBufferSameCompartment(cx, buffer, byteOffset, lengthIndex,
nullptr);
}
return fromBufferWrapped(cx, bufobj, byteOffset, lengthIndex, nullptr);
}
static bool maybeCreateArrayBuffer(JSContext* cx, uint32_t count,
HandleObject nonDefaultProto,
MutableHandle<ArrayBufferObject*> buffer) {
if (count >= INT32_MAX / BYTES_PER_ELEMENT) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_BAD_ARRAY_LENGTH);
return false;
}
uint32_t byteLength = count * BYTES_PER_ELEMENT;
MOZ_ASSERT(byteLength < INT32_MAX);
static_assert(INLINE_BUFFER_LIMIT % BYTES_PER_ELEMENT == 0,
"ArrayBuffer inline storage shouldn't waste any space");
if (!nonDefaultProto && byteLength <= INLINE_BUFFER_LIMIT) {
// The array's data can be inline, and the buffer created lazily.
return true;
}
ArrayBufferObject* buf =
ArrayBufferObject::createZeroed(cx, byteLength, nonDefaultProto);
if (!buf) {
return false;
}
buffer.set(buf);
return true;
}
// 22.2.4.1 TypedArray ( )
// 22.2.4.2 TypedArray ( length )
static JSObject* fromLength(JSContext* cx, uint64_t nelements,
HandleObject proto = nullptr) {
// 22.2.4.1, step 1 and 22.2.4.2, steps 1-3 (performed in caller).
// 22.2.4.1, step 2 and 22.2.4.2, step 4 (implicit).
// 22.2.4.1, step 3 and 22.2.4.2, step 5 (call AllocateTypedArray).
if (nelements > UINT32_MAX) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_BAD_ARRAY_LENGTH);
return nullptr;
}
Rooted<ArrayBufferObject*> buffer(cx);
if (!maybeCreateArrayBuffer(cx, uint32_t(nelements), nullptr, &buffer)) {
return nullptr;
}
return makeInstance(cx, buffer, CreateSingleton::No, 0, uint32_t(nelements),
proto);
}
static bool AllocateArrayBuffer(JSContext* cx, HandleObject ctor,
uint32_t count,
MutableHandle<ArrayBufferObject*> buffer);
static TypedArrayObject* fromArray(JSContext* cx, HandleObject other,
HandleObject proto = nullptr,
HandleObjectGroup group = nullptr);
static TypedArrayObject* fromTypedArray(JSContext* cx, HandleObject other,
bool isWrapped, HandleObject proto,
HandleObjectGroup group);
static TypedArrayObject* fromObject(JSContext* cx, HandleObject other,
HandleObject proto,
HandleObjectGroup group);
static const NativeType getIndex(TypedArrayObject* tarray, uint32_t index) {
MOZ_ASSERT(index < tarray->length());
return jit::AtomicOperations::loadSafeWhenRacy(
tarray->dataPointerEither().cast<NativeType*>() + index);
}
static void setIndex(TypedArrayObject& tarray, uint32_t index,
NativeType val) {
MOZ_ASSERT(index < tarray.length());
jit::AtomicOperations::storeSafeWhenRacy(
tarray.dataPointerEither().cast<NativeType*>() + index, val);
}
static bool getElement(JSContext* cx, TypedArrayObject* tarray,
uint32_t index, MutableHandleValue val);
static bool getElementPure(TypedArrayObject* tarray, uint32_t index,
Value* vp);
static bool setElement(JSContext* cx, Handle<TypedArrayObject*> obj,
uint64_t index, HandleValue v, ObjectOpResult& result);
static bool defineElement(JSContext* cx, HandleObject obj, uint64_t index,
HandleValue v, ObjectOpResult& result);
};
template <typename NativeType>
bool TypedArrayObjectTemplate<NativeType>::convertValue(JSContext* cx,
HandleValue v,
NativeType* result) {
double d;
if (!ToNumber(cx, v, &d)) {
return false;
}