Repository navigation
Conversation
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.
…eact 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.
|
I agree that it is a library error but it falsely suggests that React Native failed as its error handlers are crashing. What kind of metadata do you mean? I thought that re-creating the error with the message and stack would be sufficient here. |
|
Hi, Bruce here. On the metadata question, checked against the code: the loss is real, but it hits errors of the React Native runtime, not the foreign ones.
For a foreign error, message and stack are all that can be read safely, so rebuilding them is enough there. So the change is only safe if it rebuilds foreign errors and leaves own errors untouched. JSI has no way to ask which runtime a value belongs to, so React Native cannot do that on its own. Hermes can: meta/hermes#2360 checks whether the error's Two ways forward:
|
|
That's a bummer then |
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.
|
Hi, Bruce here. Updated to address the metadata concern (f0a6c10). To tell the two apart, the runtime has to implement a new JSI interface, meta/hermes#2360, stacked on #2361, uses the same check at Hermes' host function boundary, which covers the case that React Native cannot see. |
…/runtime-scheduler-foreign-jserror # Conflicts: # packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp
Note
This pull request was authored by AI on behalf of @tjzel.
Summary:
Human track
Why
Fixes #60439. Earlier report of the same root cause: #55913.
Libraries that run a second Hermes runtime, such as
react-native-worklets, can let ajsi::JSErrorof that runtime escape from a native callback that theRuntimeSchedulerruns on the JS thread, for example aCallInvoker::invokeAsynccallback. React Native then reports the error with its value, which belongs to the other runtime, and Hermes crashes when the React Native runtime reads it. The reproducer in the issue crashes withSIGSEGVon 0.88.1.What
When a native task of the
RuntimeSchedulerthrows ajsi::JSError, React Native now checks whether the error belongs to its own runtime. An error of another runtime is reported as anErrorthat React Native creates on its own runtime, with the message and stack of the original error. An error of its own runtime is reported unchanged, with its type, properties and identity. The check needs the JS engine to implement the new JSI interfacejsi::IValueOwnership(meta/hermes#2361). On engines without it, every error from a native task is rebuilt, which keeps only its message and stack. Tasks that are JS functions are not changed.The JSI header change mirrors meta/hermes#2361 byte for byte and should come with the next JSI sync from Hermes; this PR includes it so that it builds on its own.
How
A
jsi::JSErrorkeeps its message and stack as C++ strings, read when it is created, so they can be read on any runtime. Its value cannot. meta/hermes#2361 addsjsi::IValueOwnership, which a runtime can implement to tell whether a value belongs to it; Hermes implements it.The change is in the one place that both
RuntimeSchedulerimplementations run native tasks. Ajsi::JSErrorthrown from a native task is caught there. If the runtime implementsIValueOwnershipand says the error is its own, the error is thrown again unchanged. Otherwise, it is thrown again as a new error, created on the React Native runtime from the strings of the original. The error handlers then always get a value that belongs to the runtime they use.This PR does not cover a foreign
jsi::JSErrorthat a synchronous host function lets escape into JS. Hermes rethrows such an error into JS at the host function boundary, before React Native sees it. meta/hermes#2360 fixes that path in Hermes. The reproducer shows both cases.Changelog:
[GENERAL] [FIXED] - Fix a crash when a native task on the JS thread throws a
jsi::JSErrorof another JS runtimeTest Plan:
Testing
Two new
RuntimeSchedulerunit tests run for both the legacy and the modern scheduler:Errorwith the original message.Four more
RuntimeSchedulertests run a native task on a wrapper runtime that implementsIValueOwnershipwith a fixed answer, because the Hermes binary that the test build links does not have the interface yet:TypeErrorwith a custom property is reported as the same object, with its name and property.Errorwith the original message.Without the
Task::executechange, the first test fails and the others pass. The scheduler and React instance tests also pass against a Hermes build with meta/hermes#2360 and meta/hermes#2361, where the existing test with an error of a second runtime goes through the real Hermes implementation. Two death tests fail there because they expect a crash that meta/hermes#2360 prevents. The device reproduction was not repeated with this version.### Alternatives, replace item 1 and 2:jsi::JSErrorin the scheduler, as in the first version of this PR and in Fix LogBox parsing for cross-runtime jsi::JSErrors #55994 (open, marked stale) and Fixes LogBox displaying "Unknown" when an exception is thrown from an… #56000 (closed as a duplicate of Fix LogBox parsing for cross-runtime jsi::JSErrors #55994). Errors of the React Native runtime thrown by a native task then lose their type and extra properties such ascomponentStackandcause. This PR still does that, but only on engines withoutIValueOwnership.jsi::Runtimethat reports which runtime a value belongs to. That needs a default implementation in every JSI runtime and changes theRuntimeABI; an optional interface found withcastInterfacedoes not.Agent track, add under
### Files:packages/react-native/ReactCommon/jsi/jsi/jsi.h:IValueOwnership(UUIDf92f55b7-3d5c-441e-8b2d-7e88f267cd40), identical toAPI/jsi/jsi/jsi.hof Add jsi::IValueOwnership to tell whether a value belongs to a runtime meta/hermes#2361 (the RN copy was byte-identical to Hermesstatic_hbefore).Task.cpp:isOwnValue(runtime, value)=castInterface<IValueOwnership>(&runtime) != nullptr && ->isOwnValue(value); own →throw;, elsethrow recreateJSErrorInRuntime(runtime, error);.tests/RuntimeSchedulerTest.cpp:ValueOwnershipRuntime(RuntimeDecorator<jsi::Runtime>+IValueOwnership, modesOwn/Foreign/Unavailable), fixture executor passes it when set; testshandlingOwnErrorInRawCallbackKeepsTheError,handlingErrorReportedAsForeignInRawCallbackRebuildsTheError,handlingErrorOfAnotherRuntimeReportedAsForeignInRawCallback,handlingOwnErrorInRawCallbackWithoutValueOwnershipRebuildsTheError.tests/StubErrorUtils.h:reportFatalErrorstores the reported value asglobal.lastReportedError.Results at the new head:
react_renderer_runtimescheduler_tests110/110,react_runtime_tests45 passed / 9 skipped (prebuilt Hermes). Against Hermes9d0c4fcaf(#2360 on #2361, noJSI_UNSTABLE): scheduler-*/060/60 (*/0aborts onMicrotaskQueue must be enabled, Hermesstatic_hvs RN main),react_runtime_tests44 passed / 8 skipped / F3, H3 death tests fail (no crash any more).Changelog line: unchanged.
The whole
RuntimeSchedulertest suite passes locally with this change. Without the change, the first test fails on the legacy scheduler and crashes the test process withSIGSEGVon the modern scheduler.On a device, the reproducer from #60439 crashes on 0.88.1 (POCO X3 Pro, Android 11), and the same callback does not crash when it converts the error itself, which is what this change does inside React Native. With this change built into the reproducer app (ReactAndroid from source on 0.88.1 with this patch), variant A no longer crashes and shows a RedBox with the original message.
Startup cases (reproducer variants F, G, H on a device, with and without this change, 3 cold starts each): a foreign
jsi::JSErrorthrown by a synchronous TurboModule method (F) or by a host function onglobal(H) at module scope ofindex.js, and one thrown by an appBindingsInstallerin theinitializeRuntimetask (G). None crashes before or after this change, and the output does not change. This change does not cover F and H: Hermes moves the foreign value into the runtime at the host function boundary, beforeTask::executesees it, and they crash as soon as a GC runs while the error is reported (variants F3/H3), with or without this change. G reaches the error handler as anErrorof the React Native runtime with this change. After startup, a host function onglobalcalled from asetTimeoutcallback (I) crashes without this change. With it, it shows a RedBox with an empty message instead of crashing, because the foreign value already entered the runtime at the host function boundary.Every way a
jsi::JSErrorof another runtime can reach React NativeDevice results are from React Native 0.88.1 Debug on an Android 11 phone (arm64), 3 cold starts per variant for F to I2. The C++ tests run on the macOS host build.
invokeAsyncErrorof the React Native runtimeglobal, while the bundle evaluatesglobal, in asetTimeoutcallbackThis change cannot fix the variants where the error passes through a host function (B, F to F3, H to I2): Hermes stores the error of the other runtime in the React Native runtime at the host function boundary, before React Native code sees it, so the value is already corrupted. In C, F2, H2 and I2 the error itself points into a runtime that no longer exists, and React Native crashes as soon as it releases it. The skipped tests crash on the macOS host build but not on the Android phone, so their outcome depends on how Hermes lays out its heap; the death tests force a garbage collection, which crashed on both. The tests with a destroyed runtime (C, F2, H2, I2) are skipped too: they rely on reading freed memory, which crashed on macOS and on the phone, but not on the Linux CI runner.
The variants that this change cannot fix (an error that leaves a host function) are addressed in Hermes by meta/hermes#2360, which rebuilds a
jsi::JSErrorof another runtime as anErrorof the calling runtime at the host function boundary.Performance
No measurement. The change adds a
try/catcharound native tasks, which costs nothing unless the task throws.Alternatives
jsi::JSErrorin the scheduler, as in Fix LogBox parsing for cross-runtime jsi::JSErrors #55994 (open, marked stale) and Fixes LogBox displaying "Unknown" when an exception is thrown from an… #56000 (closed as a duplicate of Fix LogBox parsing for cross-runtime jsi::JSErrors #55994). That also rebuilds errors thrown by JS functions, which always belong to the React Native runtime, and drops their extra properties such ascomponentStackandcause.jsi::JSErrorbelongs to. That is a JSI and Hermes API change, much larger than this fix. The Hermes maintainers consider passing a value to another runtime a bug in the caller (JSError outliving its host runtime leads to crashes on deconstructor invocation meta/hermes#1927).Agent track
Details
Files
packages/react-native/ReactCommon/react/renderer/runtimescheduler/Task.cpp:Task::executewraps theRawCallbackcall intry { ... } catch (const jsi::JSError& error) { throw recreateJSErrorInRuntime(runtime, error); }.recreateJSErrorInRuntimecreatesjsi::JSError(runtime, error.getMessage())(which usesIRuntime::createError, so the value is a realErrorwith the right prototype), sets itsstackproperty toerror.getStack(), and returnsjsi::JSError(jsi::Value(errorObject), error.getMessage(), error.getStack()). The last constructor does not callsetValue, sogetMessage()/getStack()stay equal to the original strings, whichJsErrorHandler::handleErrorWithCppPipelineuses forrawStackandoriginalMessage.tests/RuntimeSchedulerTest.cpp:handlingErrorOfAnotherRuntimeInRawCallback,handlingErrorInRawCallback.tests/StubErrorUtils.h:reportFatalErrorstub records themessageof the reported value when it isinstanceof Error(getLastReportedErrorMessage()), so the tests also check that the reported value is a realErrorand not the plain object thatjsi::JSError(rt, message, stack)creates (the problem described in Poor handling of exceptions from extra Hermes Runtimes #55913).Why
Task::executeRuntimeScheduler_Legacy::executeTask(task->execute) andRuntimeScheduler_Modern::executeTask(task.execute) go through it, so one change covers both schedulers and all their catch sites (callExpiredTasks,startWorkLoop,executeTask).jsi::Functionbranch is left alone.jsi::Function::callthrows ajsi::JSErrorthat Hermes builds from the thrown value of its own heap (HermesRuntimeImpl::throwPendingErrorends withthrow jsi::JSError(std::move(jsiVal), msg, stack), https://github.com/facebook/hermes/blob/7a9359527cb174f438395cb105c03473f1a6409c/API/hermes/hermes.cpp#L3186-L3252, the Hermes revision RN main builds), so its value belongs toruntimeand keeps all its properties (componentStack,cause,RN$ErrorExtraDataKey).jsi::JSErrorstoresmessage_andstack_asstd::string, filled in the constructor on the throwing runtime (JSError::setValueinReactCommon/jsi/jsi/jsi.cpp).value()returns ajsi::ValuewhosePointerValuebelongs to the throwing runtime. JSI has no API that maps a value to its runtime.What stays broken (not in scope)
jsi::JSErrorthrown from a synchronous host function (TurboModule method called from JS): Hermes catches it at the host function boundary withcatch (const jsi::JSError &error) { return rt_.runtime_.setThrownValue(hvFromValue(error.value())); }(https://github.com/facebook/hermes/blob/7a9359527cb174f438395cb105c03473f1a6409c/API/hermes/hermes.cpp#L881-L882), so the React Native runtime holds a value of the other heap before React Native sees it. Reproducer variant B, crashes with the same stack as A. Fix belongs to the library.jsi::JSErroris still alive: the destructor of the exception object releases aPointerValueof a freed runtime (reproducer variant C, JSError outliving its host runtime leads to crashes on deconstructor invocation meta/hermes#1927). Task::execute cannot help, the exception object outlives the runtime.ReactInstancerunsruntimeExecutorcallbacks outside the scheduler with its owncatch (jsi::JSError&)(ReactCommon/react/runtime/ReactInstance.cpp, thejsThread->runOnQueuelambda). Not changed here; the reproducer path goes throughRuntimeSchedulerCallInvoker.Commands and results
[ PASSED ] 102 tests.(/0= legacy,/1= modern scheduler).Task.cppchange:handlingErrorOfAnotherRuntimeInRawCallback/0fails (getLastReportedErrorMessage()is"", expected"Error of another runtime"),handlingErrorOfAnotherRuntimeInRawCallback/1crashes the process (exit code 139,SIGSEGV).buildCodegenCLIwas skipped only because itsbuild.shrunsyarn installin a temporary directory and picked a global Yarn 4 on the test machine; the codegenlib/was built with the repository's Yarn 1 instead.dotslash scripts/clang-format -i(clang-format 21.1.2) on the three files.Device reproduction (0.88.1, POCO X3 Pro, Android 11, Debug build with embedded bundle)
invokeAsynccallback throws on the second runtime):Fatal signal 11 (SIGSEGV), code 2 (SEGV_ACCERR)onmqt_v_js; frameshandleJSError->JsErrorHandler::handleError->RuntimeScheduler_Modern::handleTaskError->RuntimeScheduler_Modern::executeTask.throw jsi::JSError(rnRuntime, error.getMessage())): no crash, RedBox "Error: thrown on the second runtime".Related
jsi::JSErrorin both schedulers withnew Error(message)and the original stack.jsi::JSErroroutliving its runtime.Tests per variant
Tests (all in
packages/react-native/ReactCommon/react/runtime/tests/cxx/ReactInstanceTest.cppunless noted):ReactInstanceTest.testNativeTaskThrowsErrorOfAnotherRuntimeRuntimeSchedulerTest.handlingErrorOfAnotherRuntimeInRawCallback/{0,1}(renderer/runtimescheduler/tests/RuntimeSchedulerTest.cpp)""), /1 SIGSEGVReactInstanceTest.testNativeModuleMethodThrowsErrorOfAnotherRuntimeGTEST_SKIPReactInstanceDeathTest.testNativeTaskThrowsErrorOfDestroyedRuntimeGTEST_SKIPReactInstanceTest.testNativeTaskThrowsErrorConvertedFromAnotherRuntimeReactInstanceTest.testNativeModuleMethodThrowsErrorConvertedFromAnotherRuntimeReactInstanceTest.testNativeModuleMethodThrowsErrorOfAnotherRuntimeDuringBundleEvaluationGTEST_SKIPReactInstanceDeathTest.testNativeModuleMethodThrowsErrorOfDestroyedRuntimeDuringBundleEvaluationGTEST_SKIPReactInstanceDeathTest.testNativeModuleMethodThrowsErrorOfAnotherRuntimeDuringBundleEvaluationAndGarbageCollectionReactInstanceTest.testBindingsInstallerThrowsErrorOfAnotherRuntimeReactInstanceTest.testGlobalHostFunctionThrowsErrorOfAnotherRuntimeDuringBundleEvaluationGTEST_SKIPReactInstanceDeathTest.testGlobalHostFunctionThrowsErrorOfDestroyedRuntimeDuringBundleEvaluationGTEST_SKIPReactInstanceDeathTest.testGlobalHostFunctionThrowsErrorOfAnotherRuntimeDuringBundleEvaluationAndGarbageCollectionReactInstanceTest.testGlobalHostFunctionThrowsErrorOfAnotherRuntimeInTimerGTEST_SKIPReactInstanceDeathTest.testGlobalHostFunctionThrowsErrorOfDestroyedRuntimeInTimerGTEST_SKIPcmake --build private/react-native-fantom/build/tester --target react_runtime_tests react_renderer_runtimescheduler_tests. With the fix, 3 full runs:react_runtime_tests49 passed / 5 skipped (one pre-existing skip),react_renderer_runtimescheduler_tests102 passed.global.__getBundleMetadata, whichJsErrorHandler::handleErrorWithCppPipelinecalls while it reports the error (ReactCommon/jserrorhandler/JsErrorHandler.cpp:98).death_test_style = "threadsafe"because Hermes starts threads before the fork.HFContext::func(API/hermes/hermes.cpp) doessetThrownValue(hvFromValue(error.value())), which moves the pointer of the other runtime's object into the React Native heap. On the macOS host (non-contiguous heap) the crash comes earlier, inthrowPendingError→getNamedWithReceiverwhile Hermes reads the error message.react/renderer/scheduler/tests/SchedulerDelegateInvalidationTest.cppabout flaky death tests).