-
Notifications
You must be signed in to change notification settings - Fork 54
/
ArrayBufferObject.cpp
1823 lines (1543 loc) · 58.4 KB
/
ArrayBufferObject.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/ArrayBufferObject-inl.h"
#include "vm/ArrayBufferObject.h"
#include "mozilla/Alignment.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/FloatingPoint.h"
#include "mozilla/Maybe.h"
#include "mozilla/PodOperations.h"
#include "mozilla/TaggedAnonymousMemory.h"
#include <string.h>
#ifndef XP_WIN
#include <sys/mman.h>
#endif
#ifdef MOZ_VALGRIND
#include <valgrind/memcheck.h>
#endif
#include "jsapi.h"
#include "jsfriendapi.h"
#include "jsnum.h"
#include "jstypes.h"
#include "jsutil.h"
#include "builtin/Array.h"
#include "builtin/DataViewObject.h"
#include "gc/Barrier.h"
#include "gc/FreeOp.h"
#include "gc/Memory.h"
#include "js/Conversions.h"
#include "js/MemoryMetrics.h"
#include "js/Wrapper.h"
#include "util/Windows.h"
#include "vm/GlobalObject.h"
#include "vm/Interpreter.h"
#include "vm/JSContext.h"
#include "vm/JSObject.h"
#include "vm/SharedArrayObject.h"
#include "vm/WrapperObject.h"
#include "wasm/WasmSignalHandlers.h"
#include "wasm/WasmTypes.h"
#include "gc/Marking-inl.h"
#include "gc/Nursery-inl.h"
#include "vm/JSAtom-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/Shape-inl.h"
using JS::ToInt32;
using mozilla::Atomic;
using mozilla::CheckedInt;
using mozilla::Maybe;
using mozilla::Nothing;
using mozilla::Some;
using mozilla::Unused;
using namespace js;
/*
* Convert |v| to an array index for an array of length |length| per
* the Typed Array Specification section 7.0, |subarray|. If successful,
* the output value is in the range [0, length].
*/
bool js::ToClampedIndex(JSContext* cx, HandleValue v, uint32_t length,
uint32_t* out) {
int32_t result;
if (!ToInt32(cx, v, &result)) {
return false;
}
if (result < 0) {
result += length;
if (result < 0) {
result = 0;
}
} else if (uint32_t(result) > length) {
result = length;
}
*out = uint32_t(result);
return true;
}
// If there are too many 4GB buffers live we run up against system resource
// exhaustion (address space or number of memory map descriptors), see
// bug 1068684, bug 1073934 for details. The limiting case seems to be
// Windows Vista Home 64-bit, where the per-process address space is limited
// to 8TB. Thus we track the number of live objects, and set a limit of
// 1000 live objects per process and we throw an OOM error if the per-process
// limit is exceeded.
//
// Since the MaximumLiveMappedBuffers limit is not generally accounted for by
// any existing GC-trigger heuristics, we need an extra heuristic for triggering
// GCs when the caller is allocating memories rapidly without other garbage.
// Thus, once the live buffer count crosses a certain threshold, we start
// triggering GCs every N allocations. As we get close to the limit, perform
// expensive non-incremental full GCs as a last-ditch effort to avoid
// unnecessary failure. The *Sans use a ton of vmem for bookkeeping leaving a
// lot less for the program so use a lower limit.
#if defined(MOZ_TSAN) || defined(MOZ_ASAN)
static const int32_t MaximumLiveMappedBuffers = 500;
#else
static const int32_t MaximumLiveMappedBuffers = 1000;
#endif
static const int32_t StartTriggeringAtLiveBufferCount = 100;
static const int32_t StartSyncFullGCAtLiveBufferCount =
MaximumLiveMappedBuffers - 100;
static const int32_t AllocatedBuffersPerTrigger = 100;
static Atomic<int32_t, mozilla::ReleaseAcquire> liveBufferCount(0);
static Atomic<int32_t, mozilla::ReleaseAcquire> allocatedSinceLastTrigger(0);
int32_t js::LiveMappedBufferCount() { return liveBufferCount; }
void* js::MapBufferMemory(size_t mappedSize, size_t initialCommittedSize) {
MOZ_ASSERT(mappedSize % gc::SystemPageSize() == 0);
MOZ_ASSERT(initialCommittedSize % gc::SystemPageSize() == 0);
MOZ_ASSERT(initialCommittedSize <= mappedSize);
// Test >= to guard against the case where multiple extant runtimes
// race to allocate.
if (++liveBufferCount >= MaximumLiveMappedBuffers) {
if (OnLargeAllocationFailure) {
OnLargeAllocationFailure();
}
if (liveBufferCount >= MaximumLiveMappedBuffers) {
liveBufferCount--;
return nullptr;
}
}
#ifdef XP_WIN
void* data = VirtualAlloc(nullptr, mappedSize, MEM_RESERVE, PAGE_NOACCESS);
if (!data) {
liveBufferCount--;
return nullptr;
}
if (!VirtualAlloc(data, initialCommittedSize, MEM_COMMIT, PAGE_READWRITE)) {
VirtualFree(data, 0, MEM_RELEASE);
liveBufferCount--;
return nullptr;
}
#else // XP_WIN
void* data =
MozTaggedAnonymousMmap(nullptr, mappedSize, PROT_NONE,
MAP_PRIVATE | MAP_ANON, -1, 0, "wasm-reserved");
if (data == MAP_FAILED) {
liveBufferCount--;
return nullptr;
}
// Note we will waste a page on zero-sized memories here
if (mprotect(data, initialCommittedSize, PROT_READ | PROT_WRITE)) {
munmap(data, mappedSize);
liveBufferCount--;
return nullptr;
}
#endif // !XP_WIN
#if defined(MOZ_VALGRIND) && \
defined(VALGRIND_DISABLE_ADDR_ERROR_REPORTING_IN_RANGE)
VALGRIND_DISABLE_ADDR_ERROR_REPORTING_IN_RANGE(
(unsigned char*)data + initialCommittedSize,
mappedSize - initialCommittedSize);
#endif
return data;
}
bool js::CommitBufferMemory(void* dataEnd, uint32_t delta) {
MOZ_ASSERT(delta);
MOZ_ASSERT(delta % gc::SystemPageSize() == 0);
#ifdef XP_WIN
if (!VirtualAlloc(dataEnd, delta, MEM_COMMIT, PAGE_READWRITE)) {
return false;
}
#else // XP_WIN
if (mprotect(dataEnd, delta, PROT_READ | PROT_WRITE)) {
return false;
}
#endif // !XP_WIN
#if defined(MOZ_VALGRIND) && \
defined(VALGRIND_DISABLE_ADDR_ERROR_REPORTING_IN_RANGE)
VALGRIND_ENABLE_ADDR_ERROR_REPORTING_IN_RANGE((unsigned char*)dataEnd, delta);
#endif
return true;
}
#ifndef WASM_HUGE_MEMORY
bool js::ExtendBufferMapping(void* dataPointer, size_t mappedSize,
size_t newMappedSize) {
MOZ_ASSERT(mappedSize % gc::SystemPageSize() == 0);
MOZ_ASSERT(newMappedSize % gc::SystemPageSize() == 0);
MOZ_ASSERT(newMappedSize >= mappedSize);
#ifdef XP_WIN
void* mappedEnd = (char*)dataPointer + mappedSize;
uint32_t delta = newMappedSize - mappedSize;
if (!VirtualAlloc(mappedEnd, delta, MEM_RESERVE, PAGE_NOACCESS)) {
return false;
}
return true;
#elif defined(XP_LINUX)
// Note this will not move memory (no MREMAP_MAYMOVE specified)
if (MAP_FAILED == mremap(dataPointer, mappedSize, newMappedSize, 0)) {
return false;
}
return true;
#else
// No mechanism for remapping on MacOS and other Unices. Luckily
// shouldn't need it here as most of these are 64-bit.
return false;
#endif
}
#endif
void js::UnmapBufferMemory(void* base, size_t mappedSize) {
MOZ_ASSERT(mappedSize % gc::SystemPageSize() == 0);
#ifdef XP_WIN
VirtualFree(base, 0, MEM_RELEASE);
#else // XP_WIN
munmap(base, mappedSize);
#endif // !XP_WIN
#if defined(MOZ_VALGRIND) && \
defined(VALGRIND_ENABLE_ADDR_ERROR_REPORTING_IN_RANGE)
VALGRIND_ENABLE_ADDR_ERROR_REPORTING_IN_RANGE((unsigned char*)base,
mappedSize);
#endif
// Decrement the buffer counter at the end -- otherwise, a race condition
// could enable the creation of unlimited buffers.
liveBufferCount--;
}
/*
* ArrayBufferObject
*
* This class holds the underlying raw buffer that the TypedArrayObject classes
* access. It can be created explicitly and passed to a TypedArrayObject, or
* can be created implicitly by constructing a TypedArrayObject with a size.
*/
/*
* ArrayBufferObject (base)
*/
static const ClassOps ArrayBufferObjectClassOps = {
nullptr, /* addProperty */
nullptr, /* delProperty */
nullptr, /* enumerate */
nullptr, /* newEnumerate */
nullptr, /* resolve */
nullptr, /* mayResolve */
ArrayBufferObject::finalize,
nullptr, /* call */
nullptr, /* hasInstance */
nullptr, /* construct */
ArrayBufferObject::trace,
};
static const JSFunctionSpec arraybuffer_functions[] = {
JS_FN("isView", ArrayBufferObject::fun_isView, 1, 0), JS_FS_END};
static const JSPropertySpec arraybuffer_properties[] = {
JS_SELF_HOSTED_SYM_GET(species, "ArrayBufferSpecies", 0), JS_PS_END};
static const JSFunctionSpec arraybuffer_proto_functions[] = {
JS_SELF_HOSTED_FN("slice", "ArrayBufferSlice", 2, 0), JS_FS_END};
static const JSPropertySpec arraybuffer_proto_properties[] = {
JS_PSG("byteLength", ArrayBufferObject::byteLengthGetter, 0),
JS_STRING_SYM_PS(toStringTag, "ArrayBuffer", JSPROP_READONLY), JS_PS_END};
static const ClassSpec ArrayBufferObjectClassSpec = {
GenericCreateConstructor<ArrayBufferObject::class_constructor, 1,
gc::AllocKind::FUNCTION>,
GenericCreatePrototype<ArrayBufferObject>,
arraybuffer_functions,
arraybuffer_properties,
arraybuffer_proto_functions,
arraybuffer_proto_properties};
static const ClassExtension ArrayBufferObjectClassExtension = {
nullptr, /* weakmapKeyDelegateOp */
ArrayBufferObject::objectMoved};
const Class ArrayBufferObject::class_ = {
"ArrayBuffer",
JSCLASS_DELAY_METADATA_BUILDER |
JSCLASS_HAS_RESERVED_SLOTS(RESERVED_SLOTS) |
JSCLASS_HAS_CACHED_PROTO(JSProto_ArrayBuffer) |
JSCLASS_BACKGROUND_FINALIZE,
&ArrayBufferObjectClassOps, &ArrayBufferObjectClassSpec,
&ArrayBufferObjectClassExtension};
const Class ArrayBufferObject::protoClass_ = {
"ArrayBufferPrototype", JSCLASS_HAS_CACHED_PROTO(JSProto_ArrayBuffer),
JS_NULL_CLASS_OPS, &ArrayBufferObjectClassSpec};
bool js::IsArrayBuffer(HandleValue v) {
return v.isObject() && v.toObject().is<ArrayBufferObject>();
}
bool js::IsArrayBuffer(HandleObject obj) {
return obj->is<ArrayBufferObject>();
}
bool js::IsArrayBuffer(JSObject* obj) { return obj->is<ArrayBufferObject>(); }
ArrayBufferObject& js::AsArrayBuffer(HandleObject obj) {
MOZ_ASSERT(IsArrayBuffer(obj));
return obj->as<ArrayBufferObject>();
}
ArrayBufferObject& js::AsArrayBuffer(JSObject* obj) {
MOZ_ASSERT(IsArrayBuffer(obj));
return obj->as<ArrayBufferObject>();
}
bool js::IsArrayBufferMaybeShared(HandleValue v) {
return v.isObject() && v.toObject().is<ArrayBufferObjectMaybeShared>();
}
bool js::IsArrayBufferMaybeShared(HandleObject obj) {
return obj->is<ArrayBufferObjectMaybeShared>();
}
bool js::IsArrayBufferMaybeShared(JSObject* obj) {
return obj->is<ArrayBufferObjectMaybeShared>();
}
ArrayBufferObjectMaybeShared& js::AsArrayBufferMaybeShared(HandleObject obj) {
MOZ_ASSERT(IsArrayBufferMaybeShared(obj));
return obj->as<ArrayBufferObjectMaybeShared>();
}
ArrayBufferObjectMaybeShared& js::AsArrayBufferMaybeShared(JSObject* obj) {
MOZ_ASSERT(IsArrayBufferMaybeShared(obj));
return obj->as<ArrayBufferObjectMaybeShared>();
}
MOZ_ALWAYS_INLINE bool ArrayBufferObject::byteLengthGetterImpl(
JSContext* cx, const CallArgs& args) {
MOZ_ASSERT(IsArrayBuffer(args.thisv()));
args.rval().setInt32(
args.thisv().toObject().as<ArrayBufferObject>().byteLength());
return true;
}
bool ArrayBufferObject::byteLengthGetter(JSContext* cx, unsigned argc,
Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsArrayBuffer, byteLengthGetterImpl>(cx, args);
}
/*
* ArrayBuffer.isView(obj); ES6 (Dec 2013 draft) 24.1.3.1
*/
bool ArrayBufferObject::fun_isView(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
args.rval().setBoolean(args.get(0).isObject() &&
JS_IsArrayBufferViewObject(&args.get(0).toObject()));
return true;
}
// ES2017 draft 24.1.2.1
bool ArrayBufferObject::class_constructor(JSContext* cx, unsigned argc,
Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
// Step 1.
if (!ThrowIfNotConstructing(cx, args, "ArrayBuffer")) {
return false;
}
// Step 2.
uint64_t byteLength;
if (!ToIndex(cx, args.get(0), &byteLength)) {
return false;
}
// Step 3 (Inlined 24.1.1.1 AllocateArrayBuffer).
// 24.1.1.1, step 1 (Inlined 9.1.14 OrdinaryCreateFromConstructor).
RootedObject proto(cx);
if (!GetPrototypeFromBuiltinConstructor(cx, args, &proto)) {
return false;
}
// 24.1.1.1, step 3 (Inlined 6.2.6.1 CreateByteDataBlock, step 2).
// Refuse to allocate too large buffers, currently limited to ~2 GiB.
if (byteLength > INT32_MAX) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_BAD_ARRAY_LENGTH);
return false;
}
// 24.1.1.1, steps 1 and 4-6.
JSObject* bufobj = create(cx, uint32_t(byteLength), proto);
if (!bufobj) {
return false;
}
args.rval().setObject(*bufobj);
return true;
}
static ArrayBufferObject::BufferContents AllocateArrayBufferContents(
JSContext* cx, uint32_t nbytes) {
uint8_t* p =
cx->pod_callocCanGC<uint8_t>(nbytes, js::ArrayBufferContentsArena);
return ArrayBufferObject::BufferContents::create<ArrayBufferObject::PLAIN>(p);
}
static void NoteViewBufferWasDetached(
ArrayBufferViewObject* view, ArrayBufferObject::BufferContents newContents,
JSContext* cx) {
view->notifyBufferDetached(cx, newContents.data());
// Notify compiled jit code that the base pointer has moved.
MarkObjectStateChange(cx, view);
}
/* static */ void ArrayBufferObject::detach(JSContext* cx,
Handle<ArrayBufferObject*> buffer,
BufferContents newContents) {
cx->check(buffer);
MOZ_ASSERT(!buffer->isPreparedForAsmJS());
// When detaching buffers where we don't know all views, the new data must
// match the old data. All missing views are typed objects, which do not
// expect their data to ever change.
MOZ_ASSERT_IF(buffer->forInlineTypedObject(),
newContents.data() == buffer->dataPointer());
// When detaching a buffer with typed object views, any jitcode accessing
// such views must be deoptimized so that detachment checks are performed.
// This is done by setting a zone-wide flag indicating that buffers with
// typed object views have been detached.
if (buffer->hasTypedObjectViews()) {
// Make sure the global object's group has been instantiated, so the
// flag change will be observed.
AutoEnterOOMUnsafeRegion oomUnsafe;
if (!JSObject::getGroup(cx, cx->global())) {
oomUnsafe.crash("ArrayBufferObject::detach");
}
MarkObjectGroupFlags(cx, cx->global(),
OBJECT_FLAG_TYPED_OBJECT_HAS_DETACHED_BUFFER);
cx->zone()->detachedTypedObjects = 1;
}
// Update all views of the buffer to account for the buffer having been
// detached, and clear the buffer's data and list of views.
//
// Typed object buffers are not exposed and cannot be detached.
auto& innerViews = ObjectRealm::get(buffer).innerViews.get();
if (InnerViewTable::ViewVector* views =
innerViews.maybeViewsUnbarriered(buffer)) {
for (size_t i = 0; i < views->length(); i++) {
JSObject* view = (*views)[i];
NoteViewBufferWasDetached(&view->as<ArrayBufferViewObject>(), newContents,
cx);
}
innerViews.removeViews(buffer);
}
if (JSObject* view = buffer->firstView()) {
MOZ_ASSERT(!buffer->forInlineTypedObject(),
"Typed object buffers cannot be detached");
NoteViewBufferWasDetached(&view->as<ArrayBufferViewObject>(), newContents,
cx);
buffer->setFirstView(nullptr);
}
if (newContents.data() != buffer->dataPointer()) {
buffer->setNewData(cx->runtime()->defaultFreeOp(), newContents, OwnsData);
}
buffer->setByteLength(0);
buffer->setIsDetached();
}
void ArrayBufferObject::setNewData(FreeOp* fop, BufferContents newContents,
OwnsState ownsState) {
if (ownsData()) {
MOZ_ASSERT(newContents.data() != dataPointer());
releaseData(fop);
}
setDataPointer(newContents, ownsState);
}
// This is called *only* from changeContents(), below.
// By construction, every view parameter will be mapping unshared memory (an
// ArrayBuffer). Hence no reason to worry about shared memory here.
void ArrayBufferObject::changeViewContents(JSContext* cx,
ArrayBufferViewObject* view,
uint8_t* oldDataPointer,
BufferContents newContents) {
MOZ_ASSERT(!view->isSharedMemory());
// Watch out for NULL data pointers in views. This means that the view
// is not fully initialized (in which case it'll be initialized later
// with the correct pointer).
JS::AutoCheckCannotGC nogc;
uint8_t* viewDataPointer = view->dataPointerUnshared(nogc);
if (viewDataPointer) {
MOZ_ASSERT(newContents);
ptrdiff_t offset = viewDataPointer - oldDataPointer;
viewDataPointer = static_cast<uint8_t*>(newContents.data()) + offset;
view->setDataPointerUnshared(viewDataPointer);
}
// Notify compiled jit code that the base pointer has moved.
MarkObjectStateChange(cx, view);
}
// BufferContents is specific to ArrayBuffer, hence it will not represent shared
// memory.
void ArrayBufferObject::changeContents(JSContext* cx,
BufferContents newContents,
OwnsState ownsState) {
MOZ_RELEASE_ASSERT(!isWasm());
MOZ_ASSERT(!forInlineTypedObject());
// Change buffer contents.
uint8_t* oldDataPointer = dataPointer();
setNewData(cx->runtime()->defaultFreeOp(), newContents, ownsState);
// Update all views.
auto& innerViews = ObjectRealm::get(this).innerViews.get();
if (InnerViewTable::ViewVector* views =
innerViews.maybeViewsUnbarriered(this)) {
for (size_t i = 0; i < views->length(); i++) {
JSObject* view = (*views)[i];
changeViewContents(cx, &view->as<ArrayBufferViewObject>(), oldDataPointer,
newContents);
}
}
if (JSObject* view = firstView()) {
changeViewContents(cx, &view->as<ArrayBufferViewObject>(), oldDataPointer,
newContents);
}
}
/*
* [SMDOC] WASM Linear Memory structure
*
* Wasm Raw Buf Linear Memory Structure
*
* The linear heap in Wasm is an mmaped array buffer. Several
* constants manage its lifetime:
*
* - length - the wasm-visible current length of the buffer. Accesses in the
* range [0, length] succeed. May only increase.
*
* - boundsCheckLimit - the size against which we perform bounds checks. It is
* always a constant offset smaller than mappedSize. Currently that constant
* offset is 64k (wasm::GuardSize).
*
* - maxSize - the optional declared limit on how much length can grow.
*
* - mappedSize - the actual mmaped size. Access in the range
* [0, mappedSize] will either succeed, or be handled by the wasm signal
* handlers.
*
* The below diagram shows the layout of the wasm heap. The wasm-visible
* portion of the heap starts at 0. There is one extra page prior to the
* start of the wasm heap which contains the WasmArrayRawBuffer struct at
* its end (i.e. right before the start of the WASM heap).
*
* WasmArrayRawBuffer
* \ ArrayBufferObject::dataPointer()
* \ /
* \ |
* ______|_|____________________________________________________________
* |______|_|______________|___________________|____________|____________|
* 0 length maxSize boundsCheckLimit mappedSize
*
* \_______________________/
* COMMITED
* \____________________________________________/
* SLOP
* \_____________________________________________________________________/
* MAPPED
*
* Invariants:
* - length only increases
* - 0 <= length <= maxSize (if present) <= boundsCheckLimit <= mappedSize
* - on ARM boundsCheckLimit must be a valid ARM immediate.
* - if maxSize is not specified, boundsCheckLimit/mappedSize may grow. They
* are otherwise constant.
*
* NOTE: For asm.js on non-x64 we guarantee that
*
* length == maxSize == boundsCheckLimit == mappedSize
*
* That is, signal handlers will not be invoked, since they cannot emulate
* asm.js accesses on non-x64 architectures.
*
* The region between length and mappedSize is the SLOP - an area where we use
* signal handlers to catch things that slip by bounds checks. Logically it has
* two parts:
*
* - from length to boundsCheckLimit - this part of the SLOP serves to catch
* accesses to memory we have reserved but not yet grown into. This allows us
* to grow memory up to max (when present) without having to patch/update the
* bounds checks.
*
* - from boundsCheckLimit to mappedSize - this part of the SLOP allows us to
* bounds check against base pointers and fold some constant offsets inside
* loads. This enables better Bounds Check Elimination.
*
*/
class js::WasmArrayRawBuffer {
Maybe<uint32_t> maxSize_;
size_t mappedSize_; // Not including the header page
protected:
WasmArrayRawBuffer(uint8_t* buffer, const Maybe<uint32_t>& maxSize,
size_t mappedSize)
: maxSize_(maxSize), mappedSize_(mappedSize) {
MOZ_ASSERT(buffer == dataPointer());
}
public:
static WasmArrayRawBuffer* Allocate(uint32_t numBytes,
const Maybe<uint32_t>& maxSize);
static void Release(void* mem);
uint8_t* dataPointer() {
uint8_t* ptr = reinterpret_cast<uint8_t*>(this);
return ptr + sizeof(WasmArrayRawBuffer);
}
uint8_t* basePointer() { return dataPointer() - gc::SystemPageSize(); }
size_t mappedSize() const { return mappedSize_; }
Maybe<uint32_t> maxSize() const { return maxSize_; }
#ifndef WASM_HUGE_MEMORY
uint32_t boundsCheckLimit() const {
MOZ_ASSERT(mappedSize_ <= UINT32_MAX);
MOZ_ASSERT(mappedSize_ >= wasm::GuardSize);
MOZ_ASSERT(
wasm::IsValidBoundsCheckImmediate(mappedSize_ - wasm::GuardSize));
return mappedSize_ - wasm::GuardSize;
}
#endif
MOZ_MUST_USE bool growToSizeInPlace(uint32_t oldSize, uint32_t newSize) {
MOZ_ASSERT(newSize >= oldSize);
MOZ_ASSERT_IF(maxSize(), newSize <= maxSize().value());
MOZ_ASSERT(newSize <= mappedSize());
uint32_t delta = newSize - oldSize;
MOZ_ASSERT(delta % wasm::PageSize == 0);
uint8_t* dataEnd = dataPointer() + oldSize;
MOZ_ASSERT(uintptr_t(dataEnd) % gc::SystemPageSize() == 0);
if (delta && !CommitBufferMemory(dataEnd, delta)) {
return false;
}
return true;
}
#ifndef WASM_HUGE_MEMORY
bool extendMappedSize(uint32_t maxSize) {
size_t newMappedSize = wasm::ComputeMappedSize(maxSize);
MOZ_ASSERT(mappedSize_ <= newMappedSize);
if (mappedSize_ == newMappedSize) {
return true;
}
if (!ExtendBufferMapping(dataPointer(), mappedSize_, newMappedSize)) {
return false;
}
mappedSize_ = newMappedSize;
return true;
}
// Try and grow the mapped region of memory. Does not change current size.
// Does not move memory if no space to grow.
void tryGrowMaxSizeInPlace(uint32_t deltaMaxSize) {
CheckedInt<uint32_t> newMaxSize = maxSize_.value();
newMaxSize += deltaMaxSize;
MOZ_ASSERT(newMaxSize.isValid());
MOZ_ASSERT(newMaxSize.value() % wasm::PageSize == 0);
if (!extendMappedSize(newMaxSize.value())) {
return;
}
maxSize_ = Some(newMaxSize.value());
}
#endif // WASM_HUGE_MEMORY
};
/* static */ WasmArrayRawBuffer* WasmArrayRawBuffer::Allocate(
uint32_t numBytes, const Maybe<uint32_t>& maxSize) {
MOZ_RELEASE_ASSERT(numBytes <= ArrayBufferObject::MaxBufferByteLength);
size_t mappedSize;
#ifdef WASM_HUGE_MEMORY
mappedSize = wasm::HugeMappedSize;
#else
mappedSize = wasm::ComputeMappedSize(maxSize.valueOr(numBytes));
#endif
MOZ_RELEASE_ASSERT(mappedSize <= SIZE_MAX - gc::SystemPageSize());
MOZ_RELEASE_ASSERT(numBytes <= maxSize.valueOr(UINT32_MAX));
MOZ_ASSERT(numBytes % gc::SystemPageSize() == 0);
MOZ_ASSERT(mappedSize % gc::SystemPageSize() == 0);
uint64_t mappedSizeWithHeader = mappedSize + gc::SystemPageSize();
uint64_t numBytesWithHeader = numBytes + gc::SystemPageSize();
void* data =
MapBufferMemory((size_t)mappedSizeWithHeader, (size_t)numBytesWithHeader);
if (!data) {
return nullptr;
}
uint8_t* base = reinterpret_cast<uint8_t*>(data) + gc::SystemPageSize();
uint8_t* header = base - sizeof(WasmArrayRawBuffer);
auto rawBuf = new (header) WasmArrayRawBuffer(base, maxSize, mappedSize);
return rawBuf;
}
/* static */ void WasmArrayRawBuffer::Release(void* mem) {
WasmArrayRawBuffer* header =
(WasmArrayRawBuffer*)((uint8_t*)mem - sizeof(WasmArrayRawBuffer));
MOZ_RELEASE_ASSERT(header->mappedSize() <= SIZE_MAX - gc::SystemPageSize());
size_t mappedSizeWithHeader = header->mappedSize() + gc::SystemPageSize();
UnmapBufferMemory(header->basePointer(), mappedSizeWithHeader);
}
WasmArrayRawBuffer* ArrayBufferObject::BufferContents::wasmBuffer() const {
MOZ_RELEASE_ASSERT(kind_ == WASM);
return (WasmArrayRawBuffer*)(data_ - sizeof(WasmArrayRawBuffer));
}
template <typename ObjT, typename RawbufT>
static bool CreateBuffer(
JSContext* cx, uint32_t initialSize, const Maybe<uint32_t>& maxSize,
MutableHandleArrayBufferObjectMaybeShared maybeSharedObject) {
#define ROUND_UP(v, a) ((v) % (a) == 0 ? (v) : v + a - ((v) % (a)))
RawbufT* buffer = RawbufT::Allocate(initialSize, maxSize);
if (!buffer) {
#ifdef WASM_HUGE_MEMORY
ReportOutOfMemory(cx);
return false;
#else
// If we fail, and have a maxSize, try to reserve the biggest chunk in
// the range [initialSize, maxSize) using log backoff.
if (!maxSize) {
ReportOutOfMemory(cx);
return false;
}
uint32_t cur = maxSize.value() / 2;
for (; cur > initialSize; cur /= 2) {
buffer = RawbufT::Allocate(initialSize,
mozilla::Some(ROUND_UP(cur, wasm::PageSize)));
if (buffer) {
break;
}
}
if (!buffer) {
ReportOutOfMemory(cx);
return false;
}
// Try to grow our chunk as much as possible.
for (size_t d = cur / 2; d >= wasm::PageSize; d /= 2) {
buffer->tryGrowMaxSizeInPlace(ROUND_UP(d, wasm::PageSize));
}
#endif
}
#undef ROUND_UP
// ObjT::createFromNewRawBuffer assumes ownership of |buffer| even in case
// of failure.
ObjT* object = ObjT::createFromNewRawBuffer(cx, buffer, initialSize);
if (!object) {
return false;
}
maybeSharedObject.set(object);
// See MaximumLiveMappedBuffers comment above.
if (liveBufferCount > StartSyncFullGCAtLiveBufferCount) {
JS::PrepareForFullGC(cx);
JS::NonIncrementalGC(cx, GC_NORMAL, JS::gcreason::TOO_MUCH_WASM_MEMORY);
allocatedSinceLastTrigger = 0;
} else if (liveBufferCount > StartTriggeringAtLiveBufferCount) {
allocatedSinceLastTrigger++;
if (allocatedSinceLastTrigger > AllocatedBuffersPerTrigger) {
Unused << cx->runtime()->gc.triggerGC(JS::gcreason::TOO_MUCH_WASM_MEMORY);
allocatedSinceLastTrigger = 0;
}
} else {
allocatedSinceLastTrigger = 0;
}
return true;
}
bool js::CreateWasmBuffer(JSContext* cx, const wasm::Limits& memory,
MutableHandleArrayBufferObjectMaybeShared buffer) {
MOZ_ASSERT(memory.initial % wasm::PageSize == 0);
MOZ_RELEASE_ASSERT(cx->wasmHaveSignalHandlers);
MOZ_RELEASE_ASSERT((memory.initial / wasm::PageSize) <=
wasm::MaxMemoryInitialPages);
// Prevent applications specifying a large max (like UINT32_MAX) from
// unintentially OOMing the browser on 32-bit: they just want "a lot of
// memory". Maintain the invariant that initialSize <= maxSize.
Maybe<uint32_t> maxSize = memory.maximum;
if (sizeof(void*) == 4 && maxSize) {
static const uint32_t OneGiB = 1 << 30;
uint32_t clamp = Max(OneGiB, memory.initial);
maxSize = Some(Min(clamp, *maxSize));
}
#ifndef WASM_HUGE_MEMORY
if (sizeof(void*) == 8 && maxSize &&
maxSize.value() >= (UINT32_MAX - wasm::PageSize)) {
// On 64-bit platforms that don't define WASM_HUGE_MEMORY
// clamp maxSize to smaller value that satisfies the 32-bit invariants
// maxSize + wasm::PageSize < UINT32_MAX and maxSize % wasm::PageSize == 0
uint32_t clamp = (wasm::MaxMemoryMaximumPages - 2) * wasm::PageSize;
MOZ_ASSERT(clamp < UINT32_MAX);
MOZ_ASSERT(memory.initial <= clamp);
maxSize = Some(clamp);
}
#endif
if (memory.shared == wasm::Shareable::True) {
if (!cx->realm()->creationOptions().getSharedMemoryAndAtomicsEnabled()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_WASM_NO_SHMEM_LINK);
return false;
}
return CreateBuffer<SharedArrayBufferObject, SharedArrayRawBuffer>(
cx, memory.initial, maxSize, buffer);
}
return CreateBuffer<ArrayBufferObject, WasmArrayRawBuffer>(cx, memory.initial,
maxSize, buffer);
}
// Note this function can return false with or without an exception pending. The
// asm.js caller checks cx->isExceptionPending before propagating failure.
// Returning false without throwing means that asm.js linking will fail which
// will recompile as non-asm.js.
/* static */ bool ArrayBufferObject::prepareForAsmJS(
JSContext* cx, Handle<ArrayBufferObject*> buffer) {
MOZ_ASSERT(buffer->byteLength() % wasm::PageSize == 0);
// Don't assert cx->wasmHaveSignalHandlers because (1) they aren't needed
// for asm.js, (2) they are only installed for WebAssembly, not asm.js.
if (buffer->forInlineTypedObject()) {
return false;
}
if (!buffer->isWasm() && buffer->isPreparedForAsmJS()) {
return true;
}
// Non-prepared-for-asm.js wasm buffers can be detached at any time.
if (buffer->isWasm()) {
return false;
}
if (!buffer->ownsData()) {
BufferContents contents =
AllocateArrayBufferContents(cx, buffer->byteLength());
if (!contents) {
return false;
}
memcpy(contents.data(), buffer->dataPointer(), buffer->byteLength());
buffer->changeContents(cx, contents, OwnsData);
}
buffer->setIsPreparedForAsmJS();
return true;
}
ArrayBufferObject::BufferContents ArrayBufferObject::createMappedContents(
int fd, size_t offset, size_t length) {
void* data =
gc::AllocateMappedContent(fd, offset, length, ARRAY_BUFFER_ALIGNMENT);
return BufferContents::create<MAPPED>(data);
}
uint8_t* ArrayBufferObject::inlineDataPointer() const {
return static_cast<uint8_t*>(fixedData(JSCLASS_RESERVED_SLOTS(&class_)));
}
uint8_t* ArrayBufferObject::dataPointer() const {
return static_cast<uint8_t*>(getFixedSlot(DATA_SLOT).toPrivate());
}
SharedMem<uint8_t*> ArrayBufferObject::dataPointerShared() const {
return SharedMem<uint8_t*>::unshared(getFixedSlot(DATA_SLOT).toPrivate());
}
ArrayBufferObject::FreeInfo* ArrayBufferObject::freeInfo() const {
MOZ_ASSERT(isExternal());
return reinterpret_cast<FreeInfo*>(inlineDataPointer());
}
void ArrayBufferObject::releaseData(FreeOp* fop) {
MOZ_ASSERT(ownsData());
switch (bufferKind()) {
case PLAIN:
fop->free_(dataPointer());
break;
case MAPPED:
gc::DeallocateMappedContent(dataPointer(), byteLength());
break;
case WASM:
WasmArrayRawBuffer::Release(dataPointer());
break;
case EXTERNAL:
if (freeInfo()->freeFunc) {
// The analyzer can't know for sure whether the embedder-supplied
// free function will GC. We give the analyzer a hint here.
// (Doing a GC in the free function is considered a programmer
// error.)
JS::AutoSuppressGCAnalysis nogc;
freeInfo()->freeFunc(dataPointer(), freeInfo()->freeUserData);
}
break;
}
}
void ArrayBufferObject::setDataPointer(BufferContents contents,
OwnsState ownsData) {
setFixedSlot(DATA_SLOT, PrivateValue(contents.data()));
setOwnsData(ownsData);
setFlags((flags() & ~KIND_MASK) | contents.kind());
if (isExternal()) {
auto info = freeInfo();
info->freeFunc = contents.freeFunc();
info->freeUserData = contents.freeUserData();
}
}
uint32_t ArrayBufferObject::byteLength() const {
return getFixedSlot(BYTE_LENGTH_SLOT).toInt32();
}
void ArrayBufferObject::setByteLength(uint32_t length) {
MOZ_ASSERT(length <= INT32_MAX);
setFixedSlot(BYTE_LENGTH_SLOT, Int32Value(length));
}
size_t ArrayBufferObject::wasmMappedSize() const {
if (isWasm()) {
return contents().wasmBuffer()->mappedSize();
}
return byteLength();
}
size_t js::WasmArrayBufferMappedSize(const ArrayBufferObjectMaybeShared* buf) {
if (buf->is<ArrayBufferObject>()) {
return buf->as<ArrayBufferObject>().wasmMappedSize();
}
return buf->as<SharedArrayBufferObject>().wasmMappedSize();
}
Maybe<uint32_t> ArrayBufferObject::wasmMaxSize() const {