Skip to content

Commit 1993735

Browse files
Check if the memory is backed by a SAB by checking the constructor name
1 parent 9b87015 commit 1993735

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

Plugins/PackageToJS/Templates/runtime.mjs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,12 @@ class SwiftRuntime {
308308
// Cache the DataView as it's not a cheap operation
309309
let cachedDataView = new DataView(wasmMemory.buffer);
310310
let cachedUint8Array = new Uint8Array(wasmMemory.buffer);
311-
if (typeof SharedArrayBuffer !== "undefined" && wasmMemory.buffer instanceof SharedArrayBuffer) {
311+
// Check the constructor name of the buffer to determine if it's backed by a SharedArrayBuffer.
312+
// We can't reference SharedArrayBuffer directly here because:
313+
// 1. It may not be available in the global scope if the context is not cross-origin isolated.
314+
// 2. The underlying buffer may be still backed by SAB even if the context is not cross-origin
315+
// isolated (e.g. localhost on Chrome on Android).
316+
if (Object.getPrototypeOf(wasmMemory.buffer).constructor.name === "SharedArrayBuffer") {
312317
// When the wasm memory is backed by a SharedArrayBuffer, growing the memory
313318
// doesn't invalidate the data view by setting the byte length to 0. Instead,
314319
// the data view points to an old buffer after growing the memory. So we have

Runtime/src/index.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,13 @@ export class SwiftRuntime {
6464
// Cache the DataView as it's not a cheap operation
6565
let cachedDataView = new DataView(wasmMemory.buffer);
6666
let cachedUint8Array = new Uint8Array(wasmMemory.buffer);
67-
if (typeof SharedArrayBuffer !== "undefined" && wasmMemory.buffer instanceof SharedArrayBuffer) {
67+
68+
// Check the constructor name of the buffer to determine if it's backed by a SharedArrayBuffer.
69+
// We can't reference SharedArrayBuffer directly here because:
70+
// 1. It may not be available in the global scope if the context is not cross-origin isolated.
71+
// 2. The underlying buffer may be still backed by SAB even if the context is not cross-origin
72+
// isolated (e.g. localhost on Chrome on Android).
73+
if (Object.getPrototypeOf(wasmMemory.buffer).constructor.name === "SharedArrayBuffer") {
6874
// When the wasm memory is backed by a SharedArrayBuffer, growing the memory
6975
// doesn't invalidate the data view by setting the byte length to 0. Instead,
7076
// the data view points to an old buffer after growing the memory. So we have

0 commit comments

Comments
 (0)