Summary:
Some third-party libraries, like react-native-reanimated, can clone nodes in a different thread while react-native is calling `setNativeProps_DEPRECATED`. This results in a race condition, where a stale pointer to `nativeProps_DEPRECATED` can be accessed, resulting in a crash. This usually manifests as a `EXC_BAD_ACCESS` crash on iOS. On Android it seems more rare. We've added a lock around accesses to nativeProps_DEPRECATED, but alternative options of fixing this can be considered too.
For more information see https://github.com/software-mansion/react-native-reanimated/issues/7666
[INTERNAL] [FIXED] - Fixed crashes caused by race conditions when third-party libraries clone the shadow dom from a different thread
Pull Request resolved: https://github.com/react/react-native/pull/52646
Test Plan:
Due to this being a race condition that only manifests in rare circumstances, it's very difficult to create a reliable reproduction case. The issue mentioned above contains ThreadSanitizer logs that demonstrate this issue. TSan no longer complains with this patch applied, and we've not seen any additional issues from it after deploying it in production over the past week.
Added unit test covering the `nativeProps_DEPRECATED` merge logic in `UIManager::cloneNode` and `ShadowNode::clone`:
```
buck2 test //xplat/js/react-native-github/packages/react-native/ReactCommon/react/renderer/uimanager:tests -- --regex FabricUIManagerTest
```
Reviewed By: zeyap
Differential Revision: D110169424
Pulled By: javache
fbshipit-source-id: 6139253dcc2c33348a0c1a3bd01e695d15aa83bc
Summary:
This fixes an Android Fabric crash in the `overrideBySynchronousMountPropsAtMountingAndroid` path when Native Animated has stored a synchronous `transform` / `opacity` override and a later regular Fabric commit contains `null` for the same prop.
| As-is | To-be |
| --- | --- |
| <img src="https://raw.githubusercontent.com/jingjing2222/react-native-fabric-transform-repro/main/crashed.gif" alt="Baseline Android Fabric transform crash repro" width="320" /> | <img src="https://raw.githubusercontent.com/jingjing2222/react-native-fabric-transform-repro/main/patched.gif" alt="Patched Android Fabric transform result" width="320" /> |
| [crashed.gif](https://github.com/jingjing2222/react-native-fabric-transform-repro/blob/main/crashed.gif) | [patched.gif](https://github.com/jingjing2222/react-native-fabric-transform-repro/blob/main/patched.gif) |
Native Animated can synchronously update `transform` / `opacity` on the UI thread. A regular Fabric commit for the same view may arrive later with stale props, including `transform: null` or `opacity: null`. Those regular Fabric null values should not clear the stored synchronous override, because the override may still represent the fresher Native Animated value.
Before this patch, the override merge path assumed that the incoming Fabric prop had the same non-null type as the stored override. For example, a stored `transform` override is an array, but a regular Fabric update may contain `transform: null`. That mismatch could crash in `SurfaceMountingManager.overridePropsReadableMap`.
This patch:
- Allows regular Fabric `null` updates to be overridden by stored synchronous `transform` / `opacity` values instead of crashing.
- Keeps regular Fabric `transform: null` / `opacity: null` from clearing the stored synchronous override.
- Scopes synchronous null clearing to `transform` / `opacity` only.
- Leaves null values for other props untouched, since other view prop nulls may be meaningful.
This PR intentionally does not change Java Native Animated `restoreDefaultValues()` behavior. That restore implementation can be handled separately because changing it may affect existing apps.
Repro repository:
https://github.com/jingjing2222/react-native-fabric-transform-repro
## Why this is correct
A regular Fabric `null` update is not enough to prove user intent to clear the native animated value, because it can be the stale commit produced after Native Animated already wrote a fresher value on the UI thread. In that case, the stored synchronous override should continue to win.
If the synchronous Native Animated path explicitly sends `transform: null` or `opacity: null`, this patch treats that as a clear signal for that stored override key. The clear behavior is intentionally scoped to the props currently stored by this override path.
```text
regular Fabric null: possible stale commit -> stored synchronous override wins
synchronous transform / opacity null: explicit clear -> stored override key is removed
other null props: left untouched
```
## Changelog:
[ANDROID] [FIXED] - Fix Android Fabric Native Animated crash when regular Fabric null props collide with stored synchronous transform or opacity overrides.
Pull Request resolved: https://github.com/facebook/react-native/pull/56913
Test Plan:
Added regression coverage for stale regular Fabric null commits and scoped synchronous null clears:
- `updateProps_withNullOpacity_keepsStoredSynchronousProp`
- `updateProps_withNullTransform_keepsStoredSynchronousProp`
- `updatePropsSynchronously_withNullOpacity_removesStoredSynchronousProp`
- `updatePropsSynchronously_withNullTransform_removesStoredSynchronousProp`
Ran:
```sh
./gradlew :packages:react-native:ReactAndroid:testDebugUnitTest --tests com.facebook.react.fabric.SurfaceMountingManagerSynchronousMountPropsTest -Preact.internal.useHermesStable=true
```
Result:
```text
BUILD SUCCESSFUL
```
Ran:
```sh
./gradlew :packages:react-native:ReactAndroid:testDebugUnitTest --tests com.facebook.react.animated.NativeAnimatedNodeTraversalTest -Preact.internal.useHermesStable=true
```
Result:
```text
BUILD SUCCESSFUL
```
Ran:
```sh
./gradlew :packages:react-native:ReactAndroid:ktfmtCheck -Preact.internal.useHermesStable=true
```
Result:
```text
BUILD SUCCESSFUL
```
Reviewed By: javache
Differential Revision: D105974289
Pulled By: zeyap
fbshipit-source-id: 7688cfa6b89f2d107c7ae58356864835d41f6add
Summary:
## Summary: Do not synchronize on java.lang.Boolean.
Once JEP 401 is implemented synchronization on
value classes (which box classes are) will throw IdentityException.
In general synchronization on 1) mutable field 2) box class is
inefficient (instances are shared) at best and a bug at worst case
as synchronization is done holding different monitors (it might be
fine, but is hard to reason about).
## Changelog:
[ANDROID] [FIXED] Use explicit `ReactInstanceManager.mHasStartedDestroyingLock` instead of using `ReactInstanceManager.mHasStartedDestroying`
<!-- Help reviewers and the release process by writing your own changelog entry.
Pick one each for the category and type tags:
[ANDROID|GENERAL|IOS|INTERNAL] [BREAKING|ADDED|CHANGED|DEPRECATED|REMOVED|FIXED|SECURITY] - Message
For more details, see:
https://reactnative.dev/contributing/changelogs-in-pull-requests
Pull Request resolved: https://github.com/react/react-native/pull/56196
Test Plan: GHA
Reviewed By: cortinico
Differential Revision: D110168816
Pulled By: javache
fbshipit-source-id: dae081dc00a94859f19dcc3607971a9c3d6fbd44
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/57103
Changelog: [General][Fixed] Fixed `display: contents` nodes having `hasNewLayout` set incorrectly
`cleanupContentsNodesRecursively` unconditionally sets `hasNewLayout=true` on `display: contents` children, including on code paths where their parent's layout was not actually performed in this pass. The stale flag can survive across layout passes and, in clone-on-write renderers (e.g. React Native Fabric), be observed by a subsequent pass whose parent was cloned but whose layout was served from cache, leaving the contents child's owner pointing at the previous parent revision.
There are two paths through which the cleanup could stamp a contents child whose parent's `hasNewLayout` would end up false:
1. Measure-phase visit. Inside `calculateLayoutImpl`, the cleanup ran with no knowledge of `performLayout`. When the parent's `calculateLayoutImpl` was invoked only with `performLayout=false` (cache miss on measure, cache hit on layout), the cleanup stamped contents children even though the parent itself never had its `hasNewLayout` set.
2. Absolute-layout walk. `layoutAbsoluteDescendants` walks every static layout descendant of the containing block - including ones whose own `calculateLayoutImpl` was skipped via the layout-phase cache. The cleanup invoked along that walk unconditionally stamped contents children, but the parent's `hasNewLayout` was only updated when the recursion actually found new layout downstream.
In both cases, the result is the same invariant violation: a contents node with `hasNewLayout=true` whose parent has `hasNewLayout=false`. A consumer iterating the tree via `hasNewLayout` skips the parent and never clears the stale flag.
X-link: https://github.com/facebook/yoga/pull/1970
Test Plan:
Added `YGContentsNodeHasNewLayoutTest.cpp` with regression tests:
- `contents_child_hasNewLayout_not_stamped_on_measure_only_visit` - pins the measure-phase fix
- `absolute_descendant_through_contents_is_reachable_via_hasNewLayout` - pins the positive case for absolute-layout path
- `absolute_phase_cleanup_does_not_stamp_when_parent_layout_skipped` - pins the negative case for absolute-layout path
Reviewed By: javache
Differential Revision: D107854528
Pulled By: j-piasecki
fbshipit-source-id: cae5e889622296e8b6380a6428509b5ffea3e9ae
Summary:
https://github.com/facebook/react-native/issues/56878 shows that using unicode characters in paths fails with pod install.
Expo fixed this internally here: https://github.com/expo/expo/pull/45779
Fixes https://github.com/facebook/react-native/issues/56878
## How:
Build local `file://` sources through a shared helper that percent-encodes filesystem paths before passing them to `URI::File.build`. This avoids Ruby/CocoaPods URI failures when React Native projects or local prebuilt tarballs live under paths containing Unicode characters or spaces.
Apply the helper to `RNCore` and `ReactNativeDependencies` local tarball sources, including RNCore dSYM-processed prebuilt paths, while leaving remote Maven and Sonatype URLs unchanged.
Add focused coverage for Unicode, spaces, ASCII paths, and the raw `URI::File.build` regression case.
## Changelog:
[IOS] [FIXED] - fixed escaping local file URIs for unicode paths in ruby scripts
Pull Request resolved: https://github.com/facebook/react-native/pull/56907
Test Plan: - Test with creating a new project in a path containing a unicode character and the run pod install.
Reviewed By: cortinico
Differential Revision: D105968728
Pulled By: cipolleschi
fbshipit-source-id: 6d5b9043aafe3d86494f3b5ca0f208e46f1f3739
Summary:
`android_ripple` on `Pressable` (and `TouchableNativeFeedback.Ripple()`) only
accepted numeric (pre-processed ARGB int) colors. Passing a `PlatformColor`
would throw an invariant in JS, making theme-aware ripple colors impossible.
This PR removes those guards and wires up the full color pipeline:
1. **JS** (`useAndroidRippleForView.js`, `TouchableNativeFeedback.js`):
removed the `invariant` that rejected non-numeric processed colors.
`TouchableNativeFeedback.Ripple()` now accepts `ColorValue` instead of
`string`.
2. **C++** (`NativeDrawable.h`, `HostPlatformViewProps.cpp`): `color`
changed from `int32_t` to `SharedColor` + a separate `colorResourcePaths`
field for `PlatformColor` resource paths. The `fromRawValue` pipeline now
resolves both plain colors and `PlatformColor` objects.
3. **Kotlin** (`ReactDrawableHelper.kt`): `getColor()` now handles both
numeric and `PlatformColor` map values via `ColorPropConverter.getColor()`,
catching `JSApplicationCausedNativeException` to fall back gracefully
instead of crashing.
4. **Theme change support** (`ReactViewGroup.kt`): the raw drawable
description maps are retained on the view, and `onConfigurationChanged`
re-applies them so ripple colors update automatically on light/dark mode
switch.
A new `alpha: number` (0–1) field is also added so users can apply opacity to
a `PlatformColor` whose value is fully opaque and can't have alpha embedded at
the JS level. It is applied by multiplying into the resolved color's alpha
channel.
Unresolvable `PlatformColor` resources are handled gracefully: on New Arch,
C++ omits the `color` key so Kotlin falls back to `colorControlHighlight`; on
Old Arch, `ReactDrawableHelper` catches the `JSApplicationCausedNativeException`
and falls back to `colorControlHighlight` instead of crashing.
[ANDROID] [ADDED] - `android_ripple` now accepts `PlatformColor` for
theme-aware ripple colors, and a new `alpha` (0–1) parameter for controlling
ripple opacity independently of the color value.
Pull Request resolved: https://github.com/facebook/react-native/pull/56395
Test Plan:
**Automated:**
- Existing Pressable snapshot tests pass unchanged.
- Updated snapshot for `PlatformColor + alpha` to use `?attr/colorAccent`
(matching the RNTester example).
- Added snapshot test `should not crash with an unresolvable PlatformColor`
verifying the component renders at the JS level without throwing.
**Manual (RNTester → Pressable → "Pressable with PlatformColor ripple and alpha"):**
1. `PlatformColor('?attr/colorAccent'), no alpha` → full-opacity accent ripple
2. `PlatformColor('?attr/colorAccent'), alpha=0.3` → 30% opacity accent ripple
3. `#FF0000, no alpha` → full red ripple (regression check)
4. `#FF0000, alpha=0.5` → 50% opacity red ripple
5. Toggle system light/dark mode → ripple color updates automatically
6. Pass an intentionally invalid attribute (e.g. `?attr/doesNotExist`) → no
crash, ripple falls back to default `colorControlHighlight` grey
[Screen_recording_20260410_091000.webm](https://github.com/user-attachments/assets/5607d267-8cf1-4bbe-bad1-a80aac82d027)
> [!NOTE]
This is required in [React Native Paper](https://github.com/callstack/react-native-paper) to be able to fully support the Material Design specs but also useful as a general purpose feature for providing more flexibility when customizing ripple color.
Reviewed By: javache
Differential Revision: D105819708
Pulled By: fabriziocucci
fbshipit-source-id: d27c43e0b4e619b6af1c8de0cdb2882db05ee33c
Summary:
Two developers (or one developer on two paths, or CI vs. local) running pod install on the same React Native project at the same commit get different SPEC CHECKSUMS entries for React-Core-prebuilt and ReactNativeDependencies in Podfile.lock. That breaks pod install-deployment style verification and any workflow that expects Podfile.lock to be reproducible.
CocoaPods derives each SPEC CHECKSUMS entry by hashing the in-memory podspec JSON. So anything embedded in source.http, prepare_command, user_target_xcconfig, etc. becomes part of the hash. Two podspec-resolution sites in this repo build their source.http from an absolute on-disk path.
Because project_pods_root is an absolute path, the resulting file://<abs>/... URL differs across machines or working-tree paths, so the hashed JSON differs, so the checksum differs.
### How
The Maven URL for each tarball is already computed inside both functions (stable_tarball_url(...) / nightly_tarball_url(...) / release_tarball_url(...)). Returning that URL — a stable string identical across machines — instead of the local file:// URL makes source.http path-free. CocoaPods downloads from Maven and caches the tarball itself, so functionality is preserved.
The pre-existing local-tarball download is kept untouched (its only remaining consumer is the opt-in `RCT_SYMBOLICATE_PREBUILT_FRAMEWORKS=1` dSYM-injection path in rncore.rb, which still needs file:// to feed CocoaPods a mutated tarball — gated by unless @download_dsyms so the leak is preserved only for that flag).
**Out of scope: **
hermes-engine.podspec has the same shape of leak in user_target_xcconfig.HERMES_CLI_PATH. Fixing it requires a paired change to ensure hermesc lands at the new ${PODS_ROOT}-relative path; that's a separate PR.
## Changelog:
[IOS] [FIXED] - Fix Pod install checksum drifting
Pull Request resolved: https://github.com/facebook/react-native/pull/56803
Test Plan:
Run `pod install` and verify that none of the following files contains absolute paths:
- Pods/Local Podspecs/React-Core-prebuilt.podspec.json
- Pods/Local Podspecs/ReactNativeDependencies.podspec.json
Reviewed By: christophpurrer
Differential Revision: D104889112
Pulled By: CalixTang
fbshipit-source-id: 97505a8bf78f7df57bda2d87705da5a20c934d2b
Summary:
When `RCT_USE_PREBUILT_RNCORE=1` (the 0.84+ default) and a consumer pod builds under `use_frameworks!`, RCT macros like `RCT_EXTERN`, `RCT_EXTERN_C_BEGIN`, `RCT_EXPORT_METHOD`, `RCT_REMAP_METHOD` fail to propagate.
The `.m` files using these macros hit cascading parse errors like :
- `unknown type name 'RCT_EXTERN_C_BEGIN'` in `<React/RCTBridgeModule.h>` line 51,
- `unknown type name 'RCT_EXTERN'` in `<React/RCTEventDispatcherProtocol.h>` line 17,
- and `type specifier missing, defaults to 'int'` on every `RCT_EXPORT_METHOD(...)` call site.
Root cause is in two places in `packages/react-native/scripts/ios-prebuild/templates/`:
1. `React-umbrella.h` orders `RCTBridgeConstants.h` (line 56) before `RCTDefines.h` (line 84). `RCTBridgeConstants.h` uses `RCT_EXTERN` at its first declaration but the macro is only defined later in `RCTDefines.h`. When the umbrella is loaded as a single parse context, the `RCT_EXTERN` use is unresolvable.
2. `module.modulemap` declares `module * { export * }` inside both `framework module` blocks, which creates an inferred submodule per header. That isolates macro `#define`s into per-header parse scopes. Even fixing the umbrella order, sibling submodules don't share macros: macros defined in the `RCTDefines.h` submodule are invisible to the `RCTBridgeConstants.h` submodule, and to consumers of the `React` module.
This PR fixes both:
- Move `#import <React/RCTDefines.h>` to the very top of the umbrella (right after the prologue and before any other `<React/...>` import), with a comment explaining why ordering matters.
- Remove the `module * { export * }` wildcard from both `framework module` blocks in the modulemap. The umbrella header alone is sufficient to declare the module's contents, and dropping the wildcard means the whole module shares one parse context where macros propagate.
The combination of `use_frameworks!` + prebuilt RNCore is the path of least resistance today: `use_frameworks!` is the Expo default and is required by `firebase-ios-sdk` for its Swift bridges. Prebuilt RNCore is the 0.84+ default. The colliding defaults break native-module ecosystems like `react-native-firebase` that consume the RCT macros. Producer-side fix is in flight at invertase/react-native-firebase#9024; this PR closes the consumer side.
## Changelog:
[IOS] [FIXED] - Load `RCTDefines.h` first in the prebuilt React umbrella and drop the `module *` submodule wildcard so RCT_* macros propagate to consumer pods under `use_frameworks!`.
Pull Request resolved: https://github.com/facebook/react-native/pull/56862
Test Plan:
Reproduced on RN 0.85.3 (latest stable at time of writing) on macOS 26.3.1 / Xcode 26.5 / iOS 26.5 Simulator (iPhone 17 Pro).
**Reproducer setup**
Fork of `mikehardy/rnfbdemo` with these adjustments in `make-demo.sh`:
- `RN_VER=0.85.3`
- `RNFB_VER=24.0.0`
- `FB_IOS_VER=12.10.0`
- Remove `react-native-firebase/dynamic-links` from the bulk yarn add (deprecated and removed in RNFB 24.x).
Default Podfile mods produced by `make-demo.sh` are preserved: `use_frameworks! :linkage => :static` + `$RNFirebaseAsStaticFramework = true`. No `RCT_USE_PREBUILT_RNCORE` override (stays at the `1` default).
Public reproducer: https://github.com/wneel/rnfbdemo (see its `REPRO.md` for the two-stage flow).
The reproducer also has invertase/react-native-firebase#9024 (producer-side podspec fixes) applied as an overlay. Without those, the build fails earlier at `-Wnon-modular-include-in-framework-module`. With them applied, the build progresses to the consumer side and surfaces the macro propagation bug this PR fixes.
**Before this PR**
Same reproducer config. iOS build fails on consumer pods (RNFBAuth, RNFBStorage, RNFBMessaging) with:
```
.../Pods/Headers/Public/React-Core/React/RCTEventDispatcherProtocol.h:17:1: error: unknown type name 'RCT_EXTERN'
.../Pods/Headers/Public/React-Core/React/RCTEventDispatcherProtocol.h:17:27: error: expected ';' after top level declarator
.../node_modules/react-native-firebase/messaging/ios/RNFBMessaging/RNFBMessaging+AppDelegate.h:26:21: error: declaration of 'RCTPromiseRejectBlock' must be imported from module 'RNFBApp.RNFBAppModule' before it is required
```
**After this PR**
Same reproducer config builds cleanly: `pod install` clean, `xcodebuild` Debug build produces the app, zero `RCT_EXTERN` macro errors anywhere in the log.
Verified by editing `packages/react-native/scripts/ios-prebuild/templates/React-umbrella.h` and `packages/react-native/scripts/ios-prebuild/templates/module.modulemap` in place (the diff in this PR), regenerating the prebuilt React.xcframework artifact, and re-running the reproducer.
**Output of `npx react-native-community/cli info` from the reproducer environment:**
```
System:
OS: macOS 26.3.1
CPU: (10) arm64 Apple M2 Pro
Memory: 466.16 MB / 16.00 GB
Shell:
version: "5.9"
path: /bin/zsh
Binaries:
Node:
version: 22.14.0
path: /usr/local/bin/node
Yarn:
version: 3.6.4
path: /usr/local/bin/yarn
npm:
version: 11.12.1
path: /usr/local/bin/npm
Watchman:
version: 2026.05.11.00
path: /opt/homebrew/bin/watchman
Managers:
CocoaPods:
version: 1.16.2
path: /opt/homebrew/bin/pod
SDKs:
iOS SDK:
Platforms:
- DriverKit 25.5
- iOS 26.5
- macOS 26.5
- tvOS 26.5
- visionOS 26.5
- watchOS 26.5
IDEs:
Xcode:
version: 26.5/17F42
path: /usr/bin/xcodebuild
Languages:
Java:
version: 21.0.9
path: /usr/bin/javac
```
**Cross-references**
- `react-native-firebase` producer-side fix in flight: invertase/react-native-firebase#9024
- `react-native-firebase` `.m` import hygiene follow-up: invertase/react-native-firebase#9026
- Original RNFB user-facing issue: invertase/react-native-firebase#8883
Reviewed By: cortinico
Differential Revision: D105582598
Pulled By: cipolleschi
fbshipit-source-id: ab364d46fc94d64274197cdd717a06e425a9324f
Summary:
`Image.getSize` and `getSizeWithHeaders` call Fresco's `fetchDecodedImage`, which returns a `CloseableImage` whose width / height reflect the bitmap after Fresco's automatic downsampling (typically capped at the screen size).
For sources larger than the screen this returned the wrong dimensions. ex: a 4000x3000 image on a 1920x1080 device came back as 1920x1440.
Switch to `fetchEncodedImage` and read the dimensions from the parsed image metadata (JPEG / PNG / WebP / HEIF headers), so the values are the true source dimensions. Swap width / height for 90°/270° EXIF rotation to match the iOS behavior in `RCTImageLoader`.
Fixes https://github.com/facebook/react-native/issues/33498Closesfacebook/fresco#2236
## Changelog:
<!-- Help reviewers and the release process by writing your own changelog entry.
Pick one each for the category and type tags:
[ANDROID|GENERAL|IOS|INTERNAL] [BREAKING|ADDED|CHANGED|DEPRECATED|REMOVED|FIXED|SECURITY] - Message
For more details, see:
https://reactnative.dev/contributing/changelogs-in-pull-requests
-->
[ANDROID] [FIXED] - `Image.getSize` and `Image.getSizeWithHeaders` now return the true source dimensions instead of Fresco's downsampled values
Pull Request resolved: https://github.com/facebook/react-native/pull/56736
Test Plan:
In the RNTester app, add:
```ts
useEffect(() => {
Image.getSize(
'https://images.pexels.com/photos/842711/pexels-photo-842711.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2',
(width, height) => {
console.log({width, height});
},
);
}, []);
```
### Before
<img width="811" height="467" alt="before" src="https://github.com/user-attachments/assets/6fb401ed-cf5a-4496-bcc1-4cfd243bc0b7" />
### After
<img width="811" height="467" alt="after" src="https://github.com/user-attachments/assets/dc809d5f-c554-45d6-a3a3-7712bf39ac44" />
Reviewed By: javache
Differential Revision: D104533593
Pulled By: Abbondanzo
fbshipit-source-id: f087d528474c40cffbf24eb1e3958b4b18fb118e
Summary:
`PODFILE_DIR` was being set to `Pod::Config.instance.installation_root.to_s`, which bakes the contributor's absolute path (e.g. `/Users/alice/Projects/MyApp/ios`) into `project.pbxproj` — every `pod install` on a different machine churns the diff, and a checked-in pbxproj points at someone else's filesystem.
Set `PODFILE_DIR` per-project via Xcode variable substitution: `$(SRCROOT)` for user projects, `$(SRCROOT)/..` for the Pods project. Resolved value is identical at build time; the persisted string is now machine-independent.
## Changelog:
[IOS] [FIXED] - Persist `PODFILE_DIR` as `$(SRCROOT)`-relative so `project.pbxproj` is portable across machines
Pull Request resolved: https://github.com/facebook/react-native/pull/56732
Test Plan:
1. `pod install`, inspect host-app and Pods `pbxproj`: `PODFILE_DIR` should be `$(SRCROOT)` and `$(SRCROOT)/..`, not an absolute path.
2. Build the app and confirm consumers of `${PODFILE_DIR}` still resolve correctly (`with-environment.sh`, codegen script phases).
Reviewed By: christophpurrer
Differential Revision: D104398698
Pulled By: cipolleschi
fbshipit-source-id: e00f027d5c3570ac1a9c78b54fdbdaf81f98f17f
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/56680
Scheduler::uiManagerDidFinishTransaction and Scheduler::uiManagerDidDispatchCommand queue lambdas via runtimeScheduler_->scheduleRenderingUpdate that capture the raw delegate_ pointer by value. With RuntimeScheduler_Modern (the bridgeless implementation), the lambda runs asynchronously, so if the SchedulerDelegate is destroyed between enqueue and execution (surface teardown, Scheduler destruction, or setDelegate flip), the lambda dereferences dangling memory → EXC_BAD_ACCESS / KERN_INVALID_ADDRESS.
Add a per-delegate-identity invalidation token (`shared_ptr<atomic<bool>>`) owned by Scheduler and captured by-value into the deferred lambdas. The destructor and setDelegate flip the flag to true; lambdas check it (acquire ordering) before dereferencing the captured raw delegate.
The shared_ptr keeps the atomic alive for any outstanding lambdas. Public API is unchanged (private member only), so C++ API snapshots are unaffected.
Changelog:
[General][Fixed] - Prevent Scheduler use-after-free crash when surfaces tear down with pending rendering updates
Reviewed By: mdvacca, Abbondanzo
Differential Revision: D103727974
fbshipit-source-id: 8abf5073b7fd35e88d65a91c42f311b238d8f156
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/56678
Introduces a new common React Native feature flag, `enableSchedulerDelegateInvalidation`, that gates a defensive guard around `Scheduler::uiManagerDidDispatchCommand` and `uiManagerDidFinishTransaction`. Those call sites enqueue a lambda via `runtimeScheduler_->scheduleRenderingUpdate` that captures the raw `SchedulerDelegate` pointer by value. With `RuntimeScheduler_Modern` (bridgeless) the lambda runs asynchronously, so if the `SchedulerDelegate` is destroyed between enqueue and execution the lambda dereferences dangling memory and the process crashes (`EXC_BAD_ACCESS` / `KERN_INVALID_ADDRESS`). The follow-up commit adds the actual guard wired to this flag.
Defaults to `false` so behavior is unchanged on landing. Apps opt in by overriding the flag in their own `ReactNativeFeatureFlagsDefaults` subclass.
Includes the regenerated feature-flag boilerplate (Kotlin/Java/Cxx accessors, defaults, providers, JS spec, native module) emitted by `yarn featureflags --update`.
Changelog:
[Internal]
Reviewed By: shwanton
Differential Revision: D103757271
fbshipit-source-id: 85991de4a21e3946a25571b6488bee9c0a4e1caf
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/56610
Removes deprecated feature flags `enableImagePrefetchingJNIBatchingAndroid` and `enableImagePrefetchingOnUiThreadAndroid` by consolidating their behavior into `enableImagePrefetchingAndroid`.
The changes make image prefetch batching and UI thread dispatch the default behavior when `enableImagePrefetchingAndroid` is enabled. This simplifies the feature flag system and removes intermediate experimentation flags that are no longer needed.
Changelog: [Internal]
Reviewed By: sammy-SC
Differential Revision: D102428102
fbshipit-source-id: af7387e5a3144d7c425fc600a04b33e830d6e2e7
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/56534
Fix two ThreadSanitizer data races caught by the messenger_demo integration test under dev-tsan mode.
**InspectorFlags**: `loadFlagsAndAssertUnchanged()` reads and writes `cachedValues_` without synchronization. The main thread calls it via `getIsProfilingBuild()` while the JS thread calls it via `getNetworkInspectionEnabled()`, racing on the shared `optional<Values>`. Add a `std::mutex` to protect `cachedValues_` access. The lock is taken after computing `newValues` from feature flags, so flag reads stay outside the critical section. `dangerouslyResetFlags()` also acquires the lock to avoid racing with concurrent flag reads.
**Inspector**: `Inspector::connectDebugger()` is called from the main thread but creates and uses `packagerConnection_` which is also accessed on the inspector thread. Dispatch the body of `connectDebugger()` to the task dispatch thread via `invokeElsePost()`, matching the pattern other Inspector methods already use. This ensures `InspectorPackagerConnection::connect()` is called on the correct thread as its API requires.
Changelog: [Internal]
Reviewed By: hoxyq
Differential Revision: D101809616
fbshipit-source-id: 92eac22ca9ab364daafc403a0fdbb39394bd0f63
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/56646
Replace `ConcurrentHashMap<Int, ViewState>` with `MutableIntObjectMap<ViewState>` + `ReentrantReadWriteLock` in `SurfaceMountingManager`, behind the `useOptimizedViewRegistryOnAndroid` feature flag.
`ConcurrentHashMap<Int, ViewState>` boxes every `Int` key to `java.lang.Integer` (16 bytes) and allocates a `Node` object per entry (~32 bytes). `MutableIntObjectMap` from `androidx.collection` uses a Swiss Table layout with primitive `IntArray` keys — ~9 bytes/entry vs ~56-64 bytes, a ~6x reduction in map overhead. For a complex surface with 2000+ views, this saves ~90KB per surface in map overhead alone, plus reduced GC pressure from eliminating `Integer` boxing.
The `ReentrantReadWriteLock` replaces CHM's built-in concurrency. This matches the access pattern: reads from any thread (`getEventEmitter`, `enqueuePendingEvent`), writes almost exclusively from the UI thread. Readers never block each other. `stopSurface` snapshots entries under the write lock and processes `onViewStateDeleted` outside the lock to minimize reader blocking.
Changelog: [Internal]
Reviewed By: sammy-SC
Differential Revision: D102797904
fbshipit-source-id: c951fd31c9582f2196c3e09b0e41b8b29e889d85
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/56666
The feature flag `enableNativeEventTargetEventDispatching` switches the React Native renderer from the legacy plugin-based event dispatch to a new W3C `EventTarget`-based dispatch in `dispatchNativeEvent.js`. The legacy path honors the `phasedRegistrationNames.skipBubbling` flag declared in view configs by short-circuiting the bubble traversal. The new path was unconditionally setting `bubbles: true` for any event with a `customBubblingEventTypes` entry, so `topPointerEnter` / `topPointerLeave` (the only events that declare `skipBubbling: true` today) ended up bubbling to all ancestors, breaking the W3C Pointer Events contract that `pointerenter` / `pointerleave` do not bubble.
Map `skipBubbling: true` to `bubbles: false` on the synthesized `LegacySyntheticEvent`. The existing `EventTarget.dispatch()` bubble loop already short-circuits when `event.bubbles` is `false` and `target !== eventTarget`, so the target's own bubble + capture handlers still fire — only ancestor bubble handlers are suppressed. Capture-phase listeners are unaffected.
Changelog: [internal]
Reviewed By: sammy-SC
Differential Revision: D103200424
fbshipit-source-id: 8f246b09017bd1a1026e79f5aeb78123f5bba873
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/56651
## Context
On Android TV, text inside absolutely-positioned Views wraps unexpectedly when the computed width from Yoga is fractional. This manifests in Instagram TV as "Keep watching" breaking to two lines in the exit dialog when the button text is focused (rendered via an absolutely-positioned overlay for color animation).
The root cause is a rounding mismatch in React Native's Android `TextLayoutManager`: `desiredWidth` (the text's needed width) uses `ceil()` (rounds up), but `layoutWidth` in `EXACTLY` mode uses `floor()` (rounds down). When Yoga passes a fractional width (e.g. 258.5px), the container gets `floor(258.5) = 258px` but the text needs `ceil(258.3) = 259px`, causing a 1px shortfall that triggers wrapping.
## Fix
In `TextLayoutManager.createLayout()`, change `floor(width).toInt()` to `ceil(width).toInt()` for `YogaMeasureMode.EXACTLY` in **both** layout paths so the behavior is consistent regardless of which `Layout` class is chosen:
- BoringLayout (single-line text that fits)
- StaticLayout (multi-line or complex text)
`YogaMeasureMode.AT_MOST` is intentionally left as `floor(width).toInt()`. `AT_MOST` is a constraint contract from Yoga ("do not exceed this width"), so flooring remains the correct conservative behavior — ceiling there could violate the constraint by up to 1px.
The BoringLayout entry guard (`boring.width <= floor(width)`) is also left unchanged. If a boring text fails the guard, it falls through to the StaticLayout path, which now also ceils for `EXACTLY`, so no truncation results — the only effect is a slightly less optimal layout class choice in a narrow edge case.
## Why ceiling `EXACTLY` is safe
`EXACTLY` means Yoga has guaranteed this width — the container has been allocated at least the full fractional width upstream. Ceiling the local layout width by 1px cannot exceed what Yoga has reserved, while flooring it produced a 1px shortfall that mismatched `desiredWidth`'s ceiling and triggered wrapping.
The compensating mechanism in `calculateWidth()` — which returns the raw fractional width to Yoga for `EXACTLY` mode rather than the floored `layout.width` — is preserved, so Yoga's upstream allocation reasoning is unchanged. This was the subpixel-safety property introduced in D74685353; only the local pixel rounding inside `createLayout` changes from "round down 1px and risk wrapping" to "round up 1px and match `desiredWidth`".
## Testing
Added a new test case to cover this behavior. If this needs to be adjusted in the future, a failure will highlight this bug and ensure it's covered or mitigated with additional test cases.
## Notes
This was confirmed as a problem with an absolutely positioned style with `left:0, right:0` applied. Width sizing was confirmed to be the issue when `left:-1, right:-1` resolved the issue. Further investigation found this fix in text sizing.
Only `EXACTLY` is needed to fix the observed Instagram TV bug. `AT_MOST` is left untouched because the constraint semantics differ.
## Changelog: [Android] [Fixed] - Fix 1px text wrapping in absolutely positioned elements caused by fractional Yoga widths
Reviewed By: Abbondanzo
Differential Revision: D102920508
fbshipit-source-id: 05fad96333a282ad274a5686af3a0d30e6a712f2
Summary:
Enable `overrideBySynchronousMountPropsAtMountingAndroid` by default on Android.
This flag was added to prevent regular Fabric mount updates from overriding newer props that were already applied synchronously by Native Animated direct manipulation. Without this path enabled, Android can still hit a race where:
1. Native Animated applies `transform` props synchronously on the UI thread.
2. A regular Fabric mount update for the same view is already in flight with older props.
3. That regular mount update reaches `SurfaceMountingManager.updateProps()` later and overwrites the newer synchronous animated value.
4. The view visibly jumps/flickers during the animation.
This is not just theoretical. I spent about a week debugging this from a real Android flickering issue, and the final repro is intentionally very small. The visual impact is clear in the README videos, and I am attaching the same videos here as well.
Minimal repro:
https://github.com/jingjing2222/fix-react-native-android-flickering
The repro uses React Native 0.85.2 with Android Fabric. The JS only runs `Animated.timing(..., {useNativeDriver: true})` for `translateX` and `translateY`.
## As-is
https://github.com/user-attachments/assets/64882c09-1580-4209-a4aa-aa62bcf58287
With the current default, flickering is visible during the animation.
## To-be
https://github.com/user-attachments/assets/fa929562-36b3-4930-98b5-754098e571e3
With `overrideBySynchronousMountPropsAtMountingAndroid` enabled, the flickering is gone.
The existing mounting-layer flag fixes this by storing the latest synchronous mount props and reapplying them when regular mount props are processed. This makes the final mounted props preserve the latest Native Animated direct manipulation value.
Because this can happen with a simple native-driver transform animation, enabling this default should prevent other Android users from spending time debugging the same race condition.
### Why Android only?
iOS Fabric already tracks props managed by NativeAnimated on the component view. When NativeAnimated synchronously updates props such as `transform` or `opacity`, iOS records those prop keys and prevents later normal Fabric updates from re-applying stale values for those props.
Android Fabric has a similar mechanism through `tagToSynchronousMountProps`, but it was gated behind `overrideBySynchronousMountPropsAtMountingAndroid`, which defaults to false. Therefore, NativeAnimated could synchronously apply the final transform to the view, and a later normal Fabric props update could re-apply stale transform props, causing a transient flicker.
This change makes Android preserve synchronously mounted NativeAnimated props across later Fabric prop updates, matching the ownership behavior already present on iOS.
## Changelog:
[ANDROID] [FIXED] - Prevent stale Fabric mount updates from overriding newer Native Animated synchronous prop updates.
Pull Request resolved: https://github.com/facebook/react-native/pull/56652
Test Plan:
- Ran `yarn featureflags --update`
- Ran `git diff --check`
- Verified generated feature flag defaults were updated for Android, C++, and JS.
- Verified the minimal repro with the README videos attached above:
- as-is/current default: flickering is visible during `translateX`/`translateY` native-driver animation
- to-be/flag enabled: flickering is not visible
Reviewed By: javache, sammy-SC
Differential Revision: D103070058
Pulled By: zeyap
fbshipit-source-id: c5f140ee28ec090677b0cc1b1ad9db35c79aba8d
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/56629
`LayoutAnimationDriver::animationMutationsForFrame` was sorting animation-frame Update mutations together with structural mutations (Remove/Insert/Delete) from completed animations. Animation-frame Updates reference views by their pre-structural-change parentTag. When `std::stable_sort` reordered these Updates after Remove/Insert pairs that reparented a view, `StubViewTree::mutate` hit a parentTag mismatch assertion (`react_native_assert(oldStubView->parentTag == mutation.parentTag)`) and crashed with SIGABRT.
The fix records the boundary between animation-frame Updates and final structural mutations, then only sorts the structural portion. This preserves the invariant that animation-frame Updates execute before any structural changes.
Per zeyap's review: simplified to just the LayoutAnimationDriver.cpp change. The earlier MutationComparator (`Update < Insert`) tweak and the `TEST_F` + feature-flag test refactor were dropped — the driver-side fix alone unbreaks the failing test.
Changelog: [Internal]
Reviewed By: zeyap
Differential Revision: D102696875
fbshipit-source-id: abaac2ae6dae44f7df1f4088bb8ec19b055c2b1a
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/56661
Expand the Fantom integration test for `setUpDefaultReactNativeEnvironment` globals so it covers the full set of globals that React Native's default environment is expected to install, not just the global-object aliases and `__DEV__`/`NODE_ENV`.
Reorganized the existing tests into nested `describe` blocks (`global object`, `environment`, `JavaScript language features`, `Web APIs`) and added coverage for:
- DOM: `Node`, `Document`, `CharacterData`, `Text`, `Element`, `HTMLElement`, `HTMLCollection`, `NodeList`.
- Geometry: `DOMRect`, `DOMRectReadOnly`, `DOMRectList`.
- Events: `Event`, `EventTarget`, `CustomEvent`.
- Performance: `performance`, `Performance`, `PerformanceEntry`, `PerformanceMark`, `PerformanceMeasure`, `PerformanceObserver`, `PerformanceObserverEntryList`, `PerformanceEventTiming`, `PerformanceLongTaskTiming`, `PerformanceResourceTiming`, `EventCounts`, `TaskAttributionTiming`.
- Timers and microtasks: `setTimeout`/`clearTimeout`, `setInterval`/`clearInterval`, `setImmediate`/`clearImmediate`, `requestAnimationFrame`/`cancelAnimationFrame`, `requestIdleCallback`/`cancelIdleCallback`, `queueMicrotask`.
- Networking: `XMLHttpRequest`, `FormData`, `fetch`, `Headers`, `Request`, `Response`, `WebSocket`, `AbortController`, `AbortSignal`, `URL`, `URLSearchParams`.
- File: `Blob`, `File`, and a presence-only check for `FileReader` (accessing the lazy getter triggers a native module that isn't available in the Fantom environment, so we assert the property is registered on `globalThis` without reading it).
- JavaScript language features: `Promise`.
- Other: `alert`, `navigator`.
`PerformanceObserverEntryList` and `EventCounts` aren't recognized as globals by Flow in this file, so they're declared via `declare var ... : unknown` at the top of the file and the assertion checks `typeof`.
Changelog: [Internal]
___
overriding_review_checks_triggers_an_audit_and_retroactive_review
Oncall Short Name: react_native_iroc
landed-with-radar-review
Differential Revision: D103224423
fbshipit-source-id: 561687eb5c4b489d3beea0d83fc544d5ac9363d4
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/56650
## Summary
Fix occasional SIGSEGV in `operator new` during `InspectorPackagerConnection::connectWebSocket()`.
### Root Cause
The `InspectorPackagerConnection` reconnection loop retries every 2 seconds with no backoff or limit. When no Metro dev server is reachable, this results in hundreds of failed WebSocket connection attempts over the app lifetime. Each attempt allocates and deallocates C++ hybrid objects, JNI references, and OkHttp WebSocket instances. This accumulated churn leads to heap fragmentation and eventual heap metadata corruption, manifesting as SIGSEGV in `operator new` when the allocator follows corrupted internal pointers.
Additionally, the `connect()` method had no exception handling around the `connectWebSocket()` call, meaning any JNI/Java exception would propagate uncaught.
### Changes
1. **Exponential backoff in `reconnect()`**: Start at 2s, double each retry, cap at 120s. This reduces reconnection attempts from ~500 in 17 minutes to ~15, drastically reducing resource churn.
2. **Try-catch in `connect()`**: Catch exceptions from `connectWebSocket()` (e.g., fbjni/JNI exceptions) and gracefully trigger a reconnect instead of crashing.
3. **Reset backoff on success**: When `didOpen()` fires (successful connection), reset the delay back to 2s and clear `suppressConnectionErrors_`.
## Changelog:
[General][Fixed] - Add exponential backoff and exception handling to InspectorPackagerConnection reconnect loop to prevent heap fragmentation crashes
Reviewed By: cipolleschi
Differential Revision: D100956687
fbshipit-source-id: 235dc0f65f1a4083acf52be4348f4932bb739d33
Summary:
This PR adds two focused unit tests for `DeviceInfoModule.getWindowDisplayMetrics()` that attach a mocked `Activity`, swap in a fake `WindowMetricsCalculator` via `WindowMetricsCalculator.overrideDecorator()` and verify both branches of `isEdgeToEdgeFeatureFlagOn`:
- edge-to-edge on -> `WindowMetrics.bounds` are used directly.
- edge-to-edge off -> bounds minus `systemBars | displayCutout` insets.
To make this testable without reflection or `SuppressLint("RestrictedApi")` outside the production code, three small visibility tweaks:
- `DeviceInfoModule.getWindowDisplayMetrics()` and `getDisplayMetricsWritableMap()`: `private` → `internal` + `VisibleForTesting`
- `WindowUtilKt.isEdgeToEdgeFeatureFlagOn` setter: `private set` → `VisibleForTesting internal set`
## Changelog:
[INTERNAL] [ADDED] - Add unit tests for `DeviceInfoModule.getWindowDisplayMetrics` covering both edge-to-edge branches
Pull Request resolved: https://github.com/facebook/react-native/pull/56632
Test Plan:
```
./gradlew :packages:react-native:ReactAndroid:testDebugUnitTest \
--tests com.facebook.react.modules.deviceinfo.DeviceInfoModuleTest
```
Reviewed By: javache
Differential Revision: D102801090
Pulled By: alanleedev
fbshipit-source-id: 5e103404ef822d782c87117d77916221c512eaa2
Summary:
Bumps Metro dependency from `^0.84.2` to `^0.84.3` across all packages.
Metro 0.84.3 adds `changeId` to HMR `update-done` messages, which is required by the `unstable_fastRefreshComplete` CDP event and the Fast Refresh performance marker to deduplicate events across multiple updates for the same file change.
## Changelog:
[Internal]
Pull Request resolved: https://github.com/facebook/react-native/pull/56638
Test Plan:
- CI
cc huntie
Reviewed By: cortinico
Differential Revision: D102810175
Pulled By: motiz88
fbshipit-source-id: b05bc522fd7815f2858ce645b03bdea86a8027ea