From 6123612ccb15108064809510b583d1a1ef70bbbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20=C5=BBelawski?= Date: Tue, 1 Dec 2026 18:16:16 +0100 Subject: [PATCH 1/5] Fix crash when a native task throws a jsi::JSError of another runtime A native callback that the RuntimeScheduler runs on the JS thread can let a jsi::JSError of another jsi::Runtime escape. The error handlers then pass its value, which belongs to that other runtime, to ErrorUtils on the React Native runtime, and Hermes crashes. Task::execute now rethrows a jsi::JSError that escapes a raw callback as a new Error created on the React Native runtime, with the message and stack of the original error. jsi::JSError keeps both as std::string, so reading them does not touch the other runtime. --- .../react/renderer/runtimescheduler/Task.cpp | 16 +++++++- .../tests/RuntimeSchedulerTest.cpp | 40 +++++++++++++++++++ .../runtimescheduler/tests/StubErrorUtils.h | 19 +++++++++ 3 files changed, 74 insertions(+), 1 deletion(-) diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/Task.cpp b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/Task.cpp index fced88bb4079..9646bcb2b4d6 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/Task.cpp +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/Task.cpp @@ -17,6 +17,16 @@ inline uint64_t getNextId() noexcept { return nextId++; } +jsi::JSError recreateJSErrorInRuntime( + jsi::Runtime& runtime, + const jsi::JSError& error) { + auto errorObject = + jsi::JSError(runtime, error.getMessage()).value().getObject(runtime); + errorObject.setProperty(runtime, "stack", error.getStack()); + return { + jsi::Value(std::move(errorObject)), error.getMessage(), error.getStack()}; +} + } // namespace Task::Task( @@ -57,7 +67,11 @@ jsi::Value Task::execute(jsi::Runtime& runtime, bool didUserCallbackTimeout) { .call(runtime, {didUserCallbackTimeout}); } else { // Calling a raw callback - std::get(originalCallback)(runtime); + try { + std::get(originalCallback)(runtime); + } catch (const jsi::JSError& error) { + throw recreateJSErrorInRuntime(runtime, error); + } } return result; diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp index 5d1d3499804d..5325f6772240 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp @@ -908,6 +908,46 @@ TEST_P(RuntimeSchedulerTest, handlingError) { EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1); } +TEST_P(RuntimeSchedulerTest, handlingErrorOfAnotherRuntimeInRawCallback) { + auto anotherRuntime = facebook::hermes::makeHermesRuntime(); + bool didRunTask = false; + + runtimeScheduler_->scheduleTask( + SchedulerPriority::NormalPriority, [&](jsi::Runtime& /*unused*/) { + didRunTask = true; + anotherRuntime->evaluateJavaScript( + std::make_shared( + "throw new Error('Error of another runtime');"), + "anotherRuntime.js"); + }); + + stubQueue_->tick(); + + EXPECT_TRUE(didRunTask); + EXPECT_EQ(stubQueue_->size(), 0); + EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1); + EXPECT_EQ( + stubErrorUtils_->getLastReportedErrorMessage(), + "Error of another runtime"); +} + +TEST_P(RuntimeSchedulerTest, handlingErrorInRawCallback) { + bool didRunTask = false; + + runtimeScheduler_->scheduleTask( + SchedulerPriority::NormalPriority, [&](jsi::Runtime& runtime) { + didRunTask = true; + throw jsi::JSError(runtime, "Test error"); + }); + + stubQueue_->tick(); + + EXPECT_TRUE(didRunTask); + EXPECT_EQ(stubQueue_->size(), 0); + EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1); + EXPECT_EQ(stubErrorUtils_->getLastReportedErrorMessage(), "Test error"); +} + TEST_P(RuntimeSchedulerTest, clearsQueuesOnError) { // Only for event loop if (!GetParam()) { diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubErrorUtils.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubErrorUtils.h index 4d82dc1df680..364e13e7ff76 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubErrorUtils.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubErrorUtils.h @@ -10,6 +10,8 @@ #include #include +#include + namespace facebook::react { /* @@ -48,6 +50,7 @@ class StubErrorUtils : public jsi::HostObject { [this]( jsi::Runtime &runtime, const jsi::Value &, const jsi::Value *arguments, size_t) noexcept -> jsi::Value { reportFatalCallCount_++; + lastReportedErrorMessage_ = getErrorMessage(runtime, arguments[0]); return jsi::Value::undefined(); }); } @@ -60,8 +63,24 @@ class StubErrorUtils : public jsi::HostObject { return reportFatalCallCount_; } + const std::string &getLastReportedErrorMessage() const + { + return lastReportedErrorMessage_; + } + private: + static std::string getErrorMessage(jsi::Runtime &runtime, const jsi::Value &error) + { + if (!error.isObject() || + !error.getObject(runtime).instanceOf(runtime, runtime.global().getPropertyAsFunction(runtime, "Error"))) { + return ""; + } + auto message = error.getObject(runtime).getProperty(runtime, "message"); + return message.isString() ? message.getString(runtime).utf8(runtime) : ""; + } + int reportFatalCallCount_; + std::string lastReportedErrorMessage_; }; } // namespace facebook::react From 629641a1e060e5b36285bb12f2762d9508654f82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20=C5=BBelawski?= Date: Tue, 1 Dec 2026 23:03:49 +0100 Subject: [PATCH 2/5] Add tests for every way a jsi::JSError of another runtime can reach React Native ReactInstanceTest covers each way a native callback can let a jsi::JSError of a second Hermes runtime escape into React Native: a raw task scheduled with invokeAsync, a bindings installer, a native module method and a global host function, during bundle evaluation and after startup. The raw task and bindings installer cases now report an Error of the React Native runtime. The cases where the second runtime is destroyed, or where the React Native runtime collects garbage while it holds the foreign error, still crash and run as death tests. The host function cases without such a trigger are skipped: Hermes stores the foreign error in the React Native runtime at the host function boundary, so their outcome depends on the Hermes heap layout. --- .../runtime/tests/cxx/ReactInstanceTest.cpp | 344 +++++++++++++++++- 1 file changed, 339 insertions(+), 5 deletions(-) diff --git a/packages/react-native/ReactCommon/react/runtime/tests/cxx/ReactInstanceTest.cpp b/packages/react-native/ReactCommon/react/runtime/tests/cxx/ReactInstanceTest.cpp index e8c12e2d8106..79927d84c159 100644 --- a/packages/react-native/ReactCommon/react/runtime/tests/cxx/ReactInstanceTest.cpp +++ b/packages/react-native/ReactCommon/react/runtime/tests/cxx/ReactInstanceTest.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include @@ -130,11 +131,11 @@ class ReactInstanceTest : public ::testing::Test { auto mockRegistry = std::make_unique(); mockRegistry_ = mockRegistry.get(); timerManager_ = std::make_shared(std::move(mockRegistry)); - auto onJsError = - [](jsi::Runtime& /*runtime*/, - const JsErrorHandler::ProcessedError& /*error*/) noexcept { - // Do nothing - }; + auto onJsError = [this]( + jsi::Runtime& /*runtime*/, + const JsErrorHandler::ProcessedError& error) noexcept { + processedErrorMessages_.push_back(error.message); + }; instance_ = std::make_unique( std::move(runtime), @@ -232,6 +233,7 @@ class ReactInstanceTest : public ::testing::Test { std::shared_ptr timerManager_; MockTimerRegistry* mockRegistry_{}; std::shared_ptr errorHandler_; + std::vector processedErrorMessages_; }; TEST_F(ReactInstanceTest, testRegistersRuntimeSchedulerAsEventLoopControl) { @@ -903,4 +905,336 @@ function getCalls() { EXPECT_EQ(calls.getNumber(), 0); } +namespace { + +constexpr auto kErrorOfAnotherRuntimeSkipReason = + "Hermes stores the error of another runtime in this runtime at the host " + "function boundary, so the outcome depends on the Hermes heap layout"; + +void throwErrorInRuntime(jsi::Runtime& runtime) { + runtime.evaluateJavaScript( + std::make_shared( + "throw new Error('Error of another runtime');"), + "anotherRuntime.js"); +} + +void throwErrorOfDestroyedRuntime() { + auto temporaryRuntime = hermes::makeHermesRuntime(); + throwErrorInRuntime(*temporaryRuntime); +} + +void throwErrorConvertedFromAnotherRuntime( + jsi::Runtime& runtime, + jsi::Runtime& anotherRuntime) { + try { + throwErrorInRuntime(anotherRuntime); + } catch (const jsi::JSError& error) { + throw jsi::JSError(runtime, error.getMessage()); + } +} + +jsi::Function createHostFunction( + jsi::Runtime& runtime, + std::function body) { + return jsi::Function::createFromHostFunction( + runtime, + jsi::PropNameID::forAscii(runtime, "hostFunction"), + 0, + [body = std::move(body)]( + jsi::Runtime& runtime, + const jsi::Value& /*thisValue*/, + const jsi::Value* /*arguments*/, + size_t /*count*/) -> jsi::Value { + body(runtime); + return jsi::Value::undefined(); + }); +} + +void installNativeModuleMethod( + jsi::Runtime& runtime, + std::function body) { + auto nativeModule = jsi::Object(runtime); + nativeModule.setProperty( + runtime, "throwError", createHostFunction(runtime, std::move(body))); + runtime.global().setProperty(runtime, "nativeModule", nativeModule); +} + +void installGlobalHostFunction( + jsi::Runtime& runtime, + std::function body) { + runtime.global().setProperty( + runtime, "throwError", createHostFunction(runtime, std::move(body))); +} + +void collectGarbageWhileReportingError(jsi::Runtime& runtime) { + runtime.global().setProperty( + runtime, + "__getBundleMetadata", + createHostFunction(runtime, [](jsi::Runtime& runtime) { + runtime.instrumentation().collectGarbage("ReactInstanceTest"); + })); +} + +constexpr auto kBundleThatCallsNativeModuleMethod = R"xyz123( +var module = {}; +try { + nativeModule.throwError(); +} catch (error) { + module.error = error; + throw error; +} +)xyz123"; + +constexpr auto kBundleThatCallsGlobalHostFunction = R"xyz123( +var module = {}; +try { + throwError(); +} catch (error) { + module.error = error; + throw error; +} +)xyz123"; + +} // namespace + +class ReactInstanceDeathTest : public ReactInstanceTest { + protected: + ReactInstanceDeathTest() { + GTEST_FLAG_SET(death_test_style, "threadsafe"); + } +}; + +TEST_F(ReactInstanceTest, testNativeTaskThrowsErrorOfAnotherRuntime) { + initializeRuntimeWithScript(""); + auto anotherRuntime = hermes::makeHermesRuntime(); + + instance_->createJSCallInvoker()->invokeAsync( + [&](jsi::Runtime& /*runtime*/) { throwErrorInRuntime(*anotherRuntime); }); + step(); + + expectError(); + EXPECT_EQ(getLastErrorMessage(), "Error of another runtime"); +} + +TEST_F(ReactInstanceTest, testNativeModuleMethodThrowsErrorOfAnotherRuntime) { + GTEST_SKIP() << kErrorOfAnotherRuntimeSkipReason; + initializeRuntimeWithScript(""); + auto anotherRuntime = hermes::makeHermesRuntime(); + installNativeModuleMethod(*runtime_, [&](jsi::Runtime& /*runtime*/) { + throwErrorInRuntime(*anotherRuntime); + }); + + eval("nativeModule.throwError();"); + + expectError(); + EXPECT_EQ(getLastErrorMessage(), "Error of another runtime"); +} + +TEST_F(ReactInstanceDeathTest, testNativeTaskThrowsErrorOfDestroyedRuntime) { + initializeRuntimeWithScript(""); + + EXPECT_DEATH_IF_SUPPORTED( + { + instance_->createJSCallInvoker()->invokeAsync( + [](jsi::Runtime& /*runtime*/) { throwErrorOfDestroyedRuntime(); }); + step(); + }, + ""); +} + +TEST_F( + ReactInstanceTest, + testNativeTaskThrowsErrorConvertedFromAnotherRuntime) { + initializeRuntimeWithScript(""); + auto anotherRuntime = hermes::makeHermesRuntime(); + + instance_->createJSCallInvoker()->invokeAsync([&](jsi::Runtime& runtime) { + throwErrorConvertedFromAnotherRuntime(runtime, *anotherRuntime); + }); + step(); + + expectError(); + EXPECT_EQ(getLastErrorMessage(), "Error of another runtime"); +} + +TEST_F( + ReactInstanceTest, + testNativeModuleMethodThrowsErrorConvertedFromAnotherRuntime) { + initializeRuntimeWithScript(""); + auto anotherRuntime = hermes::makeHermesRuntime(); + installNativeModuleMethod(*runtime_, [&](jsi::Runtime& runtime) { + throwErrorConvertedFromAnotherRuntime(runtime, *anotherRuntime); + }); + + auto caughtMessage = eval(R"xyz123( +(function() { + try { + nativeModule.throwError(); + return 'no error'; + } catch (error) { + return error.message; + } +})() +)xyz123"); + + expectNoError(); + EXPECT_EQ( + caughtMessage.asString(*runtime_).utf8(*runtime_), + "Error of another runtime"); +} + +TEST_F( + ReactInstanceTest, + testNativeModuleMethodThrowsErrorOfAnotherRuntimeDuringBundleEvaluation) { + GTEST_SKIP() << kErrorOfAnotherRuntimeSkipReason; + auto anotherRuntime = hermes::makeHermesRuntime(); + instance_->initializeRuntime( + {.isProfiling = false}, [&](jsi::Runtime& runtime) { + installNativeModuleMethod(runtime, [&](jsi::Runtime& /*runtime*/) { + throwErrorInRuntime(*anotherRuntime); + }); + }); + step(); + + loadScript(kBundleThatCallsNativeModuleMethod); + + ASSERT_EQ(processedErrorMessages_.size(), 1); + EXPECT_EQ( + processedErrorMessages_[0], + "[runtime not ready]: Error: Error of another runtime"); +} + +TEST_F( + ReactInstanceDeathTest, + testNativeModuleMethodThrowsErrorOfDestroyedRuntimeDuringBundleEvaluation) { + instance_->initializeRuntime( + {.isProfiling = false}, [&](jsi::Runtime& runtime) { + installNativeModuleMethod(runtime, [](jsi::Runtime& /*runtime*/) { + throwErrorOfDestroyedRuntime(); + }); + }); + step(); + + EXPECT_DEATH_IF_SUPPORTED(loadScript(kBundleThatCallsNativeModuleMethod), ""); +} + +TEST_F( + ReactInstanceDeathTest, + testNativeModuleMethodThrowsErrorOfAnotherRuntimeDuringBundleEvaluationAndGarbageCollection) { + auto anotherRuntime = hermes::makeHermesRuntime(); + instance_->initializeRuntime( + {.isProfiling = false}, [&](jsi::Runtime& runtime) { + installNativeModuleMethod(runtime, [&](jsi::Runtime& /*runtime*/) { + throwErrorInRuntime(*anotherRuntime); + }); + collectGarbageWhileReportingError(runtime); + }); + step(); + + EXPECT_DEATH_IF_SUPPORTED(loadScript(kBundleThatCallsNativeModuleMethod), ""); +} + +TEST_F(ReactInstanceTest, testBindingsInstallerThrowsErrorOfAnotherRuntime) { + auto anotherRuntime = hermes::makeHermesRuntime(); + instance_->initializeRuntime( + {.isProfiling = false}, + [&](jsi::Runtime& /*runtime*/) { throwErrorInRuntime(*anotherRuntime); }); + step(); + + ASSERT_EQ(processedErrorMessages_.size(), 1); + EXPECT_EQ( + processedErrorMessages_[0], + "[runtime not ready]: Error: Error of another runtime"); +} + +TEST_F( + ReactInstanceTest, + testGlobalHostFunctionThrowsErrorOfAnotherRuntimeDuringBundleEvaluation) { + GTEST_SKIP() << kErrorOfAnotherRuntimeSkipReason; + auto anotherRuntime = hermes::makeHermesRuntime(); + instance_->initializeRuntime( + {.isProfiling = false}, [&](jsi::Runtime& runtime) { + installGlobalHostFunction(runtime, [&](jsi::Runtime& /*runtime*/) { + throwErrorInRuntime(*anotherRuntime); + }); + }); + step(); + + loadScript(kBundleThatCallsGlobalHostFunction); + + ASSERT_EQ(processedErrorMessages_.size(), 1); + EXPECT_EQ( + processedErrorMessages_[0], + "[runtime not ready]: Error: Error of another runtime"); +} + +TEST_F( + ReactInstanceDeathTest, + testGlobalHostFunctionThrowsErrorOfDestroyedRuntimeDuringBundleEvaluation) { + instance_->initializeRuntime( + {.isProfiling = false}, [&](jsi::Runtime& runtime) { + installGlobalHostFunction(runtime, [](jsi::Runtime& /*runtime*/) { + throwErrorOfDestroyedRuntime(); + }); + }); + step(); + + EXPECT_DEATH_IF_SUPPORTED(loadScript(kBundleThatCallsGlobalHostFunction), ""); +} + +TEST_F( + ReactInstanceDeathTest, + testGlobalHostFunctionThrowsErrorOfAnotherRuntimeDuringBundleEvaluationAndGarbageCollection) { + auto anotherRuntime = hermes::makeHermesRuntime(); + instance_->initializeRuntime( + {.isProfiling = false}, [&](jsi::Runtime& runtime) { + installGlobalHostFunction(runtime, [&](jsi::Runtime& /*runtime*/) { + throwErrorInRuntime(*anotherRuntime); + }); + collectGarbageWhileReportingError(runtime); + }); + step(); + + EXPECT_DEATH_IF_SUPPORTED(loadScript(kBundleThatCallsGlobalHostFunction), ""); +} + +TEST_F( + ReactInstanceTest, + testGlobalHostFunctionThrowsErrorOfAnotherRuntimeInTimer) { + GTEST_SKIP() << kErrorOfAnotherRuntimeSkipReason; + initializeRuntimeWithScript(""); + auto anotherRuntime = hermes::makeHermesRuntime(); + installGlobalHostFunction(*runtime_, [&](jsi::Runtime& /*runtime*/) { + throwErrorInRuntime(*anotherRuntime); + }); + uint32_t timerID{0}; + EXPECT_CALL(*mockRegistry_, createTimer(_, 0)).WillOnce(SaveArg<0>(&timerID)); + eval("setTimeout(() => throwError(), 0);"); + + timerManager_->callTimer(timerID); + step(); + + expectError(); + EXPECT_EQ(getLastErrorMessage(), "Error of another runtime"); +} + +TEST_F( + ReactInstanceDeathTest, + testGlobalHostFunctionThrowsErrorOfDestroyedRuntimeInTimer) { + initializeRuntimeWithScript(""); + installGlobalHostFunction(*runtime_, [](jsi::Runtime& /*runtime*/) { + throwErrorOfDestroyedRuntime(); + }); + uint32_t timerID{0}; + EXPECT_CALL(*mockRegistry_, createTimer(_, 0)).WillOnce(SaveArg<0>(&timerID)); + eval("setTimeout(() => throwError(), 0);"); + + EXPECT_DEATH_IF_SUPPORTED( + { + timerManager_->callTimer(timerID); + step(); + }, + ""); +} + } // namespace facebook::react From 8e113705387d3b83b4fb134e13dfc07b6fe1127d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20=C5=BBelawski?= Date: Tue, 1 Dec 2026 23:25:44 +0100 Subject: [PATCH 3/5] Skip the tests that rely on reading memory of a destroyed runtime --- .../react/runtime/tests/cxx/ReactInstanceTest.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/packages/react-native/ReactCommon/react/runtime/tests/cxx/ReactInstanceTest.cpp b/packages/react-native/ReactCommon/react/runtime/tests/cxx/ReactInstanceTest.cpp index 79927d84c159..f1190aded350 100644 --- a/packages/react-native/ReactCommon/react/runtime/tests/cxx/ReactInstanceTest.cpp +++ b/packages/react-native/ReactCommon/react/runtime/tests/cxx/ReactInstanceTest.cpp @@ -911,6 +911,10 @@ constexpr auto kErrorOfAnotherRuntimeSkipReason = "Hermes stores the error of another runtime in this runtime at the host " "function boundary, so the outcome depends on the Hermes heap layout"; +constexpr auto kErrorOfDestroyedRuntimeSkipReason = + "The error points into a destroyed runtime, and reading freed memory is " + "not guaranteed to crash"; + void throwErrorInRuntime(jsi::Runtime& runtime) { runtime.evaluateJavaScript( std::make_shared( @@ -1031,6 +1035,7 @@ TEST_F(ReactInstanceTest, testNativeModuleMethodThrowsErrorOfAnotherRuntime) { } TEST_F(ReactInstanceDeathTest, testNativeTaskThrowsErrorOfDestroyedRuntime) { + GTEST_SKIP() << kErrorOfDestroyedRuntimeSkipReason; initializeRuntimeWithScript(""); EXPECT_DEATH_IF_SUPPORTED( @@ -1107,6 +1112,7 @@ TEST_F( TEST_F( ReactInstanceDeathTest, testNativeModuleMethodThrowsErrorOfDestroyedRuntimeDuringBundleEvaluation) { + GTEST_SKIP() << kErrorOfDestroyedRuntimeSkipReason; instance_->initializeRuntime( {.isProfiling = false}, [&](jsi::Runtime& runtime) { installNativeModuleMethod(runtime, [](jsi::Runtime& /*runtime*/) { @@ -1171,6 +1177,7 @@ TEST_F( TEST_F( ReactInstanceDeathTest, testGlobalHostFunctionThrowsErrorOfDestroyedRuntimeDuringBundleEvaluation) { + GTEST_SKIP() << kErrorOfDestroyedRuntimeSkipReason; instance_->initializeRuntime( {.isProfiling = false}, [&](jsi::Runtime& runtime) { installGlobalHostFunction(runtime, [](jsi::Runtime& /*runtime*/) { @@ -1221,6 +1228,7 @@ TEST_F( TEST_F( ReactInstanceDeathTest, testGlobalHostFunctionThrowsErrorOfDestroyedRuntimeInTimer) { + GTEST_SKIP() << kErrorOfDestroyedRuntimeSkipReason; initializeRuntimeWithScript(""); installGlobalHostFunction(*runtime_, [](jsi::Runtime& /*runtime*/) { throwErrorOfDestroyedRuntime(); From f0a6c10d1db1dd687cb2c05ec230c695816e4abd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20=C5=BBelawski?= Date: Wed, 2 Dec 2026 22:23:24 +0100 Subject: [PATCH 4/5] Rethrow own JSErrors of native tasks unchanged when the runtime can tell Add jsi::IValueOwnership to the JSI header, mirroring the Hermes change. When a raw callback of a task throws a jsi::JSError, Task::execute rethrows it unchanged if the runtime implements IValueOwnership and reports the error value as its own, so that the error keeps its identity, name and custom properties. Errors of another runtime, and every error of a runtime without the interface, are still rebuilt in the runtime. --- .../react-native/ReactCommon/jsi/jsi/jsi.h | 26 ++++ .../react/renderer/runtimescheduler/Task.cpp | 8 ++ .../tests/RuntimeSchedulerTest.cpp | 125 +++++++++++++++++- .../runtimescheduler/tests/StubErrorUtils.h | 1 + 4 files changed, 159 insertions(+), 1 deletion(-) diff --git a/packages/react-native/ReactCommon/jsi/jsi/jsi.h b/packages/react-native/ReactCommon/jsi/jsi/jsi.h index bf98028fb3fb..6c4d36e8fb0e 100644 --- a/packages/react-native/ReactCommon/jsi/jsi/jsi.h +++ b/packages/react-native/ReactCommon/jsi/jsi/jsi.h @@ -329,6 +329,32 @@ class JSI_EXPORT ISerialization : public ICast { #endif // JSI_UNSTABLE +/// Tells whether a Value was created by this runtime. +/// +/// - Values without a pointer (undefined, null, booleans and numbers) are +/// always reported as own. +/// - False positives: a value of a runtime that was already destroyed can be +/// reported as own when this runtime reuses the memory of that runtime. +/// - False negatives: a value created by this runtime is reported as not own +/// when it was created through a wrapper of this runtime that replaces the +/// runtime's PointerValues with its own. +/// - In all other cases the answer is exact while the runtime that created the +/// value is alive. +class JSI_EXPORT IValueOwnership : public ICast { + public: + static constexpr jsi::UUID uuid{ + 0xf92f55b7, + 0x3d5c, + 0x441e, + 0x8b2d, + 0x7e88f267cd40}; + + virtual bool isOwnValue(const Value& value) = 0; + + protected: + ~IValueOwnership() = default; +}; + /// An interface that provides various functionalities of the JS runtime. /// The APIs must not be called from multiple threads concurrently. It is the /// user's responsibility ensure thread safety when using IRuntime. diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/Task.cpp b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/Task.cpp index 9646bcb2b4d6..79b30c20ca94 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/Task.cpp +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/Task.cpp @@ -27,6 +27,11 @@ jsi::JSError recreateJSErrorInRuntime( jsi::Value(std::move(errorObject)), error.getMessage(), error.getStack()}; } +bool isOwnValue(jsi::Runtime& runtime, const jsi::Value& value) { + auto* ownership = jsi::castInterface(&runtime); + return ownership != nullptr && ownership->isOwnValue(value); +} + } // namespace Task::Task( @@ -70,6 +75,9 @@ jsi::Value Task::execute(jsi::Runtime& runtime, bool didUserCallbackTimeout) { try { std::get(originalCallback)(runtime); } catch (const jsi::JSError& error) { + if (isOwnValue(runtime, error.value())) { + throw; + } throw recreateJSErrorInRuntime(runtime, error); } } diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp index 5325f6772240..d0d867e62179 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -45,6 +46,31 @@ class RuntimeSchedulerTestFeatureFlags bool enableEventLoop_; }; +enum class ValueOwnership { Own, Foreign, Unavailable }; + +class ValueOwnershipRuntime : public jsi::RuntimeDecorator, + public jsi::IValueOwnership { + public: + ValueOwnershipRuntime(jsi::Runtime& runtime, ValueOwnership ownership) + : RuntimeDecorator(runtime), ownership_(ownership) {} + + jsi::ICast* castInterface(const jsi::UUID& interfaceUUID) override { + if (interfaceUUID == jsi::IValueOwnership::uuid) { + return ownership_ == ValueOwnership::Unavailable + ? nullptr + : static_cast(this); + } + return RuntimeDecorator::castInterface(interfaceUUID); + } + + bool isOwnValue(const jsi::Value& /*value*/) override { + return ownership_ == ValueOwnership::Own; + } + + private: + ValueOwnership ownership_; +}; + class RuntimeSchedulerTest : public testing::TestWithParam { protected: void SetUp() override { @@ -65,7 +91,11 @@ class RuntimeSchedulerTest : public testing::TestWithParam { [this]( std::function&& callback) { stubQueue_->runOnQueue([this, callback = std::move(callback)]() { - callback(*runtime_); + if (valueOwnershipRuntime_) { + callback(*valueOwnershipRuntime_); + } else { + callback(*runtime_); + } }); }; @@ -111,9 +141,30 @@ class RuntimeSchedulerTest : public testing::TestWithParam { }); } + void scheduleTaskThrowingOwnError() { + evaluate(R"( + var thrown = new TypeError('Own error'); + thrown.custom = 42; + function throwOwn() { throw thrown; } + )"); + runtimeScheduler_->scheduleTask( + SchedulerPriority::NormalPriority, [](jsi::Runtime& runtime) { + runtime.global() + .getPropertyAsFunction(runtime, "throwOwn") + .call(runtime); + }); + } + + bool evaluate(const char* code) { + auto result = runtime_->evaluateJavaScript( + std::make_shared(code), "test.js"); + return result.isBool() && result.getBool(); + } + uint hostFunctionCallCount_{}; std::unique_ptr runtime_; + std::unique_ptr valueOwnershipRuntime_; std::unique_ptr stubClock_; std::unique_ptr stubQueue_; std::unique_ptr runtimeScheduler_; @@ -931,6 +982,78 @@ TEST_P(RuntimeSchedulerTest, handlingErrorOfAnotherRuntimeInRawCallback) { "Error of another runtime"); } +TEST_P(RuntimeSchedulerTest, handlingOwnErrorInRawCallbackKeepsTheError) { + valueOwnershipRuntime_ = + std::make_unique(*runtime_, ValueOwnership::Own); + scheduleTaskThrowingOwnError(); + + stubQueue_->tick(); + + EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1); + EXPECT_EQ(stubErrorUtils_->getLastReportedErrorMessage(), "Own error"); + EXPECT_TRUE(evaluate( + "lastReportedError === thrown && " + "lastReportedError.name === 'TypeError' && " + "lastReportedError.custom === 42")); +} + +TEST_P( + RuntimeSchedulerTest, + handlingErrorReportedAsForeignInRawCallbackRebuildsTheError) { + valueOwnershipRuntime_ = std::make_unique( + *runtime_, ValueOwnership::Foreign); + scheduleTaskThrowingOwnError(); + + stubQueue_->tick(); + + EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1); + EXPECT_EQ(stubErrorUtils_->getLastReportedErrorMessage(), "Own error"); + EXPECT_TRUE(evaluate( + "lastReportedError !== thrown && " + "lastReportedError.name === 'Error' && " + "lastReportedError.custom === undefined")); +} + +TEST_P( + RuntimeSchedulerTest, + handlingErrorOfAnotherRuntimeReportedAsForeignInRawCallback) { + valueOwnershipRuntime_ = std::make_unique( + *runtime_, ValueOwnership::Foreign); + auto anotherRuntime = facebook::hermes::makeHermesRuntime(); + + runtimeScheduler_->scheduleTask( + SchedulerPriority::NormalPriority, [&](jsi::Runtime& /*unused*/) { + anotherRuntime->evaluateJavaScript( + std::make_shared( + "throw new Error('Error of another runtime');"), + "anotherRuntime.js"); + }); + + stubQueue_->tick(); + + EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1); + EXPECT_EQ( + stubErrorUtils_->getLastReportedErrorMessage(), + "Error of another runtime"); +} + +TEST_P( + RuntimeSchedulerTest, + handlingOwnErrorInRawCallbackWithoutValueOwnershipRebuildsTheError) { + valueOwnershipRuntime_ = std::make_unique( + *runtime_, ValueOwnership::Unavailable); + scheduleTaskThrowingOwnError(); + + stubQueue_->tick(); + + EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1); + EXPECT_EQ(stubErrorUtils_->getLastReportedErrorMessage(), "Own error"); + EXPECT_TRUE(evaluate( + "lastReportedError !== thrown && " + "lastReportedError.name === 'Error' && " + "lastReportedError.custom === undefined")); +} + TEST_P(RuntimeSchedulerTest, handlingErrorInRawCallback) { bool didRunTask = false; diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubErrorUtils.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubErrorUtils.h index 364e13e7ff76..be004f3fbc97 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubErrorUtils.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubErrorUtils.h @@ -51,6 +51,7 @@ class StubErrorUtils : public jsi::HostObject { jsi::Runtime &runtime, const jsi::Value &, const jsi::Value *arguments, size_t) noexcept -> jsi::Value { reportFatalCallCount_++; lastReportedErrorMessage_ = getErrorMessage(runtime, arguments[0]); + runtime.global().setProperty(runtime, "lastReportedError", arguments[0]); return jsi::Value::undefined(); }); } From 183ee7811b679ac446be7e037a5b0774a859473f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20=C5=BBelawski?= Date: Wed, 2 Dec 2026 22:48:14 +0100 Subject: [PATCH 5/5] Update the C++ API snapshots for jsi::IValueOwnership --- scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api | 6 ++++++ scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api | 6 ++++++ scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api | 6 ++++++ scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api | 6 ++++++ scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api | 6 ++++++ scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api | 6 ++++++ scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api | 6 ++++++ scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api | 6 ++++++ scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api | 6 ++++++ scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api | 6 ++++++ scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api | 6 ++++++ scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api | 6 ++++++ 12 files changed, 72 insertions(+) diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api index ece6b944c73a..bb42f82bbba5 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api @@ -5757,6 +5757,12 @@ struct facebook::jsi::IRuntime::PointerValue { public virtual void invalidate() noexcept = 0; } +class facebook::jsi::IValueOwnership : public facebook::jsi::ICast { + protected ~IValueOwnership() = default; + public static constexpr facebook::jsi::UUID uuid; + public virtual bool isOwnValue(const facebook::jsi::Value& value) = 0; +} + class facebook::jsi::Instrumentation { public using HeapStatsUpdate = std::tuple; public virtual std::string flushAndDisableBridgeTrafficTrace() = 0; diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api index 96f1de574a16..e12228b5808c 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api @@ -10268,6 +10268,12 @@ struct facebook::jsi::IRuntime::PointerValue { public virtual void invalidate() noexcept = 0; } +class facebook::jsi::IValueOwnership : public facebook::jsi::ICast { + protected ~IValueOwnership() = default; + public static constexpr facebook::jsi::UUID uuid; + public virtual bool isOwnValue(const facebook::jsi::Value& value) = 0; +} + class facebook::jsi::Instrumentation { public using HeapStatsUpdate = std::tuple; public virtual std::string flushAndDisableBridgeTrafficTrace() = 0; diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api index 809dada6ec58..6e4755292b47 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api @@ -5605,6 +5605,12 @@ struct facebook::jsi::IRuntime::PointerValue { public virtual void invalidate() noexcept = 0; } +class facebook::jsi::IValueOwnership : public facebook::jsi::ICast { + protected ~IValueOwnership() = default; + public static constexpr facebook::jsi::UUID uuid; + public virtual bool isOwnValue(const facebook::jsi::Value& value) = 0; +} + class facebook::jsi::Instrumentation { public using HeapStatsUpdate = std::tuple; public virtual std::string flushAndDisableBridgeTrafficTrace() = 0; diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api index 809dada6ec58..6e4755292b47 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api @@ -5605,6 +5605,12 @@ struct facebook::jsi::IRuntime::PointerValue { public virtual void invalidate() noexcept = 0; } +class facebook::jsi::IValueOwnership : public facebook::jsi::ICast { + protected ~IValueOwnership() = default; + public static constexpr facebook::jsi::UUID uuid; + public virtual bool isOwnValue(const facebook::jsi::Value& value) = 0; +} + class facebook::jsi::Instrumentation { public using HeapStatsUpdate = std::tuple; public virtual std::string flushAndDisableBridgeTrafficTrace() = 0; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api index 00b196227198..808afa354dcd 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api @@ -7513,6 +7513,12 @@ struct facebook::jsi::IRuntime::PointerValue { public virtual void invalidate() noexcept = 0; } +class facebook::jsi::IValueOwnership : public facebook::jsi::ICast { + protected ~IValueOwnership() = default; + public static constexpr facebook::jsi::UUID uuid; + public virtual bool isOwnValue(const facebook::jsi::Value& value) = 0; +} + class facebook::jsi::Instrumentation { public using HeapStatsUpdate = std::tuple; public virtual std::string flushAndDisableBridgeTrafficTrace() = 0; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api index fc711f07ba9a..a6c932d8d90b 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api @@ -12050,6 +12050,12 @@ struct facebook::jsi::IRuntime::PointerValue { public virtual void invalidate() noexcept = 0; } +class facebook::jsi::IValueOwnership : public facebook::jsi::ICast { + protected ~IValueOwnership() = default; + public static constexpr facebook::jsi::UUID uuid; + public virtual bool isOwnValue(const facebook::jsi::Value& value) = 0; +} + class facebook::jsi::Instrumentation { public using HeapStatsUpdate = std::tuple; public virtual std::string flushAndDisableBridgeTrafficTrace() = 0; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api index a6260dedf98d..d29b60fcfd32 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api @@ -7364,6 +7364,12 @@ struct facebook::jsi::IRuntime::PointerValue { public virtual void invalidate() noexcept = 0; } +class facebook::jsi::IValueOwnership : public facebook::jsi::ICast { + protected ~IValueOwnership() = default; + public static constexpr facebook::jsi::UUID uuid; + public virtual bool isOwnValue(const facebook::jsi::Value& value) = 0; +} + class facebook::jsi::Instrumentation { public using HeapStatsUpdate = std::tuple; public virtual std::string flushAndDisableBridgeTrafficTrace() = 0; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api index b7f61c537afd..2f1dae8ab9c9 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api @@ -7371,6 +7371,12 @@ struct facebook::jsi::IRuntime::PointerValue { public virtual void invalidate() noexcept = 0; } +class facebook::jsi::IValueOwnership : public facebook::jsi::ICast { + protected ~IValueOwnership() = default; + public static constexpr facebook::jsi::UUID uuid; + public virtual bool isOwnValue(const facebook::jsi::Value& value) = 0; +} + class facebook::jsi::Instrumentation { public using HeapStatsUpdate = std::tuple; public virtual std::string flushAndDisableBridgeTrafficTrace() = 0; diff --git a/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api index bfc0cd340bc9..eb5db22f61b9 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api @@ -2971,6 +2971,12 @@ struct facebook::jsi::IRuntime::PointerValue { public virtual void invalidate() noexcept = 0; } +class facebook::jsi::IValueOwnership : public facebook::jsi::ICast { + protected ~IValueOwnership() = default; + public static constexpr facebook::jsi::UUID uuid; + public virtual bool isOwnValue(const facebook::jsi::Value& value) = 0; +} + class facebook::jsi::Instrumentation { public using HeapStatsUpdate = std::tuple; public virtual std::string flushAndDisableBridgeTrafficTrace() = 0; diff --git a/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api index 66dccbe50765..c449fc04e2c6 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api @@ -7374,6 +7374,12 @@ struct facebook::jsi::IRuntime::PointerValue { public virtual void invalidate() noexcept = 0; } +class facebook::jsi::IValueOwnership : public facebook::jsi::ICast { + protected ~IValueOwnership() = default; + public static constexpr facebook::jsi::UUID uuid; + public virtual bool isOwnValue(const facebook::jsi::Value& value) = 0; +} + class facebook::jsi::Instrumentation { public using HeapStatsUpdate = std::tuple; public virtual std::string flushAndDisableBridgeTrafficTrace() = 0; diff --git a/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api index 230268227245..0371f03fe30f 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api @@ -2964,6 +2964,12 @@ struct facebook::jsi::IRuntime::PointerValue { public virtual void invalidate() noexcept = 0; } +class facebook::jsi::IValueOwnership : public facebook::jsi::ICast { + protected ~IValueOwnership() = default; + public static constexpr facebook::jsi::UUID uuid; + public virtual bool isOwnValue(const facebook::jsi::Value& value) = 0; +} + class facebook::jsi::Instrumentation { public using HeapStatsUpdate = std::tuple; public virtual std::string flushAndDisableBridgeTrafficTrace() = 0; diff --git a/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api index 230268227245..0371f03fe30f 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api @@ -2964,6 +2964,12 @@ struct facebook::jsi::IRuntime::PointerValue { public virtual void invalidate() noexcept = 0; } +class facebook::jsi::IValueOwnership : public facebook::jsi::ICast { + protected ~IValueOwnership() = default; + public static constexpr facebook::jsi::UUID uuid; + public virtual bool isOwnValue(const facebook::jsi::Value& value) = 0; +} + class facebook::jsi::Instrumentation { public using HeapStatsUpdate = std::tuple; public virtual std::string flushAndDisableBridgeTrafficTrace() = 0;