Debian Codegraph @

js/src/vm/ArrayBufferObject.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_ArrayBufferObject_h
8 #define vm_ArrayBufferObject_h
9
10 #include "mozilla/Maybe.h"
11
12 #include <tuple> // std::tuple
13
14 #include "builtin/TypedArrayConstants.h"
15 #include "gc/Memory.h"
16 #include "gc/ZoneAllocator.h"
17 #include "js/ArrayBuffer.h"
18 #include "js/GCHashTable.h"
19 #include "vm/JSFunction.h"
20 #include "vm/JSObject.h"
21 #include "vm/SharedMem.h"
22 #include "wasm/WasmMemory.h"
23
24 namespace js {
25
26 class JS_PUBLIC_API GenericPrinter;
27 class JSONPrinter;
28
29 class ArrayBufferViewObject;
30 class AutoSetNewObjectMetadata;
31 class WasmArrayRawBuffer;
32
33 namespace wasm {
34 struct MemoryDesc;
35 } // namespace wasm
36
37 // Create a new mapping of size `mappedSize` with an initially committed prefix
38 // of size `initialCommittedSize`. Both arguments denote bytes and must be
39 // multiples of the page size, with `initialCommittedSize` <= `mappedSize`.
40 // Returns nullptr on failure.
41 void* MapBufferMemory(wasm::AddressType, size_t mappedSize,
42 size_t initialCommittedSize);
43
44 // Commit additional memory in an existing mapping. `dataEnd` must be the
45 // correct value for the end of the existing committed area, and `delta` must be
46 // a byte amount to grow the mapping by, and must be a multiple of the page
47 // size. Returns false on failure.
48 bool CommitBufferMemory(void* dataEnd, size_t delta);
49
50 // Remove an existing mapping. `dataStart` must be the pointer to the start of
51 // the mapping, and `mappedSize` the size of that mapping.
52 void UnmapBufferMemory(wasm::AddressType t, void* dataStart, size_t mappedSize,
53 size_t committedSize);
54
55 // Return the number of bytes currently reserved for WebAssembly memory
56 uint64_t WasmReservedBytes();
57
58 // The inheritance hierarchy for the various classes relating to typed arrays
59 // is as follows.
60 //
61 //
62 // - JSObject
63 // - NativeObject
64 // - ArrayBufferObjectMaybeShared
65 // - ArrayBufferObject
66 // - FixedLengthArrayBufferObject
67 // - ResizableArrayBufferObject
68 // - SharedArrayBufferObject
69 // - FixedLengthSharedArrayBufferObject
70 // - GrowableSharedArrayBufferObject
71 // - ArrayBufferViewObject
72 // - DataViewObject
73 // - FixedLengthDataViewObject
74 // - ResizableDataViewObject
75 // - TypedArrayObject (declared in vm/TypedArrayObject.h)
76 // - FixedLengthTypedArrayObject
77 // - FixedLengthTypedArrayObjectTemplate<NativeType>, also inheriting
78 // from TypedArrayObjectTemplate<NativeType>
79 // - FixedLengthTypedArrayObjectTemplate<int8_t>
80 // - FixedLengthTypedArrayObjectTemplate<uint8_t>
81 // - ...
82 // - ResizableTypedArrayObject
83 // - ResizableTypedArrayObjectTemplate<NativeType>, also inheriting
84 // from TypedArrayObjectTemplate<NativeType>
85 // - ResizableTypedArrayObjectTemplate<int8_t>
86 // - ResizableTypedArrayObjectTemplate<uint8_t>
87 // - ...
88 //
89 // Note that |{FixedLength,Resizable}TypedArrayObjectTemplate| is just an
90 // implementation detail that makes implementing its various subclasses easier.
91 //
92 // FixedLengthArrayBufferObject and ResizableArrayBufferObject are also
93 // implementation specific types to differentiate between fixed-length and
94 // resizable ArrayBuffers.
95 //
96 // ArrayBufferObject and SharedArrayBufferObject are unrelated data types:
97 // the racy memory of the latter cannot substitute for the non-racy memory of
98 // the former; the non-racy memory of the former cannot be used with the
99 // atomics; the former can be detached and the latter not. Hence they have been
100 // separated completely.
101 //
102 // Most APIs will only accept ArrayBufferObject. ArrayBufferObjectMaybeShared
103 // exists as a join point to allow APIs that can take or use either, notably
104 // AsmJS.
105 //
106 // In contrast with the separation of ArrayBufferObject and
107 // SharedArrayBufferObject, the TypedArray types can map either.
108 //
109 // The possible data ownership and reference relationships with ArrayBuffers
110 // and related classes are enumerated below. These are the possible locations
111 // for typed data:
112 //
113 // (1) malloc'ed or mmap'ed data owned by an ArrayBufferObject.
114 // (2) Data allocated inline with an ArrayBufferObject.
115 // (3) Data allocated inline with a TypedArrayObject.
116 //
117 // An ArrayBufferObject may point to any of these sources of data, except (3).
118 // All array buffer views may point to any of these sources of data, except
119 // that (3) may only be pointed to by the typed array the data is inline with.
120 //
121 // During a minor GC, (3) may move. During a compacting GC, (2) and (3) may
122 // move.
123
124 class ArrayBufferObjectMaybeShared;
125
126 wasm::AddressType WasmArrayBufferAddressType(
127 const ArrayBufferObjectMaybeShared* buf);
128 wasm::Pages WasmArrayBufferPages(const ArrayBufferObjectMaybeShared* buf);
129 wasm::Pages WasmArrayBufferClampedMaxPages(
130 const ArrayBufferObjectMaybeShared* buf);
131 mozilla::Maybe<wasm::Pages> WasmArrayBufferSourceMaxPages(
132 const ArrayBufferObjectMaybeShared* buf);
133 size_t WasmArrayBufferMappedSize(const ArrayBufferObjectMaybeShared* buf);
134
135 class ArrayBufferObjectMaybeShared : public NativeObject {
136 public:
137 inline size_t byteLength() const;
138 inline bool isDetached() const;
139 inline bool isResizable() const;
140 inline SharedMem<uint8_t*> dataPointerEither();
141
142 inline bool pinLength(bool pin);
143
144 // WebAssembly support:
145 // Note: the eventual goal is to remove this from ArrayBuffer and have
146 // (Shared)ArrayBuffers alias memory owned by some wasm::Memory object.
147
148 wasm::AddressType wasmAddressType() const {
149 return WasmArrayBufferAddressType(this);
150 }
151 wasm::Pages wasmPages() const { return WasmArrayBufferPages(this); }
152 wasm::Pages wasmClampedMaxPages() const {
153 return WasmArrayBufferClampedMaxPages(this);
154 }
155 mozilla::Maybe<wasm::Pages> wasmSourceMaxPages() const {
156 return WasmArrayBufferSourceMaxPages(this);
157 }
158 size_t wasmMappedSize() const { return WasmArrayBufferMappedSize(this); }
159
160 inline bool isPreparedForAsmJS() const;
161 inline bool isWasm() const;
162 };
163
164 class FixedLengthArrayBufferObject;
165 class ResizableArrayBufferObject;
166
167 /*
168 * ArrayBufferObject
169 *
170 * This class holds the underlying raw buffer that the various ArrayBufferViews
171 * (DataViewObject and the TypedArrays) access. It can be created explicitly and
172 * used to construct an ArrayBufferView, or can be created lazily when it is
173 * first accessed for a TypedArrayObject that doesn't have an explicit buffer.
174 *
175 * ArrayBufferObject is an abstract base class and has exactly two concrete
176 * subclasses, FixedLengthArrayBufferObject and ResizableArrayBufferObject.
177 *
178 * ArrayBufferObject (or really the underlying memory) /is not racy/: the
179 * memory is private to a single worker.
180 */
181 class ArrayBufferObject : public ArrayBufferObjectMaybeShared {
182 static bool byteLengthGetterImpl(JSContext* cx, const CallArgs& args);
183 static bool maxByteLengthGetterImpl(JSContext* cx, const CallArgs& args);
184 static bool resizableGetterImpl(JSContext* cx, const CallArgs& args);
185 static bool detachedGetterImpl(JSContext* cx, const CallArgs& args);
186 static bool sliceImpl(JSContext* cx, const CallArgs& args);
187 static bool resizeImpl(JSContext* cx, const CallArgs& args);
188 static bool transferImpl(JSContext* cx, const CallArgs& args);
189 static bool transferToFixedLengthImpl(JSContext* cx, const CallArgs& args);
190
191 public:
192 static const uint8_t DATA_SLOT = 0;
193 static const uint8_t BYTE_LENGTH_SLOT = 1;
194 static const uint8_t FIRST_VIEW_SLOT = 2;
195 static const uint8_t FLAGS_SLOT = 3;
196
197 static const uint8_t RESERVED_SLOTS = 4;
198
199 // Alignment for ArrayBuffer objects. Must match the largest possible
200 // TypedArray scalar to ensure TypedArray and Atomics accesses are always
201 // aligned.
202 static constexpr size_t ARRAY_BUFFER_ALIGNMENT = 8;
203
204 static_assert(FLAGS_SLOT == JS_ARRAYBUFFER_FLAGS_SLOT,
205 "self-hosted code with burned-in constants must get the "
206 "right flags slot");
207
208 // The length of an ArrayBuffer or SharedArrayBuffer can be at most INT32_MAX
209 // on 32-bit platforms. Allow a larger limit on 64-bit platforms.
210 static constexpr size_t ByteLengthLimitForSmallBuffer = INT32_MAX;
211 #ifdef JS_64BIT
212 static constexpr size_t ByteLengthLimit =
213 size_t(8) * 1024 * 1024 * 1024; // 8 GB.
214 #else
215 static constexpr size_t ByteLengthLimit = ByteLengthLimitForSmallBuffer;
216 #endif
217
218 public:
219 enum BufferKind {
220 /** Inline data kept in the repurposed slots of this ArrayBufferObject. */
221 INLINE_DATA = 0b000,
222
223 /*
224 * Data allocated using the SpiderMonkey allocator, created within
225 * js::ArrayBufferContentsArena.
226 */
227 MALLOCED_ARRAYBUFFER_CONTENTS_ARENA = 0b001,
228
229 /**
230 * No bytes are associated with this buffer. (This could be because the
231 * buffer is detached, because it's an internal, newborn buffer not yet
232 * overwritten with user-exposable semantics, or some other reason. The
233 * point is, don't read precise language semantics into this kind.)
234 */
235 NO_DATA = 0b010,
236
237 /**
238 * User-owned memory. The associated buffer must be manually detached
239 * before the user invalidates (deallocates, reuses the storage of, &c.)
240 * the user-owned memory.
241 */
242 USER_OWNED = 0b011,
243
244 WASM = 0b100,
245 MAPPED = 0b101,
246 EXTERNAL = 0b110,
247
248 /**
249 * Data allocated using the SpiderMonkey allocator, created within an
250 * unknown memory arena.
251 */
252 MALLOCED_UNKNOWN_ARENA = 0b111,
253
254 KIND_MASK = 0b111
255 };
256
257 public:
258 enum ArrayBufferFlags {
259 // The flags also store the BufferKind
260 BUFFER_KIND_MASK = BufferKind::KIND_MASK,
261
262 DETACHED = 0b1000,
263
264 // Resizable ArrayBuffer.
265 RESIZABLE = 0b1'0000,
266
267 // This MALLOCED, MAPPED, or EXTERNAL buffer has been prepared for asm.js
268 // and cannot henceforth be transferred/detached. (WASM, USER_OWNED, and
269 // INLINE_DATA buffers can't be prepared for asm.js -- although if an
270 // INLINE_DATA buffer is used with asm.js, it's silently rewritten into a
271 // MALLOCED buffer which *can* be prepared.)
272 FOR_ASMJS = 0b10'0000,
273
274 // The length is temporarily pinned, so it should not be detached. In the
275 // future, this will also prevent GrowableArrayBuffer/ResizeableArrayBuffer
276 // from modifying the length while this is set.
277 PINNED_LENGTH = 0b100'0000
278 };
279
280 static_assert(JS_ARRAYBUFFER_DETACHED_FLAG == DETACHED,
281 "self-hosted code with burned-in constants must use the "
282 "correct DETACHED bit value");
283
284 protected:
285 enum class FillContents { Zero, Uninitialized };
286
287 template <class ArrayBufferType, FillContents FillType>
288 static std::tuple<ArrayBufferType*, uint8_t*>
289 createUninitializedBufferAndData(JSContext* cx, size_t nbytes,
290 AutoSetNewObjectMetadata&,
291 JS::Handle<JSObject*> proto);
292
293 template <FillContents FillType>
294 static std::tuple<ArrayBufferObject*, uint8_t*> createBufferAndData(
295 JSContext* cx, size_t nbytes, AutoSetNewObjectMetadata& metadata,
296 JS::Handle<JSObject*> proto = nullptr);
297
298 public:
299 class BufferContents {
300 uint8_t* data_;
301 BufferKind kind_;
302 JS::BufferContentsFreeFunc free_;
303 void* freeUserData_;
304
305 friend class ArrayBufferObject;
306 friend class ResizableArrayBufferObject;
307
308 BufferContents(uint8_t* data, BufferKind kind,
309 JS::BufferContentsFreeFunc freeFunc = nullptr,
310 void* freeUserData = nullptr)
311 : data_(data),
312 kind_(kind),
313 free_(freeFunc),
314 freeUserData_(freeUserData) {
315 MOZ_ASSERT((kind_ & ~KIND_MASK) == 0);
316 MOZ_ASSERT_IF(free_ || freeUserData_, kind_ == EXTERNAL);
317
318 // It is the caller's responsibility to ensure that the
319 // BufferContents does not outlive the data.
320 }
321
322 #ifdef DEBUG
323 // Checks if the buffer contents are properly aligned.
324 //
325 // `malloc(0)` is implementation defined and may return a pointer which
326 // isn't aligned to `max_align_t`, so we only require proper alignment when
327 // `byteLength` is non-zero.
328 //
329 // jemalloc doesn't implement restriction, but instead uses `sizeof(void*)`
330 // for its smallest allocation class. Larger allocations are guaranteed to
331 // be eight byte aligned.
332 bool isAligned(size_t byteLength) const {
333 // `malloc(0)` has implementation defined behavior.
334 if (byteLength == 0) {
335 return true;
336 }
337
338 // Allow jemalloc tiny allocations to have smaller alignment requirements
339 // than `std::malloc`.
340 if (sizeof(void*) < ArrayBufferObject::ARRAY_BUFFER_ALIGNMENT) {
341 if (byteLength <= sizeof(void*)) {
342 return true;
343 }
344 }
345
346 // `std::malloc` returns memory at least as strictly aligned as for
347 // max_align_t and the alignment of max_align_t is a multiple of the array
348 // buffer alignment.
349 static_assert(alignof(std::max_align_t) %
350 ArrayBufferObject::ARRAY_BUFFER_ALIGNMENT ==
351 0);
352
353 // Otherwise the memory must be correctly alignment.
354 auto ptr = reinterpret_cast<uintptr_t>(data());
355 return ptr % ArrayBufferObject::ARRAY_BUFFER_ALIGNMENT == 0;
356 }
357 #endif
358
359 public:
360 static BufferContents createInlineData(void* data) {
361 return BufferContents(static_cast<uint8_t*>(data), INLINE_DATA);
362 }
363
364 static BufferContents createMallocedArrayBufferContentsArena(void* data) {
365 return BufferContents(static_cast<uint8_t*>(data),
366 MALLOCED_ARRAYBUFFER_CONTENTS_ARENA);
367 }
368
369 static BufferContents createMallocedUnknownArena(void* data) {
370 return BufferContents(static_cast<uint8_t*>(data),
371 MALLOCED_UNKNOWN_ARENA);
372 }
373
374 static BufferContents createNoData() {
375 return BufferContents(nullptr, NO_DATA);
376 }
377
378 static BufferContents createUserOwned(void* data) {
379 return BufferContents(static_cast<uint8_t*>(data), USER_OWNED);
380 }
381
382 static BufferContents createWasm(void* data) {
383 return BufferContents(static_cast<uint8_t*>(data), WASM);
384 }
385
386 static BufferContents createMapped(void* data) {
387 return BufferContents(static_cast<uint8_t*>(data), MAPPED);
388 }
389
390 static BufferContents createExternal(void* data,
391 JS::BufferContentsFreeFunc freeFunc,
392 void* freeUserData = nullptr) {
393 MOZ_ASSERT(freeFunc);
394 return BufferContents(static_cast<uint8_t*>(data), EXTERNAL, freeFunc,
395 freeUserData);
396 }
397
398 static BufferContents createFailed() {
399 // There's no harm in tagging this as MALLOCED_ARRAYBUFFER_CONTENTS_ARENA,
400 // even tho obviously it isn't. And adding an extra tag purely for this
401 // case is a complication that presently appears avoidable.
402 return BufferContents(nullptr, MALLOCED_ARRAYBUFFER_CONTENTS_ARENA);
403 }
404
405 uint8_t* data() const { return data_; }
406 BufferKind kind() const { return kind_; }
407 JS::BufferContentsFreeFunc freeFunc() const { return free_; }
408 void* freeUserData() const { return freeUserData_; }
409
410 explicit operator bool() const { return data_ != nullptr; }
411 WasmArrayRawBuffer* wasmBuffer() const;
412 };
413
414 static const JSClass protoClass_;
415
416 static bool byteLengthGetter(JSContext* cx, unsigned argc, Value* vp);
417
418 static bool maxByteLengthGetter(JSContext* cx, unsigned argc, Value* vp);
419
420 static bool resizableGetter(JSContext* cx, unsigned argc, Value* vp);
421
422 static bool detachedGetter(JSContext* cx, unsigned argc, Value* vp);
423
424 static bool fun_isView(JSContext* cx, unsigned argc, Value* vp);
425
426 static bool slice(JSContext* cx, unsigned argc, Value* vp);
427
428 static bool resize(JSContext* cx, unsigned argc, Value* vp);
429
430 static bool transfer(JSContext* cx, unsigned argc, Value* vp);
431
432 static bool transferToFixedLength(JSContext* cx, unsigned argc, Value* vp);
433
434 static bool class_constructor(JSContext* cx, unsigned argc, Value* vp);
435
436 static bool isOriginalByteLengthGetter(Native native) {
437 return native == byteLengthGetter;
438 }
439
440 static ArrayBufferObject* createForContents(JSContext* cx, size_t nbytes,
441 BufferContents contents);
442
443 static ArrayBufferObject* copy(JSContext* cx, size_t newByteLength,
444 JS::Handle<ArrayBufferObject*> source);
445
446 static ArrayBufferObject* copyAndDetach(
447 JSContext* cx, size_t newByteLength,
448 JS::Handle<ArrayBufferObject*> source);
449
450 private:
451 static ArrayBufferObject* copyAndDetachSteal(
452 JSContext* cx, JS::Handle<ArrayBufferObject*> source);
453
454 static ArrayBufferObject* copyAndDetachRealloc(
455 JSContext* cx, size_t newByteLength,
456 JS::Handle<ArrayBufferObject*> source);
457
458 public:
459 static ArrayBufferObject* createZeroed(JSContext* cx, size_t nbytes,
460 HandleObject proto = nullptr);
461
462 // Create an ArrayBufferObject that is safely finalizable and can later be
463 // initialize()d to become a real, content-visible ArrayBufferObject.
464 static ArrayBufferObject* createEmpty(JSContext* cx);
465
466 // Create an ArrayBufferObject using the provided buffer and size. Assumes
467 // ownership of |buffer| even in case of failure, i.e. on failure |buffer|
468 // is deallocated.
469 static ArrayBufferObject* createFromNewRawBuffer(JSContext* cx,
470 WasmArrayRawBuffer* buffer,
471 size_t initialSize);
472
473 // Create an ArrayBufferObject object (resizable or fixed-length) based
474 // on the existing donor object. The |buffer| will be removed from the
475 // latter, and its ownership will be assumed by the new object.
476 template <typename ArrayBufferType>
477 static ArrayBufferType* createFromWasmObject(
478 JSContext* cx, Handle<ArrayBufferObject*> donor);
479
480 static void copyData(ArrayBufferObject* toBuffer, size_t toIndex,
481 ArrayBufferObject* fromBuffer, size_t fromIndex,
482 size_t count);
483
484 template <class ArrayBufferType>
485 static size_t objectMoved(JSObject* obj, JSObject* old);
486
487 static uint8_t* stealMallocedContents(JSContext* cx,
488 Handle<ArrayBufferObject*> buffer);
489
490 static BufferContents extractStructuredCloneContents(
491 JSContext* cx, Handle<ArrayBufferObject*> buffer);
492
493 static void addSizeOfExcludingThis(JSObject* obj,
494 mozilla::MallocSizeOf mallocSizeOf,
495 JS::ClassInfo* info,
496 JS::RuntimeSizes* runtimeSizes);
497
498 // ArrayBufferObjects (strongly) store the first view added to them, while
499 // later views are (weakly) stored in the compartment's InnerViewTable
500 // below. Buffers usually only have one view, so this slot optimizes for
501 // the common case. Avoiding entries in the InnerViewTable saves memory and
502 // non-incrementalized sweep time.
503 JSObject* firstView();
504
505 bool addView(JSContext* cx, ArrayBufferViewObject* view);
506
507 // Pin or unpin the length. Returns whether pinned status was changed.
508 bool pinLength(bool pin) {
509 if (bool(flags() & PINNED_LENGTH) == pin) {
510 return false;
511 }
512 setFlags(flags() ^ PINNED_LENGTH);
513 return true;
514 }
515
516 static bool ensureNonInline(JSContext* cx, Handle<ArrayBufferObject*> buffer);
517
518 // Detach this buffer from its original memory. (This necessarily makes
519 // views of this buffer unusable for modifying that original memory.)
520 static void detach(JSContext* cx, Handle<ArrayBufferObject*> buffer);
521
522 static constexpr size_t offsetOfByteLengthSlot() {
523 return getFixedSlotOffset(BYTE_LENGTH_SLOT);
524 }
525 static constexpr size_t offsetOfFlagsSlot() {
526 return getFixedSlotOffset(FLAGS_SLOT);
527 }
528
529 protected:
530 void setFirstView(ArrayBufferViewObject* view);
531
532 private:
533 struct FreeInfo {
534 JS::BufferContentsFreeFunc freeFunc;
535 void* freeUserData;
536 };
537 FreeInfo* freeInfo() const;
538
539 public:
540 uint8_t* dataPointer() const;
541 SharedMem<uint8_t*> dataPointerShared() const;
542 size_t byteLength() const;
543
544 BufferContents contents() const {
545 if (isExternal()) {
546 return BufferContents(dataPointer(), EXTERNAL, freeInfo()->freeFunc,
547 freeInfo()->freeUserData);
548 }
549 return BufferContents(dataPointer(), bufferKind());
550 }
551
552 void releaseData(JS::GCContext* gcx);
553
554 BufferKind bufferKind() const {
555 return BufferKind(flags() & BUFFER_KIND_MASK);
556 }
557
558 bool isInlineData() const { return bufferKind() == INLINE_DATA; }
559 bool isMalloced() const {
560 return bufferKind() == MALLOCED_ARRAYBUFFER_CONTENTS_ARENA ||
561 bufferKind() == MALLOCED_UNKNOWN_ARENA;
562 }
563 bool isNoData() const { return bufferKind() == NO_DATA; }
564 bool hasUserOwnedData() const { return bufferKind() == USER_OWNED; }
565
566 bool isWasm() const { return bufferKind() == WASM; }
567 bool isMapped() const { return bufferKind() == MAPPED; }
568 bool isExternal() const { return bufferKind() == EXTERNAL; }
569
570 bool isDetached() const { return flags() & DETACHED; }
571 bool isResizable() const { return flags() & RESIZABLE; }
572 bool isLengthPinned() const { return flags() & PINNED_LENGTH; }
573 bool isPreparedForAsmJS() const { return flags() & FOR_ASMJS; }
574
575 // Only WASM and asm.js buffers have a non-undefined [[ArrayBufferDetachKey]].
576 //
577 // https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances
578 bool hasDefinedDetachKey() const { return isWasm() || isPreparedForAsmJS(); }
579
580 // WebAssembly support:
581
582 /**
583 * Prepare this ArrayBuffer for use with asm.js. Returns true on success,
584 * false on failure. This function reports no errors.
585 */
586 [[nodiscard]] bool prepareForAsmJS();
587
588 size_t wasmMappedSize() const;
589
590 wasm::AddressType wasmAddressType() const;
591 wasm::Pages wasmPages() const;
592 wasm::Pages wasmClampedMaxPages() const;
593 mozilla::Maybe<wasm::Pages> wasmSourceMaxPages() const;
594
595 [[nodiscard]] static ArrayBufferObject* wasmGrowToPagesInPlace(
596 wasm::AddressType t, wasm::Pages newPages,
597 Handle<ArrayBufferObject*> oldBuf, JSContext* cx);
598 [[nodiscard]] static ArrayBufferObject* wasmMovingGrowToPages(
599 wasm::AddressType t, wasm::Pages newPages,
600 Handle<ArrayBufferObject*> oldBuf, JSContext* cx);
601 static void wasmDiscard(Handle<ArrayBufferObject*> buf, uint64_t byteOffset,
602 uint64_t byteLength);
603
604 static void finalize(JS::GCContext* gcx, JSObject* obj);
605
606 static BufferContents createMappedContents(int fd, size_t offset,
607 size_t length);
608
609 protected:
610 void setDataPointer(BufferContents contents);
611 void setByteLength(size_t length);
612
613 /**
614 * Return the byte length for fixed-length buffers or the maximum byte length
615 * for resizable buffers.
616 */
617 inline size_t maxByteLength() const;
618
619 size_t wasmClampedMaxByteLength() const {
620 MOZ_ASSERT(isWasm());
621 return wasmClampedMaxPages().byteLength();
622 }
623
624 size_t associatedBytes() const;
625
626 uint32_t flags() const;
627 void setFlags(uint32_t flags);
628
629 void setIsDetached() {
630 MOZ_ASSERT(!(flags() & PINNED_LENGTH));
631 setFlags(flags() | DETACHED);
632 }
633 void setIsPreparedForAsmJS() {
634 MOZ_ASSERT(!isWasm());
635 MOZ_ASSERT(!hasUserOwnedData());
636 MOZ_ASSERT(!isInlineData());
637 MOZ_ASSERT(isMalloced() || isMapped() || isExternal());
638 setFlags(flags() | FOR_ASMJS);
639 }
640
641 void initialize(size_t byteLength, BufferContents contents) {
642 MOZ_ASSERT(contents.isAligned(byteLength));
643 setByteLength(byteLength);
644 setFlags(0);
645 setFirstView(nullptr);
646 setDataPointer(contents);
647 }
648
649 public:
650 #if defined(DEBUG) || defined(JS_JITSPEW)
651 void dumpOwnFields(js::JSONPrinter& json) const;
652 void dumpOwnStringContent(js::GenericPrinter& out) const;
653 #endif
654 };
655
656 /**
657 * FixedLengthArrayBufferObject
658 *
659 * ArrayBuffer object with a fixed length. Its length is unmodifiable, except
660 * when zeroing it for detached buffers. Supports all possible memory stores
661 * for ArrayBuffer objects, including inline data, malloc'ed memory, mapped
662 * memory, and user-owner memory.
663 *
664 * Fixed-length ArrayBuffers can be used for asm.js and WebAssembly.
665 */
666 class FixedLengthArrayBufferObject : public ArrayBufferObject {
667 friend class ArrayBufferObject;
668
669 uint8_t* inlineDataPointer() const;
670
671 bool hasInlineData() const { return dataPointer() == inlineDataPointer(); }
672
673 public:
674 // Fixed-length ArrayBuffer objects don't have any additional reserved slots.
675 static const uint8_t RESERVED_SLOTS = ArrayBufferObject::RESERVED_SLOTS;
676
677 /** The largest number of bytes that can be stored inline. */
678 static constexpr size_t MaxInlineBytes =
679 (NativeObject::MAX_FIXED_SLOTS - RESERVED_SLOTS) * sizeof(JS::Value);
680
681 static const JSClass class_;
682 };
683
684 /**
685 * ResizableArrayBufferObject
686 *
687 * ArrayBuffer object which can both grow and shrink. The maximum byte length it
688 * can grow to is set when creating the object. The data of resizable
689 * ArrayBuffer object is either stored inline or malloc'ed memory.
690 *
691 * When a resizable ArrayBuffer object is detached, its maximum byte length
692 * slot is set to zero in addition to the byte length slot.
693 *
694 * Resizable ArrayBuffers can neither be used for asm.js nor WebAssembly.
695 */
696 class ResizableArrayBufferObject : public ArrayBufferObject {
697 friend class ArrayBufferObject;
698
699 template <FillContents FillType>
700 static std::tuple<ResizableArrayBufferObject*, uint8_t*> createBufferAndData(
701 JSContext* cx, size_t byteLength, size_t maxByteLength,
702 AutoSetNewObjectMetadata& metadata, Handle<JSObject*> proto);
703
704 static ResizableArrayBufferObject* createEmpty(JSContext* cx);
705
706 public:
707 static ResizableArrayBufferObject* createZeroed(
708 JSContext* cx, size_t byteLength, size_t maxByteLength,
709 Handle<JSObject*> proto = nullptr);
710
711 private:
712 uint8_t* inlineDataPointer() const;
713
714 bool hasInlineData() const { return dataPointer() == inlineDataPointer(); }
715
716 void setMaxByteLength(size_t length) {
717 MOZ_ASSERT(length <= ArrayBufferObject::ByteLengthLimit);
718 setFixedSlot(MAX_BYTE_LENGTH_SLOT, PrivateValue(length));
719 }
720
721 void initialize(size_t byteLength, size_t maxByteLength,
722 BufferContents contents) {
723 MOZ_ASSERT(contents.isAligned(byteLength));
724 setByteLength(byteLength);
725 setMaxByteLength(maxByteLength);
726 setFlags(RESIZABLE);
727 setFirstView(nullptr);
728 setDataPointer(contents);
729 }
730
731 // Resize this buffer.
732 void resize(size_t newByteLength);
733
734 static ResizableArrayBufferObject* copy(
735 JSContext* cx, size_t newByteLength,
736 JS::Handle<ResizableArrayBufferObject*> source);
737
738 public:
739 static const uint8_t MAX_BYTE_LENGTH_SLOT = ArrayBufferObject::RESERVED_SLOTS;
740
741 static const uint8_t RESERVED_SLOTS = ArrayBufferObject::RESERVED_SLOTS + 1;
742
743 /** The largest number of bytes that can be stored inline. */
744 static constexpr size_t MaxInlineBytes =
745 (NativeObject::MAX_FIXED_SLOTS - RESERVED_SLOTS) * sizeof(JS::Value);
746
747 static const JSClass class_;
748
749 size_t maxByteLength() const {
750 return size_t(getFixedSlot(MAX_BYTE_LENGTH_SLOT).toPrivate());
751 }
752
753 static ResizableArrayBufferObject* copyAndDetach(
754 JSContext* cx, size_t newByteLength,
755 JS::Handle<ResizableArrayBufferObject*> source);
756
757 private:
758 static ResizableArrayBufferObject* copyAndDetachSteal(
759 JSContext* cx, size_t newByteLength,
760 JS::Handle<ResizableArrayBufferObject*> source);
761 };
762
763 size_t ArrayBufferObject::maxByteLength() const {
764 if (isResizable()) {
765 return as<ResizableArrayBufferObject>().maxByteLength();
766 }
767 return byteLength();
768 }
769
770 // Create a buffer for a wasm memory, whose type is determined by
771 // memory.addressType().
772 ArrayBufferObjectMaybeShared* CreateWasmBuffer(JSContext* cx,
773 const wasm::MemoryDesc& memory);
774
775 // Per-compartment table that manages the relationship between array buffers
776 // and the views that use their storage.
777 class InnerViewTable {
778 // Store views in a vector such that all the tenured views come before any
779 // nursery views. Maintain the index of the first nursery view so there is an
780 // efficient way to access only the nursery views.
781 using ViewVector =
782 GCVector<UnsafeBarePtr<ArrayBufferViewObject*>, 1, ZoneAllocPolicy>;
783 struct Views {
784 ViewVector views; // List of views with tenured views at the front.
785 size_t firstNurseryView = 0;
786
787 explicit Views(JS::Zone* zone) : views(zone) {}
788 bool empty();
789 bool hasNurseryViews();
790 bool addView(ArrayBufferViewObject* view);
791
792 bool traceWeak(JSTracer* trc, size_t startIndex = 0);
793 bool sweepAfterMinorGC(JSTracer* trc);
794
795 void check();
796 };
797
798 // For all objects sharing their storage with some other view, this maps
799 // the object to the list of such views. All entries in this map are weak.
800 //
801 // This key is a raw pointer and not a WeakHeapPtr because the post-barrier
802 // would hold nursery-allocated entries live unconditionally. It is a very
803 // common pattern in low-level and performance-oriented JavaScript to create
804 // hundreds or thousands of very short lived temporary views on a larger
805 // buffer; having to tenure all of these would be a catastrophic performance
806 // regression. Thus, it is vital that nursery pointers in this map not be held
807 // live. Special support is required in the minor GC, implemented in
808 // sweepAfterMinorGC.
809 using ArrayBufferViewMap =
810 GCHashMap<UnsafeBarePtr<ArrayBufferObject*>, Views,
811 StableCellHasher<JSObject*>, ZoneAllocPolicy>;
812 ArrayBufferViewMap map;
813
814 // List of keys from map where either the source or at least one target is in
815 // the nursery. The raw pointer to a JSObject is allowed here because this
816 // vector is cleared after every minor collection. Users in sweepAfterMinorGC
817 // must be careful to use MaybeForwarded before touching these pointers.
818 using NurseryKeysVector =
819 GCVector<UnsafeBarePtr<ArrayBufferObject*>, 0, SystemAllocPolicy>;
820 NurseryKeysVector nurseryKeys;
821
822 // Whether nurseryKeys is a complete list.
823 bool nurseryKeysValid = true;
824
825 bool sweepMapEntryAfterMinorGC(UnsafeBarePtr<JSObject*>& buffer,
826 ViewVector& views);
827
828 public:
829 explicit InnerViewTable(Zone* zone) : map(zone) {}
830
831 // Remove references to dead objects in the table and update table entries
832 // to reflect moved objects.
833 bool traceWeak(JSTracer* trc);
834 void sweepAfterMinorGC(JSTracer* trc);
835
836 bool empty() const { return map.empty(); }
837
838 bool needsSweepAfterMinorGC() const {
839 return !nurseryKeys.empty() || !nurseryKeysValid;
840 }
841
842 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf);
843
844 private:
845 friend class ArrayBufferObject;
846 friend class ResizableArrayBufferObject;
847 bool addView(JSContext* cx, ArrayBufferObject* buffer,
848 ArrayBufferViewObject* view);
849 ViewVector* maybeViewsUnbarriered(ArrayBufferObject* buffer);
850 void removeViews(ArrayBufferObject* buffer);
851
852 bool sweepViewsAfterMinorGC(JSTracer* trc, ArrayBufferObject* buffer,
853 Views& views);
854 };
855
856 template <typename Wrapper>
857 class MutableWrappedPtrOperations<InnerViewTable, Wrapper>
858 : public WrappedPtrOperations<InnerViewTable, Wrapper> {
859 InnerViewTable& table() { return static_cast<Wrapper*>(this)->get(); }
860
861 public:
862 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) {
863 return table().sizeOfExcludingThis(mallocSizeOf);
864 }
865 };
866
867 class WasmArrayRawBuffer {
868 wasm::AddressType addressType_;
869 wasm::Pages clampedMaxPages_;
870 mozilla::Maybe<wasm::Pages> sourceMaxPages_;
871 size_t mappedSize_; // See comment on mappedSize().
872 size_t length_;
873
874 protected:
875 WasmArrayRawBuffer(wasm::AddressType addressType, uint8_t* buffer,
876 wasm::Pages clampedMaxPages,
877 const mozilla::Maybe<wasm::Pages>& sourceMaxPages,
878 size_t mappedSize, size_t length)
879 : addressType_(addressType),
880 clampedMaxPages_(clampedMaxPages),
881 sourceMaxPages_(sourceMaxPages),
882 mappedSize_(mappedSize),
883 length_(length) {
884 // Assert that this WasmArrayRawBuffer was allocated in the correct place
885 // relative to its data.
886 MOZ_ASSERT(buffer == dataPointer());
887 }
888
889 public:
890 static WasmArrayRawBuffer* AllocateWasm(
891 wasm::AddressType addressType, wasm::Pages initialPages,
892 wasm::Pages clampedMaxPages,
893 const mozilla::Maybe<wasm::Pages>& sourceMaxPages,
894 const mozilla::Maybe<size_t>& mappedSize);
895 static void Release(void* mem);
896
897 uint8_t* dataPointer() {
898 uint8_t* ptr = reinterpret_cast<uint8_t*>(this);
899 return ptr + sizeof(WasmArrayRawBuffer);
900 }
901
902 static const WasmArrayRawBuffer* fromDataPtr(const uint8_t* dataPtr) {
903 return reinterpret_cast<const WasmArrayRawBuffer*>(
904 dataPtr - sizeof(WasmArrayRawBuffer));
905 }
906
907 static WasmArrayRawBuffer* fromDataPtr(uint8_t* dataPtr) {
908 return reinterpret_cast<WasmArrayRawBuffer*>(dataPtr -
909 sizeof(WasmArrayRawBuffer));
910 }
911
912 wasm::AddressType addressType() const { return addressType_; }
913
914 uint8_t* basePointer() { return dataPointer() - gc::SystemPageSize(); }
915
916 /*
917 * The actual mmapped size. Access in the range [0, mappedSize) will either
918 * succeed, or be handled by the wasm signal handlers. The mapped size will be
919 * aligned to the system allocation granularity such that we can
920 * optimistically map other regions following it, in order to reduce copies
921 * when growing memory.
922 *
923 * Note that this does NOT include the header page in which this buffer itself
924 * is allocated.
925 */
926 size_t mappedSize() const { return mappedSize_; }
927
928 /*
929 * The wasm-visible current length of the buffer in bytes. Accesses in the
930 * range [0, byteLength) will succeed. May only increase.
931 *
932 * For more info see "WASM Linear Memory structure" in ArrayBufferObject.cpp.
933 */
934 size_t byteLength() const { return length_; }
935
936 wasm::Pages pages() const {
937 return wasm::Pages::fromByteLengthExact(length_);
938 }
939
940 /*
941 * The maximum size on how far the byteLength can grow in pages. This value
942 * respects implementation limits and is always representable as a byte
943 * length. Every memory has a clampedMaxSize, even if no maximum was specified
944 * in source. When a memory has no sourceMaxSize, the clampedMaxSize will be
945 * the maximum amount of memory that can be grown to while still respecting
946 * implementation limits.
947 *
948 * For more info see "WASM Linear Memory structure" in ArrayBufferObject.cpp.
949 */
950 wasm::Pages clampedMaxPages() const { return clampedMaxPages_; }
951
952 /*
953 * The optional declared limit on how far byteLength can grow in pages. This
954 * is the unmodified maximum size from the source module or JS-API invocation.
955 * This may not be representable in byte lengths, nor feasible for a module to
956 * actually grow to due to implementation limits. It is used for correct
957 * linking checks and js-types reflection.
958 *
959 * For more info see "WASM Linear Memory structure" in ArrayBufferObject.cpp.
960 */
961 mozilla::Maybe<wasm::Pages> sourceMaxPages() const { return sourceMaxPages_; }
962
963 [[nodiscard]] bool growToPagesInPlace(wasm::Pages newPages);
964
965 // Discard a region of memory, zeroing the pages and releasing physical memory
966 // back to the operating system. byteOffset and byteLen must be wasm page
967 // aligned and in bounds. A discard of zero bytes will have no effect.
968 void discard(size_t byteOffset, size_t byteLen);
969 };
970
971 } // namespace js
972
973 template <>
974 inline bool JSObject::is<js::ArrayBufferObject>() const {
975 return is<js::FixedLengthArrayBufferObject>() ||
976 is<js::ResizableArrayBufferObject>();
977 }
978
979 template <>
980 bool JSObject::is<js::ArrayBufferObjectMaybeShared>() const;
981
982 #endif // vm_ArrayBufferObject_h