Guard Scheduler deferred lambdas against delegate teardown (#56680)

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
This commit is contained in:
Kevin Gozali authored and meta-codesync[bot] committed 2026-05-04 21:16:03 -07:00
1 parent d0672fb3a9
commit aadbe96579
2 files changed
+51 -1

No files matched your search

@@ -29,7 +29,8 @@ Scheduler::Scheduler(
const SchedulerToolbox& schedulerToolbox,
UIManagerAnimationDelegate* animationDelegate,
SchedulerDelegate* delegate)
: runtimeExecutor_(schedulerToolbox.runtimeExecutor),
: delegateInvalidated_(std::make_shared<std::atomic<bool>>(false)),
runtimeExecutor_(schedulerToolbox.runtimeExecutor),
contextContainer_(schedulerToolbox.contextContainer) {
// Creating a container for future `EventDispatcher` instance.
eventDispatcher_ = std::make_shared<std::optional<const EventDispatcher>>();
@@ -171,6 +172,15 @@ Scheduler::~Scheduler() {
LOG(WARNING) << "Scheduler::~Scheduler() was called (address: " << this
<< ").";
// Invalidate any lambdas already queued via scheduleRenderingUpdate that
// captured a raw delegate_ pointer; without this they'd dereference a
// dangling SchedulerDelegate after Scheduler teardown. (No replacement
// token is allocated here — Scheduler is going away.)
// Gated to allow controlled rollout / rollback.
if (ReactNativeFeatureFlags::enableSchedulerDelegateInvalidation()) {
*delegateInvalidated_ = true;
}
auto weakRuntimeScheduler =
contextContainer_->find<std::weak_ptr<RuntimeScheduler>>(
RuntimeSchedulerKey);
@@ -260,6 +270,21 @@ Scheduler::findComponentDescriptorByHandle_DO_NOT_USE_THIS_IS_BROKEN(
#pragma mark - Delegate
void Scheduler::setDelegate(SchedulerDelegate* delegate) {
// Gated to allow controlled rollout / rollback.
if (ReactNativeFeatureFlags::enableSchedulerDelegateInvalidation() &&
delegate_ != delegate) {
// Mark the *current* token invalid: any rendering-update lambda already
// queued holds a shared_ptr to this atomic and will observe `true` on
// its next read, so it no-ops instead of calling into the previous
// delegate (which the caller is about to drop).
*delegateInvalidated_ = true;
// Then install a *fresh* token (a new atomic) so lambdas captured
// against the new delegate use their own non-invalidated flag.
// Reusing the previous atomic and flipping it back to `false` would
// re-arm the in-flight lambdas — exactly the use-after-free we're
// trying to prevent — because they share the same shared_ptr.
delegateInvalidated_ = std::make_shared<std::atomic<bool>>(false);
}
delegate_ = delegate;
}
@@ -288,10 +313,21 @@ void Scheduler::uiManagerDidFinishTransaction(
if (!mountSynchronously) {
auto surfaceId = mountingCoordinator->getSurfaceId();
// Capture the gating flag at queue time: the lambda's decision to
// honor the invalidation guard is fixed when we enqueue, not when it
// later runs. Avoids per-invocation feature-flag reads and keeps the
// contract for an in-flight lambda stable across flag flips.
auto guardEnabled =
ReactNativeFeatureFlags::enableSchedulerDelegateInvalidation();
runtimeScheduler_->scheduleRenderingUpdate(
surfaceId,
[delegate = delegate_,
invalidated = delegateInvalidated_,
guardEnabled,
mountingCoordinator = std::move(mountingCoordinator)]() {
if (guardEnabled && *invalidated) {
return;
}
delegate->schedulerShouldRenderTransactions(mountingCoordinator);
});
} else {
@@ -314,12 +350,20 @@ void Scheduler::uiManagerDidDispatchCommand(
"Scheduler::uiManagerDispatchCommand", "commandName", commandName);
if (delegate_ != nullptr) {
auto shadowView = ShadowView(*shadowNode);
// See comment in uiManagerDidFinishTransaction above for gating shape.
auto guardEnabled =
ReactNativeFeatureFlags::enableSchedulerDelegateInvalidation();
runtimeScheduler_->scheduleRenderingUpdate(
shadowNode->getSurfaceId(),
[delegate = delegate_,
invalidated = delegateInvalidated_,
guardEnabled,
shadowView = std::move(shadowView),
commandName,
args]() {
if (guardEnabled && *invalidated) {
return;
}
delegate->schedulerDidDispatchCommand(shadowView, commandName, args);
});
}
@@ -7,6 +7,7 @@
#pragma once
#include <atomic>
#include <memory>
#include <ReactCommon/RuntimeExecutor.h>
@@ -122,6 +123,11 @@ class Scheduler final : public UIManagerDelegate {
friend class SurfaceHandler;
SchedulerDelegate *delegate_;
// Invalidation token captured by-value into lambdas deferred via
// runtimeScheduler_->scheduleRenderingUpdate. Set to true on delegate
// change or Scheduler destruction so a lambda that outlives its captured
// raw delegate pointer can no-op instead of dereferencing dangling memory.
std::shared_ptr<std::atomic<bool>> delegateInvalidated_;
SharedComponentDescriptorRegistry componentDescriptorRegistry_;
RuntimeExecutor runtimeExecutor_;
std::shared_ptr<UIManager> uiManager_;