diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ArrayBuffer.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ArrayBuffer.kt index f7b69728bb9..04fe6dd2d04 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ArrayBuffer.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ArrayBuffer.kt @@ -14,11 +14,16 @@ import java.nio.ByteBuffer /** * A fixed-length byte buffer for TurboModule `ArrayBuffer` arguments and return values. * + * Returning an owning [ArrayBuffer] to JS produces a *new* JS `ArrayBuffer` object over the same + * bytes, so a module that mutates an argument in place and returns it gives JS a different object + * that aliases the memory it passed in. Returning a non-owning [ArrayBuffer] gives JS a copy. + * * @property isOwningBytes: * - `true` — safe to retain and return to JS. Synchronize externally if JS may touch the same * memory concurrently. - * - `false` — bytes are borrowed from a JS `ArrayBuffer` for the current synchronous call only. - * Copy with [arrayBufferWithCopiedBytes] to keep them. + * - `false` — the bytes are borrowed from a JS `ArrayBuffer` and are only valid until the method + * that received this [ArrayBuffer] returns. After that, [bytes] and [size] throw. Copy with + * [arrayBufferWithCopiedBytes] to keep them. */ @DoNotStrip public class ArrayBuffer : HybridClassBase { @@ -39,14 +44,50 @@ public class ArrayBuffer : HybridClassBase { initHybrid(buffer, isOwningBytes) } + /** + * The bytes as a direct [ByteBuffer]. The buffer is shared, not a copy: its position and limit + * belong to the caller, so duplicate it rather than relying on where a previous reader left it. + * + * Reading this property is the only access path that is checked against revocation, and the + * returned [ByteBuffer] is not. Its address cannot be cleared once handed out, so a [ByteBuffer] + * kept past the method that received a non-owning [ArrayBuffer] reads freed or relocated memory + * with no exception to warn you. Do not store it, and do not let it outlive the [ArrayBuffer] it + * came from: retain the [ArrayBuffer] and read [bytes] again, or copy the bytes with + * [arrayBufferWithCopiedBytes]. + * + * @throws IllegalStateException if the bytes were borrowed and the method that received this + * [ArrayBuffer] has already returned. See [isOwningBytes]. + */ public val bytes: ByteBuffer - get() = buffer + get() { + checkBytesValid() + return buffer + } + /** + * The capacity of the buffer in bytes, independent of the position and limit of [bytes]. + * + * @throws IllegalStateException if the bytes were borrowed and the method that received this + * [ArrayBuffer] has already returned. See [isOwningBytes]. + */ public val size: Int - get() = buffer.capacity() + get() { + checkBytesValid() + return buffer.capacity() + } + + private fun checkBytesValid() { + check(isBytesValid()) { + "ArrayBuffer: the bytes of a non-owning ArrayBuffer were accessed after the method " + + "that received it returned. Copy them with " + + "ArrayBuffer.arrayBufferWithCopiedBytes() to use them later." + } + } private external fun initHybrid(buffer: ByteBuffer, isOwningBytes: Boolean) + private external fun isBytesValid(): Boolean + public companion object { init { ReactNativeJniCommonSoLoader.staticInit() @@ -69,7 +110,11 @@ public class ArrayBuffer : HybridClassBase { return buffer } - /** @param source remaining bytes are copied into a new owning buffer */ + /** + * @param source the bytes between its position and limit are copied into a new owning buffer. + * Pass a buffer positioned at 0 with the limit at its capacity to copy all of it. The + * position and limit of `source` are left unchanged. + */ @JvmStatic @DoNotStrip public fun arrayBufferWithCopiedBytes(source: ByteBuffer): ArrayBuffer { @@ -83,8 +128,9 @@ public class ArrayBuffer : HybridClassBase { } /** - * @param source copied into a new owning buffer. Use to keep bytes from a non-owning argument - * after the call returns. + * @param source all [size] bytes are copied into a new owning buffer, regardless of the + * position and limit of its [bytes]. Use to keep bytes from a non-owning argument after the + * call returns. */ @JvmStatic @DoNotStrip @@ -102,8 +148,12 @@ public class ArrayBuffer : HybridClassBase { } /** - * @param buffer direct [ByteBuffer] to alias without copying. The caller must keep it valid for - * as long as this [ArrayBuffer] lives. + * Aliases an existing direct [ByteBuffer] without copying. The resulting [ArrayBuffer] reports + * [isOwningBytes] as `true`, so it may be retained and returned to JS — but it does not own the + * memory: the caller must keep `buffer` and whatever backs it valid for as long as the + * [ArrayBuffer], and any JS `ArrayBuffer` derived from it, is reachable. + * + * @param buffer direct [ByteBuffer] to alias without copying */ @JvmStatic @DoNotStrip diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/CMakeLists.txt b/packages/react-native/ReactAndroid/src/main/jni/react/jni/CMakeLists.txt index ee4912f976b..66ad89a3a2b 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/CMakeLists.txt +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/CMakeLists.txt @@ -39,7 +39,7 @@ add_library( target_merge_so(reactnativejni_common) target_include_directories(reactnativejni_common PUBLIC ../../) -target_link_libraries(reactnativejni_common fbjni folly_runtime react_cxxreact rrc_view) +target_link_libraries(reactnativejni_common fbjni folly_runtime react_bridging react_cxxreact rrc_view) target_compile_reactnative_options(reactnativejni_common PRIVATE) target_compile_options(reactnativejni_common PRIVATE -Wno-unused-lambda-capture) diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JArrayBuffer.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JArrayBuffer.cpp index ddc6ad895c7..241f032b9e6 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JArrayBuffer.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JArrayBuffer.cpp @@ -9,38 +9,29 @@ #include #include +#include #include #include +#include + #include "JByteBufferMutableBuffer.h" namespace facebook::react { namespace { -// Holds a copy of bytes borrowed from a JS ArrayBuffer. -class OwnedBytesBuffer final : public jsi::MutableBuffer { - public: - explicit OwnedBytesBuffer(std::vector bytes) noexcept - : bytes_(std::move(bytes)) {} - - size_t size() const override { - return bytes_.size(); - } - - uint8_t* data() override { - return bytes_.data(); - } - - private: - std::vector bytes_; -}; +const char* const kRevokedBorrowMessage = + "com.facebook.react.bridge.ArrayBuffer: the bytes of a non-owning ArrayBuffer " + "were accessed after the method that received it returned. Copy them with " + "ArrayBuffer.arrayBufferWithCopiedBytes() to use them later."; } // namespace void JArrayBuffer::registerNatives() { registerHybrid({ makeNativeMethod("initHybrid", JArrayBuffer::initHybrid), + makeNativeMethod("isBytesValid", JArrayBuffer::isBytesValid), }); } @@ -54,6 +45,23 @@ void JArrayBuffer::initHybrid( owningBytes != JNI_FALSE); } +jboolean JArrayBuffer::isBytesValid() { + return hasBytes() ? JNI_TRUE : JNI_FALSE; +} + +void JArrayBuffer::invalidate() noexcept { + if (!owningBytes_) { + buffer_.reset(); + } +} + +const std::shared_ptr& JArrayBuffer::mutableBuffer() const { + if (!hasBytes()) { + throw std::runtime_error(kRevokedBorrowMessage); + } + return buffer_; +} + jni::local_ref JArrayBuffer::create( jni::local_ref byteBuffer, std::shared_ptr buffer, @@ -66,12 +74,6 @@ jni::local_ref JArrayBuffer::create( jni::local_ref JArrayBuffer::createOwning( std::shared_ptr buffer) { - // NewDirectByteBuffer rejects a null address, which is what an empty - // jsi::ArrayBuffer reports, so empty buffers get an allocation of their own. - if (buffer->size() == 0) { - return create(jni::JByteBuffer::allocateDirect(0), std::move(buffer), true); - } - auto byteBuffer = jni::JByteBuffer::wrapBytes(buffer->data(), buffer->size()); return create(std::move(byteBuffer), std::move(buffer), true); } @@ -79,11 +81,8 @@ jni::local_ref JArrayBuffer::createOwning( jni::local_ref JArrayBuffer::createUnowned( void* bytes, size_t size) { - // NewDirectByteBuffer rejects a null address, which is what an empty - // jsi::ArrayBuffer reports, so empty buffers get an allocation of their own. - auto byteBuffer = size == 0 - ? jni::JByteBuffer::allocateDirect(0) - : jni::JByteBuffer::wrapBytes(static_cast(bytes), size); + auto byteBuffer = + jni::JByteBuffer::wrapBytes(static_cast(bytes), size); auto buffer = std::make_shared(byteBuffer); return create(std::move(byteBuffer), std::move(buffer), false); } @@ -102,16 +101,28 @@ jni::local_ref JArrayBuffer::createOwned( } std::shared_ptr JArrayBuffer::toJSBuffer( + jsi::Runtime& runtime, jni::alias_ref arrayBuffer) { auto* self = arrayBuffer->cthis(); + // create() runs the Kotlin constructor before setNativePointer, so a Java + // ArrayBuffer without a C++ peer is reachable if either step throws. + if (self == nullptr) { + throw jsi::JSError( + runtime, "com.facebook.react.bridge.ArrayBuffer has no native peer."); + } + if (!self->hasBytes()) { + throw jsi::JSError(runtime, kRevokedBorrowMessage); + } + + const auto& buffer = self->mutableBuffer(); if (self->owningBytes_) { - return self->buffer_; + return buffer; } // Borrowed bytes still belong to the inbound JS ArrayBuffer; copy them before // handing a new buffer back to JS. - auto bytes = std::span(self->buffer_->data(), self->buffer_->size()); - return std::make_shared( + auto bytes = std::span(buffer->data(), buffer->size()); + return std::make_shared( std::vector(bytes.begin(), bytes.end())); } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JArrayBuffer.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JArrayBuffer.h index f65ca283cc4..23029d35e75 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JArrayBuffer.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JArrayBuffer.h @@ -40,8 +40,31 @@ class JArrayBuffer : public jni::HybridClass { // Convert a module return value for rt.createArrayBuffer. Owning buffers pass // through; borrowed ones are copied because createArrayBuffer needs its own - // backing store. - static std::shared_ptr toJSBuffer(jni::alias_ref arrayBuffer); + // backing store. Raises a jsi::JSError if the buffer has no native peer or + // its borrow has been revoked. + static std::shared_ptr toJSBuffer(jsi::Runtime &runtime, jni::alias_ref arrayBuffer); + + // Revokes access to borrowed bytes. Called when the call frame that lent the + // bytes unwinds, so a module that retained a non-owning ArrayBuffer gets an + // exception instead of reading memory the JS heap has moved or freed. Owning + // buffers are unaffected. + void invalidate() noexcept; + + // The bytes this buffer was created over. Throws if a borrow has since been + // revoked by invalidate(). + const std::shared_ptr &mutableBuffer() const; + + // Whether the bytes are still reachable, i.e. this is an owning buffer or a + // borrow that invalidate() has not revoked. + bool hasBytes() const noexcept + { + return buffer_ != nullptr; + } + + bool isOwningBytes() const noexcept + { + return owningBytes_; + } JArrayBuffer(std::shared_ptr buffer, bool owningBytes) noexcept : buffer_(std::move(buffer)), owningBytes_(owningBytes) @@ -54,6 +77,8 @@ class JArrayBuffer : public jni::HybridClass { static void initHybrid(jni::alias_ref jobj, jni::alias_ref buffer, jboolean owningBytes); + jboolean isBytesValid(); + static jni::local_ref create(jni::local_ref byteBuffer, std::shared_ptr buffer, bool owningBytes); diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JByteBufferMutableBuffer.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JByteBufferMutableBuffer.h index 56b82bbd3ed..6d7558dcd2f 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JByteBufferMutableBuffer.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JByteBufferMutableBuffer.h @@ -45,6 +45,12 @@ class JByteBufferMutableBuffer final : public jsi::MutableBuffer { } uint8_t *data() override { + // GetDirectBufferAddress may report null for a zero-capacity direct buffer, + // which getDirectBytes turns into an exception. An empty buffer has no bytes + // to address, so report that directly instead. + if (byteBuffer_->getDirectSize() == 0) { + return nullptr; + } return byteBuffer_->getDirectBytes(); } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/test/JArrayBufferTest.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/jni/test/JArrayBufferTest.cpp new file mode 100644 index 00000000000..8eebde8b2ec --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/test/JArrayBufferTest.cpp @@ -0,0 +1,164 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include +#include + +#include + +#include +#include +#include +#include + +namespace facebook::react { + +namespace { + +class TestBuffer final : public jsi::MutableBuffer { + public: + explicit TestBuffer(std::vector bytes) noexcept + : bytes_(std::move(bytes)) {} + + size_t size() const override { + return bytes_.size(); + } + + uint8_t* data() override { + return bytes_.data(); + } + + private: + std::vector bytes_; +}; + +} // namespace + +/* + * The static factories and toJSBuffer all need a live JavaVM, so the coverage + * available host-side is the ownership state machine itself: which buffers + * invalidate() may revoke, and whether mutableBuffer() reports a revoked borrow + * instead of handing out a dangling pointer. The JNI section at the bottom of + * this file covers the direct-ByteBuffer adapter on device. + */ + +TEST(JArrayBufferTest, owningBufferExposesItsBytes) { + auto buffer = std::make_shared(std::vector{1, 2, 3}); + JArrayBuffer arrayBuffer{buffer, true}; + + EXPECT_TRUE(arrayBuffer.isOwningBytes()); + EXPECT_EQ(arrayBuffer.mutableBuffer(), buffer); +} + +TEST(JArrayBufferTest, borrowedBufferExposesItsBytesBeforeInvalidation) { + auto buffer = std::make_shared(std::vector{1, 2, 3}); + JArrayBuffer arrayBuffer{buffer, false}; + + EXPECT_FALSE(arrayBuffer.isOwningBytes()); + EXPECT_EQ(arrayBuffer.mutableBuffer(), buffer); +} + +/* + * Bug this catches: without the revocation, a module that stored a non-owning + * ArrayBuffer keeps a direct ByteBuffer over JS-heap bytes that the call frame + * no longer keeps alive, and every later read silently returns whatever now + * occupies that memory. + */ +TEST(JArrayBufferTest, invalidateRevokesABorrow) { + auto buffer = std::make_shared(std::vector{1, 2, 3}); + JArrayBuffer arrayBuffer{buffer, false}; + + arrayBuffer.invalidate(); + + EXPECT_THROW(arrayBuffer.mutableBuffer(), std::runtime_error); +} + +TEST(JArrayBufferTest, invalidateLeavesAnOwningBufferUsable) { + auto buffer = std::make_shared(std::vector{1, 2, 3}); + JArrayBuffer arrayBuffer{buffer, true}; + + arrayBuffer.invalidate(); + + EXPECT_EQ(arrayBuffer.mutableBuffer(), buffer); +} + +TEST(JArrayBufferTest, invalidateIsIdempotent) { + auto buffer = std::make_shared(std::vector{1, 2, 3}); + JArrayBuffer arrayBuffer{buffer, false}; + + arrayBuffer.invalidate(); + arrayBuffer.invalidate(); + + EXPECT_THROW(arrayBuffer.mutableBuffer(), std::runtime_error); +} + +// Revoking a borrow must drop the last reference this object holds, so an +// aliasing adapter (and the JNI global ref inside it) is torn down with the +// call frame rather than at the whim of the Java GC. +TEST(JArrayBufferTest, invalidateReleasesTheBorrowedBuffer) { + auto buffer = std::make_shared(std::vector{1, 2, 3}); + std::weak_ptr weakBuffer = buffer; + JArrayBuffer arrayBuffer{std::move(buffer), false}; + + arrayBuffer.invalidate(); + + EXPECT_TRUE(weakBuffer.expired()); +} + +#ifdef __ANDROID__ + +/* + * JByteBufferMutableBuffer is the adapter every ArrayBuffer is built on, and it + * is pure JNI: size() and data() read a direct java.nio.ByteBuffer. That needs + * a live JavaVM, so it is only reachable in the on-device variant of this + * target. + * + * The Kotlin peer itself is not testable here — this APK carries no RN Java + * classes — so ArrayBuffer.kt stays covered by the Robolectric test. + */ + +TEST(JByteBufferMutableBufferTest, exposesTheAddressAndSizeOfADirectBuffer) { + auto byteBuffer = jni::JByteBuffer::allocateDirect(4); + auto* bytes = byteBuffer->getDirectBytes(); + const uint8_t expected[] = {1, 2, 3, 4}; + std::memcpy(bytes, expected, sizeof(expected)); + + JByteBufferMutableBuffer buffer{byteBuffer}; + + EXPECT_EQ(buffer.size(), sizeof(expected)); + EXPECT_EQ(buffer.data(), bytes); + EXPECT_EQ(std::memcmp(buffer.data(), expected, sizeof(expected)), 0); +} + +TEST(JByteBufferMutableBufferTest, aliasesWrappedBytesWithoutCopying) { + uint8_t bytes[] = {1, 2, 3, 4}; + auto byteBuffer = jni::JByteBuffer::wrapBytes(bytes, sizeof(bytes)); + + JByteBufferMutableBuffer buffer{byteBuffer}; + + EXPECT_EQ(buffer.data(), bytes); + EXPECT_EQ(buffer.size(), sizeof(bytes)); +} + +/* + * Bug this catches: GetDirectBufferAddress reports null for a zero-capacity + * direct buffer, and getDirectBytes turns that into a JNI exception. Without + * the short-circuit in data(), a zero-length ArrayBuffer — which JS can hand a + * TurboModule at any time — throws out of a path that has no business failing. + */ +TEST(JByteBufferMutableBufferTest, reportsNoDataForAnEmptyBuffer) { + auto byteBuffer = jni::JByteBuffer::allocateDirect(0); + + JByteBufferMutableBuffer buffer{byteBuffer}; + + EXPECT_EQ(buffer.size(), 0u); + EXPECT_EQ(buffer.data(), nullptr); +} + +#endif // __ANDROID__ + +} // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/ArrayBufferTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/ArrayBufferTest.kt new file mode 100644 index 00000000000..8ebbd6f1c5e --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/ArrayBufferTest.kt @@ -0,0 +1,195 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.bridge + +import com.facebook.testutils.shadows.ShadowArrayBuffer +import com.facebook.testutils.shadows.ShadowNativeLoader +import com.facebook.testutils.shadows.ShadowSoLoader +import java.nio.ByteBuffer +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Assertions.assertThatThrownBy +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config( + shadows = [ShadowSoLoader::class, ShadowNativeLoader::class, ShadowArrayBuffer::class], +) +class ArrayBufferTest { + + @Test + fun constructorAllocatesZeroFilledBytes() { + val buffer = ArrayBuffer(4) + + assertThat(buffer.size).isEqualTo(4) + assertThat(buffer.bytes.isDirect).isTrue() + assertThat(bytesOf(buffer)).containsExactly(0, 0, 0, 0) + assertThat(buffer.isOwningBytes).isTrue() + } + + @Test + fun constructorAcceptsZeroLength() { + val buffer = ArrayBuffer(0) + + assertThat(buffer.size).isEqualTo(0) + assertThat(buffer.bytes.capacity()).isEqualTo(0) + } + + @Test + fun constructorRejectsNegativeSize() { + assertThatThrownBy { ArrayBuffer(-1) } + .isInstanceOf(IllegalArgumentException::class.java) + .hasMessageContaining("must not be negative") + } + + @Test + fun arrayBufferWithLengthMatchesConstructor() { + val buffer = ArrayBuffer.arrayBufferWithLength(3) + + assertThat(buffer.size).isEqualTo(3) + assertThat(buffer.isOwningBytes).isTrue() + } + + @Test + fun sizeIsCapacityAndIgnoresPositionAndLimit() { + val buffer = ArrayBuffer(4) + buffer.bytes.position(1) + buffer.bytes.limit(2) + + assertThat(buffer.size).isEqualTo(4) + } + + @Test + fun bytesReturnsTheSameSharedBuffer() { + val buffer = ArrayBuffer(2) + + assertThat(buffer.bytes).isSameAs(buffer.bytes) + } + + @Test + fun copiesByteArray() { + val buffer = ArrayBuffer.arrayBufferWithCopiedBytes(byteArrayOf(1, 2, 3)) + + assertThat(buffer.size).isEqualTo(3) + assertThat(bytesOf(buffer)).containsExactly(1, 2, 3) + assertThat(buffer.isOwningBytes).isTrue() + } + + @Test + fun copiesEmptyByteArray() { + val buffer = ArrayBuffer.arrayBufferWithCopiedBytes(ByteArray(0)) + + assertThat(buffer.size).isEqualTo(0) + } + + @Test + fun copiesRemainingBytesOfByteBuffer() { + val source = ByteBuffer.allocateDirect(5) + source.put(byteArrayOf(1, 2, 3, 4, 5)) + source.position(1) + source.limit(4) + + val buffer = ArrayBuffer.arrayBufferWithCopiedBytes(source) + + assertThat(buffer.size).isEqualTo(3) + assertThat(bytesOf(buffer)).containsExactly(2, 3, 4) + // The source position and limit are left untouched. + assertThat(source.position()).isEqualTo(1) + assertThat(source.limit()).isEqualTo(4) + } + + @Test + fun copiesFromNonDirectByteBuffer() { + val source = ByteBuffer.wrap(byteArrayOf(7, 8)) + + val buffer = ArrayBuffer.arrayBufferWithCopiedBytes(source) + + assertThat(bytesOf(buffer)).containsExactly(7, 8) + assertThat(buffer.bytes.isDirect).isTrue() + } + + @Test + fun copiesAllBytesOfArrayBufferRegardlessOfPositionAndLimit() { + val source = ArrayBuffer.arrayBufferWithCopiedBytes(byteArrayOf(1, 2, 3, 4)) + source.bytes.position(2) + source.bytes.limit(3) + + val buffer = ArrayBuffer.arrayBufferWithCopiedBytes(source) + + assertThat(buffer.size).isEqualTo(4) + assertThat(bytesOf(buffer)).containsExactly(1, 2, 3, 4) + } + + @Test + fun copyOfArrayBufferDoesNotAliasTheSource() { + val source = ArrayBuffer.arrayBufferWithCopiedBytes(byteArrayOf(1, 2)) + + val buffer = ArrayBuffer.arrayBufferWithCopiedBytes(source) + source.bytes.put(0, 9) + + assertThat(bytesOf(buffer)).containsExactly(1, 2) + } + + @Test + fun copiesZeroLengthArrayBuffer() { + val buffer = ArrayBuffer.arrayBufferWithCopiedBytes(ArrayBuffer(0)) + + assertThat(buffer.size).isEqualTo(0) + } + + @Test + fun aliasesOwnedDirectByteBuffer() { + val source = ByteBuffer.allocateDirect(2) + source.put(byteArrayOf(1, 2)) + + val buffer = ArrayBuffer.arrayBufferWithOwnedBytes(source) + source.put(0, 9) + + assertThat(buffer.bytes).isSameAs(source) + assertThat(buffer.bytes.get(0)).isEqualTo(9.toByte()) + assertThat(buffer.isOwningBytes).isTrue() + } + + @Test + fun arrayBufferWithOwnedBytesRejectsNonDirectByteBuffer() { + assertThatThrownBy { + ArrayBuffer.arrayBufferWithOwnedBytes(ByteBuffer.wrap(byteArrayOf(1, 2))) + } + .isInstanceOf(IllegalArgumentException::class.java) + .hasMessageContaining("requires a direct ByteBuffer") + } + + /** + * Once the native peer revokes a borrow — which it does when the method that received a + * non-owning [ArrayBuffer] returns — reading the bytes must fail loudly instead of touching freed + * memory. + */ + @Test + fun accessingBytesAfterTheBorrowIsRevokedThrows() { + val buffer = ArrayBuffer(4) + ShadowArrayBuffer.invalidate(buffer) + + assertThatThrownBy { buffer.bytes } + .isInstanceOf(IllegalStateException::class.java) + .hasMessageContaining("non-owning ArrayBuffer") + assertThatThrownBy { buffer.size } + .isInstanceOf(IllegalStateException::class.java) + .hasMessageContaining("non-owning ArrayBuffer") + } + + private fun bytesOf(buffer: ArrayBuffer): ByteArray { + val view = buffer.bytes.duplicate() + view.position(0) + view.limit(buffer.size) + val bytes = ByteArray(view.remaining()) + view.get(bytes) + return bytes + } +} diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/shadows/ShadowArrayBuffer.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/shadows/ShadowArrayBuffer.kt new file mode 100644 index 00000000000..f0b7378f6f8 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/testutils/shadows/ShadowArrayBuffer.kt @@ -0,0 +1,40 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.testutils.shadows + +import com.facebook.react.bridge.ArrayBuffer +import java.nio.ByteBuffer +import org.robolectric.annotation.Implementation +import org.robolectric.annotation.Implements +import org.robolectric.shadow.api.Shadow + +/** + * Stands in for the C++ peer of [ArrayBuffer], which Robolectric cannot load. Tracks the + * borrow-validity flag the peer owns so the Kotlin-side ownership contract can be tested. + */ +@Implements(ArrayBuffer::class) +open class ShadowArrayBuffer { + + private var bytesValid = true + + // The parameters are unused but must stay: Robolectric matches a shadow method to the native one + // by signature. + @Suppress("UNUSED_PARAMETER") + @Implementation + fun initHybrid(buffer: ByteBuffer, isOwningBytes: Boolean) = Unit + + @Implementation fun isBytesValid(): Boolean = bytesValid + + companion object { + /** Simulates the native peer revoking a borrow when the call frame that lent the bytes ends. */ + @JvmStatic + fun invalidate(arrayBuffer: ArrayBuffer) { + (Shadow.extract(arrayBuffer) as ShadowArrayBuffer).bytesValid = false + } + } +} diff --git a/packages/react-native/ReactCommon/react/bridging/ArrayBuffer.h b/packages/react-native/ReactCommon/react/bridging/ArrayBuffer.h index 93592f2779a..8739fb2881c 100644 --- a/packages/react-native/ReactCommon/react/bridging/ArrayBuffer.h +++ b/packages/react-native/ReactCommon/react/bridging/ArrayBuffer.h @@ -140,15 +140,6 @@ class AsyncArrayBuffer { return buffer_; } - private: - explicit AsyncArrayBuffer(std::shared_ptr buffer) noexcept : buffer_{std::move(buffer)} {} - - static AsyncArrayBuffer copyBytes(jsi::Runtime &rt, const jsi::ArrayBuffer &buffer) - { - auto bytes = std::span(buffer.data(rt), buffer.size(rt)); - return wrap(std::vector(bytes.begin(), bytes.end())); - } - // Best-effort detached check. jsi::ArrayBuffer::detached relies on the JS-level // `detached` property, which some runtimes (e.g. Hermes) don't implement and // signal by throwing. In that case we silently skip the check rather than @@ -166,6 +157,15 @@ class AsyncArrayBuffer { } } + private: + explicit AsyncArrayBuffer(std::shared_ptr buffer) noexcept : buffer_{std::move(buffer)} {} + + static AsyncArrayBuffer copyBytes(jsi::Runtime &rt, const jsi::ArrayBuffer &buffer) + { + auto bytes = std::span(buffer.data(rt), buffer.size(rt)); + return wrap(std::vector(bytes.begin(), bytes.end())); + } + std::shared_ptr buffer_; }; diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaTurboModule.cpp b/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaTurboModule.cpp index efd329a413c..0db4927a633 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaTurboModule.cpp +++ b/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaTurboModule.cpp @@ -63,6 +63,12 @@ JavaTurboModule::~JavaTurboModule() { namespace { +// A method whose result is delivered synchronously, so JS-heap bytes passed as +// arguments stay valid for the duration of the call. +bool isSyncMethod(TurboModuleMethodValueKind valueKind) { + return valueKind != VoidKind && valueKind != PromiseKind; +} + struct JNIArgs { JNIArgs(size_t count) : args(count) {} JNIArgs(const JNIArgs&) = delete; @@ -73,8 +79,19 @@ struct JNIArgs { std::vector args; std::vector globalRefs; + // ArrayBuffers aliasing JS-heap bytes lent for this call only. Local refs are + // enough because bytes are only lent on the synchronous path, where this + // JNIArgs is destroyed in the same native frame that created the refs. + std::vector> borrowedBuffers; ~JNIArgs() { + // Revoke the borrows before the call frame that lent the bytes unwinds, so + // a module that retained one cannot read freed or relocated memory. Runs on + // the throw path too. + for (auto& borrowedBuffer : borrowedBuffers) { + borrowedBuffer->cthis()->invalidate(); + } + JNIEnv* env = jni::Environment::current(); for (auto globalRef : globalRefs) { env->DeleteGlobalRef(globalRef); @@ -315,10 +332,10 @@ JNIArgs convertJSIArgsToJNIArgs( auto& jargs = jniArgs.args; auto& globalRefs = jniArgs.globalRefs; - auto isSyncInvocation = valueKind != VoidKind && valueKind != PromiseKind; + auto isSyncInvocation = isSyncMethod(valueKind); auto makeGlobalIfNecessary = [&](jobject obj) { - if (valueKind == VoidKind || valueKind == PromiseKind) { + if (!isSyncInvocation) { jobject globalObj = env->NewGlobalRef(obj); globalRefs.push_back(globalObj); env->DeleteLocalRef(obj); @@ -449,11 +466,8 @@ JNIArgs convertJSIArgsToJNIArgs( } auto arrayBuffer = arg->getObject(rt).getArrayBuffer(rt); - if (arrayBuffer.detached(rt)) { - throw jsi::JSError( - rt, - "JavaTurboModule::convertJSIArgsToJNIArgs: ArrayBuffer is detached."); - } + AsyncArrayBuffer::throwIfDetached( + rt, arrayBuffer, "JavaTurboModule::convertJSIArgsToJNIArgs"); auto size = arrayBuffer.size(rt); if (size > static_cast(std::numeric_limits::max())) { @@ -462,22 +476,40 @@ JNIArgs convertJSIArgsToJNIArgs( "JavaTurboModule::convertJSIArgsToJNIArgs: ArrayBuffer exceeds maximum size."); } + // Runtimes without a native buffer for this ArrayBuffer return nullptr, + // but the Static Hermes tracing runtime throws instead, and argument + // conversion runs outside any std::exception handler. Treat a failed + // probe as "no native buffer" so a traced session copies the bytes rather + // than aborting the process. + std::shared_ptr mutableBuffer; + try { + mutableBuffer = arrayBuffer.tryGetMutableBuffer(rt); + } catch (const std::exception&) { + mutableBuffer = nullptr; + } + + bool borrowsJSBytes = false; auto jArrayBuffer = [&]() { // Backed by a native buffer: alias it and retain its owner, so the // bytes stay valid for as long as the module holds the ArrayBuffer. - if (auto mutableBuffer = arrayBuffer.tryGetMutableBuffer(rt)) { + if (mutableBuffer) { return JArrayBuffer::createOwning(std::move(mutableBuffer)); } // JS heap bytes on a synchronous call: lend them for the duration of // the call. if (isSyncInvocation) { + borrowsJSBytes = true; return JArrayBuffer::createUnowned(arrayBuffer.data(rt), size); } // JS heap bytes that outlive the call: copy. return JArrayBuffer::createOwned(arrayBuffer.data(rt), size); }(); + + if (borrowsJSBytes) { + jniArgs.borrowedBuffers.push_back(jni::make_local(jArrayBuffer)); + } jarg->l = makeGlobalIfNecessary(jArrayBuffer.release()); } else { throw JavaTurboModuleInvalidArgumentTypeException( @@ -567,7 +599,7 @@ jsi::Value JavaTurboModule::invokeJavaMethod( const char* methodName = methodNameStr.c_str(); const char* moduleName = name_.c_str(); - bool isMethodSync = valueKind != VoidKind && valueKind != PromiseKind; + bool isMethodSync = isSyncMethod(valueKind); if (isMethodSync) { TMPL::syncMethodCallStart(moduleName, methodName); @@ -1021,11 +1053,20 @@ jsi::Value JavaTurboModule::invokeJavaMethod( jsi::Value returnValue = jsi::Value::null(); if (returnObject != nullptr) { - auto jArrayBuffer = jni::adopt_local( - static_cast(returnObject)); + auto returnRef = jni::adopt_local(returnObject); + if (!returnRef->isInstanceOf(JArrayBuffer::javaClassStatic())) { + throw jsi::JSError( + runtime, + "JavaTurboModule::invokeJavaMethod: expected " + methodNameStr + + " to return a com.facebook.react.bridge.ArrayBuffer."); + } + + auto jArrayBuffer = + jni::static_ref_cast(returnRef); returnValue = { runtime, - jsi::ArrayBuffer{runtime, JArrayBuffer::toJSBuffer(jArrayBuffer)}}; + jsi::ArrayBuffer{ + runtime, JArrayBuffer::toJSBuffer(runtime, jArrayBuffer)}}; } TMPL::syncMethodCallReturnConversionEnd(moduleName, methodName); diff --git a/packages/rn-tester/js/examples/TurboModule/SampleTurboModuleExample.js b/packages/rn-tester/js/examples/TurboModule/SampleTurboModuleExample.js index f7e8373a995..aab25aacd46 100644 --- a/packages/rn-tester/js/examples/TurboModule/SampleTurboModuleExample.js +++ b/packages/rn-tester/js/examples/TurboModule/SampleTurboModuleExample.js @@ -114,7 +114,15 @@ class SampleTurboModuleExample extends React.Component<{}, State> { getArrayBuffer: () => { const input = new Uint8Array([1, 2, 3, 4]); const result = NativeSampleTurboModule.getArrayBuffer(input.buffer); - return Array.from(new Uint8Array(result)); + // The native module mutates the bytes in place and returns the same buffer, + // but a returned ArrayBuffer is always a new JS object. Whether it aliases + // the input bytes depends on whether the platform lent them to native or + // copied them. + return { + bytes: Array.from(new Uint8Array(result)), + isSameObject: result === input.buffer, + aliasesInput: Array.from(input).toString() === [2, 4, 6, 8].toString(), + }; }, createNativeBuffer: () => NativeSampleTurboModule.createNativeBuffer(8).byteLength, diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api index 0b830c61fc7..828513e24e8 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api @@ -1652,6 +1652,7 @@ class facebook::react::AsyncArrayBuffer { public static facebook::react::AsyncArrayBuffer copy(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer); public static facebook::react::AsyncArrayBuffer wrap(std::shared_ptr buffer) noexcept; public static facebook::react::AsyncArrayBuffer wrap(std::vector bytes); + public static void throwIfDetached(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer, const char* callerName); public std::shared_ptr getMutableBuffer() const noexcept; public uint8_t* data() noexcept; public ~AsyncArrayBuffer() = default; @@ -2794,12 +2795,16 @@ class facebook::react::IntersectionObserverState { class facebook::react::JArrayBuffer : public jni::HybridClass { public JArrayBuffer(std::shared_ptr buffer, bool owningBytes) noexcept; + public bool hasBytes() const noexcept; + public bool isOwningBytes() const noexcept; + public const std::shared_ptr& mutableBuffer() const; public static constexpr auto kJavaDescriptor; public static jni::local_ref createOwned(const void* bytes, size_t size); public static jni::local_ref createOwning(std::shared_ptr buffer); public static jni::local_ref createUnowned(void* bytes, size_t size); - public static std::shared_ptr toJSBuffer(jni::alias_ref arrayBuffer); + public static std::shared_ptr toJSBuffer(facebook::jsi::Runtime& runtime, jni::alias_ref arrayBuffer); public static void registerNatives(); + public void invalidate() noexcept; } class facebook::react::JBindingsInstaller : public jni::HybridClass, public facebook::react::BindingsInstaller { diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api index 5c0f90207fe..39e6d87b0d0 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api @@ -1646,6 +1646,7 @@ class facebook::react::AsyncArrayBuffer { public static facebook::react::AsyncArrayBuffer copy(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer); public static facebook::react::AsyncArrayBuffer wrap(std::shared_ptr buffer) noexcept; public static facebook::react::AsyncArrayBuffer wrap(std::vector bytes); + public static void throwIfDetached(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer, const char* callerName); public std::shared_ptr getMutableBuffer() const noexcept; public uint8_t* data() noexcept; public ~AsyncArrayBuffer() = default; @@ -2752,12 +2753,16 @@ class facebook::react::IntersectionObserverState { class facebook::react::JArrayBuffer : public jni::HybridClass { public JArrayBuffer(std::shared_ptr buffer, bool owningBytes) noexcept; + public bool hasBytes() const noexcept; + public bool isOwningBytes() const noexcept; + public const std::shared_ptr& mutableBuffer() const; public static constexpr auto kJavaDescriptor; public static jni::local_ref createOwned(const void* bytes, size_t size); public static jni::local_ref createOwning(std::shared_ptr buffer); public static jni::local_ref createUnowned(void* bytes, size_t size); - public static std::shared_ptr toJSBuffer(jni::alias_ref arrayBuffer); + public static std::shared_ptr toJSBuffer(facebook::jsi::Runtime& runtime, jni::alias_ref arrayBuffer); public static void registerNatives(); + public void invalidate() noexcept; } class facebook::react::JBindingsInstaller : public jni::HybridClass, public facebook::react::BindingsInstaller { diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api index f8f8235b1b0..f5dcbb21b54 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api @@ -1650,6 +1650,7 @@ class facebook::react::AsyncArrayBuffer { public static facebook::react::AsyncArrayBuffer copy(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer); public static facebook::react::AsyncArrayBuffer wrap(std::shared_ptr buffer) noexcept; public static facebook::react::AsyncArrayBuffer wrap(std::vector bytes); + public static void throwIfDetached(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer, const char* callerName); public std::shared_ptr getMutableBuffer() const noexcept; public uint8_t* data() noexcept; public ~AsyncArrayBuffer() = default; @@ -2791,12 +2792,16 @@ class facebook::react::IntersectionObserverState { class facebook::react::JArrayBuffer : public jni::HybridClass { public JArrayBuffer(std::shared_ptr buffer, bool owningBytes) noexcept; + public bool hasBytes() const noexcept; + public bool isOwningBytes() const noexcept; + public const std::shared_ptr& mutableBuffer() const; public static constexpr auto kJavaDescriptor; public static jni::local_ref createOwned(const void* bytes, size_t size); public static jni::local_ref createOwning(std::shared_ptr buffer); public static jni::local_ref createUnowned(void* bytes, size_t size); - public static std::shared_ptr toJSBuffer(jni::alias_ref arrayBuffer); + public static std::shared_ptr toJSBuffer(facebook::jsi::Runtime& runtime, jni::alias_ref arrayBuffer); public static void registerNatives(); + public void invalidate() noexcept; } class facebook::react::JBindingsInstaller : public jni::HybridClass, public facebook::react::BindingsInstaller { diff --git a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api index 554e89df9e3..fc06c4b8f06 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api @@ -4244,6 +4244,7 @@ class facebook::react::AsyncArrayBuffer { public static facebook::react::AsyncArrayBuffer copy(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer); public static facebook::react::AsyncArrayBuffer wrap(std::shared_ptr buffer) noexcept; public static facebook::react::AsyncArrayBuffer wrap(std::vector bytes); + public static void throwIfDetached(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer, const char* callerName); public std::shared_ptr getMutableBuffer() const noexcept; public uint8_t* data() noexcept; public ~AsyncArrayBuffer() = default; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api index b7b6b8a85f1..44a2f88d865 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api @@ -4231,6 +4231,7 @@ class facebook::react::AsyncArrayBuffer { public static facebook::react::AsyncArrayBuffer copy(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer); public static facebook::react::AsyncArrayBuffer wrap(std::shared_ptr buffer) noexcept; public static facebook::react::AsyncArrayBuffer wrap(std::vector bytes); + public static void throwIfDetached(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer, const char* callerName); public std::shared_ptr getMutableBuffer() const noexcept; public uint8_t* data() noexcept; public ~AsyncArrayBuffer() = default; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api index 4a07179e470..ae987d7903f 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api @@ -4242,6 +4242,7 @@ class facebook::react::AsyncArrayBuffer { public static facebook::react::AsyncArrayBuffer copy(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer); public static facebook::react::AsyncArrayBuffer wrap(std::shared_ptr buffer) noexcept; public static facebook::react::AsyncArrayBuffer wrap(std::vector bytes); + public static void throwIfDetached(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer, const char* callerName); public std::shared_ptr getMutableBuffer() const noexcept; public uint8_t* data() noexcept; public ~AsyncArrayBuffer() = default; diff --git a/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api index ac7b12edbf9..e28f3bd7028 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api @@ -976,6 +976,7 @@ class facebook::react::AsyncArrayBuffer { public static facebook::react::AsyncArrayBuffer copy(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer); public static facebook::react::AsyncArrayBuffer wrap(std::shared_ptr buffer) noexcept; public static facebook::react::AsyncArrayBuffer wrap(std::vector bytes); + public static void throwIfDetached(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer, const char* callerName); public std::shared_ptr getMutableBuffer() const noexcept; public uint8_t* data() noexcept; public ~AsyncArrayBuffer() = default; diff --git a/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api index 088372f7849..1c421afcdf7 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api @@ -971,6 +971,7 @@ class facebook::react::AsyncArrayBuffer { public static facebook::react::AsyncArrayBuffer copy(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer); public static facebook::react::AsyncArrayBuffer wrap(std::shared_ptr buffer) noexcept; public static facebook::react::AsyncArrayBuffer wrap(std::vector bytes); + public static void throwIfDetached(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer, const char* callerName); public std::shared_ptr getMutableBuffer() const noexcept; public uint8_t* data() noexcept; public ~AsyncArrayBuffer() = default; diff --git a/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api index d248d7df3aa..2b46b26d7b0 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api @@ -974,6 +974,7 @@ class facebook::react::AsyncArrayBuffer { public static facebook::react::AsyncArrayBuffer copy(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer); public static facebook::react::AsyncArrayBuffer wrap(std::shared_ptr buffer) noexcept; public static facebook::react::AsyncArrayBuffer wrap(std::vector bytes); + public static void throwIfDetached(facebook::jsi::Runtime& rt, const facebook::jsi::ArrayBuffer& buffer, const char* callerName); public std::shared_ptr getMutableBuffer() const noexcept; public uint8_t* data() noexcept; public ~AsyncArrayBuffer() = default;