Skip to content

Commit a778979

Browse files
zhongwuzwfacebook-github-bot
authored andcommitted
Fixes main thread stuck when reload in bridgeless mode (#45486)
Summary: In fabric bridgeless mode, when we reload, main thread may block because of dead lock. the backtrace example as below: ``` (lldb) bt * thread #1, stop reason = signal SIGSTOP * frame #0: 0x000000010a5c76f2 libsystem_kernel.dylib`__psynch_mutexwait + 10 frame #1: 0x00000001099e0a70 libsystem_pthread.dylib`_pthread_mutex_firstfit_lock_wait + 78 frame #2: 0x00000001099de82b libsystem_pthread.dylib`_pthread_mutex_firstfit_lock_slow + 217 frame #3: 0x00007ff80030c6b9 libc++.1.dylib`std::__1::mutex::lock() + 9 frame #4: 0x0000000106968b13 RNTester`std::__1::lock_guard<std::__1::mutex>::lock_guard[abi:ue170006](this=0x00007ff7b95e2478, __m=0x000060000377c958) at lock_guard.h:35:10 frame #5: 0x00000001069689ed RNTester`std::__1::lock_guard<std::__1::mutex>::lock_guard[abi:ue170006](this=0x00007ff7b95e2478, __m=0x000060000377c958) at lock_guard.h:34:19 frame #6: 0x00000001070691c1 RNTester`-[RCTInstance invalidate](self=0x000060000377c900, _cmd="invalidate") at RCTInstance.mm:146:31 frame #7: 0x0000000107060fd2 RNTester`-[RCTHost didReceiveReloadCommand](self=0x0000600003d100f0, _cmd="didReceiveReloadCommand") at RCTHost.mm:317:3 frame #8: 0x0000000106b005a5 RNTester`RCTTriggerReloadCommandListeners(reason=@"Global hotkey") at RCTReloadCommand.m:57:5 frame #9: 0x0000000106b86da5 RNTester`__28-[RCTDevSettings initialize]_block_invoke.157(.block_descriptor=0x0000000107496170, params=0x00007ff84002f610) at RCTDevSettings.mm:201:11 frame #10: 0x0000000106ae658e RNTester`__65-[RCTPackagerConnection reconnectingWebSocket:didReceiveMessage:]_block_invoke.68(.block_descriptor=0x0000600000c82df0) at RCTPackagerConnection.mm:293:9 frame #11: 0x0000000109a4529d libdispatch.dylib`_dispatch_call_block_and_release + 12 frame #12: 0x0000000109a4658f libdispatch.dylib`_dispatch_client_callout + 8 frame #13: 0x0000000109a563ee libdispatch.dylib`_dispatch_main_queue_drain + 1362 frame #14: 0x0000000109a55e8e libdispatch.dylib`_dispatch_main_queue_callback_4CF + 31 frame #15: 0x00007ff800429af4 CoreFoundation`__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9 frame #16: 0x00007ff80042442f CoreFoundation`__CFRunLoopRun + 2463 frame #17: 0x00007ff8004236ad CoreFoundation`CFRunLoopRunSpecific + 557 frame #18: 0x00007ff8103da08f GraphicsServices`GSEventRunModal + 137 frame #19: 0x00007ff805cc0ad1 UIKitCore`-[UIApplication _run] + 972 frame #20: 0x00007ff805cc5551 UIKitCore`UIApplicationMain + 123 frame #21: 0x00000001069205a0 RNTester`main(argc=1, argv=0x00007ff7b95e3b60) at main.m:15:12 frame #22: 0x00000001099023e0 dyld_sim`start_sim + 10 frame #23: 0x0000000116b92366 dyld`start + 1942 (lldb) bt * thread #3 frame #0: 0x000000010a5c6b86 libsystem_kernel.dylib`__ulock_wait + 10 frame #1: 0x0000000109a46eb1 libdispatch.dylib`_dlock_wait + 46 frame #2: 0x0000000109a46d08 libdispatch.dylib`_dispatch_thread_event_wait_slow + 40 frame #3: 0x0000000109a5774a libdispatch.dylib`__DISPATCH_WAIT_FOR_QUEUE__ + 371 frame #4: 0x0000000109a57161 libdispatch.dylib`_dispatch_sync_f_slow + 240 frame #5: 0x0000000106b3b33b RNTester`RCTUnsafeExecuteOnMainQueueSync(block=0x0000000106f116c0) at RCTUtils.m:291:5 * frame #6: 0x0000000106f115ad RNTester`-[RCTFabricSurface start](self=0x000000010af0df40, _cmd="start") at RCTFabricSurface.mm:102:3 frame #7: 0x00000001070601ce RNTester`__108-[RCTHost initWithBundleURLProvider:hostDelegate:turboModuleManagerDelegate:jsEngineProvider:launchOptions:]_block_invoke_2(.block_descriptor=0x0000600000c75590) at RCTHost.mm:211:9 frame #8: 0x000000010706cdc8 RNTester`-[RCTInstance _loadScriptFromSource:](self=0x000060000377c900, _cmd="_loadScriptFromSource:", source=0x0000600000cd57d0) at RCTInstance.mm:472:5 frame #9: 0x000000010706ca81 RNTester`__29-[RCTInstance _loadJSBundle:]_block_invoke.120(.block_descriptor=0x0000600000c96d00, error=0x0000000000000000, source=0x0000600000cd57d0) at RCTInstance.mm:452:9 frame #10: 0x0000000106ab1919 RNTester`invocation function for block in attemptAsynchronousLoadOfBundleAtURL(.block_descriptor=0x00006000017b0fc0, statusCode=200, headers=6 key/value pairs, data=0x00006000002a4760, error=0x0000000000000000, done=YES) block_pointer, void (NSError*, RCTSource*) block_pointer) at RCTJavaScriptLoader.mm:318:9 frame #11: 0x0000000106ad92a6 RNTester`__80-[RCTMultipartDataTask URLSession:streamTask:didBecomeInputStream:outputStream:]_block_invoke(.block_descriptor=0x000070000035c7a0, headers=6 key/value pairs, content=0x00006000002a4760, done=YES) at RCTMultipartDataTask.m:121:9 frame #12: 0x0000000106ad9b4f RNTester`-[RCTMultipartStreamReader emitChunk:headers:callback:done:](self=0x00006000002b4220, _cmd="emitChunk:headers:callback:done:", data=0x00006000002a4020, headers=6 key/value pairs, callback=0x0000000106ad9230, done=YES) at RCTMultipartStreamReader.m:57:5 frame #13: 0x0000000106ada800 RNTester`-[RCTMultipartStreamReader readAllPartsWithCompletionCallback:progressCallback:](self=0x00006000002b4220, _cmd="readAllPartsWithCompletionCallback:progressCallback:", callback=0x0000000106ad9230, progressCallback=0x0000000106ab2a60) at RCTMultipartStreamReader.m:154:7 frame #14: 0x0000000106ad9130 RNTester`-[RCTMultipartDataTask URLSession:streamTask:didBecomeInputStream:outputStream:](self=0x00006000017b0d40, _cmd="URLSession:streamTask:didBecomeInputStream:outputStream:", session=0x000000010e02a0a0, streamTask=0x000000010c83ba00, inputStream=0x000060000300d4d0, outputStream=0x000060000300c990) at RCTMultipartDataTask.m:119:20 frame #15: 0x00007ff80479fdf9 CFNetwork`___lldb_unnamed_symbol2876 + 42 frame #16: 0x0000000109a4529d libdispatch.dylib`_dispatch_call_block_and_release + 12 frame #17: 0x0000000109a4658f libdispatch.dylib`_dispatch_client_callout + 8 frame #18: 0x0000000109a4e4ba libdispatch.dylib`_dispatch_lane_serial_drain + 1127 frame #19: 0x0000000109a4f255 libdispatch.dylib`_dispatch_lane_invoke + 441 frame #20: 0x0000000109a5c356 libdispatch.dylib`_dispatch_root_queue_drain_deferred_wlh + 318 frame #21: 0x0000000109a5b751 libdispatch.dylib`_dispatch_workloop_worker_thread + 590 frame #22: 0x00000001099dfb84 libsystem_pthread.dylib`_pthread_wqthread + 327 frame #23: 0x00000001099deacf libsystem_pthread.dylib`start_wqthread + 15 ``` ## Changelog: [IOS] [FIXED] - Fixes main thread stuck when reload in bridgeless mode Pull Request resolved: #45486 Test Plan: RNTester, enables fabric, which is very easy to repro by tapping `r` command multiple times quickly to trigger reload. Reviewed By: philIip Differential Revision: D59911929 Pulled By: cipolleschi fbshipit-source-id: e7e431a11d26c399fa767b6cbf45e16bce24b9a0
1 parent 878e1f3 commit a778979

File tree

5 files changed

+18
-68
lines changed

5 files changed

+18
-68
lines changed

packages/react-native/ReactCommon/react/runtime/ReactInstance.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -152,8 +152,8 @@ RuntimeExecutor ReactInstance::getUnbufferedRuntimeExecutor() noexcept {
152152

153153
// This BufferedRuntimeExecutor ensures that the main JS bundle finished
154154
// execution before any JS queued into it from C++ are executed. Use
155-
// getBufferedRuntimeExecutor() instead if you do not need the main JS bundle to
156-
// have finished. e.g. setting global variables into JS runtime.
155+
// getUnbufferedRuntimeExecutor() instead if you do not need the main JS bundle
156+
// to have finished. e.g. setting global variables into JS runtime.
157157
RuntimeExecutor ReactInstance::getBufferedRuntimeExecutor() noexcept {
158158
return [weakBufferedRuntimeExecutor_ =
159159
std::weak_ptr<BufferedRuntimeExecutor>(bufferedRuntimeExecutor_)](

packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTHost.mm

Lines changed: 2 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -104,11 +104,6 @@ @implementation RCTHost {
104104

105105
NSDictionary *_launchOptions;
106106

107-
// All the surfaces that need to be started after main bundle execution
108-
NSMutableArray<RCTFabricSurface *> *_surfaceStartBuffer;
109-
std::mutex _surfaceStartBufferMutex;
110-
111-
RCTInstanceInitialBundleLoadCompletionBlock _onInitialBundleLoad;
112107
std::vector<__weak RCTFabricSurface *> _attachedSurfaces;
113108

114109
RCTModuleRegistry *_moduleRegistry;
@@ -152,7 +147,6 @@ - (instancetype)initWithBundleURLProvider:(RCTHostBundleURLProvider)provider
152147
if (self = [super init]) {
153148
_hostDelegate = hostDelegate;
154149
_turboModuleManagerDelegate = turboModuleManagerDelegate;
155-
_surfaceStartBuffer = [NSMutableArray new];
156150
_bundleManager = [RCTBundleManager new];
157151
_moduleRegistry = [RCTModuleRegistry new];
158152
_jsEngineProvider = [jsEngineProvider copy];
@@ -185,33 +179,6 @@ - (instancetype)initWithBundleURLProvider:(RCTHostBundleURLProvider)provider
185179
andSetter:bundleURLSetter
186180
andDefaultGetter:defaultBundleURLGetter];
187181

188-
/**
189-
* TODO (T108401473) Remove _onInitialBundleLoad, because it was initially
190-
* introduced to start surfaces after the main JSBundle was fully executed.
191-
* It is no longer needed because Fabric now dispatches all native-to-JS calls
192-
* onto the JS thread, including JS calls to start Fabric surfaces.
193-
* JS calls should be dispatched using the BufferedRuntimeExecutor, which can buffer
194-
* JS calls before the main JSBundle finishes execution, and execute them after.
195-
*/
196-
_onInitialBundleLoad = ^{
197-
RCTHost *strongSelf = weakSelf;
198-
if (!strongSelf) {
199-
return;
200-
}
201-
202-
NSArray<RCTFabricSurface *> *unstartedSurfaces = @[];
203-
204-
{
205-
std::lock_guard<std::mutex> guard{strongSelf->_surfaceStartBufferMutex};
206-
unstartedSurfaces = [NSArray arrayWithArray:strongSelf->_surfaceStartBuffer];
207-
strongSelf->_surfaceStartBuffer = nil;
208-
}
209-
210-
for (RCTFabricSurface *surface in unstartedSurfaces) {
211-
[surface start];
212-
}
213-
};
214-
215182
// Listen to reload commands
216183
dispatch_async(dispatch_get_main_queue(), ^{
217184
RCTRegisterReloadCommandListener(self);
@@ -261,7 +228,6 @@ - (void)start
261228
jsRuntimeFactory:[self _provideJSEngine]
262229
bundleManager:_bundleManager
263230
turboModuleManagerDelegate:_turboModuleManagerDelegate
264-
onInitialBundleLoad:_onInitialBundleLoad
265231
moduleRegistry:_moduleRegistry
266232
parentInspectorTarget:_inspectorTarget.get()
267233
launchOptions:_launchOptions];
@@ -278,15 +244,7 @@ - (RCTFabricSurface *)createSurfaceWithModuleName:(NSString *)moduleName
278244
surface.surfaceHandler.setDisplayMode(displayMode);
279245
[self _attachSurface:surface];
280246

281-
{
282-
std::lock_guard<std::mutex> guard{_surfaceStartBufferMutex};
283-
if (_surfaceStartBuffer) {
284-
[_surfaceStartBuffer addObject:surface];
285-
return surface;
286-
}
287-
}
288-
289-
[surface start];
247+
[_instance callFunctionOnBufferedRumtimeExecutor:[surface](facebook::jsi::Runtime &_) { [surface start]; }];
290248
return surface;
291249
}
292250

@@ -320,24 +278,18 @@ - (void)didReceiveReloadCommand
320278
[self _setBundleURL:_bundleURLProvider()];
321279
}
322280

323-
// Ensure all attached surfaces are restarted after reload
324-
{
325-
std::lock_guard<std::mutex> guard{_surfaceStartBufferMutex};
326-
_surfaceStartBuffer = [NSMutableArray arrayWithArray:[self _getAttachedSurfaces]];
327-
}
328-
329281
_instance = [[RCTInstance alloc] initWithDelegate:self
330282
jsRuntimeFactory:[self _provideJSEngine]
331283
bundleManager:_bundleManager
332284
turboModuleManagerDelegate:_turboModuleManagerDelegate
333-
onInitialBundleLoad:_onInitialBundleLoad
334285
moduleRegistry:_moduleRegistry
335286
parentInspectorTarget:_inspectorTarget.get()
336287
launchOptions:_launchOptions];
337288
[_hostDelegate hostDidStart:self];
338289

339290
for (RCTFabricSurface *surface in [self _getAttachedSurfaces]) {
340291
[surface resetWithSurfacePresenter:self.surfacePresenter];
292+
[_instance callFunctionOnBufferedRumtimeExecutor:[surface](facebook::jsi::Runtime &_) { [surface start]; }];
341293
}
342294
}
343295

packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTInstance.h

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,6 @@ RCT_EXTERN void RCTInstanceSetRuntimeDiagnosticFlags(NSString *_Nullable flags);
4646

4747
@end
4848

49-
typedef void (^_Null_unspecified RCTInstanceInitialBundleLoadCompletionBlock)();
50-
5149
/**
5250
* RCTInstance owns and manages most of the pieces of infrastructure required to display a screen powered by React
5351
* Native. RCTInstance should never be instantiated in product code, but rather accessed through RCTHost. The host
@@ -59,12 +57,12 @@ typedef void (^_Null_unspecified RCTInstanceInitialBundleLoadCompletionBlock)();
5957
jsRuntimeFactory:(std::shared_ptr<facebook::react::JSRuntimeFactory>)jsRuntimeFactory
6058
bundleManager:(RCTBundleManager *)bundleManager
6159
turboModuleManagerDelegate:(id<RCTTurboModuleManagerDelegate>)turboModuleManagerDelegate
62-
onInitialBundleLoad:(RCTInstanceInitialBundleLoadCompletionBlock)onInitialBundleLoad
6360
moduleRegistry:(RCTModuleRegistry *)moduleRegistry
6461
parentInspectorTarget:(facebook::react::jsinspector_modern::HostTarget *)parentInspectorTarget
6562
launchOptions:(nullable NSDictionary *)launchOptions;
6663

6764
- (void)callFunctionOnJSModule:(NSString *)moduleName method:(NSString *)method args:(NSArray *)args;
65+
- (void)callFunctionOnBufferedRumtimeExecutor:(std::function<void(facebook::jsi::Runtime &runtime)> &&)executor;
6866

6967
- (void)registerSegmentWithId:(NSNumber *)segmentId path:(NSString *)path;
7068

packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTInstance.mm

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,6 @@ @implementation RCTInstance {
7878
RCTSurfacePresenter *_surfacePresenter;
7979
RCTPerformanceLogger *_performanceLogger;
8080
RCTDisplayLink *_displayLink;
81-
RCTInstanceInitialBundleLoadCompletionBlock _onInitialBundleLoad;
8281
RCTTurboModuleManager *_turboModuleManager;
8382
std::mutex _invalidationMutex;
8483
std::atomic<bool> _valid;
@@ -97,7 +96,6 @@ - (instancetype)initWithDelegate:(id<RCTInstanceDelegate>)delegate
9796
jsRuntimeFactory:(std::shared_ptr<facebook::react::JSRuntimeFactory>)jsRuntimeFactory
9897
bundleManager:(RCTBundleManager *)bundleManager
9998
turboModuleManagerDelegate:(id<RCTTurboModuleManagerDelegate>)tmmDelegate
100-
onInitialBundleLoad:(RCTInstanceInitialBundleLoadCompletionBlock)onInitialBundleLoad
10199
moduleRegistry:(RCTModuleRegistry *)moduleRegistry
102100
parentInspectorTarget:(jsinspector_modern::HostTarget *)parentInspectorTarget
103101
launchOptions:(nullable NSDictionary *)launchOptions
@@ -111,7 +109,6 @@ - (instancetype)initWithDelegate:(id<RCTInstanceDelegate>)delegate
111109
_jsRuntimeFactory = jsRuntimeFactory;
112110
_appTMMDelegate = tmmDelegate;
113111
_jsThreadManager = [RCTJSThreadManager new];
114-
_onInitialBundleLoad = onInitialBundleLoad;
115112
_bridgeModuleDecorator = [[RCTBridgeModuleDecorator alloc] initWithViewRegistry:[RCTViewRegistry new]
116113
moduleRegistry:moduleRegistry
117114
bundleManager:bundleManager
@@ -393,6 +390,15 @@ - (void)_attachBridgelessAPIsToModule:(id<RCTTurboModule>)module
393390
}
394391
}
395392

393+
- (void)callFunctionOnBufferedRumtimeExecutor:(std::function<void(facebook::jsi::Runtime &)> &&)executor
394+
{
395+
_reactInstance->getBufferedRuntimeExecutor()([=](jsi::Runtime &runtime) {
396+
if (executor) {
397+
executor(runtime);
398+
}
399+
});
400+
}
401+
396402
- (void)handleBundleLoadingError:(NSError *)error
397403
{
398404
if (!_valid) {
@@ -467,11 +473,6 @@ - (void)_loadScriptFromSource:(RCTSource *)source
467473
const auto *url = deriveSourceURL(source.url).UTF8String;
468474
_reactInstance->loadScript(std::move(script), url);
469475
[[NSNotificationCenter defaultCenter] postNotificationName:@"RCTInstanceDidLoadBundle" object:nil];
470-
471-
if (_onInitialBundleLoad) {
472-
_onInitialBundleLoad();
473-
_onInitialBundleLoad = nil;
474-
}
475476
}
476477

477478
- (void)_handleJSError:(const JsErrorHandler::ParsedError &)error

packages/react-native/ReactCommon/react/test_utils/ios/Shims/ShimRCTInstance.mm

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ - (instancetype)init
2323
[RCTInstance class],
2424
[ShimRCTInstance class],
2525
@selector(initWithDelegate:
26-
jsRuntimeFactory:bundleManager:turboModuleManagerDelegate:onInitialBundleLoad:moduleRegistry
27-
:parentInspectorTarget:launchOptions:));
26+
jsRuntimeFactory:bundleManager:turboModuleManagerDelegate:moduleRegistry:parentInspectorTarget
27+
:launchOptions:));
2828
RCTSwizzleInstanceSelector([RCTInstance class], [ShimRCTInstance class], @selector(invalidate));
2929
RCTSwizzleInstanceSelector(
3030
[RCTInstance class], [ShimRCTInstance class], @selector(callFunctionOnJSModule:method:args:));
@@ -39,8 +39,8 @@ - (void)reset
3939
[RCTInstance class],
4040
[ShimRCTInstance class],
4141
@selector(initWithDelegate:
42-
jsRuntimeFactory:bundleManager:turboModuleManagerDelegate:onInitialBundleLoad:moduleRegistry
43-
:parentInspectorTarget:launchOptions:));
42+
jsRuntimeFactory:bundleManager:turboModuleManagerDelegate:moduleRegistry:parentInspectorTarget
43+
:launchOptions:));
4444
RCTSwizzleInstanceSelector([RCTInstance class], [ShimRCTInstance class], @selector(invalidate));
4545
RCTSwizzleInstanceSelector(
4646
[RCTInstance class], [ShimRCTInstance class], @selector(callFunctionOnJSModule:method:args:));
@@ -52,7 +52,6 @@ - (instancetype)initWithDelegate:(id<RCTInstanceDelegate>)delegate
5252
jsRuntimeFactory:(std::shared_ptr<facebook::react::JSRuntimeFactory>)jsRuntimeFactory
5353
bundleManager:(RCTBundleManager *)bundleManager
5454
turboModuleManagerDelegate:(id<RCTTurboModuleManagerDelegate>)tmmDelegate
55-
onInitialBundleLoad:(RCTInstanceInitialBundleLoadCompletionBlock)onInitialBundleLoad
5655
moduleRegistry:(RCTModuleRegistry *)moduleRegistry
5756
parentInspectorTarget:(facebook::react::jsinspector_modern::HostTarget *)parentInspectorTarget
5857
launchOptions:(NSDictionary *)launchOptions

0 commit comments

Comments
 (0)