Skip to content

Commit 253a84c

Browse files
christophpurrermeta-codesync[bot]
authored andcommitted
Attach TurboModule identity to exceptions rethrown from async and void calls (#58264)
Summary: Pull Request resolved: #58264 When an ObjC TurboModule method raises an `NSException`, what happens next depends on how it was called. A sync call converts it into a JSError via `convertNSExceptionToJSError`, which builds `<module>.<method> raised an exception: <reason>`. The async and void paths cannot do that — they run on the module's method queue with no JS runtime to attach the error to — so they rethrow. Both rethrow sites discarded `moduleName` and `methodNameStr`, even though both are captured in the enclosing block and in scope at the throw site. Because void and async methods are dispatched onto the method queue, the rethrown exception is uncaught and terminates the process, and by then every module frame has unwound: the reported stack bottoms out in `objc_exception_rethrow` followed by a libdispatch queue drain. Nothing in the resulting crash says which module or method failed. The practical effect is that all such crashes — regardless of which module raised them, and regardless of whether the underlying bug is a null argument, a wrong-typed argument, or anything else — collapse into a single crash bucket with no owner attached, and cannot be split or routed. This adds an `addModuleIdentityToException` helper next to `convertNSExceptionToJSError` and applies it at both rethrow sites. It preserves the exception's `name` and its existing `userInfo` entries so any predicate-based handling is unaffected, and prefixes `reason` with `<module>.<method>` to match the sync path's wording. A freshly constructed `NSException` captures its call stack at `throw` rather than at the original raise, so the raise-site return addresses are carried across in `userInfo` and nothing is lost. Behaviour is otherwise unchanged: the exception is still thrown, on the same thread, at the same point, with the same name. Nothing is caught, swallowed, logged away, or downgraded. Reviewers should expect the crash grouping to change: the existing aggregate bucket will drain and be replaced by per-module buckets. That is the point of the change, but it is worth knowing before it happens. Changelog: [iOS][Fixed] - Include the module and method name in exceptions rethrown from async and void TurboModule calls Reviewed By: javache Differential Revision: D118144605 fbshipit-source-id: fb51936e73c7705ae4e23f650834d2c66e66a50e
1 parent 3f9f385 commit 253a84c

2 files changed

Lines changed: 132 additions & 2 deletions

File tree

packages/react-native/ReactCommon/react/nativemodule/core/iostests/RCTTurboModuleTests.mm

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,27 @@ - (void)logEvent:(NSString *)eventName data:(NSDictionary *)data analyticsModule
4848

4949
@end
5050

51+
@interface RCTThrowingTurboModule : NSObject <RCTBridgeModule>
52+
53+
@end
54+
55+
@implementation RCTThrowingTurboModule
56+
57+
RCT_EXPORT_MODULE()
58+
59+
// A plain `NSArray *` parameter has no element converter to sanitise it (unlike, say,
60+
// `NSArray<NSString *> *`, which RCTConvert routes through `NSStringArray:` and which drops nulls),
61+
// so `convertJSIArrayToNSArray` substituting `[NSNull null]` for a null element to preserve the
62+
// indices is what this loop actually receives from a JS caller passing `['a', null]`.
63+
RCT_EXPORT_METHOD(testMethodWhichReadsStringsFromArray : (NSArray *)items)
64+
{
65+
for (NSUInteger i = 0; i < items.count; i++) {
66+
(void)[(NSString *)items[i] length];
67+
}
68+
}
69+
70+
@end
71+
5172
class ReactNativeFeatureFlagsNSNullConversionEnabled : public ReactNativeFeatureFlagsDefaults {
5273
public:
5374
bool enableModuleArgumentNSNullConversionIOS() override
@@ -118,6 +139,37 @@ void invokeSync(const std::string &methodName, NativeMethodCallFunc &&func) noex
118139
}
119140
};
120141

142+
// `NativeMethodCallInvoker::invokeAsync` is noexcept, so an NSException escaping the async
143+
// invocation terminates the process — which is the production failure mode, but leaves nothing for
144+
// a test to inspect. Catching here stands in for the process-level handler and puts the exception
145+
// exactly where that handler would see it.
146+
class ExceptionCapturingNativeMethodCallInvoker : public NativeMethodCallInvoker {
147+
public:
148+
__strong NSException *caught = nil;
149+
150+
void invokeAsync(const std::string & /*methodName*/, NativeMethodCallFunc &&func) noexcept override
151+
{
152+
// The outer C++ handler is what makes the `noexcept` honest: `func` is a std::function, and
153+
// invoking an empty one throws a `std::bad_function_call` that `@catch (NSException *)` cannot
154+
// bind.
155+
try {
156+
@try {
157+
func();
158+
} @catch (NSException *exception) {
159+
caught = exception;
160+
}
161+
} catch (...) {
162+
}
163+
}
164+
void invokeSync(const std::string & /*methodName*/, NativeMethodCallFunc &&func) noexcept override
165+
{
166+
try {
167+
func();
168+
} catch (...) {
169+
}
170+
}
171+
};
172+
121173
@interface RCTTurboModuleTests : XCTestCase
122174
@end
123175

@@ -253,6 +305,55 @@ - (void)testInvokeTurboModuleKeepsNestedNullAsNSNullWhenFlagEnabled
253305
OCMVerify(OCMTimes(1), [instance_ testMethodWhichTakesObject:@{@"foo" : (id)kCFNull}]);
254306
}
255307

308+
// Void methods are always async, so an NSException raised by the module unwinds past every module
309+
// frame before anything reports it. The rethrow is the last point at which the failing module and
310+
// method are still known, so it has to put them on the exception.
311+
- (void)testVoidMethodExceptionCarriesModuleAndMethodName
312+
{
313+
auto hermesRuntime = facebook::hermes::makeHermesRuntime();
314+
facebook::jsi::Runtime *rt = hermesRuntime.get();
315+
316+
auto invoker = std::make_shared<ExceptionCapturingNativeMethodCallInvoker>();
317+
RCTThrowingTurboModule *instance = [RCTThrowingTurboModule new];
318+
ObjCTurboModule::InitParams params = {
319+
.moduleName = "ThrowingTestModule",
320+
.instance = instance,
321+
.jsInvoker = nullptr,
322+
.nativeMethodCallInvoker = invoker,
323+
.isSyncModule = false,
324+
};
325+
ObjCTurboModule module(params);
326+
327+
auto items = facebook::jsi::Array(*rt, 2);
328+
items.setValueAtIndex(*rt, 0, facebook::jsi::String::createFromAscii(*rt, "a"));
329+
items.setValueAtIndex(*rt, 1, facebook::jsi::Value::null());
330+
std::array<facebook::jsi::Value, 1> args = {facebook::jsi::Value(*rt, items)};
331+
332+
module.invokeObjCMethod(
333+
*rt,
334+
VoidKind,
335+
"testMethodWhichReadsStringsFromArray",
336+
@selector(testMethodWhichReadsStringsFromArray:),
337+
args.data(),
338+
1);
339+
340+
NSException *caught = invoker->caught;
341+
XCTAssertNotNil(caught, @"Sending -length to the NSNull standing in for the null element must raise");
342+
XCTAssertEqualObjects(caught.name, NSInvalidArgumentException);
343+
XCTAssertTrue(
344+
[caught.reason containsString:@"ThrowingTestModule"], @"reason must name the module: %@", caught.reason);
345+
XCTAssertTrue(
346+
[caught.reason containsString:@"testMethodWhichReadsStringsFromArray"],
347+
@"reason must name the method: %@",
348+
caught.reason);
349+
// The original failure has to survive alongside the identity rather than be replaced by it.
350+
XCTAssertTrue([caught.reason containsString:@"unrecognized selector"], @"%@", caught.reason);
351+
NSException *original = caught.userInfo[@"RCTTurboModuleOriginalException"];
352+
XCTAssertNotNil(original);
353+
XCTAssertNotNil(original.callStackReturnAddresses);
354+
XCTAssertNotNil(original.callStackSymbols);
355+
}
356+
256357
// A native-backed ArrayBuffer is aliased rather than copied, and the RCTArrayBuffer retains
257358
// the backing MutableBuffer, so the alias outlives the JS object.
258359
- (void)testNativeBackedArrayBufferIsAliasedAndKeepsBackingStoreAlive

packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModule.mm

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,35 @@ id convertJSIValueToObjCObject(
307307
return {runtime, std::move(error)};
308308
}
309309

310+
/**
311+
* userInfo key under which `addModuleIdentityToException` preserves the exception it wraps, so its
312+
* raise-site `callStackReturnAddresses` and `callStackSymbols` stay available to symbolication.
313+
*/
314+
static NSString *const RCTTurboModuleOriginalExceptionKey = @"RCTTurboModuleOriginalException";
315+
316+
/**
317+
* Async and void method calls have no JS runtime to attach a JSError to, so an NSException raised
318+
* by the module escapes to the process-level handler instead. The stack it arrives with has
319+
* already unwound past the module, so unless the module and method names travel on the exception
320+
* itself the resulting crash cannot be attributed to an owning module.
321+
*/
322+
static NSException *
323+
addModuleIdentityToException(NSException *exception, const std::string &moduleName, const std::string &methodName)
324+
{
325+
// A newly constructed NSException captures its call stack at @throw rather than at the original
326+
// raise, so the original exception is carried across whole.
327+
NSMutableDictionary *userInfo =
328+
[NSMutableDictionary dictionaryWithDictionary:exception.userInfo != nil ? exception.userInfo : @{}];
329+
userInfo[RCTTurboModuleOriginalExceptionKey] = exception;
330+
331+
return [NSException exceptionWithName:exception.name
332+
reason:[NSString stringWithFormat:@"%s.%s raised an exception: %@",
333+
moduleName.c_str(),
334+
methodName.c_str(),
335+
exception.reason]
336+
userInfo:userInfo];
337+
}
338+
310339
/**
311340
* Creates JS error value with current JS runtime and error details.
312341
*/
@@ -477,7 +506,7 @@ id convertJSIValueToObjCObject(
477506
// See https://github.com/reactwg/react-native-new-architecture/discussions/276#discussioncomment-12567155
478507
throw convertNSExceptionToJSError(runtime, exception, std::string{moduleName}, methodNameStr);
479508
} else {
480-
@throw exception;
509+
@throw addModuleIdentityToException(exception, std::string{moduleName}, methodNameStr);
481510
}
482511
} @finally {
483512
[retainedObjectsForInvocation removeAllObjects];
@@ -539,7 +568,7 @@ TraceSection s(
539568
} @catch (NSException *exception) {
540569
// Void methods are always async, re-throw instead of converting to
541570
// JSError, same as the async branch in performMethodInvocation.
542-
@throw exception;
571+
@throw addModuleIdentityToException(exception, std::string{moduleName}, methodNameStr);
543572
} @finally {
544573
[retainedObjectsForInvocation removeAllObjects];
545574
}

0 commit comments

Comments
 (0)