Skip to content

Commit 76eead6

Browse files
Attach TurboModule identity to exceptions rethrown from async and void calls (#58264)
Summary: 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 Differential Revision: D118144605
1 parent a862ba7 commit 76eead6

2 files changed

Lines changed: 131 additions & 2 deletions

File tree

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

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
#import <jsi/decorator.h>
1414
#import <react/featureflags/ReactNativeFeatureFlags.h>
1515

16+
#import <array>
1617
#import <memory>
1718
#import <vector>
1819

@@ -32,6 +33,27 @@ @implementation RCTTestTurboModule
3233

3334
@end
3435

36+
@interface RCTThrowingTurboModule : NSObject <RCTBridgeModule>
37+
38+
@end
39+
40+
@implementation RCTThrowingTurboModule
41+
42+
RCT_EXPORT_MODULE()
43+
44+
// A plain `NSArray *` parameter has no element converter to sanitise it (unlike, say,
45+
// `NSArray<NSString *> *`, which RCTConvert routes through `NSStringArray:` and which drops nulls),
46+
// so `convertJSIArrayToNSArray` substituting `[NSNull null]` for a null element to preserve the
47+
// indices is what this loop actually receives from a JS caller passing `['a', null]`.
48+
RCT_EXPORT_METHOD(testMethodWhichReadsStringsFromArray : (NSArray *)items)
49+
{
50+
for (NSUInteger i = 0; i < items.count; i++) {
51+
(void)[(NSString *)items[i] length];
52+
}
53+
}
54+
55+
@end
56+
3557
// Minimal concrete MutableBuffer that owns its bytes, used to observe lifetime.
3658
class TestMutableBuffer : public facebook::jsi::MutableBuffer {
3759
public:
@@ -94,6 +116,37 @@ void invokeSync(const std::string &methodName, NativeMethodCallFunc &&func) noex
94116
}
95117
};
96118

119+
// `NativeMethodCallInvoker::invokeAsync` is noexcept, so an NSException escaping the async
120+
// invocation terminates the process — which is the production failure mode, but leaves nothing for
121+
// a test to inspect. Catching here stands in for the process-level handler and puts the exception
122+
// exactly where that handler would see it.
123+
class ExceptionCapturingNativeMethodCallInvoker : public NativeMethodCallInvoker {
124+
public:
125+
__strong NSException *caught = nil;
126+
127+
void invokeAsync(const std::string & /*methodName*/, NativeMethodCallFunc &&func) noexcept override
128+
{
129+
// The outer C++ handler is what makes the `noexcept` honest: `func` is a std::function, and
130+
// invoking an empty one throws a `std::bad_function_call` that `@catch (NSException *)` cannot
131+
// bind.
132+
try {
133+
@try {
134+
func();
135+
} @catch (NSException *exception) {
136+
caught = exception;
137+
}
138+
} catch (...) {
139+
}
140+
}
141+
void invokeSync(const std::string & /*methodName*/, NativeMethodCallFunc &&func) noexcept override
142+
{
143+
try {
144+
func();
145+
} catch (...) {
146+
}
147+
}
148+
};
149+
97150
@interface RCTTurboModuleTests : XCTestCase
98151
@end
99152

@@ -159,6 +212,52 @@ - (void)testInvokeTurboModuleWithNull
159212
OCMVerify(OCMTimes(1), [instance_ testMethodWhichTakesObject:nil]);
160213
}
161214

215+
// Void methods are always async, so an NSException raised by the module unwinds past every module
216+
// frame before anything reports it. The rethrow is the last point at which the failing module and
217+
// method are still known, so it has to put them on the exception.
218+
- (void)testVoidMethodExceptionCarriesModuleAndMethodName
219+
{
220+
auto hermesRuntime = facebook::hermes::makeHermesRuntime();
221+
facebook::jsi::Runtime *rt = hermesRuntime.get();
222+
223+
auto invoker = std::make_shared<ExceptionCapturingNativeMethodCallInvoker>();
224+
RCTThrowingTurboModule *instance = [RCTThrowingTurboModule new];
225+
ObjCTurboModule::InitParams params = {
226+
.moduleName = "ThrowingTestModule",
227+
.instance = instance,
228+
.jsInvoker = nullptr,
229+
.nativeMethodCallInvoker = invoker,
230+
.isSyncModule = false,
231+
};
232+
ObjCTurboModule module(params);
233+
234+
auto items = facebook::jsi::Array(*rt, 2);
235+
items.setValueAtIndex(*rt, 0, facebook::jsi::String::createFromAscii(*rt, "a"));
236+
items.setValueAtIndex(*rt, 1, facebook::jsi::Value::null());
237+
std::array<facebook::jsi::Value, 1> args = {facebook::jsi::Value(*rt, items)};
238+
239+
module.invokeObjCMethod(
240+
*rt,
241+
VoidKind,
242+
"testMethodWhichReadsStringsFromArray",
243+
@selector(testMethodWhichReadsStringsFromArray:),
244+
args.data(),
245+
1);
246+
247+
NSException *caught = invoker->caught;
248+
XCTAssertNotNil(caught, @"Sending -length to the NSNull standing in for the null element must raise");
249+
XCTAssertEqualObjects(caught.name, NSInvalidArgumentException);
250+
XCTAssertTrue(
251+
[caught.reason containsString:@"ThrowingTestModule"], @"reason must name the module: %@", caught.reason);
252+
XCTAssertTrue(
253+
[caught.reason containsString:@"testMethodWhichReadsStringsFromArray"],
254+
@"reason must name the method: %@",
255+
caught.reason);
256+
// The original failure has to survive alongside the identity rather than be replaced by it.
257+
XCTAssertTrue([caught.reason containsString:@"unrecognized selector"], @"%@", caught.reason);
258+
XCTAssertNotNil(caught.userInfo[@"RCTTurboModuleOriginalCallStackReturnAddresses"]);
259+
}
260+
162261
// A native-backed ArrayBuffer is aliased rather than copied, and the RCTArrayBuffer retains
163262
// the backing MutableBuffer, so the alias outlives the JS object.
164263
- (void)testNativeBackedArrayBufferIsAliasedAndKeepsBackingStoreAlive

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

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

310+
/**
311+
* userInfo key under which `addModuleIdentityToException` preserves the raise-site call stack of
312+
* the exception it wraps.
313+
*/
314+
static NSString *const RCTTurboModuleOriginalCallStackReturnAddressesKey =
315+
@"RCTTurboModuleOriginalCallStackReturnAddresses";
316+
317+
/**
318+
* Async and void method calls have no JS runtime to attach a JSError to, so an NSException raised
319+
* by the module escapes to the process-level handler instead. The stack it arrives with has
320+
* already unwound past the module, so unless the module and method names travel on the exception
321+
* itself the resulting crash cannot be attributed to an owning module.
322+
*/
323+
static NSException *
324+
addModuleIdentityToException(NSException *exception, const char *moduleName, const std::string &methodName)
325+
{
326+
// A newly constructed NSException captures its call stack at @throw rather than at the original
327+
// raise, so the raise-site addresses have to be carried across by hand.
328+
NSMutableDictionary *userInfo =
329+
[NSMutableDictionary dictionaryWithDictionary:exception.userInfo != nil ? exception.userInfo : @{}];
330+
userInfo[RCTTurboModuleOriginalCallStackReturnAddressesKey] = exception.callStackReturnAddresses;
331+
332+
return [NSException exceptionWithName:exception.name
333+
reason:[NSString stringWithFormat:@"%s.%s raised an exception: %@",
334+
moduleName,
335+
methodName.c_str(),
336+
exception.reason]
337+
userInfo:userInfo];
338+
}
339+
310340
/**
311341
* Creates JS error value with current JS runtime and error details.
312342
*/
@@ -477,7 +507,7 @@ id convertJSIValueToObjCObject(
477507
// See https://github.com/reactwg/react-native-new-architecture/discussions/276#discussioncomment-12567155
478508
throw convertNSExceptionToJSError(runtime, exception, std::string{moduleName}, methodNameStr);
479509
} else {
480-
@throw exception;
510+
@throw addModuleIdentityToException(exception, moduleName, methodNameStr);
481511
}
482512
} @finally {
483513
[retainedObjectsForInvocation removeAllObjects];
@@ -539,7 +569,7 @@ TraceSection s(
539569
} @catch (NSException *exception) {
540570
// Void methods are always async, re-throw instead of converting to
541571
// JSError, same as the async branch in performMethodInvocation.
542-
@throw exception;
572+
@throw addModuleIdentityToException(exception, moduleName, methodNameStr);
543573
} @finally {
544574
[retainedObjectsForInvocation removeAllObjects];
545575
}

0 commit comments

Comments
 (0)