Repository navigation
Description
Description
Since 0.88.0, RCTDeviceInfo has a use-after-free race between the JS thread and the main thread. It shows up as a rare start-up crash: EXC_BAD_ACCESS on com.facebook.react.runtime.JavaScript in __hostFunction_NativeDeviceInfoSpecJSI_getConstants.
- The read (JS thread).
-[RCTDeviceInfo getConstants]returns the_constantsivar with no synchronisation. It is a TurboModule sync method, so it runs on the JS thread (ModuleNativeMethodCallInvoker::invokeSyncruns inline).Dimensions.jscalls it while the bundle is first evaluated, and since 9d10e39 it no longer caches the result. - The write (main thread). b743a8a ("Refresh DeviceInfo constants on resize", 0.88.0) added
-invalidateCachedConstants, which reassigns_constants, releasing the old dictionary. It runs on app activation (UIApplicationDidBecomeActiveNotification), key-window frame changes,RCTUserInterfaceStyleDidChangeNotification, device orientation changes and content-size changes. - The race. If the main thread's release lands between the JS thread's load of
_constantsand its retain, the JS thread retains a freed dictionary. The crash's top frame varies with where it lands:objc_retain←objc_storeStronginObjCTurboModule::performMethodInvocation's block,objc_retain←performMethodInvocation,objc_retainAutoreleaseReturnValue←-[NSInvocation invoke](the getter's own retain), orobjc_release←_Block_object_dispose.
Before b743a8a this was safe: since 6fa6387 (0.80), getConstants already returned the ivar from the JS thread, but _constants was written only once, in -initialize.
How likely it is. In an unmodified app the window is narrow. Dimensions.js reads once at start-up, and in a normal launch the root view's first layout pass (RCTSurfaceHostingView traitCollectionDidChange: → RCTUserInterfaceStyleDidChangeNotification → _interfaceFrameDidChange) rewrites _constants on main within a few milliseconds of that read, sometimes within tens of microseconds. So it is a rare cold-launch crash (we saw it once in roughly 1,500 cold launches of a Release app on the simulator). Nothing in the mechanism is specific to the simulator.
The reproducer widens the window instead of waiting for it. The JS side calls getConstants() in a loop for 20 s before rendering. With the launch argument -StormConstants, the main thread calls the module's own -interfaceOrientationDidChange and -_interfaceFrameDidChange (what UIApplicationDidBecomeActiveNotification calls) in a loop. That adds no new kind of write; it repeats a normal one.
Results (Release, iOS 27.2 simulator, Xcode 27.2, Apple M4; 10 interleaved cold launches per arm):
| Launch arguments | Crashed |
|---|---|
| none (JS read loop only) | 0 / 10 |
-StormConstants |
10 / 10, all within 1–2 s, all EXC_BAD_ACCESS in getConstants on the JS thread |
-StormConstants -LockConstants (getter and writer share a lock, see below) |
0 / 10, with ~1.5 M reads and ~3.8 M concurrent rewrites per launch |
The proposed fix below, tested in the same app with React Native built from source (RCT_USE_PREBUILT_RNCORE=0):
| Build | Launch arguments | Crashed |
|---|---|---|
| source, with the patch | -StormConstants |
0 / 10, with ~8 M reads and ~4.6 M concurrent rewrites per launch |
| same tree, patch reverted | -StormConstants |
10 / 10 |
Affected: 0.88.0, 0.88.1 and 0.89.0-rc.1; getConstants and invalidateCachedConstants are unchanged on main. Not affected: 0.87.x (nothing rewrites _constants after -initialize). The nearest existing work is #57989, which adds more callers of invalidateCachedConstants and notes that didReceiveNewContentSizeMultiplier can arrive off the main thread.
Proposed fix. Make the read and the write of _constants atomic with respect to each other, for example with an atomic property (the synthesized getter retains under the runtime's property lock; the setter releases the old value after the swap), used at every access including the three _constants[@"Dimensions"] reads. Separately, move didReceiveNewContentSizeMultiplier to the main queue as #57989 does, so every write stays on main. Hopping to main inside getConstants would bring back the JS → main sync call that 6fa6387 removed to avoid deadlocks.
--- a/packages/react-native/React/CoreModules/RCTDeviceInfo.mm
+++ b/packages/react-native/React/CoreModules/RCTDeviceInfo.mm
@@ -22,6 +22,9 @@
using namespace facebook::react;
@interface RCTDeviceInfo () <NativeDeviceInfoSpec, RCTInitializing, RCTInvalidating>
+// Written on the main queue, read from the JS thread by the synchronous -getConstants. Atomic, so that
+// a reader retains the dictionary before a concurrent writer can release it.
+@property (atomic, copy) NSDictionary<NSString *, id> *constants;
@end
@implementation RCTDeviceInfo {
@@ -31,7 +34,6 @@
NSDictionary *_currentInterfaceDimensions;
BOOL _isFullscreen;
std::atomic<BOOL> _invalidated;
- NSDictionary *_constants;
__weak UIWindow *_applicationWindow;
NSDictionary * (^_dimensionsProvider)(void);
@@ -132,7 +134,7 @@
- (void)invalidateCachedConstants
{
RCTAssertMainQueue();
- _constants = @{
+ self.constants = @{
@"Dimensions" : [self _exportedDimensions],
// Note:
// This prop is deprecated and will be removed in a future release.
@@ -248,21 +250,26 @@
- (NSDictionary<NSString *, id> *)getConstants
{
- return _constants;
+ return self.constants;
}
- (void)didReceiveNewContentSizeMultiplier
{
- [self invalidateCachedConstants];
- NSDictionary *nextInterfaceDimensions = _constants[@"Dimensions"];
-
- RCTModuleRegistry *moduleRegistry = _moduleRegistry;
+ // This notification can arrive off the main thread; the constants are written (and UIKit read) on main.
+ __weak __typeof(self) weakSelf = self;
RCTExecuteOnMainQueue(^{
- // Report the event across the bridge.
+ __typeof(self) strongSelf = weakSelf;
+ if (!strongSelf) {
+ return;
+ }
+ [strongSelf invalidateCachedConstants];
+ NSDictionary *nextInterfaceDimensions = strongSelf.constants[@"Dimensions"];
+
+ // Report the event across the bridge.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- [[moduleRegistry moduleForName:"EventDispatcher"] sendDeviceEventWithName:@"didUpdateDimensions"
- body:nextInterfaceDimensions];
+ [[strongSelf->_moduleRegistry moduleForName:"EventDispatcher"] sendDeviceEventWithName:@"didUpdateDimensions"
+ body:nextInterfaceDimensions];
#pragma clang diagnostic pop
});
}
@@ -292,7 +299,7 @@
if ((isOrientationChanging || isResizingOrChangingToFullscreen) && RCTIsAppActive()) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- NSDictionary *nextInterfaceDimensions = _constants[@"Dimensions"];
+ NSDictionary *nextInterfaceDimensions = self.constants[@"Dimensions"];
[[_moduleRegistry moduleForName:"EventDispatcher"] sendDeviceEventWithName:@"didUpdateDimensions"
body:nextInterfaceDimensions];
// We only want to track the current _currentInterfaceOrientation and _isFullscreen only
@@ -315,7 +322,7 @@
- (void)_interfaceFrameDidChange
{
[self invalidateCachedConstants];
- NSDictionary *nextInterfaceDimensions = _constants[@"Dimensions"];
+ NSDictionary *nextInterfaceDimensions = self.constants[@"Dimensions"];
// update and publish the even only when the app is in active state
if (!([nextInterfaceDimensions isEqual:_currentInterfaceDimensions]) && RCTIsAppActive()) {The patch is also in the reproducer (patches/RCTDeviceInfo-atomic-constants.diff). A std::mutex / os_unfair_lock around the read (into a strong local) and the write would work as well.
Links: b743a8a35b, 9d10e39d32, 6fa638799a, #57989.
Steps to reproduce
- Clone the reproducer, then:
cd DeviceInfoConstantsRace npm ci (cd ios && pod install) xcodebuild -workspace ios/DeviceInfoConstantsRace.xcworkspace -scheme DeviceInfoConstantsRace \ -configuration Release -sdk iphonesimulator -destination 'generic/platform=iOS Simulator' \ -derivedDataPath build build
- Install on a booted iOS simulator:
xcrun simctl install "$UDID" build/Build/Products/Release-iphonesimulator/DeviceInfoConstantsRace.app - Launch with the storm:
xcrun simctl launch "$UDID" com.example.deviceinfoconstantsrace -StormConstants.
The app crashes within a few seconds (EXC_BAD_ACCESSin__hostFunction_NativeDeviceInfoSpecJSI_getConstants, JS thread). - Launch without an argument: no crash; after ~20 s the app shows "Survived N getConstants() calls".
- Optional:
-StormConstants -LockConstants(a runtime workaround that serialisesgetConstantsandinvalidateCachedConstants): no crash.
scripts/launch-loop.sh "$UDID" 10 [args] in the repo runs N cold launches and prints each exit signal.
React Native Version
0.88.1
Affected Platforms
Runtime - iOS, Build - MacOS
Output of npx @react-native-community/cli info
System:
OS: macOS 27.0.1
CPU: (10) arm64 Apple M4
Memory: 172.39 MB / 16.00 GB
Shell:
version: "5.9"
path: /bin/zsh
Binaries:
Node:
version: 26.13.1
path: /opt/homebrew/bin/node
Yarn: Not Found
npm:
version: 11.20.0
path: /opt/homebrew/bin/npm
Watchman:
version: 2026.10.26.00
path: /opt/homebrew/bin/watchman
Managers:
CocoaPods:
version: 1.17.0
path: /opt/homebrew/bin/pod
SDKs:
iOS SDK:
Platforms:
- DriverKit 27.2
- iOS 27.2
- macOS 27.2
- tvOS 27.2
- visionOS 27.2
- watchOS 27.2
Android SDK: Not Found
IDEs:
Android Studio: 2025.3 AI-253.32098.37.2534.15336583
Xcode:
version: 27.2/27B52
path: /usr/bin/xcodebuild
Languages:
Java: Not Found
Ruby:
version: 4.0.9
path: /opt/homebrew/bin/ruby
npmPackages:
"@react-native-community/cli":
installed: 20.2.0
wanted: 20.2.0
react:
installed: 19.3.0
wanted: 19.3.0
react-native:
installed: 0.88.1
wanted: 0.88.1
react-native-macos: Not Found
npmGlobalPackages:
"*react-native*": Not Found
Android:
hermesEnabled: true
newArchEnabled: true
iOS:
hermesEnabled: true
newArchEnabled: true
Stacktrace or Logs
From the reproducer (-StormConstants, Release, iOS 27.2 simulator). Here the main thread is caught inside invalidateCachedConstants, building the replacement dictionary.
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x0000594c9c882458
Termination: Segmentation fault: 11
VM Region Info: 0x594c9c882458 is not in any region.
Thread 22 Crashed:: com.facebook.react.runtime.JavaScript
0 libobjc.A.dylib objc_retain + 16
1 libobjc.A.dylib objc_storeStrong + 56
2 React invocation function for block in facebook::react::ObjCTurboModule::performMethodInvocation(facebook::jsi::Runtime&, bool, char const*, NSInvocation*, NSMutableArray*) + 152
3 React facebook::react::ObjCTurboModule::performMethodInvocation(facebook::jsi::Runtime&, bool, char const*, NSInvocation*, NSMutableArray*) + 524
4 React facebook::react::ObjCTurboModule::invokeObjCMethod(facebook::jsi::Runtime&, facebook::react::TurboModuleMethodValueKind, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>> const&, objc_selector*, facebook::jsi::Value const*, unsigned long) + 292
5 React facebook::react::__hostFunction_NativeDeviceInfoSpecJSI_getConstants(facebook::jsi::Runtime&, facebook::react::TurboModule&, facebook::jsi::Value const*, unsigned long) + 96
6 hermesvm std::__1::function<facebook::jsi::Value (facebook::jsi::Runtime&, facebook::jsi::Value const&, facebook::jsi::Value const*, unsigned long)>::operator()(facebook::jsi::Runtime&, facebook::jsi::Value const&, facebook::jsi::Value const*, unsigned long) const + 44
7 hermesvm facebook::hermes::(anonymous namespace)::HermesRuntimeImpl::HFContext::func(void*, hermes::vm::Runtime&) + 216
8 hermesvm hermes::vm::NativeFunction::_nativeCall(hermes::vm::NativeFunction*, hermes::vm::Runtime&) + 64
9 hermesvm hermes::vm::FinalizableNativeFunction::_callImpl(hermes::vm::Handle<hermes::vm::Callable>, hermes::vm::Runtime&) + 32
10 hermesvm hermes::vm::Interpreter::handleCallSlowPath(hermes::vm::Runtime&, hermes::vm::PinnedHermesValue*) + 84
11 hermesvm hermes::vm::CallResult<hermes::vm::HermesValue, (hermes::vm::detail::CallResultSpecialize)2> hermes::vm::Interpreter::interpretFunction<false, false>(hermes::vm::Runtime&, hermes::vm::InterpreterState&) + 9028
... (hermes::vm::Runtime::runBytecode, HermesRuntimeImpl::evaluateJavaScript, ReactInstance::loadScript)
Thread 0:: com.apple.main-thread
0 CoreFoundation _CFRetain + 308
1 Foundation -[NSBundle bundlePath] + 64
2 React RCTRunningInAppExtension + 44
3 React RCTKeyWindow + 68
4 React -[RCTDeviceInfo _exportedDimensions] + 328
5 React -[RCTDeviceInfo invalidateCachedConstants] + 108
6 React -[RCTDeviceInfo _interfaceFrameDidChange] + 24
7 DeviceInfoConstantsRace static ConstantsRace.runStorm(_:start:) + 616
...
Across the 10 storm crashes the JS thread's top frames were: objc_retain ← objc_storeStrong ← performMethodInvocation block (5), objc_retain ← performMethodInvocation (3), objc_release ← _Block_object_dispose ← performMethodInvocation (1), objc_retainAutoreleaseReturnValue ← -[NSInvocation invoke] (1). The same signature occurs without the storm, at a far lower rate, with getConstants called from Dimensions.js during the bundle's first evaluation.
MANDATORY Reproducer
https://github.com/jeremy-robotsson/rn-deviceinfo-constants-race
Screenshots and Videos
(none)
Activity