Debian Codegraph @

js/src/vm/ArrayBufferObject.cpp

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 #include "vm/ArrayBufferObject-inl.h"
8 #include "vm/ArrayBufferObject.h"
9
10 #include "mozilla/Assertions.h"
11 #include "mozilla/Attributes.h"
12 #include "mozilla/DebugOnly.h"
13 #include "mozilla/Likely.h"
14 #include "mozilla/Maybe.h"
15 #include "mozilla/ScopeExit.h"
16 #include "mozilla/TaggedAnonymousMemory.h"
17
18 #include <algorithm> // std::max, std::min
19 #include <memory> // std::uninitialized_copy_n
20 #include <string.h>
21 #if !defined(XP_WIN) && !defined(__wasi__)
22 # include <sys/mman.h>
23 #endif
24 #include <tuple> // std::tuple
25 #include <type_traits>
26 #ifdef MOZ_VALGRIND
27 # include <valgrind/memcheck.h>
28 #endif
29
30 #include "jsnum.h"
31 #include "jstypes.h"
32
33 #include "gc/Barrier.h"
34 #include "gc/Memory.h"
35 #include "js/ArrayBuffer.h"
36 #include "js/Conversions.h"
37 #include "js/experimental/TypedData.h" // JS_IsArrayBufferViewObject
38 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
39 #include "js/MemoryMetrics.h"
40 #include "js/Prefs.h"
41 #include "js/PropertySpec.h"
42 #include "js/SharedArrayBuffer.h"
43 #include "js/Wrapper.h"
44 #include "util/WindowsWrapper.h"
45 #include "vm/GlobalObject.h"
46 #include "vm/Interpreter.h"
47 #include "vm/JSContext.h"
48 #include "vm/JSObject.h"
49 #include "vm/SelfHosting.h"
50 #include "vm/SharedArrayObject.h"
51 #include "vm/Warnings.h" // js::WarnNumberASCII
52 #include "wasm/WasmConstants.h"
53 #include "wasm/WasmLog.h"
54 #include "wasm/WasmMemory.h"
55 #include "wasm/WasmModuleTypes.h"
56 #include "wasm/WasmProcess.h"
57
58 #include "gc/GCContext-inl.h"
59 #include "gc/Marking-inl.h"
60 #include "vm/NativeObject-inl.h"
61 #include "vm/Realm-inl.h" // js::AutoRealm
62
63 using js::wasm::AddressType;
64 using js::wasm::Pages;
65 using mozilla::Atomic;
66 using mozilla::DebugOnly;
67 using mozilla::Maybe;
68 using mozilla::Nothing;
69 using mozilla::Some;
70
71 using namespace js;
72
73 // Wasm allows large amounts of memory to be reserved at a time. On 64-bit
74 // platforms (with "huge memories") we reserve around 4GB of virtual address
75 // space for every wasm memory; on 32-bit platforms we usually do not, but users
76 // often initialize memories in the hundreds of megabytes.
77 //
78 // If too many wasm memories remain live, we run up against system resource
79 // exhaustion (address space or number of memory map descriptors) - see bug
80 // 1068684, bug 1073934, bug 1517412, bug 1502733 for details. The limiting case
81 // seems to be Android on ARM64, where the per-process address space is limited
82 // to 4TB (39 bits) by the organization of the page tables. An earlier problem
83 // was Windows Vista Home 64-bit, where the per-process address space is limited
84 // to 8TB (40 bits). And 32-bit platforms only have 4GB of address space anyway.
85 //
86 // Thus we track the amount of memory reserved for wasm, and set a limit per
87 // process. We trigger GC work when we approach the limit and we throw an OOM
88 // error if the per-process limit is exceeded. The limit (WasmReservedBytesMax)
89 // is specific to architecture, OS, and OS configuration.
90 //
91 // Since the WasmReservedBytesMax limit is not generally accounted for by
92 // any existing GC-trigger heuristics, we need an extra heuristic for triggering
93 // GCs when the caller is allocating memories rapidly without other garbage
94 // (e.g. bug 1773225). Thus, once the reserved memory crosses the threshold
95 // WasmReservedBytesStartTriggering, we start triggering GCs every
96 // WasmReservedBytesPerTrigger bytes. Once we reach
97 // WasmReservedBytesStartSyncFullGC bytes reserved, we perform expensive
98 // non-incremental full GCs as a last-ditch effort to avoid unnecessary failure.
99 // Once we reach WasmReservedBytesMax, we perform further full GCs before giving
100 // up.
101 //
102 // (History: The original implementation only tracked the number of "huge
103 // memories" allocated by WASM, but this was found to be insufficient because
104 // 32-bit platforms have similar resource exhaustion issues. We now track
105 // reserved bytes directly.)
106 //
107 // (We also used to reserve significantly more than 4GB for huge memories, but
108 // this was reduced in bug 1442544.)
109
110 // ASAN and TSAN use a ton of vmem for bookkeeping leaving a lot less for the
111 // program so use a lower limit.
112 #if defined(MOZ_TSAN) || defined(MOZ_ASAN)
113 static const uint64_t WasmMemAsanOverhead = 2;
114 #else
115 static const uint64_t WasmMemAsanOverhead = 1;
116 #endif
117
118 // WasmReservedStartTriggering + WasmReservedPerTrigger must be well below
119 // WasmReservedStartSyncFullGC in order to provide enough time for incremental
120 // GC to do its job.
121
122 #if defined(JS_CODEGEN_ARM64) && defined(ANDROID)
123
124 static const uint64_t WasmReservedBytesMax =
125 75 * wasm::HugeMappedSize / WasmMemAsanOverhead;
126 static const uint64_t WasmReservedBytesStartTriggering =
127 15 * wasm::HugeMappedSize;
128 static const uint64_t WasmReservedBytesStartSyncFullGC =
129 WasmReservedBytesMax - 15 * wasm::HugeMappedSize;
130 static const uint64_t WasmReservedBytesPerTrigger = 15 * wasm::HugeMappedSize;
131
132 #elif defined(WASM_SUPPORTS_HUGE_MEMORY)
133
134 static const uint64_t WasmReservedBytesMax =
135 1000 * wasm::HugeMappedSize / WasmMemAsanOverhead;
136 static const uint64_t WasmReservedBytesStartTriggering =
137 100 * wasm::HugeMappedSize;
138 static const uint64_t WasmReservedBytesStartSyncFullGC =
139 WasmReservedBytesMax - 100 * wasm::HugeMappedSize;
140 static const uint64_t WasmReservedBytesPerTrigger = 100 * wasm::HugeMappedSize;
141
142 #else // 32-bit (and weird 64-bit platforms without huge memory)
143
144 static const uint64_t GiB = 1024 * 1024 * 1024;
145
146 static const uint64_t WasmReservedBytesMax =
147 (4 * GiB) / 2 / WasmMemAsanOverhead;
148 static const uint64_t WasmReservedBytesStartTriggering = (4 * GiB) / 8;
149 static const uint64_t WasmReservedBytesStartSyncFullGC =
150 WasmReservedBytesMax - (4 * GiB) / 8;
151 static const uint64_t WasmReservedBytesPerTrigger = (4 * GiB) / 8;
152
153 #endif
154
155 // The total number of bytes reserved for wasm memories.
156 static Atomic<uint64_t, mozilla::ReleaseAcquire> wasmReservedBytes(0);
157 // The number of bytes of wasm memory reserved since the last GC trigger.
158 static Atomic<uint64_t, mozilla::ReleaseAcquire> wasmReservedBytesSinceLast(0);
159
160 uint64_t js::WasmReservedBytes() { return wasmReservedBytes; }
161
162 [[nodiscard]] static bool CheckArrayBufferTooLarge(JSContext* cx,
163 uint64_t nbytes) {
164 // Refuse to allocate too large buffers.
165 if (MOZ_UNLIKELY(nbytes > ArrayBufferObject::ByteLengthLimit)) {
166 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
167 JSMSG_BAD_ARRAY_LENGTH);
168 return false;
169 }
170
171 return true;
172 }
173
174 void* js::MapBufferMemory(wasm::AddressType t, size_t mappedSize,
175 size_t initialCommittedSize) {
176 MOZ_ASSERT(mappedSize % gc::SystemPageSize() == 0);
177 MOZ_ASSERT(initialCommittedSize % gc::SystemPageSize() == 0);
178 MOZ_ASSERT(initialCommittedSize <= mappedSize);
179
180 auto failed = mozilla::MakeScopeExit(
181 [&] { wasmReservedBytes -= uint64_t(mappedSize); });
182 wasmReservedBytes += uint64_t(mappedSize);
183
184 // Test >= to guard against the case where multiple extant runtimes
185 // race to allocate.
186 if (wasmReservedBytes >= WasmReservedBytesMax) {
187 if (OnLargeAllocationFailure) {
188 OnLargeAllocationFailure();
189 }
190 if (wasmReservedBytes >= WasmReservedBytesMax) {
191 return nullptr;
192 }
193 }
194
195 #ifdef XP_WIN
196 void* data = VirtualAlloc(nullptr, mappedSize, MEM_RESERVE, PAGE_NOACCESS);
197 if (!data) {
198 return nullptr;
199 }
200
201 if (!VirtualAlloc(data, initialCommittedSize, MEM_COMMIT, PAGE_READWRITE)) {
202 VirtualFree(data, 0, MEM_RELEASE);
203 return nullptr;
204 }
205
206 gc::RecordMemoryAlloc(initialCommittedSize);
207 #elif defined(__wasi__)
208 void* data = nullptr;
209 if (int err = posix_memalign(&data, gc::SystemPageSize(), mappedSize)) {
210 MOZ_ASSERT(err == ENOMEM);
211 (void)err;
212 return nullptr;
213 }
214 MOZ_ASSERT(data);
215 memset(data, 0, mappedSize);
216 #else // !XP_WIN && !__wasi__
217 void* data =
218 MozTaggedAnonymousMmap(nullptr, mappedSize, PROT_NONE,
219 MAP_PRIVATE | MAP_ANON, -1, 0, "wasm-reserved");
220 if (data == MAP_FAILED) {
221 return nullptr;
222 }
223
224 // Note we will waste a page on zero-sized memories here
225 if (mprotect(data, initialCommittedSize, PROT_READ | PROT_WRITE)) {
226 munmap(data, mappedSize);
227 return nullptr;
228 }
229
230 gc::RecordMemoryAlloc(initialCommittedSize);
231 #endif // !XP_WIN && !__wasi__
232
233 #if defined(MOZ_VALGRIND) && \
234 defined(VALGRIND_DISABLE_ADDR_ERROR_REPORTING_IN_RANGE)
235 VALGRIND_DISABLE_ADDR_ERROR_REPORTING_IN_RANGE(
236 (unsigned char*)data + initialCommittedSize,
237 mappedSize - initialCommittedSize);
238 #endif
239
240 failed.release();
241 return data;
242 }
243
244 bool js::CommitBufferMemory(void* dataEnd, size_t delta) {
245 MOZ_ASSERT(delta);
246 MOZ_ASSERT(delta % gc::SystemPageSize() == 0);
247
248 #ifdef XP_WIN
249 if (!VirtualAlloc(dataEnd, delta, MEM_COMMIT, PAGE_READWRITE)) {
250 return false;
251 }
252 #elif defined(__wasi__)
253 // posix_memalign'd memory is already committed
254 return true;
255 #else
256 if (mprotect(dataEnd, delta, PROT_READ | PROT_WRITE)) {
257 return false;
258 }
259 #endif // XP_WIN
260
261 gc::RecordMemoryAlloc(delta);
262
263 #if defined(MOZ_VALGRIND) && \
264 defined(VALGRIND_DISABLE_ADDR_ERROR_REPORTING_IN_RANGE)
265 VALGRIND_ENABLE_ADDR_ERROR_REPORTING_IN_RANGE((unsigned char*)dataEnd, delta);
266 #endif
267
268 return true;
269 }
270
271 void js::UnmapBufferMemory(wasm::AddressType t, void* base, size_t mappedSize,
272 size_t committedSize) {
273 MOZ_ASSERT(mappedSize % gc::SystemPageSize() == 0);
274 MOZ_ASSERT(committedSize % gc::SystemPageSize() == 0);
275
276 #ifdef XP_WIN
277 VirtualFree(base, 0, MEM_RELEASE);
278 gc::RecordMemoryFree(committedSize);
279 #elif defined(__wasi__)
280 free(base);
281 (void)committedSize;
282 #else
283 munmap(base, mappedSize);
284 gc::RecordMemoryFree(committedSize);
285 #endif // XP_WIN
286
287 #if defined(MOZ_VALGRIND) && \
288 defined(VALGRIND_ENABLE_ADDR_ERROR_REPORTING_IN_RANGE)
289 VALGRIND_ENABLE_ADDR_ERROR_REPORTING_IN_RANGE((unsigned char*)base,
290 mappedSize);
291 #endif
292
293 // Untrack reserved memory *after* releasing memory -- otherwise, a race
294 // condition could enable the creation of unlimited buffers.
295 wasmReservedBytes -= uint64_t(mappedSize);
296 }
297
298 /*
299 * ArrayBufferObject
300 *
301 * This class holds the underlying raw buffer that the TypedArrayObject classes
302 * access. It can be created explicitly and passed to a TypedArrayObject, or
303 * can be created implicitly by constructing a TypedArrayObject with a size.
304 */
305
306 /*
307 * ArrayBufferObject (base)
308 */
309
310 static const JSClassOps ArrayBufferObjectClassOps = {
311 nullptr, // addProperty
312 nullptr, // delProperty
313 nullptr, // enumerate
314 nullptr, // newEnumerate
315 nullptr, // resolve
316 nullptr, // mayResolve
317 ArrayBufferObject::finalize, // finalize
318 nullptr, // call
319 nullptr, // construct
320 nullptr, // trace
321 };
322
323 static const JSFunctionSpec arraybuffer_functions[] = {
324 JS_FN("isView", ArrayBufferObject::fun_isView, 1, 0),
325 JS_FS_END,
326 };
327
328 static const JSPropertySpec arraybuffer_properties[] = {
329 JS_SELF_HOSTED_SYM_GET(species, "$ArrayBufferSpecies", 0),
330 JS_PS_END,
331 };
332
333 static const JSFunctionSpec arraybuffer_proto_functions[] = {
334 JS_FN("slice", ArrayBufferObject::slice, 2, 0),
335 JS_FN("resize", ArrayBufferObject::resize, 1, 0),
336 JS_FN("transfer", ArrayBufferObject::transfer, 0, 0),
337 JS_FN("transferToFixedLength", ArrayBufferObject::transferToFixedLength, 0,
338 0),
339 JS_FS_END,
340 };
341
342 static const JSPropertySpec arraybuffer_proto_properties[] = {
343 JS_PSG("byteLength", ArrayBufferObject::byteLengthGetter, 0),
344 JS_PSG("maxByteLength", ArrayBufferObject::maxByteLengthGetter, 0),
345 JS_PSG("resizable", ArrayBufferObject::resizableGetter, 0),
346 JS_PSG("detached", ArrayBufferObject::detachedGetter, 0),
347 JS_STRING_SYM_PS(toStringTag, "ArrayBuffer", JSPROP_READONLY),
348 JS_PS_END,
349 };
350
351 static JSObject* CreateArrayBufferPrototype(JSContext* cx, JSProtoKey key) {
352 return GlobalObject::createBlankPrototype(cx, cx->global(),
353 &ArrayBufferObject::protoClass_);
354 }
355
356 static const ClassSpec ArrayBufferObjectClassSpec = {
357 GenericCreateConstructor<ArrayBufferObject::class_constructor, 1,
358 gc::AllocKind::FUNCTION>,
359 CreateArrayBufferPrototype,
360 arraybuffer_functions,
361 arraybuffer_properties,
362 arraybuffer_proto_functions,
363 arraybuffer_proto_properties,
364 GenericFinishInit<WhichHasFuseProperty::ProtoAndCtor>,
365 };
366
367 static const ClassExtension FixedLengthArrayBufferObjectClassExtension = {
368 ArrayBufferObject::objectMoved<
369 FixedLengthArrayBufferObject>, // objectMovedOp
370 };
371
372 static const ClassExtension ResizableArrayBufferObjectClassExtension = {
373 ArrayBufferObject::objectMoved<
374 ResizableArrayBufferObject>, // objectMovedOp
375 };
376
377 const JSClass ArrayBufferObject::protoClass_ = {
378 "ArrayBuffer.prototype",
379 JSCLASS_HAS_CACHED_PROTO(JSProto_ArrayBuffer),
380 JS_NULL_CLASS_OPS,
381 &ArrayBufferObjectClassSpec,
382 };
383
384 const JSClass FixedLengthArrayBufferObject::class_ = {
385 "ArrayBuffer",
386 JSCLASS_DELAY_METADATA_BUILDER |
387 JSCLASS_HAS_RESERVED_SLOTS(RESERVED_SLOTS) |
388 JSCLASS_HAS_CACHED_PROTO(JSProto_ArrayBuffer) |
389 JSCLASS_BACKGROUND_FINALIZE,
390 &ArrayBufferObjectClassOps,
391 &ArrayBufferObjectClassSpec,
392 &FixedLengthArrayBufferObjectClassExtension,
393 };
394
395 const JSClass ResizableArrayBufferObject::class_ = {
396 "ArrayBuffer",
397 JSCLASS_DELAY_METADATA_BUILDER |
398 JSCLASS_HAS_RESERVED_SLOTS(RESERVED_SLOTS) |
399 JSCLASS_HAS_CACHED_PROTO(JSProto_ArrayBuffer) |
400 JSCLASS_BACKGROUND_FINALIZE,
401 &ArrayBufferObjectClassOps,
402 &ArrayBufferObjectClassSpec,
403 &ResizableArrayBufferObjectClassExtension,
404 };
405
406 static bool IsArrayBuffer(HandleValue v) {
407 return v.isObject() && v.toObject().is<ArrayBufferObject>();
408 }
409
410 static bool IsResizableArrayBuffer(HandleValue v) {
411 return v.isObject() && v.toObject().is<ResizableArrayBufferObject>();
412 }
413
414 MOZ_ALWAYS_INLINE bool ArrayBufferObject::byteLengthGetterImpl(
415 JSContext* cx, const CallArgs& args) {
416 MOZ_ASSERT(IsArrayBuffer(args.thisv()));
417 auto* buffer = &args.thisv().toObject().as<ArrayBufferObject>();
418 args.rval().setNumber(buffer->byteLength());
419 return true;
420 }
421
422 bool ArrayBufferObject::byteLengthGetter(JSContext* cx, unsigned argc,
423 Value* vp) {
424 CallArgs args = CallArgsFromVp(argc, vp);
425 return CallNonGenericMethod<IsArrayBuffer, byteLengthGetterImpl>(cx, args);
426 }
427
428 enum class PreserveResizability : bool { No, Yes };
429
430 /**
431 * ArrayBufferCopyAndDetach ( arrayBuffer, newLength, preserveResizability )
432 *
433 * https://tc39.es/proposal-arraybuffer-transfer/#sec-arraybuffercopyanddetach
434 */
435 static ArrayBufferObject* ArrayBufferCopyAndDetach(
436 JSContext* cx, Handle<ArrayBufferObject*> arrayBuffer,
437 Handle<Value> newLength, PreserveResizability preserveResizability) {
438 // Steps 1-2. (Not applicable in our implementation.)
439
440 // Steps 3-4.
441 uint64_t newByteLength;
442 if (newLength.isUndefined()) {
443 // Step 3.a.
444 newByteLength = arrayBuffer->byteLength();
445 } else {
446 // Step 4.a.
447 if (!ToIndex(cx, newLength, &newByteLength)) {
448 return nullptr;
449 }
450 }
451
452 // Step 5.
453 if (arrayBuffer->isDetached()) {
454 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
455 JSMSG_TYPED_ARRAY_DETACHED);
456 return nullptr;
457 }
458 if (arrayBuffer->isLengthPinned()) {
459 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
460 JSMSG_ARRAYBUFFER_LENGTH_PINNED);
461 return nullptr;
462 }
463
464 // Steps 6-7.
465 mozilla::Maybe<size_t> maxByteLength;
466 if (preserveResizability == PreserveResizability::Yes &&
467 arrayBuffer->isResizable()) {
468 auto* resizableBuffer = &arrayBuffer->as<ResizableArrayBufferObject>();
469 maxByteLength = mozilla::Some(resizableBuffer->maxByteLength());
470 }
471
472 // Step 8.
473 if (arrayBuffer->hasDefinedDetachKey()) {
474 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
475 JSMSG_WASM_NO_TRANSFER);
476 return nullptr;
477 }
478
479 // Steps 9-16.
480 //
481 // 25.1.2.1 AllocateArrayBuffer, step 2.
482 // 6.2.9.1 CreateByteDataBlock, step 2.
483 if (!CheckArrayBufferTooLarge(cx, newByteLength)) {
484 return nullptr;
485 }
486
487 if (maxByteLength) {
488 if (size_t(newByteLength) > *maxByteLength) {
489 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
490 JSMSG_ARRAYBUFFER_LENGTH_LARGER_THAN_MAXIMUM);
491 return nullptr;
492 }
493
494 Rooted<ResizableArrayBufferObject*> resizableBuffer(
495 cx, &arrayBuffer->as<ResizableArrayBufferObject>());
496 return ResizableArrayBufferObject::copyAndDetach(cx, size_t(newByteLength),
497 resizableBuffer);
498 }
499
500 return ArrayBufferObject::copyAndDetach(cx, size_t(newByteLength),
501 arrayBuffer);
502 }
503
504 /**
505 * get ArrayBuffer.prototype.maxByteLength
506 *
507 * https://tc39.es/ecma262/#sec-get-arraybuffer.prototype.maxbytelength
508 */
509 bool ArrayBufferObject::maxByteLengthGetterImpl(JSContext* cx,
510 const CallArgs& args) {
511 MOZ_ASSERT(IsArrayBuffer(args.thisv()));
512
513 auto* buffer = &args.thisv().toObject().as<ArrayBufferObject>();
514
515 // Steps 4-6.
516 size_t maxByteLength = buffer->maxByteLength();
517 MOZ_ASSERT_IF(buffer->isDetached(), maxByteLength == 0);
518
519 // Step 7.
520 args.rval().setNumber(maxByteLength);
521 return true;
522 }
523
524 /**
525 * get ArrayBuffer.prototype.maxByteLength
526 *
527 * https://tc39.es/ecma262/#sec-get-arraybuffer.prototype.maxbytelength
528 */
529 bool ArrayBufferObject::maxByteLengthGetter(JSContext* cx, unsigned argc,
530 Value* vp) {
531 // Steps 1-3.
532 CallArgs args = CallArgsFromVp(argc, vp);
533 return CallNonGenericMethod<IsArrayBuffer, maxByteLengthGetterImpl>(cx, args);
534 }
535
536 /**
537 * get ArrayBuffer.prototype.resizable
538 *
539 * https://tc39.es/ecma262/#sec-get-arraybuffer.prototype.resizable
540 */
541 bool ArrayBufferObject::resizableGetterImpl(JSContext* cx,
542 const CallArgs& args) {
543 MOZ_ASSERT(IsArrayBuffer(args.thisv()));
544
545 // Step 4.
546 auto* buffer = &args.thisv().toObject().as<ArrayBufferObject>();
547 args.rval().setBoolean(buffer->isResizable());
548 return true;
549 }
550
551 /**
552 * get ArrayBuffer.prototype.resizable
553 *
554 * https://tc39.es/ecma262/#sec-get-arraybuffer.prototype.resizable
555 */
556 bool ArrayBufferObject::resizableGetter(JSContext* cx, unsigned argc,
557 Value* vp) {
558 // Steps 1-3.
559 CallArgs args = CallArgsFromVp(argc, vp);
560 return CallNonGenericMethod<IsArrayBuffer, resizableGetterImpl>(cx, args);
561 }
562
563 /**
564 * get ArrayBuffer.prototype.detached
565 *
566 * https://tc39.es/proposal-arraybuffer-transfer/#sec-get-arraybuffer.prototype.detached
567 */
568 bool ArrayBufferObject::detachedGetterImpl(JSContext* cx,
569 const CallArgs& args) {
570 MOZ_ASSERT(IsArrayBuffer(args.thisv()));
571
572 // Step 4.
573 auto* buffer = &args.thisv().toObject().as<ArrayBufferObject>();
574 args.rval().setBoolean(buffer->isDetached());
575 return true;
576 }
577
578 /**
579 * get ArrayBuffer.prototype.detached
580 *
581 * https://tc39.es/proposal-arraybuffer-transfer/#sec-get-arraybuffer.prototype.detached
582 */
583 bool ArrayBufferObject::detachedGetter(JSContext* cx, unsigned argc,
584 Value* vp) {
585 // Steps 1-3.
586 CallArgs args = CallArgsFromVp(argc, vp);
587 return CallNonGenericMethod<IsArrayBuffer, detachedGetterImpl>(cx, args);
588 }
589
590 /**
591 * ArrayBuffer.prototype.transfer ( [ newLength ] )
592 *
593 * https://tc39.es/proposal-arraybuffer-transfer/#sec-arraybuffer.prototype.transfer
594 */
595 bool ArrayBufferObject::transferImpl(JSContext* cx, const CallArgs& args) {
596 MOZ_ASSERT(IsArrayBuffer(args.thisv()));
597
598 // Steps 1-2.
599 Rooted<ArrayBufferObject*> buffer(
600 cx, &args.thisv().toObject().as<ArrayBufferObject>());
601 auto* newBuffer = ArrayBufferCopyAndDetach(cx, buffer, args.get(0),
602 PreserveResizability::Yes);
603 if (!newBuffer) {
604 return false;
605 }
606
607 args.rval().setObject(*newBuffer);
608 return true;
609 }
610
611 /**
612 * ArrayBuffer.prototype.transfer ( [ newLength ] )
613 *
614 * https://tc39.es/proposal-arraybuffer-transfer/#sec-arraybuffer.prototype.transfer
615 */
616 bool ArrayBufferObject::transfer(JSContext* cx, unsigned argc, Value* vp) {
617 CallArgs args = CallArgsFromVp(argc, vp);
618 return CallNonGenericMethod<IsArrayBuffer, transferImpl>(cx, args);
619 }
620
621 /**
622 * ArrayBuffer.prototype.transferToFixedLength ( [ newLength ] )
623 *
624 * https://tc39.es/proposal-arraybuffer-transfer/#sec-arraybuffer.prototype.transfertofixedlength
625 */
626 bool ArrayBufferObject::transferToFixedLengthImpl(JSContext* cx,
627 const CallArgs& args) {
628 MOZ_ASSERT(IsArrayBuffer(args.thisv()));
629
630 // Steps 1-2.
631 Rooted<ArrayBufferObject*> buffer(
632 cx, &args.thisv().toObject().as<ArrayBufferObject>());
633 auto* newBuffer = ArrayBufferCopyAndDetach(cx, buffer, args.get(0),
634 PreserveResizability::No);
635 if (!newBuffer) {
636 return false;
637 }
638
639 args.rval().setObject(*newBuffer);
640 return true;
641 }
642
643 /**
644 * ArrayBuffer.prototype.transferToFixedLength ( [ newLength ] )
645 *
646 * https://tc39.es/proposal-arraybuffer-transfer/#sec-arraybuffer.prototype.transfertofixedlength
647 */
648 bool ArrayBufferObject::transferToFixedLength(JSContext* cx, unsigned argc,
649 Value* vp) {
650 CallArgs args = CallArgsFromVp(argc, vp);
651 return CallNonGenericMethod<IsArrayBuffer, transferToFixedLengthImpl>(cx,
652 args);
653 }
654
655 /**
656 * ArrayBuffer.prototype.resize ( newLength )
657 *
658 * https://tc39.es/ecma262/#sec-arraybuffer.prototype.resize
659 */
660 bool ArrayBufferObject::resizeImpl(JSContext* cx, const CallArgs& args) {
661 MOZ_ASSERT(IsResizableArrayBuffer(args.thisv()));
662
663 Rooted<ResizableArrayBufferObject*> obj(
664 cx, &args.thisv().toObject().as<ResizableArrayBufferObject>());
665
666 // Step 4.
667 uint64_t newByteLength;
668 if (!ToIndex(cx, args.get(0), &newByteLength)) {
669 return false;
670 }
671
672 // Step 5.
673 if (obj->isDetached()) {
674 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
675 JSMSG_TYPED_ARRAY_DETACHED);
676 return false;
677 }
678 if (obj->isLengthPinned()) {
679 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
680 JSMSG_ARRAYBUFFER_LENGTH_PINNED);
681 return false;
682 }
683
684 // Step 6.
685 if (newByteLength > obj->maxByteLength()) {
686 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
687 JSMSG_ARRAYBUFFER_LENGTH_LARGER_THAN_MAXIMUM);
688 return false;
689 }
690
691 if (obj->isWasm()) {
692 // Special case for resizing of Wasm buffers.
693 if (newByteLength % wasm::PageSize != 0) {
694 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
695 JSMSG_WASM_ARRAYBUFFER_PAGE_MULTIPLE);
696 return false;
697 }
698 if (newByteLength < obj->byteLength()) {
699 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
700 JSMSG_WASM_ARRAYBUFFER_CANNOT_SHRINK);
701 return false;
702 }
703
704 Pages newPages = Pages::fromByteLengthExact(newByteLength);
705 MOZ_RELEASE_ASSERT(WasmArrayBufferSourceMaxPages(obj).isSome());
706 Rooted<ArrayBufferObject*> res(
707 cx,
708 obj->wasmGrowToPagesInPlace(obj->wasmAddressType(), newPages, obj, cx));
709 MOZ_ASSERT_IF(res, res == obj);
710 return !!res;
711 }
712
713 // Steps 7-15.
714 obj->resize(size_t(newByteLength));
715
716 // Step 16.
717 args.rval().setUndefined();
718 return true;
719 }
720
721 /**
722 * ArrayBuffer.prototype.resize ( newLength )
723 *
724 * https://tc39.es/ecma262/#sec-arraybuffer.prototype.resize
725 */
726 bool ArrayBufferObject::resize(JSContext* cx, unsigned argc, Value* vp) {
727 // Steps 1-3.
728 CallArgs args = CallArgsFromVp(argc, vp);
729 return CallNonGenericMethod<IsResizableArrayBuffer, resizeImpl>(cx, args);
730 }
731
732 static bool IsArrayBufferSpecies(JSContext* cx, JSFunction* species) {
733 return IsSelfHostedFunctionWithName(species,
734 cx->names().dollar_ArrayBufferSpecies_);
735 }
736
737 static bool HasBuiltinArrayBufferSpecies(ArrayBufferObject* obj,
738 JSContext* cx) {
739 // Ensure `ArrayBuffer.prototype.constructor` and `ArrayBuffer[@@species]`
740 // haven't been mutated.
741 if (!cx->realm()->realmFuses.optimizeArrayBufferSpeciesFuse.intact()) {
742 return false;
743 }
744
745 // Ensure |obj|'s prototype is the actual ArrayBuffer.prototype.
746 auto* proto = cx->global()->maybeGetPrototype(JSProto_ArrayBuffer);
747 if (!proto || obj->staticPrototype() != proto) {
748 return false;
749 }
750
751 // Fail if |obj| has an own `constructor` property.
752 if (obj->containsPure(NameToId(cx->names().constructor))) {
753 return false;
754 }
755
756 return true;
757 }
758
759 /**
760 * ArrayBuffer.prototype.slice ( start, end )
761 *
762 * https://tc39.es/ecma262/#sec-arraybuffer.prototype.slice
763 */
764 bool ArrayBufferObject::sliceImpl(JSContext* cx, const CallArgs& args) {
765 MOZ_ASSERT(IsArrayBuffer(args.thisv()));
766
767 Rooted<ArrayBufferObject*> obj(
768 cx, &args.thisv().toObject().as<ArrayBufferObject>());
769
770 // Step 4.
771 if (obj->isDetached()) {
772 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
773 JSMSG_TYPED_ARRAY_DETACHED);
774 return false;
775 }
776
777 // Step 5.
778 size_t len = obj->byteLength();
779
780 // Steps 6-9.
781 size_t first = 0;
782 if (args.hasDefined(0)) {
783 if (!ToIntegerIndex(cx, args[0], len, &first)) {
784 return false;
785 }
786 }
787
788 // Steps 10-13.
789 size_t final_ = len;
790 if (args.hasDefined(1)) {
791 if (!ToIntegerIndex(cx, args[1], len, &final_)) {
792 return false;
793 }
794 }
795
796 // Step 14.
797 size_t newLen = final_ >= first ? final_ - first : 0;
798 MOZ_ASSERT(newLen <= ArrayBufferObject::ByteLengthLimit);
799
800 // Steps 15-21.
801 Rooted<JSObject*> resultObj(cx);
802 ArrayBufferObject* unwrappedResult = nullptr;
803 if (HasBuiltinArrayBufferSpecies(obj, cx)) {
804 // Steps 15-16.
805 unwrappedResult = createZeroed(cx, newLen);
806 if (!unwrappedResult) {
807 return false;
808 }
809 resultObj.set(unwrappedResult);
810
811 // Steps 17-18. (Not applicable)
812
813 // Step 19.
814 MOZ_ASSERT(!unwrappedResult->isDetached());
815
816 // Step 20.
817 MOZ_ASSERT(unwrappedResult != obj);
818
819 // Step 21.
820 MOZ_ASSERT(unwrappedResult->byteLength() == newLen);
821 } else {
822 // Step 15.
823 Rooted<JSObject*> ctor(cx, SpeciesConstructor(cx, obj, JSProto_ArrayBuffer,
824 IsArrayBufferSpecies));
825 if (!ctor) {
826 return false;
827 }
828
829 // Step 16.
830 {
831 FixedConstructArgs<1> cargs(cx);
832 cargs[0].setNumber(newLen);
833
834 Rooted<Value> ctorVal(cx, ObjectValue(*ctor));
835 if (!Construct(cx, ctorVal, cargs, ctorVal, &resultObj)) {
836 return false;
837 }
838 }
839
840 // Steps 17-18.
841 unwrappedResult = resultObj->maybeUnwrapIf<ArrayBufferObject>();
842 if (!unwrappedResult) {
843 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
844 JSMSG_NON_ARRAY_BUFFER_RETURNED);
845 return false;
846 }
847
848 // Step 19.
849 if (unwrappedResult->isDetached()) {
850 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
851 JSMSG_TYPED_ARRAY_DETACHED);
852 return false;
853 }
854
855 // Step 20.
856 if (unwrappedResult == obj) {
857 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
858 JSMSG_SAME_ARRAY_BUFFER_RETURNED);
859 return false;
860 }
861
862 // Step 21.
863 size_t resultByteLength = unwrappedResult->byteLength();
864 if (resultByteLength < newLen) {
865 ToCStringBuf resultLenCbuf;
866 const char* resultLenStr =
867 NumberToCString(&resultLenCbuf, double(resultByteLength));
868
869 ToCStringBuf newLenCbuf;
870 const char* newLenStr = NumberToCString(&newLenCbuf, double(newLen));
871
872 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
873 JSMSG_SHORT_ARRAY_BUFFER_RETURNED, newLenStr,
874 resultLenStr);
875 return false;
876 }
877 }
878
879 // Steps 22-23.
880 if (obj->isDetached()) {
881 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
882 JSMSG_TYPED_ARRAY_DETACHED);
883 return false;
884 }
885
886 // Step 26.
887 //
888 // Reacquire the length in case the buffer has been resized.
889 size_t currentLen = obj->byteLength();
890
891 // Steps 24-25 and 27.
892 if (first < currentLen) {
893 // Step 27.a.
894 size_t count = std::min(newLen, currentLen - first);
895
896 // Steps 24-25 and 27.b.
897 ArrayBufferObject::copyData(unwrappedResult, 0, obj, first, count);
898 }
899
900 // Step 28.
901 args.rval().setObject(*resultObj);
902 return true;
903 }
904
905 /**
906 * ArrayBuffer.prototype.slice ( start, end )
907 *
908 * https://tc39.es/ecma262/#sec-arraybuffer.prototype.slice
909 */
910 bool ArrayBufferObject::slice(JSContext* cx, unsigned argc, Value* vp) {
911 // Steps 1-3.
912 CallArgs args = CallArgsFromVp(argc, vp);
913 return CallNonGenericMethod<IsArrayBuffer, sliceImpl>(cx, args);
914 }
915
916 /*
917 * ArrayBuffer.isView(obj); ES6 (Dec 2013 draft) 24.1.3.1
918 */
919 bool ArrayBufferObject::fun_isView(JSContext* cx, unsigned argc, Value* vp) {
920 CallArgs args = CallArgsFromVp(argc, vp);
921 args.rval().setBoolean(args.get(0).isObject() &&
922 JS_IsArrayBufferViewObject(&args.get(0).toObject()));
923 return true;
924 }
925
926 // ES2024 draft rev 3a773fc9fae58be023228b13dbbd402ac18eeb6b
927 // 25.1.4.1 ArrayBuffer ( length [ , options ] )
928 bool ArrayBufferObject::class_constructor(JSContext* cx, unsigned argc,
929 Value* vp) {
930 CallArgs args = CallArgsFromVp(argc, vp);
931
932 // Step 1.
933 if (!ThrowIfNotConstructing(cx, args, "ArrayBuffer")) {
934 return false;
935 }
936
937 // Step 2.
938 uint64_t byteLength;
939 if (!ToIndex(cx, args.get(0), &byteLength)) {
940 return false;
941 }
942
943 // Step 3.
944 mozilla::Maybe<uint64_t> maxByteLength;
945 // Inline call to GetArrayBufferMaxByteLengthOption.
946 if (args.get(1).isObject()) {
947 Rooted<JSObject*> options(cx, &args[1].toObject());
948
949 Rooted<Value> val(cx);
950 if (!GetProperty(cx, options, options, cx->names().maxByteLength, &val)) {
951 return false;
952 }
953 if (!val.isUndefined()) {
954 uint64_t maxByteLengthInt;
955 if (!ToIndex(cx, val, &maxByteLengthInt)) {
956 return false;
957 }
958
959 // 25.1.3.1 AllocateArrayBuffer, step 3.a.
960 if (byteLength > maxByteLengthInt) {
961 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
962 JSMSG_ARRAYBUFFER_LENGTH_LARGER_THAN_MAXIMUM);
963 return false;
964 }
965 maxByteLength = mozilla::Some(maxByteLengthInt);
966 }
967 }
968
969 // Step 4 (Inlined 25.1.3.1 AllocateArrayBuffer).
970 // 25.1.3.1, step 4 (Inlined 10.1.13 OrdinaryCreateFromConstructor, step 2).
971 RootedObject proto(cx);
972 if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_ArrayBuffer,
973 &proto)) {
974 return false;
975 }
976
977 // 25.1.3.1, step 5 (Inlined 6.2.9.1 CreateByteDataBlock, step 2).
978 if (!CheckArrayBufferTooLarge(cx, byteLength)) {
979 return false;
980 }
981
982 if (maxByteLength) {
983 // 25.1.3.1, step 8.a.
984 if (!CheckArrayBufferTooLarge(cx, *maxByteLength)) {
985 return false;
986 }
987
988 // 25.1.3.1, remaining steps.
989 auto* bufobj = ResizableArrayBufferObject::createZeroed(
990 cx, byteLength, *maxByteLength, proto);
991 if (!bufobj) {
992 return false;
993 }
994 args.rval().setObject(*bufobj);
995 return true;
996 }
997
998 // 25.1.3.1, remaining steps.
999 JSObject* bufobj = createZeroed(cx, byteLength, proto);
1000 if (!bufobj) {
1001 return false;
1002 }
1003 args.rval().setObject(*bufobj);
1004 return true;
1005 }
1006
1007 using ArrayBufferContents = UniquePtr<uint8_t[], JS::FreePolicy>;
1008
1009 static ArrayBufferContents AllocateUninitializedArrayBufferContents(
1010 JSContext* cx, size_t nbytes) {
1011 // First attempt a normal allocation.
1012 uint8_t* p =
1013 cx->maybe_pod_arena_malloc<uint8_t>(js::ArrayBufferContentsArena, nbytes);
1014 if (MOZ_UNLIKELY(!p)) {
1015 // Otherwise attempt a large allocation, calling the
1016 // large-allocation-failure callback if necessary.
1017 p = static_cast<uint8_t*>(cx->runtime()->onOutOfMemoryCanGC(
1018 js::AllocFunction::Malloc, js::ArrayBufferContentsArena, nbytes));
1019 if (!p) {
1020 MOZ_DIAGNOSTIC_ASSERT(!cx->brittleMode,
1021 "OOM in AllocateUninitializedArrayBufferContents");
1022 ReportOutOfMemory(cx);
1023 }
1024 }
1025
1026 return ArrayBufferContents(p);
1027 }
1028
1029 static ArrayBufferContents AllocateArrayBufferContents(JSContext* cx,
1030 size_t nbytes) {
1031 // First attempt a normal allocation.
1032 uint8_t* p =
1033 cx->maybe_pod_arena_calloc<uint8_t>(js::ArrayBufferContentsArena, nbytes);
1034 if (MOZ_UNLIKELY(!p)) {
1035 // Otherwise attempt a large allocation, calling the
1036 // large-allocation-failure callback if necessary.
1037 p = static_cast<uint8_t*>(cx->runtime()->onOutOfMemoryCanGC(
1038 js::AllocFunction::Calloc, js::ArrayBufferContentsArena, nbytes));
1039 if (!p) {
1040 ReportOutOfMemory(cx);
1041 }
1042 }
1043
1044 return ArrayBufferContents(p);
1045 }
1046
1047 static ArrayBufferContents ReallocateArrayBufferContents(JSContext* cx,
1048 uint8_t* old,
1049 size_t oldSize,
1050 size_t newSize) {
1051 // First attempt a normal reallocation.
1052 uint8_t* p = cx->maybe_pod_arena_realloc<uint8_t>(
1053 js::ArrayBufferContentsArena, old, oldSize, newSize);
1054 if (MOZ_UNLIKELY(!p)) {
1055 // Otherwise attempt a large allocation, calling the
1056 // large-allocation-failure callback if necessary.
1057 p = static_cast<uint8_t*>(cx->runtime()->onOutOfMemoryCanGC(
1058 js::AllocFunction::Realloc, js::ArrayBufferContentsArena, newSize,
1059 old));
1060 if (!p) {
1061 ReportOutOfMemory(cx);
1062 }
1063 }
1064
1065 return ArrayBufferContents(p);
1066 }
1067
1068 static ArrayBufferContents NewCopiedBufferContents(
1069 JSContext* cx, Handle<ArrayBufferObject*> buffer) {
1070 ArrayBufferContents dataCopy =
1071 AllocateUninitializedArrayBufferContents(cx, buffer->byteLength());
1072 if (dataCopy) {
1073 if (auto count = buffer->byteLength()) {
1074 memcpy(dataCopy.get(), buffer->dataPointer(), count);
1075 }
1076 }
1077 return dataCopy;
1078 }
1079
1080 /* static */
1081 void ArrayBufferObject::detach(JSContext* cx,
1082 Handle<ArrayBufferObject*> buffer) {
1083 cx->check(buffer);
1084 MOZ_ASSERT(!buffer->isPreparedForAsmJS());
1085 MOZ_ASSERT(!buffer->isLengthPinned());
1086
1087 // Update all views of the buffer to account for the buffer having been
1088 // detached, and clear the buffer's data and list of views.
1089
1090 auto& innerViews = ObjectRealm::get(buffer).innerViews.get();
1091 if (InnerViewTable::ViewVector* views =
1092 innerViews.maybeViewsUnbarriered(buffer)) {
1093 AutoTouchingGrayThings tgt;
1094 for (size_t i = 0; i < views->length(); i++) {
1095 JSObject* view = (*views)[i];
1096 view->as<ArrayBufferViewObject>().notifyBufferDetached();
1097 }
1098 innerViews.removeViews(buffer);
1099 }
1100 if (JSObject* view = buffer->firstView()) {
1101 view->as<ArrayBufferViewObject>().notifyBufferDetached();
1102 buffer->setFirstView(nullptr);
1103 }
1104
1105 if (buffer->dataPointer()) {
1106 buffer->releaseData(cx->gcContext());
1107 buffer->setDataPointer(BufferContents::createNoData());
1108 }
1109
1110 buffer->setByteLength(0);
1111 buffer->setIsDetached();
1112 if (buffer->isResizable()) {
1113 buffer->as<ResizableArrayBufferObject>().setMaxByteLength(0);
1114 }
1115 }
1116
1117 void ResizableArrayBufferObject::resize(size_t newByteLength) {
1118 MOZ_ASSERT(!isPreparedForAsmJS());
1119 MOZ_ASSERT(!isWasm());
1120 MOZ_ASSERT(!isDetached());
1121 MOZ_ASSERT(!isLengthPinned());
1122 MOZ_ASSERT(isResizable());
1123 MOZ_ASSERT(newByteLength <= maxByteLength());
1124
1125 // Clear the bytes between `data[newByteLength..oldByteLength]` when
1126 // shrinking the buffer. We don't need to clear any bytes when growing the
1127 // buffer, because the new space was either initialized to zero when creating
1128 // the buffer, or a prior shrink zeroed it out here.
1129 size_t oldByteLength = byteLength();
1130 if (newByteLength < oldByteLength) {
1131 size_t nbytes = oldByteLength - newByteLength;
1132 memset(dataPointer() + newByteLength, 0, nbytes);
1133 }
1134
1135 setByteLength(newByteLength);
1136
1137 // Update all views of the buffer to account for the buffer having been
1138 // resized.
1139
1140 auto& innerViews = ObjectRealm::get(this).innerViews.get();
1141 if (InnerViewTable::ViewVector* views =
1142 innerViews.maybeViewsUnbarriered(this)) {
1143 AutoTouchingGrayThings tgt;
1144 for (auto& view : *views) {
1145 view->notifyBufferResized();
1146 }
1147 }
1148 if (auto* view = firstView()) {
1149 view->as<ArrayBufferViewObject>().notifyBufferResized();
1150 }
1151 }
1152
1153 /*
1154 * [SMDOC] WASM Linear Memory structure
1155 *
1156 * The wasm linear memory is, on its face, a simple buffer of memory. However,
1157 * we perform several optimizations with the memory allocation to avoid bounds
1158 * checks and to avoid moving grows. Many different types/objects are involved
1159 * in our memory allocations:
1160 *
1161 * - wasm::Instance - stores information about each memory in a
1162 * MemoryInstanceData, which itself holds a reference to a WasmMemoryObject.
1163 * Memory 0 gets special treatment to avoid loading the MemoryInstanceData at
1164 * runtime.
1165 *
1166 * - WasmMemoryObject - stores a reference to a (Shared)ArrayBufferObject for
1167 * the backing storage.
1168 *
1169 * - ArrayBufferObject - owns the actual buffer of memory for asm.js memories
1170 * and non-shared wasm memories. For wasm memories (but NOT asm.js memories),
1171 * additional wasm metadata is stored in a WasmArrayRawBuffer next to the
1172 * data itself.
1173 *
1174 * - SharedArrayBufferObject - owns the actual buffer of memory for shared wasm
1175 * memories, in the form of a WasmSharedArrayRawBuffer.
1176 *
1177 * - WasmArrayRawBuffer - metadata for a non-shared wasm memory allocation. See
1178 * below for details.
1179 *
1180 * - WasmSharedArrayRawBuffer - a nearly equivalent class to WasmArrayRawBuffer
1181 * used for shared wasm memories only. The same terminology from
1182 * WasmArrayRawBuffer applies, but the memory allocation strategy is
1183 * different.
1184 *
1185 *
1186 * ## Wasm memory terminology
1187 *
1188 * A wasm/asm.js linear memory is an mmap'd array buffer. In the general case,
1189 * accesses to memory must be bounds checked, but bounds checks can be
1190 * simplified, omitted, or deferred to signal handling based on the properties
1191 * of the memory (such as a known maximum size). Some common terminology applies
1192 * to all asm.js and wasm memories, and is generally handled by
1193 * WasmMemoryObject. The following terms are all expressed in bytes for clarity,
1194 * but in practice they may be stored as a page count instead:
1195 *
1196 * - byteLength - the actual current length of the buffer. Accesses in
1197 * the range [0, byteLength) must succeed; accesses >= byteLength must fail.
1198 * May only increase, if the memory grows.
1199 *
1200 * - boundsCheckLimit - the size against which we perform bounds checks. This
1201 * is sometimes equal to byteLength, but may be greater. Regardless, it is
1202 * always safe to use in bounds checks for reasons described in "Linear
1203 * memory addresses and bounds checking" in wasm/WasmMemory.cpp.
1204 *
1205 * - sourceMaxSize - the optional declared limit on how far byteLength can
1206 * grow. This is the unmodified maximum size from the source module or JS-API
1207 * invocation. This may not be representable in pointer size, nor feasible
1208 * for a module to actually grow to due to implementation limits. It is used
1209 * for correct linking checks and js-types reflection.
1210 *
1211 * - clampedMaxSize - the maximum size on how far the byteLength can grow. This
1212 * value respects implementation limits. Every memory has a clampedMaxSize,
1213 * even if no maximum was specified in source. This value may be greater
1214 * than or less than mappedSize.
1215 *
1216 * - mappedSize - the actual mmap'd size. Access in the range [0, mappedSize)
1217 * will either succeed, or be handled by the wasm signal handlers. The amount
1218 * that we map can vary according to multiple factors - see "Allocation
1219 * strategies" below. (This property does not apply to asm.js.)
1220 *
1221 * The below diagram shows the layout of the wasm heap. The wasm-visible portion
1222 * of the heap starts at 0. There is one extra page prior to the start of the
1223 * wasm heap which contains the WasmArrayRawBuffer struct at its end (i.e. right
1224 * before the start of the WASM memory). The mappedSize does NOT include this
1225 * page.
1226 *
1227 *
1228 * Wasm(Shared)ArrayRawBuffer
1229 * │ dataPointer() (from (Shared)ArrayBufferObject)
1230 * │ │
1231 * ┌──────│─│──────────────────────────────────────────────────────┐
1232 * └──────│─│──────────────│─────────────────────────────────│─────│
1233 * 0 byteLength boundsCheckLimit mappedSize
1234 *
1235 * └───────────────────────┘
1236 * COMMITTED
1237 * └─────────────────────────────────┴─────┘
1238 * SLOP
1239 * └───────────────────────────────────────────────────────────────┘
1240 * MAPPED
1241 *
1242 *
1243 * Invariants on byteLength and mappedSize:
1244 * - byteLength only increases.
1245 * - 0 <= byteLength <= mappedSize.
1246 * - If sourceMaxSize is not specified, mappedSize may grow.
1247 * Otherwise, mappedSize is constant.
1248 *
1249 * Invariants on sourceMaxSize and clampedMaxSize:
1250 * - initialLength <= clampedMaxSize <= sourceMaxSize (if present).
1251 * - clampedMaxSize <= wasm::MaxMemoryPages().
1252 *
1253 * Invariants on boundsCheckLimit:
1254 * - For asm.js code: boundsCheckLimit == byteLength.
1255 * Signal handlers will not be invoked.
1256 * - For wasm code without the huge memory trick:
1257 * byteLength <= boundsCheckLimit < mappedSize
1258 * - For wasm code with the huge memory trick:
1259 * boundsCheckLimit is irrelevant as bounds checks are unnecessary.
1260 * - If sourceMaxSize is present, boundsCheckLimit is constant.
1261 * Otherwise, it may increase with mappedSize.
1262 * - On ARM, boundsCheckLimit must be a valid ARM immediate.
1263 *
1264 * The region between byteLength and mappedSize is the SLOP - an area where we
1265 * use signal handlers to catch invalid accesses, including those that slip by
1266 * bounds checks. Logically it has two parts:
1267 *
1268 * - From byteLength to boundsCheckLimit - as described above, we sometimes set
1269 * boundsCheckLimit higher than byteLength, and this part of the SLOP catches
1270 * accesses to memory that therefore pass a bounds check but should
1271 * nonetheless trap.
1272 *
1273 * - From boundsCheckLimit to mappedSize - this part of the SLOP is a guard
1274 * region that allows us to ignore most offsets when performing bounds
1275 * checks.
1276 *
1277 * For more information about both of these cases, see "Linear memory addresses
1278 * and bounds checking" in wasm/WasmMemory.cpp.
1279 *
1280 *
1281 * ## Allocation strategies
1282 *
1283 * Our memory allocation strategy varies according to several factors.
1284 *
1285 * - Huge memories - if allocating a 32-bit memory on a platform with
1286 * sufficient address space, we simply map 4GiB of memory plus ample guard
1287 * space. This eliminates the need for bounds checks entirely except in cases
1288 * of very large offsets. This applies whether or not the memory has a
1289 * declared maximum. See "Linear memory addresses and bounds checking" in
1290 * wasm/WasmMemory.cpp.
1291 *
1292 * - Memories with no maximum - rather than over-allocate, we conservatively
1293 * map only the requested initial pages plus the required guard region.
1294 *
1295 * - Memories with a maximum - we do our best to reserve the entire maximum
1296 * space up front so that grows will not fail later. If we fail to map the
1297 * entire maximum, we iteratively map less and less memory until allocation
1298 * succeeds.
1299 *
1300 *
1301 * ## Grow strategies
1302 *
1303 * We have two strategies for growing a wasm memory.
1304 *
1305 * - Growing in place - if mappedSize is large enough to contain the new size,
1306 * we can simply commit the previously-mapped pages. This is always the case
1307 * for huge memories, and for memories with a declared max (and by extension
1308 * shared memories).
1309 *
1310 * - Moving grow - if we have not previously mapped enough space, we must
1311 * allocate an entirely new buffer and copy the contents of the old buffer.
1312 * This causes the memory to move and therefore requires us to update
1313 * information on the Instance. It also increases memory pressure because
1314 * both the old and new memories must be resident at the same time, and
1315 * afterwards the entirety of the old buffer's contents will be resident in
1316 * memory (even if some pages had never been touched before the move).
1317 *
1318 * A moving grow can fall back to a grow in place if the mappedSize allows
1319 * for it. However, at the time of writing, our memory allocation/grow
1320 * strategies do not allow this to happen.
1321 *
1322 */
1323
1324 [[nodiscard]] bool WasmArrayRawBuffer::growToPagesInPlace(Pages newPages) {
1325 size_t newSize = newPages.byteLength();
1326 size_t oldSize = byteLength();
1327
1328 MOZ_ASSERT(newSize >= oldSize);
1329 MOZ_ASSERT(newPages <= clampedMaxPages());
1330 MOZ_ASSERT(newSize <= mappedSize());
1331
1332 size_t delta = newSize - oldSize;
1333 MOZ_ASSERT(delta % wasm::PageSize == 0);
1334
1335 uint8_t* dataEnd = dataPointer() + oldSize;
1336 MOZ_ASSERT(uintptr_t(dataEnd) % gc::SystemPageSize() == 0);
1337
1338 if (delta && !CommitBufferMemory(dataEnd, delta)) {
1339 return false;
1340 }
1341
1342 length_ = newSize;
1343
1344 return true;
1345 }
1346
1347 void WasmArrayRawBuffer::discard(size_t byteOffset, size_t byteLen) {
1348 uint8_t* memBase = dataPointer();
1349
1350 // The caller is responsible for ensuring these conditions are met; see this
1351 // function's comment in ArrayBufferObject.h.
1352 MOZ_ASSERT(byteOffset % wasm::PageSize == 0);
1353 MOZ_ASSERT(byteLen % wasm::PageSize == 0);
1354 MOZ_ASSERT(wasm::MemoryBoundsCheck(uint64_t(byteOffset), uint64_t(byteLen),
1355 byteLength()));
1356
1357 // Discarding zero bytes "succeeds" with no effect.
1358 if (byteLen == 0) {
1359 return;
1360 }
1361
1362 void* addr = memBase + uintptr_t(byteOffset);
1363
1364 // On POSIX-ish platforms, we discard memory by overwriting previously-mapped
1365 // pages with freshly-mapped pages (which are all zeroed). The operating
1366 // system recognizes this and decreases the process RSS, and eventually
1367 // collects the abandoned physical pages.
1368 //
1369 // On Windows, committing over previously-committed pages has no effect, and
1370 // the memory must be explicitly decommitted first. This is not the same as an
1371 // munmap; the address space is still reserved.
1372
1373 #ifdef XP_WIN
1374 if (!VirtualFree(addr, byteLen, MEM_DECOMMIT)) {
1375 MOZ_CRASH("wasm discard: failed to decommit memory");
1376 }
1377 if (!VirtualAlloc(addr, byteLen, MEM_COMMIT, PAGE_READWRITE)) {
1378 MOZ_CRASH("wasm discard: decommitted memory but failed to recommit");
1379 };
1380 #elif defined(__wasi__)
1381 memset(addr, 0, byteLen);
1382 #else // !XP_WIN
1383 void* data = MozTaggedAnonymousMmap(addr, byteLen, PROT_READ | PROT_WRITE,
1384 MAP_PRIVATE | MAP_ANON | MAP_FIXED, -1, 0,
1385 "wasm-reserved");
1386 if (data == MAP_FAILED) {
1387 MOZ_CRASH("failed to discard wasm memory; memory mappings may be broken");
1388 }
1389 #endif
1390 }
1391
1392 /* static */
1393 WasmArrayRawBuffer* WasmArrayRawBuffer::AllocateWasm(
1394 AddressType addressType, Pages initialPages, Pages clampedMaxPages,
1395 const Maybe<Pages>& sourceMaxPages, const Maybe<size_t>& mapped) {
1396 // Prior code has asserted that initial pages is within our implementation
1397 // limits (wasm::MaxMemoryPages) and we can assume it is a valid size_t.
1398 MOZ_ASSERT(initialPages.hasByteLength());
1399 size_t numBytes = initialPages.byteLength();
1400
1401 // If there is a specified maximum, attempt to map the whole range for
1402 // clampedMaxPages. Or else map only what's required for initialPages.
1403 Pages initialMappedPages =
1404 sourceMaxPages.isSome() ? clampedMaxPages : initialPages;
1405
1406 // Use an override mapped size, or else compute the mapped size from
1407 // initialMappedPages.
1408 size_t mappedSize =
1409 mapped.isSome() ? *mapped : wasm::ComputeMappedSize(initialMappedPages);
1410
1411 MOZ_RELEASE_ASSERT(mappedSize <= SIZE_MAX - gc::SystemPageSize());
1412 MOZ_RELEASE_ASSERT(numBytes <= SIZE_MAX - gc::SystemPageSize());
1413 MOZ_RELEASE_ASSERT(initialPages <= clampedMaxPages);
1414 MOZ_ASSERT(numBytes % gc::SystemPageSize() == 0);
1415 MOZ_ASSERT(mappedSize % gc::SystemPageSize() == 0);
1416
1417 uint64_t mappedSizeWithHeader = mappedSize + gc::SystemPageSize();
1418 uint64_t numBytesWithHeader = numBytes + gc::SystemPageSize();
1419
1420 void* data = MapBufferMemory(addressType, (size_t)mappedSizeWithHeader,
1421 (size_t)numBytesWithHeader);
1422 if (!data) {
1423 return nullptr;
1424 }
1425
1426 uint8_t* base = reinterpret_cast<uint8_t*>(data) + gc::SystemPageSize();
1427 uint8_t* header = base - sizeof(WasmArrayRawBuffer);
1428
1429 auto rawBuf = new (header) WasmArrayRawBuffer(
1430 addressType, base, clampedMaxPages, sourceMaxPages, mappedSize, numBytes);
1431 return rawBuf;
1432 }
1433
1434 /* static */
1435 void WasmArrayRawBuffer::Release(void* mem) {
1436 WasmArrayRawBuffer* header =
1437 (WasmArrayRawBuffer*)((uint8_t*)mem - sizeof(WasmArrayRawBuffer));
1438
1439 MOZ_RELEASE_ASSERT(header->mappedSize() <= SIZE_MAX - gc::SystemPageSize());
1440 size_t mappedSizeWithHeader = header->mappedSize() + gc::SystemPageSize();
1441 size_t committedSize = header->byteLength() + gc::SystemPageSize();
1442
1443 static_assert(std::is_trivially_destructible_v<WasmArrayRawBuffer>,
1444 "no need to call the destructor");
1445
1446 UnmapBufferMemory(header->addressType(), header->basePointer(),
1447 mappedSizeWithHeader, committedSize);
1448 }
1449
1450 WasmArrayRawBuffer* ArrayBufferObject::BufferContents::wasmBuffer() const {
1451 MOZ_RELEASE_ASSERT(kind_ == WASM);
1452 return (WasmArrayRawBuffer*)(data_ - sizeof(WasmArrayRawBuffer));
1453 }
1454
1455 template <typename ObjT, typename RawbufT>
1456 static ArrayBufferObjectMaybeShared* CreateSpecificWasmBuffer(
1457 JSContext* cx, const wasm::MemoryDesc& memory) {
1458 bool useHugeMemory = wasm::IsHugeMemoryEnabled(memory.addressType());
1459 Pages initialPages = memory.initialPages();
1460 Maybe<Pages> sourceMaxPages = memory.maximumPages();
1461 Pages clampedMaxPages = wasm::ClampedMaxPages(
1462 memory.addressType(), initialPages, sourceMaxPages, useHugeMemory);
1463
1464 Maybe<size_t> mappedSize;
1465 #ifdef WASM_SUPPORTS_HUGE_MEMORY
1466 // Override the mapped size if we are using huge memory. If we are not, then
1467 // it will be calculated by the raw buffer we are using.
1468 if (useHugeMemory) {
1469 mappedSize = Some(wasm::HugeMappedSize);
1470 }
1471 #endif
1472
1473 RawbufT* buffer =
1474 RawbufT::AllocateWasm(memory.limits.addressType, initialPages,
1475 clampedMaxPages, sourceMaxPages, mappedSize);
1476 if (!buffer) {
1477 if (useHugeMemory) {
1478 WarnNumberASCII(cx, JSMSG_WASM_HUGE_MEMORY_FAILED);
1479 if (cx->isExceptionPending()) {
1480 cx->clearPendingException();
1481 }
1482
1483 ReportOutOfMemory(cx);
1484 return nullptr;
1485 }
1486
1487 // If we fail, and have a sourceMaxPages, try to reserve the biggest
1488 // chunk in the range [initialPages, clampedMaxPages) using log backoff.
1489 if (!sourceMaxPages) {
1490 wasm::Log(cx, "new Memory({initial=%" PRIu64 " pages}) failed",
1491 initialPages.value());
1492 ReportOutOfMemory(cx);
1493 return nullptr;
1494 }
1495
1496 uint64_t cur = clampedMaxPages.value() / 2;
1497 for (; Pages(cur) > initialPages; cur /= 2) {
1498 buffer = RawbufT::AllocateWasm(memory.limits.addressType, initialPages,
1499 Pages(cur), sourceMaxPages, mappedSize);
1500 if (buffer) {
1501 break;
1502 }
1503 }
1504
1505 if (!buffer) {
1506 wasm::Log(cx, "new Memory({initial=%" PRIu64 " pages}) failed",
1507 initialPages.value());
1508 ReportOutOfMemory(cx);
1509 return nullptr;
1510 }
1511 }
1512
1513 // ObjT::createFromNewRawBuffer assumes ownership of |buffer| even in case
1514 // of failure.
1515 Rooted<ArrayBufferObjectMaybeShared*> object(
1516 cx, ObjT::createFromNewRawBuffer(cx, buffer, initialPages.byteLength()));
1517 if (!object) {
1518 return nullptr;
1519 }
1520
1521 // See MaximumLiveMappedBuffers comment above.
1522 if (wasmReservedBytes > WasmReservedBytesStartSyncFullGC) {
1523 JS::PrepareForFullGC(cx);
1524 JS::NonIncrementalGC(cx, JS::GCOptions::Normal,
1525 JS::GCReason::TOO_MUCH_WASM_MEMORY);
1526 wasmReservedBytesSinceLast = 0;
1527 } else if (wasmReservedBytes > WasmReservedBytesStartTriggering) {
1528 wasmReservedBytesSinceLast += uint64_t(buffer->mappedSize());
1529 if (wasmReservedBytesSinceLast > WasmReservedBytesPerTrigger) {
1530 (void)cx->runtime()->gc.triggerGC(JS::GCReason::TOO_MUCH_WASM_MEMORY);
1531 wasmReservedBytesSinceLast = 0;
1532 }
1533 } else {
1534 wasmReservedBytesSinceLast = 0;
1535 }
1536
1537 // Log the result with details on the memory allocation
1538 if (sourceMaxPages) {
1539 if (useHugeMemory) {
1540 wasm::Log(cx,
1541 "new Memory({initial:%" PRIu64 " pages, maximum:%" PRIu64
1542 " pages}) succeeded",
1543 initialPages.value(), sourceMaxPages->value());
1544 } else {
1545 wasm::Log(cx,
1546 "new Memory({initial:%" PRIu64 " pages, maximum:%" PRIu64
1547 " pages}) succeeded "
1548 "with internal maximum of %" PRIu64 " pages",
1549 initialPages.value(), sourceMaxPages->value(),
1550 object->wasmClampedMaxPages().value());
1551 }
1552 } else {
1553 wasm::Log(cx, "new Memory({initial:%" PRIu64 " pages}) succeeded",
1554 initialPages.value());
1555 }
1556
1557 return object;
1558 }
1559
1560 ArrayBufferObjectMaybeShared* js::CreateWasmBuffer(
1561 JSContext* cx, const wasm::MemoryDesc& memory) {
1562 MOZ_RELEASE_ASSERT(memory.initialPages() <=
1563 wasm::MaxMemoryPages(memory.addressType()));
1564 MOZ_RELEASE_ASSERT(cx->wasm().haveSignalHandlers);
1565
1566 if (memory.isShared()) {
1567 if (!cx->realm()->creationOptions().getSharedMemoryAndAtomicsEnabled()) {
1568 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1569 JSMSG_WASM_NO_SHMEM_LINK);
1570 return nullptr;
1571 }
1572 return CreateSpecificWasmBuffer<SharedArrayBufferObject,
1573 WasmSharedArrayRawBuffer>(cx, memory);
1574 }
1575 return CreateSpecificWasmBuffer<ArrayBufferObject, WasmArrayRawBuffer>(
1576 cx, memory);
1577 }
1578
1579 bool ArrayBufferObject::prepareForAsmJS() {
1580 MOZ_ASSERT(byteLength() % wasm::PageSize == 0,
1581 "prior size checking should have guaranteed page-size multiple");
1582 MOZ_ASSERT(byteLength() > 0,
1583 "prior size checking should have excluded empty buffers");
1584 MOZ_ASSERT(!isResizable(),
1585 "prior checks should have excluded resizable buffers");
1586
1587 switch (bufferKind()) {
1588 case MALLOCED_ARRAYBUFFER_CONTENTS_ARENA:
1589 case MALLOCED_UNKNOWN_ARENA:
1590 case MAPPED:
1591 case EXTERNAL:
1592 // It's okay if this uselessly sets the flag a second time.
1593 setIsPreparedForAsmJS();
1594 return true;
1595
1596 case INLINE_DATA:
1597 static_assert(
1598 wasm::PageSize > FixedLengthArrayBufferObject::MaxInlineBytes,
1599 "inline data must be too small to be a page size multiple");
1600 MOZ_ASSERT_UNREACHABLE(
1601 "inline-data buffers should be implicitly excluded by size checks");
1602 return false;
1603
1604 case NO_DATA:
1605 MOZ_ASSERT_UNREACHABLE(
1606 "size checking should have excluded detached or empty buffers");
1607 return false;
1608
1609 // asm.js code and associated buffers are potentially long-lived. Yet a
1610 // buffer of user-owned data *must* be detached by the user before the
1611 // user-owned data is disposed. No caller wants to use a user-owned
1612 // ArrayBuffer with asm.js, so just don't support this and avoid a mess of
1613 // complexity.
1614 case USER_OWNED:
1615 // wasm buffers can be detached at any time.
1616 case WASM:
1617 MOZ_ASSERT(!isPreparedForAsmJS());
1618 return false;
1619 }
1620
1621 MOZ_ASSERT_UNREACHABLE("non-exhaustive kind-handling switch?");
1622 return false;
1623 }
1624
1625 ArrayBufferObject::BufferContents ArrayBufferObject::createMappedContents(
1626 int fd, size_t offset, size_t length) {
1627 void* data =
1628 gc::AllocateMappedContent(fd, offset, length, ARRAY_BUFFER_ALIGNMENT);
1629 return BufferContents::createMapped(data);
1630 }
1631
1632 uint8_t* FixedLengthArrayBufferObject::inlineDataPointer() const {
1633 return static_cast<uint8_t*>(fixedData(JSCLASS_RESERVED_SLOTS(&class_)));
1634 }
1635
1636 uint8_t* ResizableArrayBufferObject::inlineDataPointer() const {
1637 return static_cast<uint8_t*>(fixedData(JSCLASS_RESERVED_SLOTS(&class_)));
1638 }
1639
1640 uint8_t* ArrayBufferObject::dataPointer() const {
1641 return static_cast<uint8_t*>(getFixedSlot(DATA_SLOT).toPrivate());
1642 }
1643
1644 SharedMem<uint8_t*> ArrayBufferObject::dataPointerShared() const {
1645 return SharedMem<uint8_t*>::unshared(getFixedSlot(DATA_SLOT).toPrivate());
1646 }
1647
1648 ArrayBufferObject::FreeInfo* ArrayBufferObject::freeInfo() const {
1649 MOZ_ASSERT(isExternal());
1650 MOZ_ASSERT(!isResizable());
1651 auto* data = as<FixedLengthArrayBufferObject>().inlineDataPointer();
1652 return reinterpret_cast<FreeInfo*>(data);
1653 }
1654
1655 void ArrayBufferObject::releaseData(JS::GCContext* gcx) {
1656 switch (bufferKind()) {
1657 case INLINE_DATA:
1658 // Inline data doesn't require releasing.
1659 break;
1660 case MALLOCED_ARRAYBUFFER_CONTENTS_ARENA:
1661 case MALLOCED_UNKNOWN_ARENA:
1662 gcx->free_(this, dataPointer(), associatedBytes(),
1663 MemoryUse::ArrayBufferContents);
1664 break;
1665 case NO_DATA:
1666 // There's nothing to release if there's no data.
1667 MOZ_ASSERT(dataPointer() == nullptr);
1668 break;
1669 case USER_OWNED:
1670 // User-owned data is released by, well, the user.
1671 break;
1672 case MAPPED:
1673 gc::DeallocateMappedContent(dataPointer(), byteLength());
1674 gcx->removeCellMemory(this, associatedBytes(),
1675 MemoryUse::ArrayBufferContents);
1676 break;
1677 case WASM:
1678 WasmArrayRawBuffer::Release(dataPointer());
1679 gcx->removeCellMemory(this, byteLength(), MemoryUse::ArrayBufferContents);
1680 break;
1681 case EXTERNAL:
1682 MOZ_ASSERT(freeInfo()->freeFunc);
1683 {
1684 // The analyzer can't know for sure whether the embedder-supplied
1685 // free function will GC. We give the analyzer a hint here.
1686 // (Doing a GC in the free function is considered a programmer
1687 // error.)
1688 JS::AutoSuppressGCAnalysis nogc;
1689 freeInfo()->freeFunc(dataPointer(), freeInfo()->freeUserData);
1690 }
1691 break;
1692 }
1693 }
1694
1695 void ArrayBufferObject::setDataPointer(BufferContents contents) {
1696 setFixedSlot(DATA_SLOT, PrivateValue(contents.data()));
1697 setFlags((flags() & ~KIND_MASK) | contents.kind());
1698
1699 if (isExternal()) {
1700 auto info = freeInfo();
1701 info->freeFunc = contents.freeFunc();
1702 info->freeUserData = contents.freeUserData();
1703 }
1704 }
1705
1706 size_t ArrayBufferObject::byteLength() const {
1707 return size_t(getFixedSlot(BYTE_LENGTH_SLOT).toPrivate());
1708 }
1709
1710 inline size_t ArrayBufferObject::associatedBytes() const {
1711 if (isMalloced()) {
1712 return maxByteLength();
1713 }
1714 if (isMapped()) {
1715 return RoundUp(byteLength(), js::gc::SystemPageSize());
1716 }
1717 MOZ_CRASH("Unexpected buffer kind");
1718 }
1719
1720 void ArrayBufferObject::setByteLength(size_t length) {
1721 MOZ_ASSERT(length <= ArrayBufferObject::ByteLengthLimit);
1722 setFixedSlot(BYTE_LENGTH_SLOT, PrivateValue(length));
1723 }
1724
1725 size_t ArrayBufferObject::wasmMappedSize() const {
1726 if (isWasm()) {
1727 return contents().wasmBuffer()->mappedSize();
1728 }
1729 return byteLength();
1730 }
1731
1732 AddressType ArrayBufferObject::wasmAddressType() const {
1733 if (isWasm()) {
1734 return contents().wasmBuffer()->addressType();
1735 }
1736 MOZ_ASSERT(isPreparedForAsmJS());
1737 return wasm::AddressType::I32;
1738 }
1739
1740 Pages ArrayBufferObject::wasmPages() const {
1741 if (isWasm()) {
1742 return contents().wasmBuffer()->pages();
1743 }
1744 MOZ_ASSERT(isPreparedForAsmJS());
1745 return Pages::fromByteLengthExact(byteLength());
1746 }
1747
1748 Pages ArrayBufferObject::wasmClampedMaxPages() const {
1749 if (isWasm()) {
1750 return contents().wasmBuffer()->clampedMaxPages();
1751 }
1752 MOZ_ASSERT(isPreparedForAsmJS());
1753 return Pages::fromByteLengthExact(byteLength());
1754 }
1755
1756 Maybe<Pages> ArrayBufferObject::wasmSourceMaxPages() const {
1757 if (isWasm()) {
1758 return contents().wasmBuffer()->sourceMaxPages();
1759 }
1760 MOZ_ASSERT(isPreparedForAsmJS());
1761 return Some<Pages>(Pages::fromByteLengthExact(byteLength()));
1762 }
1763
1764 size_t js::WasmArrayBufferMappedSize(const ArrayBufferObjectMaybeShared* buf) {
1765 if (buf->is<ArrayBufferObject>()) {
1766 return buf->as<ArrayBufferObject>().wasmMappedSize();
1767 }
1768 return buf->as<SharedArrayBufferObject>().wasmMappedSize();
1769 }
1770
1771 AddressType js::WasmArrayBufferAddressType(
1772 const ArrayBufferObjectMaybeShared* buf) {
1773 if (buf->is<ArrayBufferObject>()) {
1774 return buf->as<ArrayBufferObject>().wasmAddressType();
1775 }
1776 return buf->as<SharedArrayBufferObject>().wasmAddressType();
1777 }
1778 Pages js::WasmArrayBufferPages(const ArrayBufferObjectMaybeShared* buf) {
1779 if (buf->is<ArrayBufferObject>()) {
1780 return buf->as<ArrayBufferObject>().wasmPages();
1781 }
1782 return buf->as<SharedArrayBufferObject>().volatileWasmPages();
1783 }
1784 Pages js::WasmArrayBufferClampedMaxPages(
1785 const ArrayBufferObjectMaybeShared* buf) {
1786 if (buf->is<ArrayBufferObject>()) {
1787 return buf->as<ArrayBufferObject>().wasmClampedMaxPages();
1788 }
1789 return buf->as<SharedArrayBufferObject>().wasmClampedMaxPages();
1790 }
1791 Maybe<Pages> js::WasmArrayBufferSourceMaxPages(
1792 const ArrayBufferObjectMaybeShared* buf) {
1793 if (buf->is<ArrayBufferObject>()) {
1794 return buf->as<ArrayBufferObject>().wasmSourceMaxPages();
1795 }
1796 return Some(buf->as<SharedArrayBufferObject>().wasmSourceMaxPages());
1797 }
1798
1799 static void CheckStealPreconditions(Handle<ArrayBufferObject*> buffer,
1800 JSContext* cx) {
1801 cx->check(buffer);
1802
1803 MOZ_ASSERT(!buffer->isDetached(), "can't steal from a detached buffer");
1804 MOZ_ASSERT(!buffer->isLengthPinned(),
1805 "can't steal from a buffer with a pinned length");
1806 MOZ_ASSERT(!buffer->isPreparedForAsmJS(),
1807 "asm.js-prepared buffers don't have detachable/stealable data");
1808 }
1809
1810 /* static */
1811 ArrayBufferObject* ArrayBufferObject::wasmGrowToPagesInPlace(
1812 wasm::AddressType t, Pages newPages, Handle<ArrayBufferObject*> oldBuf,
1813 JSContext* cx) {
1814 if (oldBuf->isLengthPinned()) {
1815 return nullptr;
1816 }
1817
1818 MOZ_ASSERT(oldBuf->isWasm());
1819
1820 // Check that the new pages is within our allowable range. This will
1821 // simultaneously check against the maximum specified in source and our
1822 // implementation limits.
1823 if (newPages > oldBuf->wasmClampedMaxPages()) {
1824 return nullptr;
1825 }
1826 MOZ_ASSERT(newPages <= wasm::MaxMemoryPages(t) &&
1827 newPages.byteLength() <= ArrayBufferObject::ByteLengthLimit);
1828
1829 if (oldBuf->is<ResizableArrayBufferObject>()) {
1830 RemoveCellMemory(oldBuf, oldBuf->byteLength(),
1831 MemoryUse::ArrayBufferContents);
1832
1833 if (!oldBuf->contents().wasmBuffer()->growToPagesInPlace(newPages)) {
1834 // If fails, the buffer still exists on oldBuf, keep tracking
1835 // cell memory there.
1836 AddCellMemory(oldBuf, oldBuf->byteLength(),
1837 MemoryUse::ArrayBufferContents);
1838 return nullptr;
1839 }
1840 oldBuf->setByteLength(newPages.byteLength());
1841 AddCellMemory(oldBuf, newPages.byteLength(),
1842 MemoryUse::ArrayBufferContents);
1843 return oldBuf;
1844 }
1845
1846 CheckStealPreconditions(oldBuf, cx);
1847
1848 // We have checked against the clamped maximum and so we know we can convert
1849 // to byte lengths now.
1850 size_t newSize = newPages.byteLength();
1851
1852 // On failure, do not throw and ensure that the original buffer is
1853 // unmodified and valid. After WasmArrayRawBuffer::growToPagesInPlace(), the
1854 // wasm-visible length of the buffer has been increased so it must be the
1855 // last fallible operation.
1856
1857 auto* newBuf = ArrayBufferObject::createEmpty(cx);
1858 if (!newBuf) {
1859 cx->clearPendingException();
1860 return nullptr;
1861 }
1862
1863 MOZ_ASSERT(newBuf->isNoData());
1864
1865 if (!oldBuf->contents().wasmBuffer()->growToPagesInPlace(newPages)) {
1866 return nullptr;
1867 }
1868
1869 // Extract the grown contents from |oldBuf|.
1870 BufferContents oldContents = oldBuf->contents();
1871
1872 // Overwrite |oldBuf|'s data pointer *without* releasing old data.
1873 oldBuf->setDataPointer(BufferContents::createNoData());
1874
1875 // Detach |oldBuf| now that doing so won't release |oldContents|.
1876 RemoveCellMemory(oldBuf, oldBuf->byteLength(),
1877 MemoryUse::ArrayBufferContents);
1878 ArrayBufferObject::detach(cx, oldBuf);
1879
1880 // Set |newBuf|'s contents to |oldBuf|'s original contents.
1881 newBuf->initialize(newSize, oldContents);
1882 AddCellMemory(newBuf, newSize, MemoryUse::ArrayBufferContents);
1883
1884 return newBuf;
1885 }
1886
1887 /* static */
1888 ArrayBufferObject* ArrayBufferObject::wasmMovingGrowToPages(
1889 AddressType t, Pages newPages, Handle<ArrayBufferObject*> oldBuf,
1890 JSContext* cx) {
1891 MOZ_ASSERT(oldBuf->is<FixedLengthArrayBufferObject>());
1892
1893 // On failure, do not throw and ensure that the original buffer is
1894 // unmodified and valid.
1895 if (oldBuf->isLengthPinned()) {
1896 return nullptr;
1897 }
1898
1899 // Check that the new pages is within our allowable range. This will
1900 // simultaneously check against the maximum specified in source and our
1901 // implementation limits.
1902 if (newPages > oldBuf->wasmClampedMaxPages()) {
1903 return nullptr;
1904 }
1905 MOZ_ASSERT(newPages <= wasm::MaxMemoryPages(t) &&
1906 newPages.byteLength() <= ArrayBufferObject::ByteLengthLimit);
1907
1908 // We have checked against the clamped maximum and so we know we can convert
1909 // to byte lengths now.
1910 size_t newSize = newPages.byteLength();
1911
1912 // TODO: If the memory reservation allows, or if we can extend the mapping in
1913 // place, fall back to wasmGrowToPagesInPlace to avoid a new allocation +
1914 // copy.
1915
1916 Rooted<ArrayBufferObject*> newBuf(cx, ArrayBufferObject::createEmpty(cx));
1917 if (!newBuf) {
1918 cx->clearPendingException();
1919 return nullptr;
1920 }
1921
1922 Pages clampedMaxPages =
1923 wasm::ClampedMaxPages(t, newPages, Nothing(), /* hugeMemory */ false);
1924 WasmArrayRawBuffer* newRawBuf =
1925 WasmArrayRawBuffer::AllocateWasm(oldBuf->wasmAddressType(), newPages,
1926 clampedMaxPages, Nothing(), Nothing());
1927 if (!newRawBuf) {
1928 return nullptr;
1929 }
1930
1931 AddCellMemory(newBuf, newSize, MemoryUse::ArrayBufferContents);
1932
1933 BufferContents contents =
1934 BufferContents::createWasm(newRawBuf->dataPointer());
1935 newBuf->initialize(newSize, contents);
1936
1937 memcpy(newBuf->dataPointer(), oldBuf->dataPointer(), oldBuf->byteLength());
1938 ArrayBufferObject::detach(cx, oldBuf);
1939
1940 return newBuf;
1941 }
1942
1943 /* static */
1944 void ArrayBufferObject::wasmDiscard(Handle<ArrayBufferObject*> buf,
1945 uint64_t byteOffset, uint64_t byteLen) {
1946 MOZ_ASSERT(buf->isWasm());
1947 buf->contents().wasmBuffer()->discard(byteOffset, byteLen);
1948 }
1949
1950 uint32_t ArrayBufferObject::flags() const {
1951 return uint32_t(getFixedSlot(FLAGS_SLOT).toInt32());
1952 }
1953
1954 void ArrayBufferObject::setFlags(uint32_t flags) {
1955 setFixedSlot(FLAGS_SLOT, Int32Value(flags));
1956 }
1957
1958 static constexpr js::gc::AllocKind GetArrayBufferGCObjectKind(size_t numSlots) {
1959 if (numSlots <= 4) {
1960 return js::gc::AllocKind::ARRAYBUFFER4;
1961 }
1962 if (numSlots <= 8) {
1963 return js::gc::AllocKind::ARRAYBUFFER8;
1964 }
1965 if (numSlots <= 12) {
1966 return js::gc::AllocKind::ARRAYBUFFER12;
1967 }
1968 return js::gc::AllocKind::ARRAYBUFFER16;
1969 }
1970
1971 template <class ArrayBufferType>
1972 static ArrayBufferType* NewArrayBufferObject(JSContext* cx, HandleObject proto_,
1973 gc::AllocKind allocKind) {
1974 MOZ_ASSERT(allocKind == gc::AllocKind::ARRAYBUFFER4 ||
1975 allocKind == gc::AllocKind::ARRAYBUFFER8 ||
1976 allocKind == gc::AllocKind::ARRAYBUFFER12 ||
1977 allocKind == gc::AllocKind::ARRAYBUFFER16);
1978
1979 static_assert(std::is_same_v<ArrayBufferType, FixedLengthArrayBufferObject> ||
1980 std::is_same_v<ArrayBufferType, ResizableArrayBufferObject>);
1981
1982 RootedObject proto(cx, proto_);
1983 if (!proto) {
1984 proto = GlobalObject::getOrCreatePrototype(cx, JSProto_ArrayBuffer);
1985 if (!proto) {
1986 MOZ_DIAGNOSTIC_ASSERT(!cx->brittleMode, "creating ArrayBuffer proto");
1987 return nullptr;
1988 }
1989 }
1990
1991 const JSClass* clasp = &ArrayBufferType::class_;
1992
1993 // Array buffers can store data inline so we only use fixed slots to cover the
1994 // reserved slots, ignoring the AllocKind.
1995 MOZ_ASSERT(ClassCanHaveFixedData(clasp));
1996 constexpr size_t nfixed = ArrayBufferType::RESERVED_SLOTS;
1997 static_assert(nfixed <= NativeObject::MAX_FIXED_SLOTS);
1998
1999 Rooted<SharedShape*> shape(
2000 cx,
2001 SharedShape::getInitialShape(cx, clasp, cx->realm(), AsTaggedProto(proto),
2002 nfixed, ObjectFlags()));
2003 if (!shape) {
2004 MOZ_DIAGNOSTIC_ASSERT(!cx->brittleMode, "get ArrayBuffer initial shape");
2005 return nullptr;
2006 }
2007
2008 // Array buffers can't be nursery allocated but can be background-finalized.
2009 MOZ_ASSERT(IsBackgroundFinalized(allocKind));
2010 MOZ_ASSERT(!CanNurseryAllocateFinalizedClass(clasp));
2011 constexpr gc::Heap heap = gc::Heap::Tenured;
2012
2013 auto* buffer =
2014 NativeObject::create<ArrayBufferType>(cx, allocKind, heap, shape);
2015 if (!buffer) {
2016 MOZ_DIAGNOSTIC_ASSERT(!cx->brittleMode, "create NativeObject failed");
2017 }
2018 return buffer;
2019 }
2020
2021 // Creates a new ArrayBufferObject with %ArrayBuffer.prototype% as proto and no
2022 // space for inline data.
2023 static ArrayBufferObject* NewArrayBufferObject(JSContext* cx) {
2024 constexpr auto allocKind =
2025 GetArrayBufferGCObjectKind(FixedLengthArrayBufferObject::RESERVED_SLOTS);
2026 return NewArrayBufferObject<FixedLengthArrayBufferObject>(cx, nullptr,
2027 allocKind);
2028 }
2029 static ResizableArrayBufferObject* NewResizableArrayBufferObject(
2030 JSContext* cx) {
2031 constexpr auto allocKind =
2032 GetArrayBufferGCObjectKind(ResizableArrayBufferObject::RESERVED_SLOTS);
2033 return NewArrayBufferObject<ResizableArrayBufferObject>(cx, nullptr,
2034 allocKind);
2035 }
2036
2037 ArrayBufferObject* ArrayBufferObject::createForContents(
2038 JSContext* cx, size_t nbytes, BufferContents contents) {
2039 MOZ_ASSERT(contents);
2040 MOZ_ASSERT(contents.kind() != INLINE_DATA);
2041 MOZ_ASSERT(contents.kind() != NO_DATA);
2042 MOZ_ASSERT(contents.kind() != WASM);
2043
2044 // 24.1.1.1, step 3 (Inlined 6.2.6.1 CreateByteDataBlock, step 2).
2045 if (!CheckArrayBufferTooLarge(cx, nbytes)) {
2046 return nullptr;
2047 }
2048
2049 // Some |contents| kinds need to store extra data in the ArrayBuffer beyond a
2050 // data pointer. If needed for the particular kind, add extra fixed slots to
2051 // the ArrayBuffer for use as raw storage to store such information.
2052 constexpr size_t reservedSlots = FixedLengthArrayBufferObject::RESERVED_SLOTS;
2053
2054 size_t nAllocated = 0;
2055 size_t nslots = reservedSlots;
2056 if (contents.kind() == USER_OWNED) {
2057 // No accounting to do in this case.
2058 } else if (contents.kind() == EXTERNAL) {
2059 // Store the FreeInfo in the inline data slots so that we
2060 // don't use up slots for it in non-refcounted array buffers.
2061 constexpr size_t freeInfoSlots = HowMany(sizeof(FreeInfo), sizeof(Value));
2062 static_assert(
2063 reservedSlots + freeInfoSlots <= NativeObject::MAX_FIXED_SLOTS,
2064 "FreeInfo must fit in inline slots");
2065 nslots += freeInfoSlots;
2066 } else {
2067 // The ABO is taking ownership, so account the bytes against the zone.
2068 nAllocated = nbytes;
2069 if (contents.kind() == MAPPED) {
2070 nAllocated = RoundUp(nbytes, js::gc::SystemPageSize());
2071 } else {
2072 MOZ_ASSERT(contents.kind() == MALLOCED_ARRAYBUFFER_CONTENTS_ARENA ||
2073 contents.kind() == MALLOCED_UNKNOWN_ARENA,
2074 "should have handled all possible callers' kinds");
2075 }
2076 }
2077
2078 gc::AllocKind allocKind = GetArrayBufferGCObjectKind(nslots);
2079
2080 AutoSetNewObjectMetadata metadata(cx);
2081 Rooted<ArrayBufferObject*> buffer(
2082 cx, NewArrayBufferObject<FixedLengthArrayBufferObject>(cx, nullptr,
2083 allocKind));
2084 if (!buffer) {
2085 return nullptr;
2086 }
2087
2088 MOZ_ASSERT(!gc::IsInsideNursery(buffer),
2089 "ArrayBufferObject has a finalizer that must be called to not "
2090 "leak in some cases, so it can't be nursery-allocated");
2091
2092 buffer->initialize(nbytes, contents);
2093
2094 if (contents.kind() == MAPPED ||
2095 contents.kind() == MALLOCED_ARRAYBUFFER_CONTENTS_ARENA ||
2096 contents.kind() == MALLOCED_UNKNOWN_ARENA) {
2097 AddCellMemory(buffer, nAllocated, MemoryUse::ArrayBufferContents);
2098 }
2099
2100 return buffer;
2101 }
2102
2103 template <class ArrayBufferType, ArrayBufferObject::FillContents FillType>
2104 /* static */ std::tuple<ArrayBufferType*, uint8_t*>
2105 ArrayBufferObject::createUninitializedBufferAndData(
2106 JSContext* cx, size_t nbytes, AutoSetNewObjectMetadata&,
2107 JS::Handle<JSObject*> proto) {
2108 MOZ_ASSERT(nbytes <= ArrayBufferObject::ByteLengthLimit,
2109 "caller must validate the byte count it passes");
2110
2111 static_assert(std::is_same_v<ArrayBufferType, FixedLengthArrayBufferObject> ||
2112 std::is_same_v<ArrayBufferType, ResizableArrayBufferObject>);
2113
2114 // Try fitting the data inline with the object by repurposing fixed-slot
2115 // storage. Add extra fixed slots if necessary to accomplish this, but don't
2116 // exceed the maximum number of fixed slots!
2117 size_t nslots = ArrayBufferType::RESERVED_SLOTS;
2118 ArrayBufferContents data;
2119 if (nbytes <= ArrayBufferType::MaxInlineBytes) {
2120 int newSlots = HowMany(nbytes, sizeof(Value));
2121 MOZ_ASSERT(int(nbytes) <= newSlots * int(sizeof(Value)));
2122
2123 nslots += newSlots;
2124 } else {
2125 data = FillType == FillContents::Uninitialized
2126 ? AllocateUninitializedArrayBufferContents(cx, nbytes)
2127 : AllocateArrayBufferContents(cx, nbytes);
2128 if (!data) {
2129 if (cx->brittleMode) {
2130 if (nbytes < INT32_MAX) {
2131 MOZ_DIAGNOSTIC_CRASH("ArrayBuffer allocation OOM < 2GB - 1");
2132 } else {
2133 MOZ_DIAGNOSTIC_ASSERT(
2134 false,
2135 "ArrayBuffer allocation OOM between 2GB and ByteLengthLimit");
2136 }
2137 }
2138 return {nullptr, nullptr};
2139 }
2140 }
2141
2142 gc::AllocKind allocKind = GetArrayBufferGCObjectKind(nslots);
2143
2144 auto* buffer = NewArrayBufferObject<ArrayBufferType>(cx, proto, allocKind);
2145 if (!buffer) {
2146 return {nullptr, nullptr};
2147 }
2148
2149 MOZ_ASSERT(!gc::IsInsideNursery(buffer),
2150 "ArrayBufferObject has a finalizer that must be called to not "
2151 "leak in some cases, so it can't be nursery-allocated");
2152
2153 if (data) {
2154 return {buffer, data.release()};
2155 }
2156
2157 if constexpr (FillType == FillContents::Zero) {
2158 memset(buffer->inlineDataPointer(), 0, nbytes);
2159 }
2160 return {buffer, nullptr};
2161 }
2162
2163 template <ArrayBufferObject::FillContents FillType>
2164 /* static */ std::tuple<ArrayBufferObject*, uint8_t*>
2165 ArrayBufferObject::createBufferAndData(
2166 JSContext* cx, size_t nbytes, AutoSetNewObjectMetadata& metadata,
2167 JS::Handle<JSObject*> proto /* = nullptr */) {
2168 MOZ_ASSERT(nbytes <= ArrayBufferObject::ByteLengthLimit,
2169 "caller must validate the byte count it passes");
2170
2171 auto [buffer, data] =
2172 createUninitializedBufferAndData<FixedLengthArrayBufferObject, FillType>(
2173 cx, nbytes, metadata, proto);
2174 if (!buffer) {
2175 return {nullptr, nullptr};
2176 }
2177
2178 if (data) {
2179 buffer->initialize(
2180 nbytes, BufferContents::createMallocedArrayBufferContentsArena(data));
2181 AddCellMemory(buffer, nbytes, MemoryUse::ArrayBufferContents);
2182 } else {
2183 data = buffer->inlineDataPointer();
2184 buffer->initialize(nbytes, BufferContents::createInlineData(data));
2185 }
2186 return {buffer, data};
2187 }
2188
2189 template <ArrayBufferObject::FillContents FillType>
2190 /* static */ std::tuple<ResizableArrayBufferObject*, uint8_t*>
2191 ResizableArrayBufferObject::createBufferAndData(
2192 JSContext* cx, size_t byteLength, size_t maxByteLength,
2193 AutoSetNewObjectMetadata& metadata, Handle<JSObject*> proto) {
2194 MOZ_ASSERT(byteLength <= maxByteLength);
2195 MOZ_ASSERT(maxByteLength <= ArrayBufferObject::ByteLengthLimit,
2196 "caller must validate the byte count it passes");
2197
2198 // NOTE: The spec proposal for resizable ArrayBuffers suggests to use a
2199 // virtual memory based approach to avoid eagerly allocating the maximum byte
2200 // length. We don't yet support this and instead are allocating the maximum
2201 // byte length direct from the start.
2202 size_t nbytes = maxByteLength;
2203
2204 auto [buffer, data] =
2205 createUninitializedBufferAndData<ResizableArrayBufferObject, FillType>(
2206 cx, nbytes, metadata, proto);
2207 if (!buffer) {
2208 return {nullptr, nullptr};
2209 }
2210
2211 if (data) {
2212 buffer->initialize(
2213 byteLength, maxByteLength,
2214 BufferContents::createMallocedArrayBufferContentsArena(data));
2215 AddCellMemory(buffer, nbytes, MemoryUse::ArrayBufferContents);
2216 } else {
2217 data = buffer->inlineDataPointer();
2218 buffer->initialize(byteLength, maxByteLength,
2219 BufferContents::createInlineData(data));
2220 }
2221 return {buffer, data};
2222 }
2223
2224 /* static */ ArrayBufferObject* ArrayBufferObject::copy(
2225 JSContext* cx, size_t newByteLength,
2226 JS::Handle<ArrayBufferObject*> source) {
2227 MOZ_ASSERT(!source->isDetached());
2228 MOZ_ASSERT(newByteLength <= ArrayBufferObject::ByteLengthLimit,
2229 "caller must validate the byte count it passes");
2230
2231 size_t sourceByteLength = source->byteLength();
2232
2233 if (newByteLength > sourceByteLength) {
2234 // Copy into a larger buffer.
2235 AutoSetNewObjectMetadata metadata(cx);
2236 auto [buffer, toFill] = createBufferAndData<FillContents::Zero>(
2237 cx, newByteLength, metadata, nullptr);
2238 if (!buffer) {
2239 return nullptr;
2240 }
2241
2242 std::copy_n(source->dataPointer(), sourceByteLength, toFill);
2243
2244 return buffer;
2245 }
2246
2247 // Copy into a smaller or same size buffer.
2248 AutoSetNewObjectMetadata metadata(cx);
2249 auto [buffer, toFill] = createBufferAndData<FillContents::Uninitialized>(
2250 cx, newByteLength, metadata, nullptr);
2251 if (!buffer) {
2252 return nullptr;
2253 }
2254
2255 std::uninitialized_copy_n(source->dataPointer(), newByteLength, toFill);
2256
2257 return buffer;
2258 }
2259
2260 /* static */ ResizableArrayBufferObject* ResizableArrayBufferObject::copy(
2261 JSContext* cx, size_t newByteLength,
2262 JS::Handle<ResizableArrayBufferObject*> source) {
2263 MOZ_ASSERT(!source->isDetached());
2264 MOZ_ASSERT(newByteLength <= source->maxByteLength());
2265
2266 size_t sourceByteLength = source->byteLength();
2267 size_t newMaxByteLength = source->maxByteLength();
2268
2269 AutoSetNewObjectMetadata metadata(cx);
2270 auto [buffer, toFill] = createBufferAndData<FillContents::Zero>(
2271 cx, newByteLength, newMaxByteLength, metadata, nullptr);
2272 if (!buffer) {
2273 return nullptr;
2274 }
2275
2276 size_t nbytes = std::min(newByteLength, sourceByteLength);
2277 std::copy_n(source->dataPointer(), nbytes, toFill);
2278
2279 return buffer;
2280 }
2281
2282 /* static */ ArrayBufferObject* ArrayBufferObject::copyAndDetach(
2283 JSContext* cx, size_t newByteLength,
2284 JS::Handle<ArrayBufferObject*> source) {
2285 MOZ_ASSERT(!source->isDetached());
2286 MOZ_ASSERT(!source->isLengthPinned());
2287 MOZ_ASSERT(newByteLength <= ArrayBufferObject::ByteLengthLimit,
2288 "caller must validate the byte count it passes");
2289
2290 if (newByteLength > FixedLengthArrayBufferObject::MaxInlineBytes &&
2291 source->isMalloced()) {
2292 if (newByteLength == source->associatedBytes()) {
2293 return copyAndDetachSteal(cx, source);
2294 }
2295 if (source->bufferKind() ==
2296 ArrayBufferObject::MALLOCED_ARRAYBUFFER_CONTENTS_ARENA) {
2297 return copyAndDetachRealloc(cx, newByteLength, source);
2298 }
2299 }
2300
2301 auto* newBuffer = ArrayBufferObject::copy(cx, newByteLength, source);
2302 if (!newBuffer) {
2303 return nullptr;
2304 }
2305 ArrayBufferObject::detach(cx, source);
2306
2307 return newBuffer;
2308 }
2309
2310 /* static */ ArrayBufferObject* ArrayBufferObject::copyAndDetachSteal(
2311 JSContext* cx, JS::Handle<ArrayBufferObject*> source) {
2312 MOZ_ASSERT(!source->isDetached());
2313 MOZ_ASSERT(!source->isLengthPinned());
2314 MOZ_ASSERT(source->isMalloced());
2315
2316 size_t newByteLength = source->associatedBytes();
2317 MOZ_ASSERT(newByteLength > FixedLengthArrayBufferObject::MaxInlineBytes,
2318 "prefer copying small buffers");
2319 MOZ_ASSERT(source->byteLength() <= newByteLength,
2320 "source length is less-or-equal to |newByteLength|");
2321
2322 auto* newBuffer = ArrayBufferObject::createEmpty(cx);
2323 if (!newBuffer) {
2324 return nullptr;
2325 }
2326
2327 // Extract the contents from |source|.
2328 BufferContents contents = source->contents();
2329 MOZ_ASSERT(contents);
2330 MOZ_ASSERT(contents.kind() == MALLOCED_ARRAYBUFFER_CONTENTS_ARENA ||
2331 contents.kind() == MALLOCED_UNKNOWN_ARENA);
2332
2333 // Overwrite |source|'s data pointer *without* releasing the data.
2334 source->setDataPointer(BufferContents::createNoData());
2335
2336 // Detach |source| now that doing so won't release |contents|.
2337 RemoveCellMemory(source, newByteLength, MemoryUse::ArrayBufferContents);
2338 ArrayBufferObject::detach(cx, source);
2339
2340 // Set |newBuffer|'s contents to |source|'s original contents.
2341 newBuffer->initialize(newByteLength, contents);
2342 AddCellMemory(newBuffer, newByteLength, MemoryUse::ArrayBufferContents);
2343
2344 return newBuffer;
2345 }
2346
2347 /* static */ ArrayBufferObject* ArrayBufferObject::copyAndDetachRealloc(
2348 JSContext* cx, size_t newByteLength,
2349 JS::Handle<ArrayBufferObject*> source) {
2350 MOZ_ASSERT(!source->isDetached());
2351 MOZ_ASSERT(!source->isLengthPinned());
2352 MOZ_ASSERT(source->bufferKind() == MALLOCED_ARRAYBUFFER_CONTENTS_ARENA);
2353 MOZ_ASSERT(newByteLength > FixedLengthArrayBufferObject::MaxInlineBytes,
2354 "prefer copying small buffers");
2355 MOZ_ASSERT(newByteLength <= ArrayBufferObject::ByteLengthLimit,
2356 "caller must validate the byte count it passes");
2357
2358 size_t oldByteLength = source->associatedBytes();
2359 MOZ_ASSERT(oldByteLength != newByteLength,
2360 "steal instead of realloc same size buffers");
2361 MOZ_ASSERT(source->byteLength() <= oldByteLength,
2362 "source length is less-or-equal to |oldByteLength|");
2363
2364 Rooted<ArrayBufferObject*> newBuffer(cx, ArrayBufferObject::createEmpty(cx));
2365 if (!newBuffer) {
2366 return nullptr;
2367 }
2368
2369 // Extract the contents from |source|.
2370 BufferContents contents = source->contents();
2371 MOZ_ASSERT(contents);
2372 MOZ_ASSERT(contents.kind() == MALLOCED_ARRAYBUFFER_CONTENTS_ARENA);
2373
2374 // Reallocate the data pointer.
2375 auto newData = ReallocateArrayBufferContents(cx, contents.data(),
2376 oldByteLength, newByteLength);
2377 if (!newData) {
2378 // If reallocation failed, the old pointer is still valid, so just return.
2379 return nullptr;
2380 }
2381 auto newContents =
2382 BufferContents::createMallocedArrayBufferContentsArena(newData.release());
2383
2384 // Overwrite |source|'s data pointer *without* releasing the data.
2385 source->setDataPointer(BufferContents::createNoData());
2386
2387 // Detach |source| now that doing so won't release |contents|.
2388 RemoveCellMemory(source, oldByteLength, MemoryUse::ArrayBufferContents);
2389 ArrayBufferObject::detach(cx, source);
2390
2391 // Set |newBuffer|'s contents to |newContents|.
2392 newBuffer->initialize(newByteLength, newContents);
2393 AddCellMemory(newBuffer, newByteLength, MemoryUse::ArrayBufferContents);
2394
2395 // Zero initialize the newly allocated memory, if necessary.
2396 if (newByteLength > oldByteLength) {
2397 size_t count = newByteLength - oldByteLength;
2398 std::uninitialized_fill_n(newContents.data() + oldByteLength, count, 0);
2399 }
2400
2401 return newBuffer;
2402 }
2403
2404 /* static */ ResizableArrayBufferObject*
2405 ResizableArrayBufferObject::copyAndDetach(
2406 JSContext* cx, size_t newByteLength,
2407 JS::Handle<ResizableArrayBufferObject*> source) {
2408 MOZ_ASSERT(!source->isDetached());
2409 MOZ_ASSERT(!source->isLengthPinned());
2410 MOZ_ASSERT(newByteLength <= source->maxByteLength());
2411
2412 if (source->maxByteLength() > ResizableArrayBufferObject::MaxInlineBytes &&
2413 source->isMalloced()) {
2414 return copyAndDetachSteal(cx, newByteLength, source);
2415 }
2416
2417 auto* newBuffer = ResizableArrayBufferObject::copy(cx, newByteLength, source);
2418 if (!newBuffer) {
2419 return nullptr;
2420 }
2421 ArrayBufferObject::detach(cx, source);
2422
2423 return newBuffer;
2424 }
2425
2426 /* static */ ResizableArrayBufferObject*
2427 ResizableArrayBufferObject::copyAndDetachSteal(
2428 JSContext* cx, size_t newByteLength,
2429 JS::Handle<ResizableArrayBufferObject*> source) {
2430 MOZ_ASSERT(!source->isDetached());
2431 MOZ_ASSERT(!source->isLengthPinned());
2432 MOZ_ASSERT(newByteLength <= source->maxByteLength());
2433 MOZ_ASSERT(source->isMalloced());
2434
2435 size_t sourceByteLength = source->byteLength();
2436 size_t maxByteLength = source->maxByteLength();
2437 MOZ_ASSERT(maxByteLength > ResizableArrayBufferObject::MaxInlineBytes,
2438 "prefer copying small buffers");
2439
2440 auto* newBuffer = ResizableArrayBufferObject::createEmpty(cx);
2441 if (!newBuffer) {
2442 return nullptr;
2443 }
2444
2445 // Extract the contents from |source|.
2446 BufferContents contents = source->contents();
2447 MOZ_ASSERT(contents);
2448 MOZ_ASSERT(contents.kind() == MALLOCED_ARRAYBUFFER_CONTENTS_ARENA ||
2449 contents.kind() == MALLOCED_UNKNOWN_ARENA);
2450
2451 // Overwrite |source|'s data pointer *without* releasing the data.
2452 source->setDataPointer(BufferContents::createNoData());
2453
2454 // Detach |source| now that doing so won't release |contents|.
2455 RemoveCellMemory(source, maxByteLength, MemoryUse::ArrayBufferContents);
2456 ArrayBufferObject::detach(cx, source);
2457
2458 // Set |newBuffer|'s contents to |source|'s original contents.
2459 newBuffer->initialize(newByteLength, maxByteLength, contents);
2460 AddCellMemory(newBuffer, maxByteLength, MemoryUse::ArrayBufferContents);
2461
2462 // Clear the bytes between `data[newByteLength..sourceByteLength]`.
2463 if (newByteLength < sourceByteLength) {
2464 size_t nbytes = sourceByteLength - newByteLength;
2465 memset(newBuffer->dataPointer() + newByteLength, 0, nbytes);
2466 }
2467
2468 return newBuffer;
2469 }
2470
2471 ArrayBufferObject* ArrayBufferObject::createZeroed(
2472 JSContext* cx, size_t nbytes, HandleObject proto /* = nullptr */) {
2473 // 24.1.1.1, step 3 (Inlined 6.2.6.1 CreateByteDataBlock, step 2).
2474 if (!CheckArrayBufferTooLarge(cx, nbytes)) {
2475 MOZ_DIAGNOSTIC_ASSERT(!cx->brittleMode, "buffer too large");
2476 return nullptr;
2477 }
2478
2479 AutoSetNewObjectMetadata metadata(cx);
2480 auto [buffer, toFill] =
2481 createBufferAndData<FillContents::Zero>(cx, nbytes, metadata, proto);
2482 (void)toFill;
2483 return buffer;
2484 }
2485
2486 ResizableArrayBufferObject* ResizableArrayBufferObject::createZeroed(
2487 JSContext* cx, size_t byteLength, size_t maxByteLength,
2488 HandleObject proto /* = nullptr */) {
2489 // 24.1.1.1, step 3 (Inlined 6.2.6.1 CreateByteDataBlock, step 2).
2490 if (!CheckArrayBufferTooLarge(cx, byteLength) ||
2491 !CheckArrayBufferTooLarge(cx, maxByteLength)) {
2492 return nullptr;
2493 }
2494 if (byteLength > maxByteLength) {
2495 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2496 JSMSG_ARRAYBUFFER_LENGTH_LARGER_THAN_MAXIMUM);
2497 return nullptr;
2498 }
2499
2500 AutoSetNewObjectMetadata metadata(cx);
2501 auto [buffer, toFill] = createBufferAndData<FillContents::Zero>(
2502 cx, byteLength, maxByteLength, metadata, proto);
2503 (void)toFill;
2504 return buffer;
2505 }
2506
2507 ArrayBufferObject* ArrayBufferObject::createEmpty(JSContext* cx) {
2508 AutoSetNewObjectMetadata metadata(cx);
2509 ArrayBufferObject* obj = NewArrayBufferObject(cx);
2510 if (!obj) {
2511 return nullptr;
2512 }
2513
2514 obj->initialize(0, BufferContents::createNoData());
2515 return obj;
2516 }
2517
2518 ResizableArrayBufferObject* ResizableArrayBufferObject::createEmpty(
2519 JSContext* cx) {
2520 AutoSetNewObjectMetadata metadata(cx);
2521 auto* obj = NewResizableArrayBufferObject(cx);
2522 if (!obj) {
2523 return nullptr;
2524 }
2525
2526 obj->initialize(0, 0, BufferContents::createNoData());
2527 return obj;
2528 }
2529
2530 ArrayBufferObject* ArrayBufferObject::createFromNewRawBuffer(
2531 JSContext* cx, WasmArrayRawBuffer* rawBuffer, size_t initialSize) {
2532 AutoSetNewObjectMetadata metadata(cx);
2533 ArrayBufferObject* buffer = NewArrayBufferObject(cx);
2534 if (!buffer) {
2535 WasmArrayRawBuffer::Release(rawBuffer->dataPointer());
2536 return nullptr;
2537 }
2538
2539 MOZ_ASSERT(initialSize == rawBuffer->byteLength());
2540
2541 auto contents = BufferContents::createWasm(rawBuffer->dataPointer());
2542 buffer->initialize(initialSize, contents);
2543
2544 AddCellMemory(buffer, initialSize, MemoryUse::ArrayBufferContents);
2545
2546 return buffer;
2547 }
2548
2549 template <typename ArrayBufferType>
2550 ArrayBufferType* ArrayBufferObject::createFromWasmObject(
2551 JSContext* cx, Handle<ArrayBufferObject*> donor) {
2552 AutoSetNewObjectMetadata metadata(cx);
2553 // Similar to NewResizableArrayBufferObject/NewArrayBufferObject
2554 constexpr auto allocKind =
2555 GetArrayBufferGCObjectKind(ArrayBufferType::RESERVED_SLOTS);
2556 ArrayBufferType* buffer =
2557 NewArrayBufferObject<ArrayBufferType>(cx, nullptr, allocKind);
2558 if (!buffer) {
2559 return nullptr;
2560 }
2561
2562 RemoveCellMemory(donor, donor->byteLength(), MemoryUse::ArrayBufferContents);
2563
2564 MOZ_RELEASE_ASSERT(donor->isWasm());
2565 // The only flag allowed to be set on the `donor` is the resizable flag.
2566 MOZ_RELEASE_ASSERT((donor->flags() & ~KIND_MASK & ~RESIZABLE) == 0);
2567 BufferContents contents(donor->dataPointer(), WASM);
2568 size_t byteLength = donor->byteLength();
2569 [[maybe_unused]] size_t maxByteLength = donor->wasmClampedMaxByteLength();
2570
2571 // Overwrite |oldBuf|'s data pointer *without* releasing old data.
2572 donor->setDataPointer(BufferContents::createNoData());
2573 ArrayBufferObject::detach(cx, donor);
2574
2575 if constexpr (std::is_same_v<ArrayBufferType, ResizableArrayBufferObject>) {
2576 buffer->initialize(byteLength, maxByteLength, contents);
2577 } else {
2578 static_assert(
2579 std::is_same_v<ArrayBufferType, FixedLengthArrayBufferObject>);
2580 buffer->initialize(byteLength, contents);
2581 }
2582
2583 AddCellMemory(buffer, buffer->byteLength(), MemoryUse::ArrayBufferContents);
2584 return buffer;
2585 }
2586
2587 template FixedLengthArrayBufferObject*
2588 ArrayBufferObject::createFromWasmObject<FixedLengthArrayBufferObject>(
2589 JSContext* cx, Handle<ArrayBufferObject*> donor);
2590
2591 template ResizableArrayBufferObject*
2592 ArrayBufferObject::createFromWasmObject<ResizableArrayBufferObject>(
2593 JSContext* cx, Handle<ArrayBufferObject*> donor);
2594
2595 /* static */ uint8_t* ArrayBufferObject::stealMallocedContents(
2596 JSContext* cx, Handle<ArrayBufferObject*> buffer) {
2597 CheckStealPreconditions(buffer, cx);
2598
2599 switch (buffer->bufferKind()) {
2600 case MALLOCED_ARRAYBUFFER_CONTENTS_ARENA:
2601 case MALLOCED_UNKNOWN_ARENA: {
2602 uint8_t* stolenData = buffer->dataPointer();
2603 MOZ_ASSERT(stolenData);
2604
2605 // Resizable buffers are initially allocated with their maximum
2606 // byte-length. When stealing the buffer contents shrink the allocated
2607 // memory to the actually used byte-length.
2608 if (buffer->isResizable()) {
2609 auto* resizableBuffer = &buffer->as<ResizableArrayBufferObject>();
2610 size_t byteLength = resizableBuffer->byteLength();
2611 size_t maxByteLength = resizableBuffer->maxByteLength();
2612 MOZ_ASSERT(byteLength <= maxByteLength);
2613
2614 if (byteLength < maxByteLength) {
2615 auto newData = ReallocateArrayBufferContents(
2616 cx, stolenData, maxByteLength, byteLength);
2617 if (!newData) {
2618 // If reallocation failed, the old pointer is still valid. The
2619 // ArrayBuffer isn't detached and still owns the malloc'ed memory.
2620 return nullptr;
2621 }
2622
2623 // The following code must be infallible, because the data pointer of
2624 // |buffer| is possibly no longer valid after the above realloc.
2625
2626 stolenData = newData.release();
2627 }
2628 }
2629
2630 RemoveCellMemory(buffer, buffer->associatedBytes(),
2631 MemoryUse::ArrayBufferContents);
2632
2633 // Overwrite the old data pointer *without* releasing the contents
2634 // being stolen.
2635 buffer->setDataPointer(BufferContents::createNoData());
2636
2637 // Detach |buffer| now that doing so won't free |stolenData|.
2638 ArrayBufferObject::detach(cx, buffer);
2639 return stolenData;
2640 }
2641
2642 case INLINE_DATA:
2643 case NO_DATA:
2644 case USER_OWNED:
2645 case MAPPED:
2646 case EXTERNAL: {
2647 // We can't use these data types directly. Make a copy to return.
2648 ArrayBufferContents copiedData = NewCopiedBufferContents(cx, buffer);
2649 if (!copiedData) {
2650 return nullptr;
2651 }
2652
2653 // Detach |buffer|. This immediately releases the currently owned
2654 // contents, freeing or unmapping data in the MAPPED and EXTERNAL cases.
2655 ArrayBufferObject::detach(cx, buffer);
2656 return copiedData.release();
2657 }
2658
2659 case WASM:
2660 MOZ_ASSERT_UNREACHABLE(
2661 "wasm buffers aren't stealable except by a "
2662 "memory.grow operation that shouldn't call this "
2663 "function");
2664 return nullptr;
2665 }
2666
2667 MOZ_ASSERT_UNREACHABLE("garbage kind computed");
2668 return nullptr;
2669 }
2670
2671 /* static */ ArrayBufferObject::BufferContents
2672 ArrayBufferObject::extractStructuredCloneContents(
2673 JSContext* cx, Handle<ArrayBufferObject*> buffer) {
2674 if (buffer->isLengthPinned()) {
2675 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2676 JSMSG_ARRAYBUFFER_LENGTH_PINNED);
2677 return BufferContents::createFailed();
2678 }
2679
2680 CheckStealPreconditions(buffer, cx);
2681
2682 // We don't yet support extracting the contents of resizable buffers.
2683 MOZ_ASSERT(!buffer->isResizable(),
2684 "extracting the contents of resizable buffers not supported");
2685
2686 BufferContents contents = buffer->contents();
2687
2688 switch (contents.kind()) {
2689 case INLINE_DATA:
2690 case NO_DATA:
2691 case USER_OWNED: {
2692 ArrayBufferContents copiedData = NewCopiedBufferContents(cx, buffer);
2693 if (!copiedData) {
2694 return BufferContents::createFailed();
2695 }
2696
2697 ArrayBufferObject::detach(cx, buffer);
2698 return BufferContents::createMallocedArrayBufferContentsArena(
2699 copiedData.release());
2700 }
2701
2702 case MALLOCED_ARRAYBUFFER_CONTENTS_ARENA:
2703 case MALLOCED_UNKNOWN_ARENA:
2704 case MAPPED: {
2705 MOZ_ASSERT(contents);
2706
2707 RemoveCellMemory(buffer, buffer->associatedBytes(),
2708 MemoryUse::ArrayBufferContents);
2709
2710 // Overwrite the old data pointer *without* releasing old data.
2711 buffer->setDataPointer(BufferContents::createNoData());
2712
2713 // Detach |buffer| now that doing so won't release |oldContents|.
2714 ArrayBufferObject::detach(cx, buffer);
2715 return contents;
2716 }
2717
2718 case WASM:
2719 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2720 JSMSG_WASM_NO_TRANSFER);
2721 return BufferContents::createFailed();
2722
2723 case EXTERNAL:
2724 MOZ_ASSERT_UNREACHABLE(
2725 "external ArrayBuffer shouldn't have passed the "
2726 "structured-clone preflighting");
2727 break;
2728 }
2729
2730 MOZ_ASSERT_UNREACHABLE("garbage kind computed");
2731 return BufferContents::createFailed();
2732 }
2733
2734 /* static */
2735 bool ArrayBufferObject::ensureNonInline(JSContext* cx,
2736 Handle<ArrayBufferObject*> buffer) {
2737 if (buffer->isDetached() || buffer->isPreparedForAsmJS()) {
2738 return true;
2739 }
2740
2741 if (buffer->isLengthPinned()) {
2742 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2743 JSMSG_ARRAYBUFFER_LENGTH_PINNED);
2744 MOZ_DIAGNOSTIC_ASSERT(!cx->brittleMode, "ArrayBuffer length pinned");
2745 return false;
2746 }
2747
2748 BufferContents inlineContents = buffer->contents();
2749 if (inlineContents.kind() != INLINE_DATA) {
2750 return true;
2751 }
2752
2753 size_t nbytes = buffer->maxByteLength();
2754 ArrayBufferContents copy = NewCopiedBufferContents(cx, buffer);
2755 if (!copy) {
2756 return false;
2757 }
2758 BufferContents outOfLineContents =
2759 BufferContents::createMallocedArrayBufferContentsArena(copy.release());
2760 buffer->setDataPointer(outOfLineContents);
2761 AddCellMemory(buffer, nbytes, MemoryUse::ArrayBufferContents);
2762
2763 if (!buffer->firstView()) {
2764 return true; // No views! Easy!
2765 }
2766
2767 buffer->firstView()->as<ArrayBufferViewObject>().notifyBufferMoved(
2768 inlineContents.data(), outOfLineContents.data());
2769
2770 auto& innerViews = ObjectRealm::get(buffer).innerViews.get();
2771 if (InnerViewTable::ViewVector* views =
2772 innerViews.maybeViewsUnbarriered(buffer)) {
2773 for (JSObject* view : *views) {
2774 view->as<ArrayBufferViewObject>().notifyBufferMoved(
2775 inlineContents.data(), outOfLineContents.data());
2776 }
2777 }
2778
2779 return true;
2780 }
2781
2782 /* static */
2783 void ArrayBufferObject::addSizeOfExcludingThis(
2784 JSObject* obj, mozilla::MallocSizeOf mallocSizeOf, JS::ClassInfo* info,
2785 JS::RuntimeSizes* runtimeSizes) {
2786 auto& buffer = obj->as<ArrayBufferObject>();
2787 switch (buffer.bufferKind()) {
2788 case INLINE_DATA:
2789 // Inline data's size should be reported by this object's size-class
2790 // reporting.
2791 break;
2792 case MALLOCED_ARRAYBUFFER_CONTENTS_ARENA:
2793 case MALLOCED_UNKNOWN_ARENA:
2794 if (buffer.isPreparedForAsmJS()) {
2795 info->objectsMallocHeapElementsAsmJS +=
2796 mallocSizeOf(buffer.dataPointer());
2797 } else {
2798 info->objectsMallocHeapElementsNormal +=
2799 mallocSizeOf(buffer.dataPointer());
2800 }
2801 break;
2802 case NO_DATA:
2803 // No data is no memory.
2804 MOZ_ASSERT(buffer.dataPointer() == nullptr);
2805 break;
2806 case USER_OWNED:
2807 // User-owned data should be accounted for by the user.
2808 break;
2809 case EXTERNAL:
2810 // External data will be accounted for by the owner of the buffer,
2811 // not this view.
2812 break;
2813 case MAPPED:
2814 info->objectsNonHeapElementsNormal += buffer.byteLength();
2815 break;
2816 case WASM:
2817 if (!buffer.isDetached()) {
2818 info->objectsNonHeapElementsWasm += buffer.byteLength();
2819 if (runtimeSizes) {
2820 MOZ_ASSERT(buffer.wasmMappedSize() >= buffer.byteLength());
2821 runtimeSizes->wasmGuardPages +=
2822 buffer.wasmMappedSize() - buffer.byteLength();
2823 }
2824 }
2825 break;
2826 }
2827 }
2828
2829 /* static */
2830 void ArrayBufferObject::finalize(JS::GCContext* gcx, JSObject* obj) {
2831 obj->as<ArrayBufferObject>().releaseData(gcx);
2832 }
2833
2834 /* static */
2835 void ArrayBufferObject::copyData(ArrayBufferObject* toBuffer, size_t toIndex,
2836 ArrayBufferObject* fromBuffer,
2837 size_t fromIndex, size_t count) {
2838 MOZ_ASSERT(!toBuffer->isDetached());
2839 MOZ_ASSERT(toBuffer->byteLength() >= count);
2840 MOZ_ASSERT(toBuffer->byteLength() >= toIndex + count);
2841 MOZ_ASSERT(!fromBuffer->isDetached());
2842 MOZ_ASSERT(fromBuffer->byteLength() >= fromIndex);
2843 MOZ_ASSERT(fromBuffer->byteLength() >= fromIndex + count);
2844
2845 memcpy(toBuffer->dataPointer() + toIndex,
2846 fromBuffer->dataPointer() + fromIndex, count);
2847 }
2848
2849 template <class ArrayBufferType>
2850 /* static */
2851 size_t ArrayBufferObject::objectMoved(JSObject* obj, JSObject* old) {
2852 auto& dst = obj->as<ArrayBufferType>();
2853 const auto& src = old->as<ArrayBufferType>();
2854
2855 #ifdef DEBUG
2856 // Check the data pointer is not inside the nursery, but take account of the
2857 // fact that inline data pointers for zero length buffers can point to the end
2858 // of a chunk which can abut the start of the nursery.
2859 if (src.byteLength() != 0 || (uintptr_t(src.dataPointer()) & gc::ChunkMask)) {
2860 Nursery& nursery = obj->runtimeFromMainThread()->gc.nursery();
2861 MOZ_ASSERT(!nursery.isInside(src.dataPointer()));
2862 }
2863 #endif
2864
2865 // Fix up possible inline data pointer.
2866 if (src.hasInlineData()) {
2867 dst.setFixedSlot(DATA_SLOT, PrivateValue(dst.inlineDataPointer()));
2868 }
2869
2870 return 0;
2871 }
2872
2873 JSObject* ArrayBufferObject::firstView() {
2874 return getFixedSlot(FIRST_VIEW_SLOT).isObject()
2875 ? &getFixedSlot(FIRST_VIEW_SLOT).toObject()
2876 : nullptr;
2877 }
2878
2879 void ArrayBufferObject::setFirstView(ArrayBufferViewObject* view) {
2880 setFixedSlot(FIRST_VIEW_SLOT, ObjectOrNullValue(view));
2881 }
2882
2883 bool ArrayBufferObject::addView(JSContext* cx, ArrayBufferViewObject* view) {
2884 if (!firstView()) {
2885 setFirstView(view);
2886 return true;
2887 }
2888
2889 return ObjectRealm::get(this).innerViews.get().addView(cx, this, view);
2890 }
2891
2892 #if defined(DEBUG) || defined(JS_JITSPEW)
2893
2894 template <typename KnownF, typename UnknownF>
2895 void BufferKindToString(ArrayBufferObject::BufferKind kind, KnownF known,
2896 UnknownF unknown) {
2897 switch (kind) {
2898 case ArrayBufferObject::BufferKind::INLINE_DATA:
2899 known("INLINE_DATA");
2900 break;
2901 case ArrayBufferObject::BufferKind::MALLOCED_ARRAYBUFFER_CONTENTS_ARENA:
2902 known("MALLOCED_ARRAYBUFFER_CONTENTS_ARENA");
2903 break;
2904 case ArrayBufferObject::BufferKind::NO_DATA:
2905 known("NO_DATA");
2906 break;
2907 case ArrayBufferObject::BufferKind::USER_OWNED:
2908 known("USER_OWNED");
2909 break;
2910 case ArrayBufferObject::BufferKind::WASM:
2911 known("WASM");
2912 break;
2913 case ArrayBufferObject::BufferKind::MAPPED:
2914 known("MAPPED");
2915 break;
2916 case ArrayBufferObject::BufferKind::EXTERNAL:
2917 known("EXTERNAL");
2918 break;
2919 case ArrayBufferObject::BufferKind::MALLOCED_UNKNOWN_ARENA:
2920 known("MALLOCED_UNKNOWN_ARENA");
2921 break;
2922 default:
2923 unknown(uint8_t(kind));
2924 break;
2925 }
2926 }
2927
2928 template <typename KnownF, typename UnknownF>
2929 void ForEachArrayBufferFlag(uint32_t flags, KnownF known, UnknownF unknown) {
2930 for (uint32_t i = ArrayBufferObject::ArrayBufferFlags::BUFFER_KIND_MASK + 1;
2931 i; i = i << 1) {
2932 if (!(flags & i)) {
2933 continue;
2934 }
2935 switch (ArrayBufferObject::ArrayBufferFlags(flags & i)) {
2936 case ArrayBufferObject::ArrayBufferFlags::DETACHED:
2937 known("DETACHED");
2938 break;
2939 case ArrayBufferObject::ArrayBufferFlags::FOR_ASMJS:
2940 known("FOR_ASMJS");
2941 break;
2942 default:
2943 unknown(i);
2944 break;
2945 }
2946 }
2947 }
2948
2949 void ArrayBufferObject::dumpOwnFields(js::JSONPrinter& json) const {
2950 json.formatProperty("byteLength", "%zu",
2951 size_t(getFixedSlot(BYTE_LENGTH_SLOT).toPrivate()));
2952
2953 BufferKindToString(
2954 bufferKind(),
2955 [&](const char* name) { json.property("bufferKind", name); },
2956 [&](uint8_t value) {
2957 json.formatProperty("bufferKind", "Unknown(%02x)", value);
2958 });
2959
2960 json.beginInlineListProperty("flags");
2961 ForEachArrayBufferFlag(
2962 flags(), [&](const char* name) { json.value("%s", name); },
2963 [&](uint32_t value) { json.value("Unknown(%08x)", value); });
2964 json.endInlineList();
2965
2966 void* data = dataPointer();
2967 if (data) {
2968 json.formatProperty("data", "0x%p", data);
2969 } else {
2970 json.nullProperty("data");
2971 }
2972 }
2973
2974 void ArrayBufferObject::dumpOwnStringContent(js::GenericPrinter& out) const {
2975 out.printf("byteLength=%zu, ",
2976 size_t(getFixedSlot(BYTE_LENGTH_SLOT).toPrivate()));
2977
2978 BufferKindToString(
2979 bufferKind(),
2980 [&](const char* name) { out.printf("bufferKind=%s, ", name); },
2981 [&](uint8_t value) { out.printf("bufferKind=Unknown(%02x), ", value); });
2982
2983 out.printf("flags=[");
2984 bool first = true;
2985 ForEachArrayBufferFlag(
2986 flags(),
2987 [&](const char* name) {
2988 if (!first) {
2989 out.put(",");
2990 }
2991 first = false;
2992 out.put(name);
2993 },
2994 [&](uint32_t value) {
2995 if (!first) {
2996 out.put(",");
2997 }
2998 first = false;
2999 out.printf("Unknown(%08x)", value);
3000 });
3001 out.put("], ");
3002
3003 void* data = dataPointer();
3004 if (data) {
3005 out.printf("data=0x%p", data);
3006 } else {
3007 out.put("data=null");
3008 }
3009 }
3010 #endif
3011
3012 /*
3013 * InnerViewTable
3014 */
3015
3016 inline bool InnerViewTable::Views::empty() { return views.empty(); }
3017
3018 inline bool InnerViewTable::Views::hasNurseryViews() {
3019 return firstNurseryView < views.length();
3020 }
3021
3022 bool InnerViewTable::Views::addView(ArrayBufferViewObject* view) {
3023 // Add the view to the list, ensuring that all nursery views are at end.
3024
3025 if (!views.append(view)) {
3026 return false;
3027 }
3028
3029 if (!gc::IsInsideNursery(view)) {
3030 // Move tenured views before |firstNurseryView|.
3031 if (firstNurseryView != views.length() - 1) {
3032 std::swap(views[firstNurseryView], views.back());
3033 }
3034 firstNurseryView++;
3035 }
3036
3037 check();
3038
3039 return true;
3040 }
3041
3042 bool InnerViewTable::Views::sweepAfterMinorGC(JSTracer* trc) {
3043 return traceWeak(trc, firstNurseryView);
3044 }
3045
3046 bool InnerViewTable::Views::traceWeak(JSTracer* trc, size_t startIndex) {
3047 // Use |trc| to trace the view vector from |startIndex| to the end, removing
3048 // dead views and updating |firstNurseryView|.
3049
3050 size_t index = startIndex;
3051 bool sawNurseryView = false;
3052 views.mutableEraseIf(
3053 [&](auto& view) {
3054 if (!JS::GCPolicy<ViewVector::ElementType>::traceWeak(trc, &view)) {
3055 return true;
3056 }
3057
3058 if (!sawNurseryView && gc::IsInsideNursery(view)) {
3059 sawNurseryView = true;
3060 firstNurseryView = index;
3061 }
3062
3063 index++;
3064 return false;
3065 },
3066 startIndex);
3067
3068 if (!sawNurseryView) {
3069 firstNurseryView = views.length();
3070 }
3071
3072 check();
3073
3074 return !views.empty();
3075 }
3076
3077 inline void InnerViewTable::Views::check() {
3078 #ifdef DEBUG
3079 MOZ_ASSERT(firstNurseryView <= views.length());
3080 if (views.length() < 100) {
3081 for (size_t i = 0; i < views.length(); i++) {
3082 MOZ_ASSERT(gc::IsInsideNursery(views[i]) == (i >= firstNurseryView));
3083 }
3084 }
3085 #endif
3086 }
3087
3088 bool InnerViewTable::addView(JSContext* cx, ArrayBufferObject* buffer,
3089 ArrayBufferViewObject* view) {
3090 // ArrayBufferObject entries are only added when there are multiple views.
3091 MOZ_ASSERT(buffer->firstView());
3092 MOZ_ASSERT(!gc::IsInsideNursery(buffer));
3093
3094 // Ensure the buffer is present in the map, getting the list of views.
3095 auto ptr = map.lookupForAdd(buffer);
3096 if (!ptr && !map.add(ptr, buffer, Views(cx->zone()))) {
3097 ReportOutOfMemory(cx);
3098 return false;
3099 }
3100 Views& views = ptr->value();
3101
3102 bool isNurseryView = gc::IsInsideNursery(view);
3103 bool hadNurseryViews = views.hasNurseryViews();
3104 if (!views.addView(view)) {
3105 ReportOutOfMemory(cx);
3106 return false;
3107 }
3108
3109 // If we added the first nursery view, add the buffer to the list of buffers
3110 // which have nursery views.
3111 if (isNurseryView && !hadNurseryViews && nurseryKeysValid) {
3112 #ifdef DEBUG
3113 if (nurseryKeys.length() < 100) {
3114 for (const auto& key : nurseryKeys) {
3115 MOZ_ASSERT(key != buffer);
3116 }
3117 }
3118 #endif
3119 if (!nurseryKeys.append(buffer)) {
3120 nurseryKeysValid = false;
3121 }
3122 }
3123
3124 return true;
3125 }
3126
3127 InnerViewTable::ViewVector* InnerViewTable::maybeViewsUnbarriered(
3128 ArrayBufferObject* buffer) {
3129 auto ptr = map.lookup(buffer);
3130 if (ptr) {
3131 return &ptr->value().views;
3132 }
3133 return nullptr;
3134 }
3135
3136 void InnerViewTable::removeViews(ArrayBufferObject* buffer) {
3137 auto ptr = map.lookup(buffer);
3138 MOZ_ASSERT(ptr);
3139
3140 map.remove(ptr);
3141 }
3142
3143 bool InnerViewTable::traceWeak(JSTracer* trc) {
3144 nurseryKeys.traceWeak(trc);
3145 map.traceWeak(trc);
3146 return true;
3147 }
3148
3149 void InnerViewTable::sweepAfterMinorGC(JSTracer* trc) {
3150 MOZ_ASSERT(needsSweepAfterMinorGC());
3151
3152 NurseryKeysVector keys;
3153 bool valid = true;
3154 std::swap(nurseryKeys, keys);
3155 std::swap(nurseryKeysValid, valid);
3156
3157 // Use nursery keys vector if possible.
3158 if (valid) {
3159 for (ArrayBufferObject* buffer : keys) {
3160 MOZ_ASSERT(!gc::IsInsideNursery(buffer));
3161 auto ptr = map.lookup(buffer);
3162 if (ptr && !sweepViewsAfterMinorGC(trc, buffer, ptr->value())) {
3163 map.remove(ptr);
3164 }
3165 }
3166 return;
3167 }
3168
3169 // Otherwise look at every map entry.
3170 for (ArrayBufferViewMap::Enum e(map); !e.empty(); e.popFront()) {
3171 MOZ_ASSERT(!gc::IsInsideNursery(e.front().key()));
3172 if (!sweepViewsAfterMinorGC(trc, e.front().key(), e.front().value())) {
3173 e.removeFront();
3174 }
3175 }
3176 }
3177
3178 bool InnerViewTable::sweepViewsAfterMinorGC(JSTracer* trc,
3179 ArrayBufferObject* buffer,
3180 Views& views) {
3181 if (!views.sweepAfterMinorGC(trc)) {
3182 return false; // No more views.
3183 }
3184
3185 if (views.hasNurseryViews() && !nurseryKeys.append(buffer)) {
3186 nurseryKeysValid = false;
3187 }
3188
3189 return true;
3190 }
3191
3192 size_t InnerViewTable::sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) {
3193 size_t vectorSize = 0;
3194 for (auto r = map.all(); !r.empty(); r.popFront()) {
3195 vectorSize += r.front().value().views.sizeOfExcludingThis(mallocSizeOf);
3196 }
3197
3198 return vectorSize + map.shallowSizeOfExcludingThis(mallocSizeOf) +
3199 nurseryKeys.sizeOfExcludingThis(mallocSizeOf);
3200 }
3201
3202 template <>
3203 bool JSObject::is<js::ArrayBufferObjectMaybeShared>() const {
3204 return is<ArrayBufferObject>() || is<SharedArrayBufferObject>();
3205 }
3206
3207 JS_PUBLIC_API size_t JS::GetArrayBufferByteLength(JSObject* obj) {
3208 ArrayBufferObject* aobj = obj->maybeUnwrapAs<ArrayBufferObject>();
3209 return aobj ? aobj->byteLength() : 0;
3210 }
3211
3212 JS_PUBLIC_API uint8_t* JS::GetArrayBufferData(JSObject* obj,
3213 bool* isSharedMemory,
3214 const JS::AutoRequireNoGC&) {
3215 ArrayBufferObject* aobj = obj->maybeUnwrapIf<ArrayBufferObject>();
3216 if (!aobj) {
3217 return nullptr;
3218 }
3219 *isSharedMemory = false;
3220 return aobj->dataPointer();
3221 }
3222
3223 static ArrayBufferObject* UnwrapOrReportArrayBuffer(
3224 JSContext* cx, JS::Handle<JSObject*> maybeArrayBuffer) {
3225 JSObject* obj = CheckedUnwrapStatic(maybeArrayBuffer);
3226 if (!obj) {
3227 ReportAccessDenied(cx);
3228 return nullptr;
3229 }
3230
3231 if (!obj->is<ArrayBufferObject>()) {
3232 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3233 JSMSG_ARRAYBUFFER_REQUIRED);
3234 return nullptr;
3235 }
3236
3237 return &obj->as<ArrayBufferObject>();
3238 }
3239
3240 JS_PUBLIC_API bool JS::DetachArrayBuffer(JSContext* cx, HandleObject obj) {
3241 AssertHeapIsIdle();
3242 CHECK_THREAD(cx);
3243 cx->check(obj);
3244
3245 Rooted<ArrayBufferObject*> unwrappedBuffer(
3246 cx, UnwrapOrReportArrayBuffer(cx, obj));
3247 if (!unwrappedBuffer) {
3248 return false;
3249 }
3250
3251 if (unwrappedBuffer->hasDefinedDetachKey()) {
3252 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3253 JSMSG_WASM_NO_TRANSFER);
3254 return false;
3255 }
3256 if (unwrappedBuffer->isLengthPinned()) {
3257 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3258 JSMSG_ARRAYBUFFER_LENGTH_PINNED);
3259 return false;
3260 }
3261
3262 AutoRealm ar(cx, unwrappedBuffer);
3263 ArrayBufferObject::detach(cx, unwrappedBuffer);
3264 return true;
3265 }
3266
3267 JS_PUBLIC_API bool JS::HasDefinedArrayBufferDetachKey(JSContext* cx,
3268 HandleObject obj,
3269 bool* isDefined) {
3270 Rooted<ArrayBufferObject*> unwrappedBuffer(
3271 cx, UnwrapOrReportArrayBuffer(cx, obj));
3272 if (!unwrappedBuffer) {
3273 return false;
3274 }
3275
3276 *isDefined = unwrappedBuffer->hasDefinedDetachKey();
3277 return true;
3278 }
3279
3280 JS_PUBLIC_API bool JS::IsDetachedArrayBufferObject(JSObject* obj) {
3281 ArrayBufferObject* aobj = obj->maybeUnwrapIf<ArrayBufferObject>();
3282 if (!aobj) {
3283 return false;
3284 }
3285
3286 return aobj->isDetached();
3287 }
3288
3289 JS_PUBLIC_API JSObject* JS::NewArrayBuffer(JSContext* cx, size_t nbytes) {
3290 AssertHeapIsIdle();
3291 CHECK_THREAD(cx);
3292
3293 return ArrayBufferObject::createZeroed(cx, nbytes);
3294 }
3295
3296 JS_PUBLIC_API JSObject* JS::NewArrayBufferWithContents(
3297 JSContext* cx, size_t nbytes,
3298 mozilla::UniquePtr<void, JS::FreePolicy> contents) {
3299 auto* result = NewArrayBufferWithContents(
3300 cx, nbytes, contents.get(),
3301 JS::NewArrayBufferOutOfMemory::CallerMustFreeMemory);
3302 if (result) {
3303 // If and only if an ArrayBuffer is successfully created, ownership of
3304 // |contents| is transferred to the new ArrayBuffer.
3305 (void)contents.release();
3306 }
3307 return result;
3308 }
3309
3310 JS_PUBLIC_API JSObject* JS::NewArrayBufferWithContents(
3311 JSContext* cx, size_t nbytes, void* data, NewArrayBufferOutOfMemory) {
3312 AssertHeapIsIdle();
3313 CHECK_THREAD(cx);
3314 MOZ_ASSERT_IF(!data, nbytes == 0);
3315
3316 if (!data) {
3317 // Don't pass nulled contents to |createForContents|.
3318 return ArrayBufferObject::createZeroed(cx, 0);
3319 }
3320
3321 using BufferContents = ArrayBufferObject::BufferContents;
3322
3323 BufferContents contents = BufferContents::createMallocedUnknownArena(data);
3324 return ArrayBufferObject::createForContents(cx, nbytes, contents);
3325 }
3326
3327 JS_PUBLIC_API JSObject* JS::CopyArrayBuffer(JSContext* cx,
3328 Handle<JSObject*> arrayBuffer) {
3329 AssertHeapIsIdle();
3330 CHECK_THREAD(cx);
3331
3332 MOZ_ASSERT(arrayBuffer != nullptr);
3333
3334 Rooted<ArrayBufferObject*> unwrappedSource(
3335 cx, UnwrapOrReportArrayBuffer(cx, arrayBuffer));
3336 if (!unwrappedSource) {
3337 return nullptr;
3338 }
3339
3340 if (unwrappedSource->isDetached()) {
3341 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3342 JSMSG_TYPED_ARRAY_DETACHED);
3343 return nullptr;
3344 }
3345
3346 return ArrayBufferObject::copy(cx, unwrappedSource->byteLength(),
3347 unwrappedSource);
3348 }
3349
3350 JS_PUBLIC_API JSObject* JS::NewExternalArrayBuffer(
3351 JSContext* cx, size_t nbytes,
3352 mozilla::UniquePtr<void, JS::BufferContentsDeleter> contents) {
3353 AssertHeapIsIdle();
3354 CHECK_THREAD(cx);
3355
3356 MOZ_ASSERT(contents);
3357
3358 using BufferContents = ArrayBufferObject::BufferContents;
3359
3360 BufferContents bufferContents = BufferContents::createExternal(
3361 contents.get(), contents.get_deleter().freeFunc(),
3362 contents.get_deleter().userData());
3363 auto* result =
3364 ArrayBufferObject::createForContents(cx, nbytes, bufferContents);
3365 if (result) {
3366 // If and only if an ArrayBuffer is successfully created, ownership of
3367 // |contents| is transferred to the new ArrayBuffer.
3368 (void)contents.release();
3369 }
3370 return result;
3371 }
3372
3373 JS_PUBLIC_API JSObject* JS::NewArrayBufferWithUserOwnedContents(JSContext* cx,
3374 size_t nbytes,
3375 void* data) {
3376 AssertHeapIsIdle();
3377 CHECK_THREAD(cx);
3378
3379 MOZ_ASSERT(data);
3380
3381 using BufferContents = ArrayBufferObject::BufferContents;
3382
3383 BufferContents contents = BufferContents::createUserOwned(data);
3384 return ArrayBufferObject::createForContents(cx, nbytes, contents);
3385 }
3386
3387 JS_PUBLIC_API bool JS::IsArrayBufferObject(JSObject* obj) {
3388 return obj->canUnwrapAs<ArrayBufferObject>();
3389 }
3390
3391 JS_PUBLIC_API bool JS::ArrayBufferHasData(JSObject* obj) {
3392 return !obj->unwrapAs<ArrayBufferObject>().isDetached();
3393 }
3394
3395 JS_PUBLIC_API JSObject* JS::UnwrapArrayBuffer(JSObject* obj) {
3396 return obj->maybeUnwrapIf<ArrayBufferObject>();
3397 }
3398
3399 JS_PUBLIC_API JSObject* JS::UnwrapSharedArrayBuffer(JSObject* obj) {
3400 return obj->maybeUnwrapIf<SharedArrayBufferObject>();
3401 }
3402
3403 JS_PUBLIC_API void* JS::StealArrayBufferContents(JSContext* cx,
3404 HandleObject obj) {
3405 AssertHeapIsIdle();
3406 CHECK_THREAD(cx);
3407 cx->check(obj);
3408
3409 Rooted<ArrayBufferObject*> unwrappedBuffer(
3410 cx, UnwrapOrReportArrayBuffer(cx, obj));
3411 if (!unwrappedBuffer) {
3412 return nullptr;
3413 }
3414
3415 if (unwrappedBuffer->isDetached()) {
3416 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3417 JSMSG_TYPED_ARRAY_DETACHED);
3418 return nullptr;
3419 }
3420 if (unwrappedBuffer->isLengthPinned()) {
3421 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3422 JSMSG_ARRAYBUFFER_LENGTH_PINNED);
3423 return nullptr;
3424 }
3425
3426 if (unwrappedBuffer->hasDefinedDetachKey()) {
3427 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3428 JSMSG_WASM_NO_TRANSFER);
3429 return nullptr;
3430 }
3431
3432 AutoRealm ar(cx, unwrappedBuffer);
3433 return ArrayBufferObject::stealMallocedContents(cx, unwrappedBuffer);
3434 }
3435
3436 JS_PUBLIC_API JSObject* JS::NewMappedArrayBufferWithContents(JSContext* cx,
3437 size_t nbytes,
3438 void* data) {
3439 AssertHeapIsIdle();
3440 CHECK_THREAD(cx);
3441
3442 MOZ_ASSERT(data);
3443
3444 using BufferContents = ArrayBufferObject::BufferContents;
3445
3446 BufferContents contents = BufferContents::createMapped(data);
3447 return ArrayBufferObject::createForContents(cx, nbytes, contents);
3448 }
3449
3450 JS_PUBLIC_API void* JS::CreateMappedArrayBufferContents(int fd, size_t offset,
3451 size_t length) {
3452 return ArrayBufferObject::createMappedContents(fd, offset, length).data();
3453 }
3454
3455 JS_PUBLIC_API void JS::ReleaseMappedArrayBufferContents(void* contents,
3456 size_t length) {
3457 gc::DeallocateMappedContent(contents, length);
3458 }
3459
3460 JS_PUBLIC_API bool JS::IsMappedArrayBufferObject(JSObject* obj) {
3461 ArrayBufferObject* aobj = obj->maybeUnwrapIf<ArrayBufferObject>();
3462 if (!aobj) {
3463 return false;
3464 }
3465
3466 return aobj->isMapped();
3467 }
3468
3469 JS_PUBLIC_API JSObject* JS::GetObjectAsArrayBuffer(JSObject* obj,
3470 size_t* length,
3471 uint8_t** data) {
3472 ArrayBufferObject* aobj = obj->maybeUnwrapIf<ArrayBufferObject>();
3473 if (!aobj) {
3474 return nullptr;
3475 }
3476
3477 *length = aobj->byteLength();
3478 *data = aobj->dataPointer();
3479
3480 return aobj;
3481 }
3482
3483 JS_PUBLIC_API void JS::GetArrayBufferLengthAndData(JSObject* obj,
3484 size_t* length,
3485 bool* isSharedMemory,
3486 uint8_t** data) {
3487 auto& aobj = obj->as<ArrayBufferObject>();
3488 *length = aobj.byteLength();
3489 *data = aobj.dataPointer();
3490 *isSharedMemory = false;
3491 }
3492
3493 const JSClass* const JS::ArrayBuffer::FixedLengthUnsharedClass =
3494 &FixedLengthArrayBufferObject::class_;
3495 const JSClass* const JS::ArrayBuffer::ResizableUnsharedClass =
3496 &ResizableArrayBufferObject::class_;
3497 const JSClass* const JS::ArrayBuffer::FixedLengthSharedClass =
3498 &FixedLengthSharedArrayBufferObject::class_;
3499 const JSClass* const JS::ArrayBuffer::GrowableSharedClass =
3500 &GrowableSharedArrayBufferObject::class_;
3501
3502 /* static */ JS::ArrayBuffer JS::ArrayBuffer::create(JSContext* cx,
3503 size_t nbytes) {
3504 AssertHeapIsIdle();
3505 CHECK_THREAD(cx);
3506 return JS::ArrayBuffer(ArrayBufferObject::createZeroed(cx, nbytes));
3507 }
3508
3509 mozilla::Span<uint8_t> JS::ArrayBuffer::getData(
3510 bool* isSharedMemory, const JS::AutoRequireNoGC& nogc) {
3511 auto* buffer = obj->maybeUnwrapAs<ArrayBufferObjectMaybeShared>();
3512 if (!buffer) {
3513 return nullptr;
3514 }
3515 size_t length = buffer->byteLength();
3516 if (buffer->is<SharedArrayBufferObject>()) {
3517 *isSharedMemory = true;
3518 return {buffer->dataPointerEither().unwrap(), length};
3519 }
3520 *isSharedMemory = false;
3521 return {buffer->as<ArrayBufferObject>().dataPointer(), length};
3522 };
3523
3524 JS::ArrayBuffer JS::ArrayBuffer::unwrap(JSObject* maybeWrapped) {
3525 if (!maybeWrapped) {
3526 return JS::ArrayBuffer(nullptr);
3527 }
3528 auto* ab = maybeWrapped->maybeUnwrapIf<ArrayBufferObjectMaybeShared>();
3529 return fromObject(ab);
3530 }
3531
3532 bool JS::ArrayBufferCopyData(JSContext* cx, Handle<JSObject*> toBlock,
3533 size_t toIndex, Handle<JSObject*> fromBlock,
3534 size_t fromIndex, size_t count) {
3535 Rooted<ArrayBufferObjectMaybeShared*> unwrappedToBlock(
3536 cx, toBlock->maybeUnwrapIf<ArrayBufferObjectMaybeShared>());
3537 if (!unwrappedToBlock) {
3538 ReportAccessDenied(cx);
3539 return false;
3540 }
3541
3542 Rooted<ArrayBufferObjectMaybeShared*> unwrappedFromBlock(
3543 cx, fromBlock->maybeUnwrapIf<ArrayBufferObjectMaybeShared>());
3544 if (!unwrappedFromBlock) {
3545 ReportAccessDenied(cx);
3546 return false;
3547 }
3548
3549 // Verify that lengths still make sense and throw otherwise.
3550 if (toIndex + count < toIndex || // size_t overflow
3551 fromIndex + count < fromIndex || // size_t overflow
3552 toIndex + count > unwrappedToBlock->byteLength() ||
3553 fromIndex + count > unwrappedFromBlock->byteLength()) {
3554 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3555 JSMSG_ARRAYBUFFER_COPY_RANGE);
3556 return false;
3557 }
3558
3559 // If both are array buffers, can use ArrayBufferCopyData
3560 if (unwrappedToBlock->is<ArrayBufferObject>() &&
3561 unwrappedFromBlock->is<ArrayBufferObject>()) {
3562 Rooted<ArrayBufferObject*> toArray(
3563 cx, &unwrappedToBlock->as<ArrayBufferObject>());
3564 Rooted<ArrayBufferObject*> fromArray(
3565 cx, &unwrappedFromBlock->as<ArrayBufferObject>());
3566 ArrayBufferObject::copyData(toArray, toIndex, fromArray, fromIndex, count);
3567 return true;
3568 }
3569
3570 Rooted<ArrayBufferObjectMaybeShared*> toArray(
3571 cx, &unwrappedToBlock->as<ArrayBufferObjectMaybeShared>());
3572 Rooted<ArrayBufferObjectMaybeShared*> fromArray(
3573 cx, &unwrappedFromBlock->as<ArrayBufferObjectMaybeShared>());
3574 SharedArrayBufferObject::copyData(toArray, toIndex, fromArray, fromIndex,
3575 count);
3576
3577 return true;
3578 }
3579
3580 // https://tc39.es/ecma262/#sec-clonearraybuffer
3581 // We only support the case where cloneConstructor is %ArrayBuffer%. Note,
3582 // this means that cloning a SharedArrayBuffer will produce an ArrayBuffer
3583 JSObject* JS::ArrayBufferClone(JSContext* cx, Handle<JSObject*> srcBuffer,
3584 size_t srcByteOffset, size_t srcLength) {
3585 MOZ_ASSERT(srcBuffer->is<ArrayBufferObjectMaybeShared>());
3586
3587 // 2. (reordered) If IsDetachedBuffer(srcBuffer) is true, throw a TypeError
3588 // exception.
3589 if (IsDetachedArrayBufferObject(srcBuffer)) {
3590 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3591 JSMSG_TYPED_ARRAY_DETACHED);
3592 return nullptr;
3593 }
3594
3595 // 1. Let targetBuffer be ? AllocateArrayBuffer(cloneConstructor, srcLength).
3596 JS::RootedObject targetBuffer(cx, JS::NewArrayBuffer(cx, srcLength));
3597 if (!targetBuffer) {
3598 return nullptr;
3599 }
3600
3601 // 3. Let srcBlock be srcBuffer.[[ArrayBufferData]].
3602 // 4. Let targetBlock be targetBuffer.[[ArrayBufferData]].
3603 // 5. Perform CopyDataBlockBytes(targetBlock, 0, srcBlock, srcByteOffset,
3604 // srcLength).
3605 if (!ArrayBufferCopyData(cx, targetBuffer, 0, srcBuffer, srcByteOffset,
3606 srcLength)) {
3607 return nullptr;
3608 }
3609
3610 // 6. Return targetBuffer.
3611 return targetBuffer;
3612 }