Skip to content

Commit 66afb82

Browse files
authored
[Android] Fix the HCPP SurfaceControl transaction-list race and split the transaction entry points (flutter#192606)
## Description Fix the Android 14+ HCPP transaction-list race. The raster thread added to the pending transaction list while the platform thread swapped it, leaving null entries that made `merge(null)` throw and abort the engine through JNI. - Guard the pending raster transaction list with one lock shared by raster-thread additions and platform-thread draining. The active raster transaction list and both platform transaction slots are confined to the platform thread. - Split the entry points by caller rather than inferring the thread at runtime: `createTransaction()` is the raster/JNI entry and always returns an isolated transaction, while a private `platformTransaction()` consolidates platform-thread mutations (clips, overlay visibility) into one transaction per frame. - Close platform transactions once they are merged or discarded. Raster transactions are not closed here, because their native producer may still be writing through them. - Detached-view handling is unchanged: `onEndFrame()` still allocates a merge destination, merges, invalidates and applies on every frame, exactly as before. - Remove the unused `applyTransactions()` JNI path, which nothing has ever called. This fixes the Java-side list corruption only. Two pre-existing native ownership hazards remain, and both need the same follow-up: 1. `AHBSwapchainImplVK::Present` writes through the borrowed `ASurfaceTransaction*` after the transaction has been published to Java, so a merge on the platform thread can race those writes. 2. Once Java drops its last reference, the `NativeAllocationRegistry` cleaner can free the native transaction while native code is still using it. Avoiding an explicit `close()` narrows this window but does not close it. Fixing either one properly requires the native side to retain the transaction and publish it only after the producer has finished writing. That is a separate change. ## Tests Coverage includes platform consolidation, raster isolation, the separate merge destination, transactions still in use by a paused producer, discarded platform transactions, and detached frames. The tests drive platform mutations through their real call sites rather than calling `createTransaction()` directly. Verified locally with a Robolectric harness built against these sources: - 20/20 `PlatformViewsController2Test` tests pass. - The stress test passes 10 consecutive runs with 0 skips (3.4s total). - With the locks removed from a copy of the sources, the same test reports `NullPointerException: Cannot read field "mResizedSurfaces" because "other" is null` in 10/10 runs — the production stack trace, which `FML_CHECK(fml::jni::CheckException(env))` turns into an `abort()` on device. Detection is probabilistic and one-sided: the test contains no timing assertions, so scheduling decides whether it catches an unsynchronized implementation, never whether it fails a synchronized one. A barrier timeout skips the run; a producer that fails to terminate fails it. It covers list corruption, not liveness, and does not exercise the native writes described above. Java formatting and `git diff --check` pass. --- *Portions of this change and this description were authored with AI assistance.* ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant in-code documentation (doc comments with `///`). - [x] If this PR introduces a new feature or capability, I created and linked a website documentation issue or PR in [flutter/website] (or verified none is needed). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. If this change needs to override an active code freeze, provide a comment explaining why. The code freeze workflow can be overridden by code reviewers. See pinned issues for any active code freezes with guidance. **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [flutter/website]: https://github.com/flutter/website [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
1 parent ff7eec8 commit 66afb82

8 files changed

Lines changed: 413 additions & 88 deletions

File tree

‎engine/src/flutter/shell/platform/android/android_shell_holder_unittests.cc‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,6 @@ class MockPlatformViewAndroidJNI : public PlatformViewAndroidJNI {
101101
MOCK_METHOD(void, FlutterViewDestroyOverlaySurfaces, (), (override));
102102
MOCK_METHOD(ASurfaceTransaction*, createTransaction, (), (override));
103103
MOCK_METHOD(void, swapTransaction, (), (override));
104-
MOCK_METHOD(void, applyTransaction, (), (override));
105104
MOCK_METHOD(void, destroyOverlaySurface2, (), (override));
106105
MOCK_METHOD(std::unique_ptr<PlatformViewAndroidJNI::OverlayMetadata>,
107106
createOverlaySurface2,

‎engine/src/flutter/shell/platform/android/io/flutter/embedding/engine/FlutterJNI.java‎

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1358,9 +1358,9 @@ public void maybeResizeSurfaceView(int width, int height) {
13581358

13591359
// ----- New Platform Views ----------
13601360

1361+
// Called from the raster thread for AHB swapchain presentation.
13611362
@SuppressWarnings("unused")
13621363
@SuppressLint("NewApi")
1363-
@UiThread
13641364
public SurfaceControl.Transaction createTransaction() {
13651365
if (platformViewsController2 == null) {
13661366
throw new RuntimeException("");
@@ -1378,16 +1378,6 @@ public void swapTransactions() {
13781378
platformViewsController2.swapTransactions();
13791379
}
13801380

1381-
@SuppressWarnings("unused")
1382-
@SuppressLint("NewApi")
1383-
@UiThread
1384-
public void applyTransactions() {
1385-
if (platformViewsController2 == null) {
1386-
throw new RuntimeException("");
1387-
}
1388-
platformViewsController2.applyTransactions();
1389-
}
1390-
13911381
@SuppressWarnings("unused")
13921382
@SuppressLint("NewApi")
13931383
@UiThread

‎engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewsController2.java‎

Lines changed: 100 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import android.graphics.PixelFormat;
1212
import android.graphics.Rect;
1313
import android.graphics.RectF;
14+
import android.os.Build;
1415
import android.util.SparseArray;
1516
import android.view.AttachedSurfaceControl;
1617
import android.view.Gravity;
@@ -75,8 +76,17 @@ public class PlatformViewsController2 implements PlatformViewsAccessibilityDeleg
7576
private final SparseArray<FlutterMutatorView> platformViewParent;
7677
private final MotionEventTracker motionEventTracker;
7778

78-
private final ArrayList<SurfaceControl.Transaction> pendingTransactions;
79-
private final ArrayList<SurfaceControl.Transaction> activeTransactions;
79+
// Guarded by transactionLock: the raster thread appends; the platform thread drains.
80+
private final ArrayList<SurfaceControl.Transaction> pendingRasterTransactions;
81+
private final Object transactionLock = new Object();
82+
83+
// Platform-thread only: populated by swapTransactions(), drained by onEndFrame().
84+
private final ArrayList<SurfaceControl.Transaction> activeRasterTransactions;
85+
86+
// Platform-thread only. Clips and overlay visibility share one transaction per frame.
87+
private SurfaceControl.Transaction pendingPlatformTransaction;
88+
private SurfaceControl.Transaction activePlatformTransaction;
89+
8090
private Surface overlayerSurface = null;
8191
private SurfaceControl overlaySurfaceControl = null;
8292

@@ -86,8 +96,8 @@ public PlatformViewsController2() {
8696
accessibilityEventsDelegate = new AccessibilityEventsDelegate();
8797
platformViews = new SparseArray<>();
8898
platformViewParent = new SparseArray<>();
89-
pendingTransactions = new ArrayList<>();
90-
activeTransactions = new ArrayList<>();
99+
pendingRasterTransactions = new ArrayList<>();
100+
activeRasterTransactions = new ArrayList<>();
91101
motionEventTracker = MotionEventTracker.getInstance();
92102
}
93103

@@ -269,6 +279,10 @@ public void detachFromView() {
269279
destroyOverlaySurface();
270280
flutterView = null;
271281

282+
if (Build.VERSION.SDK_INT >= API_LEVELS.API_34) {
283+
dropTransactions();
284+
}
285+
272286
// Notify that the platform view have been detached from FlutterView.
273287
for (int index = 0; index < platformViews.size(); index++) {
274288
final PlatformView view = platformViews.valueAt(index);
@@ -616,7 +630,7 @@ private void maybeApplyClipToSurfaceView(
616630
return;
617631
}
618632
SurfaceControl.Transaction tx =
619-
createTransaction().setAlpha(sc, opacity).setCrop(sc, screenRect);
633+
platformTransaction().setAlpha(sc, opacity).setCrop(sc, screenRect);
620634
}
621635

622636
@RequiresApi(API_LEVELS.API_34)
@@ -631,7 +645,7 @@ public void surfaceCreated(@NonNull SurfaceHolder holder) {
631645
SurfaceControl surfaceControl = surfaceView.getSurfaceControl();
632646
if (surfaceControl != null && surfaceControl.isValid()) {
633647
SurfaceControl.Transaction tx =
634-
createTransaction()
648+
platformTransaction()
635649
.setAlpha(surfaceControl, opacity)
636650
.setCrop(surfaceControl, screenRect);
637651
} else {
@@ -671,22 +685,29 @@ public void hidePlatformView(int viewId) {
671685
parentView.setVisibility(View.GONE);
672686
}
673687

688+
@UiThread
674689
@RequiresApi(API_LEVELS.API_34)
675690
public void onEndFrame() {
691+
final SurfaceControl.Transaction platformTx = activePlatformTransaction;
692+
activePlatformTransaction = null;
693+
694+
// Use a fresh destination so cleanup cannot close a raster input still in native use.
695+
// Bypass newTransaction(), which tests may override to return an existing input.
676696
SurfaceControl.Transaction tx = new SurfaceControl.Transaction();
677-
for (int i = 0; i < activeTransactions.size(); i++) {
678-
tx = tx.merge(activeTransactions.get(i));
697+
if (platformTx != null) {
698+
tx = tx.merge(platformTx);
699+
platformTx.close();
679700
}
680-
activeTransactions.clear();
701+
for (SurfaceControl.Transaction rasterTx : activeRasterTransactions) {
702+
tx = tx.merge(rasterTx);
703+
}
704+
activeRasterTransactions.clear();
681705

682-
// This runs on the platform thread but is posted from the raster thread, so by the time it
683-
// runs the FlutterView may have been detached from the controller, or detached from its
684-
// window (in which case getRootSurfaceControl() returns null). Throwing here is fatal rather
685-
// than merely wrong: the JNI caller, onEndFrame2(), turns a pending Java exception into an
686-
// abort() via FML_CHECK(fml::jni::CheckException(env)).
706+
// The view or its window may detach before this posted frame runs.
687707
final AttachedSurfaceControl rootSurfaceControl =
688708
flutterView == null ? null : flutterView.getRootSurfaceControl();
689709
if (rootSurfaceControl == null) {
710+
// Release the unapplied transaction and its owned fence FDs.
690711
tx.close();
691712
return;
692713
}
@@ -695,30 +716,77 @@ public void onEndFrame() {
695716
rootSurfaceControl.applyTransactionOnDraw(tx);
696717
}
697718

698-
// NOT called from UI thread.
699-
public synchronized void swapTransactions() {
700-
activeTransactions.clear();
701-
activeTransactions.addAll(pendingTransactions);
702-
pendingTransactions.clear();
719+
@UiThread
720+
@RequiresApi(API_LEVELS.API_34)
721+
public void swapTransactions() {
722+
// Do not close discarded raster inputs; native producers may still use them.
723+
activeRasterTransactions.clear();
724+
synchronized (transactionLock) {
725+
activeRasterTransactions.addAll(pendingRasterTransactions);
726+
pendingRasterTransactions.clear();
727+
}
728+
729+
if (activePlatformTransaction != null) {
730+
// Discard a platform transaction whose onEndFrame() never ran.
731+
activePlatformTransaction.close();
732+
}
733+
activePlatformTransaction = pendingPlatformTransaction;
734+
pendingPlatformTransaction = null;
735+
}
736+
737+
/**
738+
* Discards the transaction state of the view that just detached.
739+
*
740+
* <p>Platform transactions are closed here: they only touch SurfaceControls that this detach
741+
* invalidates, including the overlay that {@link #destroyOverlaySurface()} just released, and
742+
* nothing outside the platform thread references them. Raster transactions are dropped without
743+
* closing them, because their native producers may still be writing into them.
744+
*/
745+
@UiThread
746+
@RequiresApi(API_LEVELS.API_34)
747+
private void dropTransactions() {
748+
activeRasterTransactions.clear();
749+
synchronized (transactionLock) {
750+
pendingRasterTransactions.clear();
751+
}
752+
753+
if (activePlatformTransaction != null) {
754+
activePlatformTransaction.close();
755+
activePlatformTransaction = null;
756+
}
757+
if (pendingPlatformTransaction != null) {
758+
pendingPlatformTransaction.close();
759+
pendingPlatformTransaction = null;
760+
}
761+
}
762+
763+
@UiThread
764+
@RequiresApi(API_LEVELS.API_34)
765+
private SurfaceControl.Transaction platformTransaction() {
766+
if (pendingPlatformTransaction == null) {
767+
pendingPlatformTransaction = newTransaction();
768+
}
769+
return pendingPlatformTransaction;
703770
}
704771

705-
// NOT called from UI thread.
772+
// Called from the raster thread through FlutterJNI.
706773
@RequiresApi(API_LEVELS.API_34)
707774
public SurfaceControl.Transaction createTransaction() {
708-
SurfaceControl.Transaction tx = new SurfaceControl.Transaction();
709-
pendingTransactions.add(tx);
775+
final SurfaceControl.Transaction tx = newTransaction();
776+
// This lock protects the list, not AHBSwapchainImplVK::Present's later native writes.
777+
// Those can race merging or GC freeing the transaction. Fix both hazards by retaining it
778+
// natively and publishing only after the writes finish.
779+
synchronized (transactionLock) {
780+
pendingRasterTransactions.add(tx);
781+
}
710782
return tx;
711783
}
712784

713-
// NOT called from UI thread.
785+
/** Allocates a transaction so tests can spy on the instance retained by the controller. */
786+
@VisibleForTesting
714787
@RequiresApi(API_LEVELS.API_34)
715-
public void applyTransactions() {
716-
SurfaceControl.Transaction tx = new SurfaceControl.Transaction();
717-
for (int i = 0; i < pendingTransactions.size(); i++) {
718-
tx = tx.merge(pendingTransactions.get(i));
719-
}
720-
tx.apply();
721-
pendingTransactions.clear();
788+
SurfaceControl.Transaction newTransaction() {
789+
return new SurfaceControl.Transaction();
722790
}
723791

724792
@RequiresApi(API_LEVELS.API_34)
@@ -755,7 +823,7 @@ public void showOverlaySurface() {
755823
if (overlaySurfaceControl == null) {
756824
return;
757825
}
758-
SurfaceControl.Transaction tx = createTransaction();
826+
SurfaceControl.Transaction tx = platformTransaction();
759827
tx.setVisibility(overlaySurfaceControl, /*visible=*/ true);
760828
}
761829

@@ -764,7 +832,7 @@ public void hideOverlaySurface() {
764832
if (overlaySurfaceControl == null) {
765833
return;
766834
}
767-
SurfaceControl.Transaction tx = createTransaction();
835+
SurfaceControl.Transaction tx = platformTransaction();
768836
tx.setVisibility(overlaySurfaceControl, /*visible=*/ false);
769837
}
770838

‎engine/src/flutter/shell/platform/android/jni/jni_mock.h‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,8 +127,6 @@ class JNIMock final : public PlatformViewAndroidJNI {
127127

128128
MOCK_METHOD(void, swapTransaction, (), (override));
129129

130-
MOCK_METHOD(void, applyTransaction, (), (override));
131-
132130
MOCK_METHOD(void, destroyOverlaySurface2, (), (override));
133131

134132
MOCK_METHOD(std::unique_ptr<PlatformViewAndroidJNI::OverlayMetadata>,

‎engine/src/flutter/shell/platform/android/jni/platform_view_android_jni.h‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -233,8 +233,6 @@ class PlatformViewAndroidJNI {
233233

234234
virtual void swapTransaction() = 0;
235235

236-
virtual void applyTransaction() = 0;
237-
238236
virtual std::unique_ptr<PlatformViewAndroidJNI::OverlayMetadata>
239237
createOverlaySurface2() = 0;
240238

‎engine/src/flutter/shell/platform/android/platform_view_android_jni_impl.cc‎

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,6 @@ static jfieldID g_jni_shell_holder_field = nullptr;
8181
V(g_create_transaction_method, createTransaction, \
8282
"()Landroid/view/SurfaceControl$Transaction;") \
8383
V(g_swap_transaction_method, swapTransactions, "()V") \
84-
V(g_apply_transaction_method, applyTransactions, "()V") \
8584
V(g_create_overlay_surface2_method, createOverlaySurface2, \
8685
"()Lio/flutter/embedding/engine/FlutterOverlaySurface;") \
8786
V(g_destroy_overlay_surface2_method, destroyOverlaySurface2, "()V") \
@@ -2099,19 +2098,6 @@ void PlatformViewAndroidJNIImpl::swapTransaction() {
20992098
FML_CHECK(fml::jni::CheckException(env));
21002099
}
21012100

2102-
void PlatformViewAndroidJNIImpl::applyTransaction() {
2103-
JNIEnv* env = fml::jni::AttachCurrentThread();
2104-
2105-
auto java_object = java_object_.get(env);
2106-
if (java_object.is_null()) {
2107-
return;
2108-
}
2109-
2110-
env->CallVoidMethod(java_object.obj(), g_apply_transaction_method);
2111-
2112-
FML_CHECK(fml::jni::CheckException(env));
2113-
}
2114-
21152101
std::unique_ptr<PlatformViewAndroidJNI::OverlayMetadata>
21162102
PlatformViewAndroidJNIImpl::createOverlaySurface2() {
21172103
JNIEnv* env = fml::jni::AttachCurrentThread();

‎engine/src/flutter/shell/platform/android/platform_view_android_jni_impl.h‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,8 +132,6 @@ class PlatformViewAndroidJNIImpl final : public PlatformViewAndroidJNI {
132132

133133
void swapTransaction() override;
134134

135-
void applyTransaction() override;
136-
137135
std::unique_ptr<PlatformViewAndroidJNI::OverlayMetadata>
138136
createOverlaySurface2() override;
139137

0 commit comments

Comments
 (0)