Debian Codegraph @

js/src/vm/SharedArrayObject.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/SharedArrayObject.h"
8
9 #include "mozilla/Atomics.h"
10 #include "mozilla/DebugOnly.h"
11 #include "mozilla/TaggedAnonymousMemory.h"
12
13 #include "jsnum.h"
14
15 #include "gc/GCContext.h"
16 #include "gc/Memory.h"
17 #include "jit/AtomicOperations.h"
18 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
19 #include "js/Prefs.h"
20 #include "js/PropertySpec.h"
21 #include "js/SharedArrayBuffer.h"
22 #include "util/Memory.h"
23 #include "util/WindowsWrapper.h"
24 #include "vm/Interpreter.h"
25 #include "vm/SelfHosting.h"
26 #include "vm/SharedMem.h"
27 #include "wasm/WasmConstants.h"
28 #include "wasm/WasmMemory.h"
29
30 #include "vm/ArrayBufferObject-inl.h"
31 #include "vm/JSObject-inl.h"
32 #include "vm/NativeObject-inl.h"
33
34 using js::wasm::Pages;
35 using mozilla::DebugOnly;
36
37 using namespace js;
38 using namespace js::jit;
39
40 static size_t WasmSharedArrayAccessibleSize(size_t length) {
41 return AlignBytes(length, gc::SystemPageSize());
42 }
43
44 static size_t NonWasmSharedArrayAllocSize(size_t length) {
45 MOZ_ASSERT(length <= ArrayBufferObject::ByteLengthLimit);
46 return sizeof(SharedArrayRawBuffer) + length;
47 }
48
49 // The mapped size for a plain shared array buffer, used only for tracking
50 // memory usage. This is incorrect for some WASM cases, and for hypothetical
51 // callers of js::SharedArrayBufferObject::createFromNewRawBuffer that do not
52 // currently exist, but it's fine as a signal of GC pressure.
53 static size_t SharedArrayMappedSize(bool isWasm, size_t length) {
54 // Wasm buffers use MapBufferMemory and allocate a full page for the header.
55 // Non-Wasm buffers use malloc.
56 if (isWasm) {
57 return WasmSharedArrayAccessibleSize(length) + gc::SystemPageSize();
58 }
59 return NonWasmSharedArrayAllocSize(length);
60 }
61
62 SharedArrayRawBuffer* SharedArrayRawBuffer::Allocate(bool isGrowable,
63 size_t length,
64 size_t maxLength) {
65 MOZ_RELEASE_ASSERT(length <= ArrayBufferObject::ByteLengthLimit);
66 MOZ_RELEASE_ASSERT(maxLength <= ArrayBufferObject::ByteLengthLimit);
67 MOZ_ASSERT_IF(!isGrowable, length == maxLength);
68 MOZ_ASSERT_IF(isGrowable, length <= maxLength);
69
70 size_t allocSize = NonWasmSharedArrayAllocSize(maxLength);
71 uint8_t* p = js_pod_calloc<uint8_t>(allocSize);
72 if (!p) {
73 return nullptr;
74 }
75 MOZ_ASSERT(reinterpret_cast<uintptr_t>(p) %
76 ArrayBufferObject::ARRAY_BUFFER_ALIGNMENT ==
77 0,
78 "shared array buffer memory is aligned");
79
80 // jemalloc tiny allocations can produce allocations not aligned to the
81 // smallest std::malloc allocation. Ensure shared array buffer allocations
82 // don't have to worry about this special case.
83 static_assert(sizeof(SharedArrayRawBuffer) > sizeof(void*),
84 "SharedArrayRawBuffer doesn't fit in jemalloc tiny allocation");
85
86 static_assert(sizeof(SharedArrayRawBuffer) %
87 ArrayBufferObject::ARRAY_BUFFER_ALIGNMENT ==
88 0,
89 "sizeof(SharedArrayRawBuffer) is a multiple of the array "
90 "buffer alignment, so |p + sizeof(SharedArrayRawBuffer)| is "
91 "also array buffer aligned");
92
93 uint8_t* buffer = p + sizeof(SharedArrayRawBuffer);
94 return new (p) SharedArrayRawBuffer(isGrowable, buffer, length);
95 }
96
97 WasmSharedArrayRawBuffer* WasmSharedArrayRawBuffer::AllocateWasm(
98 wasm::AddressType addressType, Pages initialPages,
99 wasm::Pages clampedMaxPages,
100 const mozilla::Maybe<wasm::Pages>& sourceMaxPages,
101 const mozilla::Maybe<size_t>& mappedSize) {
102 // Prior code has asserted that initial pages is within our implementation
103 // limits (wasm::MaxMemoryPages()) and we can assume it is a valid size_t.
104 MOZ_ASSERT(initialPages.hasByteLength());
105 size_t length = initialPages.byteLength();
106
107 MOZ_RELEASE_ASSERT(length <= ArrayBufferObject::ByteLengthLimit);
108
109 size_t accessibleSize = WasmSharedArrayAccessibleSize(length);
110 if (accessibleSize < length) {
111 return nullptr;
112 }
113
114 size_t computedMappedSize = mappedSize.isSome()
115 ? *mappedSize
116 : wasm::ComputeMappedSize(clampedMaxPages);
117 MOZ_ASSERT(accessibleSize <= computedMappedSize);
118
119 uint64_t mappedSizeWithHeader = computedMappedSize + gc::SystemPageSize();
120 uint64_t accessibleSizeWithHeader = accessibleSize + gc::SystemPageSize();
121
122 void* p = MapBufferMemory(addressType, mappedSizeWithHeader,
123 accessibleSizeWithHeader);
124 if (!p) {
125 return nullptr;
126 }
127
128 uint8_t* buffer = reinterpret_cast<uint8_t*>(p) + gc::SystemPageSize();
129 uint8_t* base = buffer - sizeof(WasmSharedArrayRawBuffer);
130 return new (base) WasmSharedArrayRawBuffer(
131 buffer, length, addressType, clampedMaxPages,
132 sourceMaxPages.valueOr(Pages(0)), computedMappedSize);
133 }
134
135 bool WasmSharedArrayRawBuffer::wasmGrowToPagesInPlace(const Lock&,
136 wasm::AddressType t,
137 wasm::Pages newPages) {
138 // Check that the new pages is within our allowable range. This will
139 // simultaneously check against the maximum specified in source and our
140 // implementation limits.
141 if (newPages > clampedMaxPages_) {
142 return false;
143 }
144 MOZ_ASSERT(newPages <= wasm::MaxMemoryPages(t) &&
145 newPages.byteLength() <= ArrayBufferObject::ByteLengthLimit);
146
147 // We have checked against the clamped maximum and so we know we can convert
148 // to byte lengths now.
149 size_t newLength = newPages.byteLength();
150
151 MOZ_ASSERT(newLength >= length_);
152
153 if (newLength == length_) {
154 return true;
155 }
156
157 size_t delta = newLength - length_;
158 MOZ_ASSERT(delta % wasm::PageSize == 0);
159
160 uint8_t* dataEnd = dataPointerShared().unwrap(/* for resize */) + length_;
161 MOZ_ASSERT(uintptr_t(dataEnd) % gc::SystemPageSize() == 0);
162
163 if (!CommitBufferMemory(dataEnd, delta)) {
164 return false;
165 }
166
167 // We rely on CommitBufferMemory (and therefore memmap/VirtualAlloc) to only
168 // return once it has committed memory for all threads. We only update with a
169 // new length once this has occurred.
170 length_ = newLength;
171
172 return true;
173 }
174
175 void WasmSharedArrayRawBuffer::discard(size_t byteOffset, size_t byteLen) {
176 SharedMem<uint8_t*> memBase = dataPointerShared();
177
178 // The caller is responsible for ensuring these conditions are met; see this
179 // function's comment in SharedArrayObject.h.
180 MOZ_ASSERT(byteOffset % wasm::PageSize == 0);
181 MOZ_ASSERT(byteLen % wasm::PageSize == 0);
182 MOZ_ASSERT(wasm::MemoryBoundsCheck(uint64_t(byteOffset), uint64_t(byteLen),
183 volatileByteLength()));
184
185 // Discarding zero bytes "succeeds" with no effect.
186 if (byteLen == 0) {
187 return;
188 }
189
190 SharedMem<uint8_t*> addr = memBase + uintptr_t(byteOffset);
191
192 // On POSIX-ish platforms, we discard memory by overwriting previously-mapped
193 // pages with freshly-mapped pages (which are all zeroed). The operating
194 // system recognizes this and decreases the process RSS, and eventually
195 // collects the abandoned physical pages.
196 //
197 // On Windows, committing over previously-committed pages has no effect. We
198 // could decommit and recommit, but this doesn't work for shared memories
199 // since other threads could access decommitted memory - causing a trap.
200 // Instead, we simply zero memory (memset 0), and then VirtualUnlock(), which
201 // for Historical Reasons immediately removes the pages from the working set.
202 // And then, because the pages were zeroed, Windows will actually reclaim the
203 // memory entirely instead of paging it out to disk. Naturally this behavior
204 // is not officially documented, but a Raymond Chen blog post is basically as
205 // good as MSDN, right?
206 //
207 // https://devblogs.microsoft.com/oldnewthing/20170113-00/?p=95185
208
209 #ifdef XP_WIN
210 // Discarding the entire region at once causes us to page the entire region
211 // into the working set, only to throw it out again. This can be actually
212 // disastrous when discarding already-discarded memory. To mitigate this, we
213 // discard a chunk of memory at a time - this comes at a small performance
214 // cost from syscalls and potentially less-optimal memsets.
215 size_t numPages = byteLen / wasm::PageSize;
216 for (size_t i = 0; i < numPages; i++) {
217 AtomicOperations::memsetSafeWhenRacy(addr + (i * wasm::PageSize), 0,
218 wasm::PageSize);
219 DebugOnly<bool> result =
220 VirtualUnlock(addr.unwrap() + (i * wasm::PageSize), wasm::PageSize);
221 MOZ_ASSERT(!result); // this always "fails" when unlocking unlocked
222 // memory...which is the only case we care about
223 }
224 #elif defined(__wasi__)
225 AtomicOperations::memsetSafeWhenRacy(addr, 0, byteLen);
226 #else // !XP_WIN
227 void* data = MozTaggedAnonymousMmap(
228 addr.unwrap(), byteLen, PROT_READ | PROT_WRITE,
229 MAP_PRIVATE | MAP_ANON | MAP_FIXED, -1, 0, "wasm-reserved");
230 if (data == MAP_FAILED) {
231 MOZ_CRASH("failed to discard wasm memory; memory mappings may be broken");
232 }
233 #endif
234 }
235
236 bool SharedArrayRawBuffer::addReference() {
237 MOZ_RELEASE_ASSERT(refcount_ > 0);
238
239 // Be careful never to overflow the refcount field.
240 for (;;) {
241 uint32_t old_refcount = refcount_;
242 uint32_t new_refcount = old_refcount + 1;
243 if (new_refcount == 0) {
244 return false;
245 }
246 if (refcount_.compareExchange(old_refcount, new_refcount)) {
247 return true;
248 }
249 }
250 }
251
252 void SharedArrayRawBuffer::dropReference() {
253 // Normally if the refcount is zero then the memory will have been unmapped
254 // and this test may just crash, but if the memory has been retained for any
255 // reason we will catch the underflow here.
256 MOZ_RELEASE_ASSERT(refcount_ > 0);
257
258 // Drop the reference to the buffer.
259 uint32_t new_refcount = --refcount_; // Atomic.
260 if (new_refcount) {
261 return;
262 }
263
264 // This was the final reference, so release the buffer.
265 if (isWasm()) {
266 WasmSharedArrayRawBuffer* wasmBuf = toWasmBuffer();
267 wasm::AddressType addressType = wasmBuf->wasmAddressType();
268 uint8_t* basePointer = wasmBuf->basePointer();
269 size_t mappedSizeWithHeader = wasmBuf->mappedSize() + gc::SystemPageSize();
270 size_t committedSize = wasmBuf->volatileByteLength() + gc::SystemPageSize();
271 // Call the destructor to destroy the growLock_ Mutex.
272 wasmBuf->~WasmSharedArrayRawBuffer();
273 UnmapBufferMemory(addressType, basePointer, mappedSizeWithHeader,
274 committedSize);
275 } else {
276 js_delete(this);
277 }
278 }
279
280 bool SharedArrayRawBuffer::growJS(size_t newByteLength) {
281 MOZ_ASSERT(!isWasm());
282 MOZ_RELEASE_ASSERT(isGrowableJS());
283
284 // The caller is responsible to ensure |newByteLength| doesn't exceed the
285 // maximum allowed byte length.
286
287 while (true) {
288 // `mozilla::Atomic::compareExchange` doesn't return the current value, so
289 // we need to perform a normal load here. (bug 1005335)
290 size_t oldByteLength = length_;
291 if (newByteLength == oldByteLength) {
292 return true;
293 }
294 if (newByteLength < oldByteLength) {
295 return false;
296 }
297 if (length_.compareExchange(oldByteLength, newByteLength)) {
298 return true;
299 }
300 }
301 }
302
303 static bool IsSharedArrayBuffer(HandleValue v) {
304 return v.isObject() && v.toObject().is<SharedArrayBufferObject>();
305 }
306
307 static bool IsGrowableSharedArrayBuffer(HandleValue v) {
308 return v.isObject() && v.toObject().is<GrowableSharedArrayBufferObject>();
309 }
310
311 MOZ_ALWAYS_INLINE bool SharedArrayBufferObject::byteLengthGetterImpl(
312 JSContext* cx, const CallArgs& args) {
313 MOZ_ASSERT(IsSharedArrayBuffer(args.thisv()));
314 auto* buffer = &args.thisv().toObject().as<SharedArrayBufferObject>();
315 args.rval().setNumber(buffer->byteLength());
316 return true;
317 }
318
319 bool SharedArrayBufferObject::byteLengthGetter(JSContext* cx, unsigned argc,
320 Value* vp) {
321 CallArgs args = CallArgsFromVp(argc, vp);
322 return CallNonGenericMethod<IsSharedArrayBuffer, byteLengthGetterImpl>(cx,
323 args);
324 }
325
326 /**
327 * get SharedArrayBuffer.prototype.maxByteLength
328 */
329 bool SharedArrayBufferObject::maxByteLengthGetterImpl(JSContext* cx,
330 const CallArgs& args) {
331 MOZ_ASSERT(IsSharedArrayBuffer(args.thisv()));
332 auto* buffer = &args.thisv().toObject().as<SharedArrayBufferObject>();
333
334 // Steps 4-6.
335 args.rval().setNumber(buffer->byteLengthOrMaxByteLength());
336 return true;
337 }
338
339 /**
340 * get SharedArrayBuffer.prototype.maxByteLength
341 */
342 bool SharedArrayBufferObject::maxByteLengthGetter(JSContext* cx, unsigned argc,
343 Value* vp) {
344 // Steps 1-3.
345 CallArgs args = CallArgsFromVp(argc, vp);
346 return CallNonGenericMethod<IsSharedArrayBuffer, maxByteLengthGetterImpl>(
347 cx, args);
348 }
349
350 /**
351 * get SharedArrayBuffer.prototype.growable
352 */
353 bool SharedArrayBufferObject::growableGetterImpl(JSContext* cx,
354 const CallArgs& args) {
355 MOZ_ASSERT(IsSharedArrayBuffer(args.thisv()));
356 auto* buffer = &args.thisv().toObject().as<SharedArrayBufferObject>();
357
358 // Step 4.
359 args.rval().setBoolean(buffer->isGrowable());
360 return true;
361 }
362
363 /**
364 * get SharedArrayBuffer.prototype.growable
365 */
366 bool SharedArrayBufferObject::growableGetter(JSContext* cx, unsigned argc,
367 Value* vp) {
368 // Steps 1-3.
369 CallArgs args = CallArgsFromVp(argc, vp);
370 return CallNonGenericMethod<IsSharedArrayBuffer, growableGetterImpl>(cx,
371 args);
372 }
373
374 /**
375 * SharedArrayBuffer.prototype.grow ( newLength )
376 */
377 bool SharedArrayBufferObject::growImpl(JSContext* cx, const CallArgs& args) {
378 MOZ_ASSERT(IsGrowableSharedArrayBuffer(args.thisv()));
379 Rooted<GrowableSharedArrayBufferObject*> buffer(
380 cx, &args.thisv().toObject().as<GrowableSharedArrayBufferObject>());
381
382 // Step 4.
383 uint64_t newByteLength;
384 if (!ToIndex(cx, args.get(0), &newByteLength)) {
385 return false;
386 }
387
388 // Steps 5-11.
389 if (newByteLength > buffer->maxByteLength()) {
390 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
391 JSMSG_ARRAYBUFFER_LENGTH_LARGER_THAN_MAXIMUM);
392 return false;
393 }
394
395 if (buffer->isWasm()) {
396 // Special case for resizing of Wasm buffers.
397 if (newByteLength % wasm::PageSize != 0) {
398 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
399 JSMSG_WASM_ARRAYBUFFER_PAGE_MULTIPLE);
400 return false;
401 }
402
403 mozilla::Maybe<WasmSharedArrayRawBuffer::Lock> lock(
404 mozilla::Some(buffer->rawWasmBufferObject()));
405
406 if (newByteLength < buffer->rawWasmBufferObject()->volatileByteLength()) {
407 lock.reset();
408 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
409 JSMSG_WASM_ARRAYBUFFER_CANNOT_SHRINK);
410 return false;
411 }
412
413 Pages newPages = Pages::fromByteLengthExact(newByteLength);
414 return buffer->rawWasmBufferObject()->wasmGrowToPagesInPlace(
415 *lock, buffer->wasmAddressType(), newPages);
416 }
417
418 if (!buffer->rawBufferObject()->growJS(newByteLength)) {
419 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
420 JSMSG_SHARED_ARRAY_LENGTH_SMALLER_THAN_CURRENT);
421 return false;
422 }
423
424 args.rval().setUndefined();
425 return true;
426 }
427
428 /**
429 * SharedArrayBuffer.prototype.grow ( newLength )
430 */
431 bool SharedArrayBufferObject::grow(JSContext* cx, unsigned argc, Value* vp) {
432 // Steps 1-3.
433 CallArgs args = CallArgsFromVp(argc, vp);
434 return CallNonGenericMethod<IsGrowableSharedArrayBuffer, growImpl>(cx, args);
435 }
436
437 static bool IsSharedArrayBufferSpecies(JSContext* cx, JSFunction* species) {
438 return IsSelfHostedFunctionWithName(
439 species, cx->names().dollar_SharedArrayBufferSpecies_);
440 }
441
442 static bool HasBuiltinSharedArrayBufferSpecies(SharedArrayBufferObject* obj,
443 JSContext* cx) {
444 // Ensure `SharedArrayBuffer.prototype.constructor` and
445 // `SharedArrayBuffer[@@species]` haven't been mutated.
446 if (!cx->realm()->realmFuses.optimizeSharedArrayBufferSpeciesFuse.intact()) {
447 return false;
448 }
449
450 // Ensure |obj|'s prototype is the actual SharedArrayBuffer.prototype.
451 auto* proto = cx->global()->maybeGetPrototype(JSProto_SharedArrayBuffer);
452 if (!proto || obj->staticPrototype() != proto) {
453 return false;
454 }
455
456 // Fail if |obj| has an own `constructor` property.
457 if (obj->containsPure(NameToId(cx->names().constructor))) {
458 return false;
459 }
460
461 return true;
462 }
463
464 /**
465 * SharedArrayBuffer.prototype.slice ( start, end )
466 *
467 * https://tc39.es/ecma262/#sec-sharedarraybuffer.prototype.slice
468 */
469 bool SharedArrayBufferObject::sliceImpl(JSContext* cx, const CallArgs& args) {
470 MOZ_ASSERT(IsSharedArrayBuffer(args.thisv()));
471
472 Rooted<SharedArrayBufferObject*> obj(
473 cx, &args.thisv().toObject().as<SharedArrayBufferObject>());
474
475 // Step 4.
476 size_t len = obj->byteLength();
477
478 // Steps 5-8.
479 size_t first = 0;
480 if (args.hasDefined(0)) {
481 if (!ToIntegerIndex(cx, args[0], len, &first)) {
482 return false;
483 }
484 }
485
486 // Steps 9-12.
487 size_t final_ = len;
488 if (args.hasDefined(1)) {
489 if (!ToIntegerIndex(cx, args[1], len, &final_)) {
490 return false;
491 }
492 }
493
494 // Step 13.
495 size_t newLen = final_ >= first ? final_ - first : 0;
496 MOZ_ASSERT(newLen <= ArrayBufferObject::ByteLengthLimit);
497
498 // Steps 14-19.
499 Rooted<JSObject*> resultObj(cx);
500 SharedArrayBufferObject* unwrappedResult = nullptr;
501 if (HasBuiltinSharedArrayBufferSpecies(obj, cx)) {
502 // Steps 14-15.
503 unwrappedResult = New(cx, newLen);
504 if (!unwrappedResult) {
505 return false;
506 }
507 resultObj.set(unwrappedResult);
508
509 // Steps 16-17. (Not applicable)
510
511 // Step 18.
512 MOZ_ASSERT(obj->rawBufferObject() != unwrappedResult->rawBufferObject());
513
514 // Step 19.
515 MOZ_ASSERT(unwrappedResult->byteLength() == newLen);
516 } else {
517 // Step 14.
518 Rooted<JSObject*> ctor(
519 cx, SpeciesConstructor(cx, obj, JSProto_SharedArrayBuffer,
520 IsSharedArrayBufferSpecies));
521 if (!ctor) {
522 return false;
523 }
524
525 // Step 15.
526 {
527 FixedConstructArgs<1> cargs(cx);
528 cargs[0].setNumber(newLen);
529
530 Rooted<Value> ctorVal(cx, ObjectValue(*ctor));
531 if (!Construct(cx, ctorVal, cargs, ctorVal, &resultObj)) {
532 return false;
533 }
534 }
535
536 // Steps 16-17.
537 unwrappedResult = resultObj->maybeUnwrapIf<SharedArrayBufferObject>();
538 if (!unwrappedResult) {
539 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
540 JSMSG_NON_SHARED_ARRAY_BUFFER_RETURNED);
541 return false;
542 }
543
544 // Step 18.
545 if (obj->rawBufferObject() == unwrappedResult->rawBufferObject()) {
546 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
547 JSMSG_SAME_SHARED_ARRAY_BUFFER_RETURNED);
548 return false;
549 }
550
551 // Step 19.
552 size_t resultByteLength = unwrappedResult->byteLength();
553 if (resultByteLength < newLen) {
554 ToCStringBuf resultLenCbuf;
555 const char* resultLenStr =
556 NumberToCString(&resultLenCbuf, double(resultByteLength));
557
558 ToCStringBuf newLenCbuf;
559 const char* newLenStr = NumberToCString(&newLenCbuf, double(newLen));
560
561 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
562 JSMSG_SHORT_SHARED_ARRAY_BUFFER_RETURNED,
563 newLenStr, resultLenStr);
564 return false;
565 }
566 }
567
568 // Steps 20-22.
569 SharedArrayBufferObject::copyData(unwrappedResult, 0, obj, first, newLen);
570
571 // Step 23.
572 args.rval().setObject(*resultObj);
573 return true;
574 }
575
576 /**
577 * SharedArrayBuffer.prototype.slice ( start, end )
578 *
579 * https://tc39.es/ecma262/#sec-sharedarraybuffer.prototype.slice
580 */
581 bool SharedArrayBufferObject::slice(JSContext* cx, unsigned argc, Value* vp) {
582 // Steps 1-3.
583 CallArgs args = CallArgsFromVp(argc, vp);
584 return CallNonGenericMethod<IsSharedArrayBuffer, sliceImpl>(cx, args);
585 }
586
587 // ES2024 draft rev 3a773fc9fae58be023228b13dbbd402ac18eeb6b
588 // 25.2.3.1 SharedArrayBuffer ( length [ , options ] )
589 bool SharedArrayBufferObject::class_constructor(JSContext* cx, unsigned argc,
590 Value* vp) {
591 CallArgs args = CallArgsFromVp(argc, vp);
592
593 // Step 1.
594 if (!ThrowIfNotConstructing(cx, args, "SharedArrayBuffer")) {
595 return false;
596 }
597
598 // Step 2.
599 uint64_t byteLength;
600 if (!ToIndex(cx, args.get(0), &byteLength)) {
601 return false;
602 }
603
604 // Step 3.
605 mozilla::Maybe<uint64_t> maxByteLength;
606 // Inline call to GetArrayBufferMaxByteLengthOption.
607 if (args.get(1).isObject()) {
608 Rooted<JSObject*> options(cx, &args[1].toObject());
609
610 Rooted<Value> val(cx);
611 if (!GetProperty(cx, options, options, cx->names().maxByteLength, &val)) {
612 return false;
613 }
614 if (!val.isUndefined()) {
615 uint64_t maxByteLengthInt;
616 if (!ToIndex(cx, val, &maxByteLengthInt)) {
617 return false;
618 }
619
620 // 25.2.2.1 AllocateSharedArrayBuffer, step 3.a.
621 if (byteLength > maxByteLengthInt) {
622 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
623 JSMSG_ARRAYBUFFER_LENGTH_LARGER_THAN_MAXIMUM);
624 return false;
625 }
626 maxByteLength = mozilla::Some(maxByteLengthInt);
627 }
628 }
629
630 // Step 4 (Inlined 25.2.2.1 AllocateSharedArrayBuffer).
631 // 25.2.2.1, step 5 (Inlined 10.1.13 OrdinaryCreateFromConstructor, step 2).
632 RootedObject proto(cx);
633 if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_SharedArrayBuffer,
634 &proto)) {
635 return false;
636 }
637
638 // 25.2.2.1, step 6.
639 uint64_t allocLength = maxByteLength.valueOr(byteLength);
640
641 // 25.2.2.1, step 7 (Inlined 6.2.9.2 CreateSharedByteDataBlock, step 1).
642 // Refuse to allocate too large buffers.
643 if (allocLength > ArrayBufferObject::ByteLengthLimit) {
644 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
645 JSMSG_SHARED_ARRAY_BAD_LENGTH);
646 return false;
647 }
648
649 if (maxByteLength) {
650 // 25.2.2.1, remaining steps.
651 auto* bufobj = NewGrowable(cx, byteLength, *maxByteLength, proto);
652 if (!bufobj) {
653 return false;
654 }
655 args.rval().setObject(*bufobj);
656 return true;
657 }
658
659 // 25.2.2.1, remaining steps.
660 JSObject* bufobj = New(cx, byteLength, proto);
661 if (!bufobj) {
662 return false;
663 }
664 args.rval().setObject(*bufobj);
665 return true;
666 }
667
668 FixedLengthSharedArrayBufferObject* SharedArrayBufferObject::New(
669 JSContext* cx, size_t length, HandleObject proto) {
670 bool isGrowable = false;
671 size_t maxLength = length;
672 auto* buffer = SharedArrayRawBuffer::Allocate(isGrowable, length, maxLength);
673 if (!buffer) {
674 js::ReportOutOfMemory(cx);
675 return nullptr;
676 }
677
678 auto* obj = New(cx, buffer, length, proto);
679 if (!obj) {
680 buffer->dropReference();
681 return nullptr;
682 }
683
684 return obj;
685 }
686
687 FixedLengthSharedArrayBufferObject* SharedArrayBufferObject::New(
688 JSContext* cx, SharedArrayRawBuffer* buffer, size_t length,
689 HandleObject proto) {
690 return NewWith<FixedLengthSharedArrayBufferObject>(cx, buffer, length, proto);
691 }
692
693 GrowableSharedArrayBufferObject* SharedArrayBufferObject::NewGrowable(
694 JSContext* cx, size_t length, size_t maxLength, HandleObject proto) {
695 bool isGrowable = true;
696 auto* buffer = SharedArrayRawBuffer::Allocate(isGrowable, length, maxLength);
697 if (!buffer) {
698 js::ReportOutOfMemory(cx);
699 return nullptr;
700 }
701
702 auto* obj = NewGrowable(cx, buffer, maxLength, proto);
703 if (!obj) {
704 buffer->dropReference();
705 return nullptr;
706 }
707
708 return obj;
709 }
710
711 GrowableSharedArrayBufferObject* SharedArrayBufferObject::NewGrowable(
712 JSContext* cx, SharedArrayRawBuffer* buffer, size_t maxLength,
713 HandleObject proto) {
714 return NewWith<GrowableSharedArrayBufferObject>(cx, buffer, maxLength, proto);
715 }
716
717 template <class SharedArrayBufferType>
718 SharedArrayBufferType* SharedArrayBufferObject::NewWith(
719 JSContext* cx, SharedArrayRawBuffer* buffer, size_t length,
720 HandleObject proto) {
721 MOZ_ASSERT(cx->realm()->creationOptions().getSharedMemoryAndAtomicsEnabled());
722
723 static_assert(
724 std::is_same_v<SharedArrayBufferType,
725 FixedLengthSharedArrayBufferObject> ||
726 std::is_same_v<SharedArrayBufferType, GrowableSharedArrayBufferObject>);
727
728 if (!buffer->isWasm()) {
729 if constexpr (std::is_same_v<SharedArrayBufferType,
730 FixedLengthSharedArrayBufferObject>) {
731 MOZ_ASSERT(!buffer->isGrowableJS());
732 } else {
733 MOZ_ASSERT(buffer->isGrowableJS());
734 }
735 }
736
737 AutoSetNewObjectMetadata metadata(cx);
738 auto* obj = NewObjectWithClassProto<SharedArrayBufferType>(cx, proto);
739 if (!obj) {
740 return nullptr;
741 }
742
743 MOZ_ASSERT(obj->getClass() == &SharedArrayBufferType::class_);
744
745 cx->runtime()->incSABCount();
746
747 if (!obj->acceptRawBuffer(buffer, length)) {
748 js::ReportOutOfMemory(cx);
749 return nullptr;
750 }
751
752 return obj;
753 }
754
755 bool SharedArrayBufferObject::acceptRawBuffer(SharedArrayRawBuffer* buffer,
756 size_t length) {
757 MOZ_ASSERT(!isInitialized());
758 if (!zone()->addSharedMemory(buffer,
759 SharedArrayMappedSize(buffer->isWasm(), length),
760 MemoryUse::SharedArrayRawBuffer)) {
761 return false;
762 }
763
764 setFixedSlot(RAWBUF_SLOT, PrivateValue(buffer));
765 setFixedSlot(LENGTH_SLOT, PrivateValue(length));
766 MOZ_ASSERT(isInitialized());
767 return true;
768 }
769
770 void SharedArrayBufferObject::dropRawBuffer() {
771 size_t length = byteLengthOrMaxByteLength();
772 size_t size = SharedArrayMappedSize(isWasm(), length);
773 zoneFromAnyThread()->removeSharedMemory(rawBufferObject(), size,
774 MemoryUse::SharedArrayRawBuffer);
775 rawBufferObject()->dropReference();
776 setFixedSlot(RAWBUF_SLOT, UndefinedValue());
777 MOZ_ASSERT(!isInitialized());
778 }
779
780 SharedArrayRawBuffer* SharedArrayBufferObject::rawBufferObject() const {
781 Value v = getFixedSlot(RAWBUF_SLOT);
782 MOZ_ASSERT(!v.isUndefined());
783 return reinterpret_cast<SharedArrayRawBuffer*>(v.toPrivate());
784 }
785
786 void SharedArrayBufferObject::Finalize(JS::GCContext* gcx, JSObject* obj) {
787 // Must be foreground finalizable so that we can account for the object.
788 MOZ_ASSERT(gcx->onMainThread());
789 gcx->runtime()->decSABCount();
790
791 SharedArrayBufferObject& buf = obj->as<SharedArrayBufferObject>();
792
793 // Detect the case of failure during SharedArrayBufferObject creation,
794 // which causes a SharedArrayRawBuffer to never be attached.
795 Value v = buf.getFixedSlot(RAWBUF_SLOT);
796 if (!v.isUndefined()) {
797 buf.dropRawBuffer();
798 }
799 }
800
801 /* static */
802 void SharedArrayBufferObject::addSizeOfExcludingThis(
803 JSObject* obj, mozilla::MallocSizeOf mallocSizeOf, JS::ClassInfo* info,
804 JS::RuntimeSizes* runtimeSizes) {
805 // Divide the buffer size by the refcount to get the fraction of the buffer
806 // owned by this thread. It's conceivable that the refcount might change in
807 // the middle of memory reporting, in which case the amount reported for
808 // some threads might be to high (if the refcount goes up) or too low (if
809 // the refcount goes down). But that's unlikely and hard to avoid, so we
810 // just live with the risk.
811 const SharedArrayBufferObject& buf = obj->as<SharedArrayBufferObject>();
812
813 if (MOZ_UNLIKELY(!buf.isInitialized())) {
814 return;
815 }
816
817 size_t nbytes = buf.byteLengthOrMaxByteLength();
818 size_t owned = nbytes / buf.rawBufferObject()->refcount();
819 if (buf.isWasm()) {
820 info->objectsNonHeapElementsWasmShared += owned;
821 if (runtimeSizes) {
822 size_t ownedGuardPages =
823 (buf.wasmMappedSize() - nbytes) / buf.rawBufferObject()->refcount();
824 runtimeSizes->wasmGuardPages += ownedGuardPages;
825 }
826 } else {
827 info->objectsNonHeapElementsShared += owned;
828 }
829 }
830
831 /* static */
832 void SharedArrayBufferObject::copyData(ArrayBufferObjectMaybeShared* toBuffer,
833 size_t toIndex,
834 ArrayBufferObjectMaybeShared* fromBuffer,
835 size_t fromIndex, size_t count) {
836 MOZ_ASSERT(toBuffer->byteLength() >= count);
837 MOZ_ASSERT(toBuffer->byteLength() >= toIndex + count);
838 MOZ_ASSERT(fromBuffer->byteLength() >= fromIndex);
839 MOZ_ASSERT(fromBuffer->byteLength() >= fromIndex + count);
840
841 jit::AtomicOperations::memcpySafeWhenRacy(
842 toBuffer->dataPointerEither() + toIndex,
843 fromBuffer->dataPointerEither() + fromIndex, count);
844 }
845
846 SharedArrayBufferObject* SharedArrayBufferObject::createFromNewRawBuffer(
847 JSContext* cx, WasmSharedArrayRawBuffer* buffer, size_t initialSize) {
848 MOZ_ASSERT(cx->realm()->creationOptions().getSharedMemoryAndAtomicsEnabled());
849
850 AutoSetNewObjectMetadata metadata(cx);
851 auto* obj = NewBuiltinClassInstance<FixedLengthSharedArrayBufferObject>(cx);
852 if (!obj) {
853 buffer->dropReference();
854 return nullptr;
855 }
856
857 cx->runtime()->incSABCount();
858
859 if (!obj->acceptRawBuffer(buffer, initialSize)) {
860 buffer->dropReference();
861 js::ReportOutOfMemory(cx);
862 return nullptr;
863 }
864
865 return obj;
866 }
867
868 template <typename SharedArrayBufferType>
869 SharedArrayBufferType* SharedArrayBufferObject::createFromWasmObject(
870 JSContext* cx, Handle<SharedArrayBufferObject*> wasmBuffer) {
871 MOZ_ASSERT(cx->realm()->creationOptions().getSharedMemoryAndAtomicsEnabled());
872 MOZ_ASSERT(wasmBuffer->isWasm());
873
874 SharedArrayRawBuffer* rawBuffer = wasmBuffer->rawBufferObject();
875 size_t byteLengthOrMaximum;
876 if constexpr (std::is_same_v<SharedArrayBufferType,
877 GrowableSharedArrayBufferObject>) {
878 byteLengthOrMaximum = rawBuffer->toWasmBuffer()->wasmClampedMaxByteLength();
879 } else {
880 static_assert(std::is_same_v<SharedArrayBufferType,
881 FixedLengthSharedArrayBufferObject>);
882 byteLengthOrMaximum = rawBuffer->volatileByteLength();
883 }
884
885 if (!rawBuffer->addReference()) {
886 JS_ReportErrorASCII(cx, "Reference count overflow on SharedArrayBuffer");
887 return nullptr;
888 }
889
890 SharedArrayBufferType* obj = NewWith<SharedArrayBufferType>(
891 cx, rawBuffer, byteLengthOrMaximum, nullptr);
892 if (!obj) {
893 rawBuffer->dropReference();
894 return nullptr;
895 }
896
897 return obj;
898 }
899
900 template FixedLengthSharedArrayBufferObject* SharedArrayBufferObject::
901 createFromWasmObject<FixedLengthSharedArrayBufferObject>(
902 JSContext* cx, Handle<SharedArrayBufferObject*> wasmBuffer);
903
904 template GrowableSharedArrayBufferObject*
905 SharedArrayBufferObject::createFromWasmObject<GrowableSharedArrayBufferObject>(
906 JSContext* cx, Handle<SharedArrayBufferObject*> wasmBuffer);
907
908 /* static */
909 void SharedArrayBufferObject::wasmDiscard(Handle<SharedArrayBufferObject*> buf,
910 uint64_t byteOffset,
911 uint64_t byteLen) {
912 MOZ_ASSERT(buf->isWasm());
913 buf->rawWasmBufferObject()->discard(byteOffset, byteLen);
914 }
915
916 static const JSClassOps SharedArrayBufferObjectClassOps = {
917 nullptr, // addProperty
918 nullptr, // delProperty
919 nullptr, // enumerate
920 nullptr, // newEnumerate
921 nullptr, // resolve
922 nullptr, // mayResolve
923 SharedArrayBufferObject::Finalize, // finalize
924 nullptr, // call
925 nullptr, // construct
926 nullptr, // trace
927 };
928
929 static const JSFunctionSpec sharedarray_functions[] = {
930 JS_FS_END,
931 };
932
933 static const JSPropertySpec sharedarray_properties[] = {
934 JS_SELF_HOSTED_SYM_GET(species, "$SharedArrayBufferSpecies", 0),
935 JS_PS_END,
936 };
937
938 static const JSFunctionSpec sharedarray_proto_functions[] = {
939 JS_FN("slice", SharedArrayBufferObject::slice, 2, 0),
940 JS_FN("grow", SharedArrayBufferObject::grow, 1, 0),
941 JS_FS_END,
942 };
943
944 static const JSPropertySpec sharedarray_proto_properties[] = {
945 JS_PSG("byteLength", SharedArrayBufferObject::byteLengthGetter, 0),
946 JS_PSG("maxByteLength", SharedArrayBufferObject::maxByteLengthGetter, 0),
947 JS_PSG("growable", SharedArrayBufferObject::growableGetter, 0),
948 JS_STRING_SYM_PS(toStringTag, "SharedArrayBuffer", JSPROP_READONLY),
949 JS_PS_END,
950 };
951
952 static JSObject* CreateSharedArrayBufferPrototype(JSContext* cx,
953 JSProtoKey key) {
954 return GlobalObject::createBlankPrototype(
955 cx, cx->global(), &SharedArrayBufferObject::protoClass_);
956 }
957
958 static const ClassSpec SharedArrayBufferObjectClassSpec = {
959 GenericCreateConstructor<SharedArrayBufferObject::class_constructor, 1,
960 gc::AllocKind::FUNCTION>,
961 CreateSharedArrayBufferPrototype,
962 sharedarray_functions,
963 sharedarray_properties,
964 sharedarray_proto_functions,
965 sharedarray_proto_properties,
966 GenericFinishInit<WhichHasFuseProperty::ProtoAndCtor>,
967 };
968
969 const JSClass SharedArrayBufferObject::protoClass_ = {
970 "SharedArrayBuffer.prototype",
971 JSCLASS_HAS_CACHED_PROTO(JSProto_SharedArrayBuffer),
972 JS_NULL_CLASS_OPS,
973 &SharedArrayBufferObjectClassSpec,
974 };
975
976 const JSClass FixedLengthSharedArrayBufferObject::class_ = {
977 "SharedArrayBuffer",
978 JSCLASS_DELAY_METADATA_BUILDER |
979 JSCLASS_HAS_RESERVED_SLOTS(SharedArrayBufferObject::RESERVED_SLOTS) |
980 JSCLASS_HAS_CACHED_PROTO(JSProto_SharedArrayBuffer) |
981 JSCLASS_FOREGROUND_FINALIZE,
982 &SharedArrayBufferObjectClassOps,
983 &SharedArrayBufferObjectClassSpec,
984 JS_NULL_CLASS_EXT,
985 };
986
987 const JSClass GrowableSharedArrayBufferObject::class_ = {
988 "SharedArrayBuffer",
989 JSCLASS_DELAY_METADATA_BUILDER |
990 JSCLASS_HAS_RESERVED_SLOTS(SharedArrayBufferObject::RESERVED_SLOTS) |
991 JSCLASS_HAS_CACHED_PROTO(JSProto_SharedArrayBuffer) |
992 JSCLASS_FOREGROUND_FINALIZE,
993 &SharedArrayBufferObjectClassOps,
994 &SharedArrayBufferObjectClassSpec,
995 JS_NULL_CLASS_EXT,
996 };
997
998 JS_PUBLIC_API size_t JS::GetSharedArrayBufferByteLength(JSObject* obj) {
999 auto* aobj = obj->maybeUnwrapAs<SharedArrayBufferObject>();
1000 return aobj ? aobj->byteLength() : 0;
1001 }
1002
1003 JS_PUBLIC_API void JS::GetSharedArrayBufferLengthAndData(JSObject* obj,
1004 size_t* length,
1005 bool* isSharedMemory,
1006 uint8_t** data) {
1007 MOZ_ASSERT(obj->is<SharedArrayBufferObject>());
1008 *length = obj->as<SharedArrayBufferObject>().byteLength();
1009 *data = obj->as<SharedArrayBufferObject>().dataPointerShared().unwrap(
1010 /*safe - caller knows*/);
1011 *isSharedMemory = true;
1012 }
1013
1014 JS_PUBLIC_API JSObject* JS::NewSharedArrayBuffer(JSContext* cx, size_t nbytes) {
1015 MOZ_ASSERT(cx->realm()->creationOptions().getSharedMemoryAndAtomicsEnabled());
1016
1017 if (nbytes > ArrayBufferObject::ByteLengthLimit) {
1018 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1019 JSMSG_SHARED_ARRAY_BAD_LENGTH);
1020 return nullptr;
1021 }
1022
1023 return SharedArrayBufferObject::New(cx, nbytes,
1024 /* proto = */ nullptr);
1025 }
1026
1027 JS_PUBLIC_API bool JS::IsSharedArrayBufferObject(JSObject* obj) {
1028 return obj->canUnwrapAs<SharedArrayBufferObject>();
1029 }
1030
1031 JS_PUBLIC_API uint8_t* JS::GetSharedArrayBufferData(
1032 JSObject* obj, bool* isSharedMemory, const JS::AutoRequireNoGC&) {
1033 auto* aobj = obj->maybeUnwrapAs<SharedArrayBufferObject>();
1034 if (!aobj) {
1035 return nullptr;
1036 }
1037 *isSharedMemory = true;
1038 return aobj->dataPointerShared().unwrap(/*safe - caller knows*/);
1039 }
1040
1041 JS_PUBLIC_API bool JS::ContainsSharedArrayBuffer(JSContext* cx) {
1042 return cx->runtime()->hasLiveSABs();
1043 }