Skip to content

Commit 91d9b9c

Browse files
[Android] Fix use-after-free of SurfaceControl.Transaction in HCPP (flutter#192969)
Fixes a native `SIGABRT` in `SurfaceComposerClient::Transaction` that we were seeing with HCPP under heavy platform view churn. `createTransaction()` was adding the transaction to `pendingRasterTransactions` before handing it back to native, but `AHBSwapchainImplVK::Present()` keeps writing into it after that (`setBuffer`, `setOnComplete`). So the platform thread could merge or close it mid-write. Separately, nothing was holding a reference to the Java object (`ASurfaceTransaction_fromJava` doesn't take one), so it could also just get GC'd out from under us. This splits creation from publication. Native now gets an unpublished transaction, holds a global ref to it while writing, and calls `publishTransaction` from `SurfaceTransaction::Apply()` after its last write. If publishing fails for whatever reason (`FlutterJNI` is gone, Java throws), we apply the transaction natively instead of dropping it, so the completion callback still fires and we don't leak the buffer. I don't think those paths are reachable today, but they're easy to just handle. On a stress test that cycles ~2,900 `SurfaceView`s per run on a low-core emulator, this went from 24 aborts in 100 runs to 0 in 75. It's a little awkward that the NDK only goes one direction here: there's `ASurfaceTransaction_fromJava`, but no `toJava`. If we could create the transaction natively and hand it to Java at the end, most of this wouldn't be needed, might be feedback that is worth filing. --------- Co-authored-by: Gray Mackall <[email protected]>
1 parent 92b6e5a commit 91d9b9c

15 files changed

Lines changed: 445 additions & 39 deletions

‎engine/src/flutter/impeller/toolkit/android/surface_transaction.cc‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,14 @@
1111
namespace impeller::android {
1212

1313
SurfaceTransaction::SurfaceTransaction()
14-
: transaction_(
15-
WrappedSurfaceTransaction{GetProcTable().ASurfaceTransaction_create(),
16-
/*owned=*/true}) {}
14+
: transaction_(WrappedSurfaceTransaction{
15+
GetProcTable().ASurfaceTransaction_create(), /*owned=*/true,
16+
/*publish_callback=*/nullptr}) {}
1717

18-
SurfaceTransaction::SurfaceTransaction(ASurfaceTransaction* transaction)
19-
: transaction_(WrappedSurfaceTransaction{transaction, /*owned=*/false}) {}
18+
SurfaceTransaction::SurfaceTransaction(ASurfaceTransaction* transaction,
19+
std::function<void()> publish_callback)
20+
: transaction_(WrappedSurfaceTransaction{transaction, /*owned=*/false,
21+
std::move(publish_callback)}) {}
2022

2123
SurfaceTransaction::~SurfaceTransaction() = default;
2224

@@ -53,7 +55,13 @@ bool SurfaceTransaction::Apply(OnCompleteCallback callback) {
5355
// the Java PlatformViewController and not as a part of the engine render
5456
// loop.
5557
if (!transaction_.get().owned) {
58+
// All native writes into the transaction are done at this point. Hand it
59+
// back to Java, which owns applying it.
60+
std::function<void()> publish_cb = transaction_.get().publish_callback;
5661
transaction_.reset();
62+
if (publish_cb) {
63+
publish_cb();
64+
}
5765
return true;
5866
}
5967

‎engine/src/flutter/impeller/toolkit/android/surface_transaction.h‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,11 @@ struct WrappedSurfaceTransaction {
2828
/// Java.
2929
bool owned = true;
3030

31-
constexpr bool operator==(const WrappedSurfaceTransaction& other) const {
31+
/// Invoked after all native writes into a borrowed (non-owned) transaction
32+
/// have completed, to hand the transaction back to Java for application.
33+
std::function<void()> publish_callback;
34+
35+
bool operator==(const WrappedSurfaceTransaction& other) const {
3236
return other.tx == tx;
3337
}
3438
};
@@ -63,7 +67,17 @@ class SurfaceTransaction {
6367

6468
SurfaceTransaction& operator=(const SurfaceTransaction&) = delete;
6569

66-
explicit SurfaceTransaction(ASurfaceTransaction* transaction);
70+
//----------------------------------------------------------------------------
71+
/// @brief Wraps a transaction borrowed from Java.
72+
///
73+
/// @param[in] transaction The borrowed transaction.
74+
/// @param[in] publish_callback Invoked from `Apply` once all native writes
75+
/// into the transaction have completed. This
76+
/// is the point at which it is safe for Java to
77+
/// merge, apply, or close the transaction.
78+
///
79+
SurfaceTransaction(ASurfaceTransaction* transaction,
80+
std::function<void()> publish_callback);
6781

6882
bool IsValid() const;
6983

‎engine/src/flutter/impeller/toolkit/android/toolkit_android_unittests.cc‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,33 @@ TEST(ToolkitAndroidTest, CanApplySurfaceTransaction) {
9191
event.Wait();
9292
}
9393

94+
TEST(ToolkitAndroidTest,
95+
BorrowedSurfaceTransactionInvokesPublishCallbackAndFiresOnComplete) {
96+
if (!SurfaceTransaction::IsAvailableOnPlatform()) {
97+
GTEST_SKIP() << "Surface controls are not supported on this platform.";
98+
}
99+
ASurfaceTransaction* raw_tx = GetProcTable().ASurfaceTransaction_create();
100+
ASSERT_NE(raw_tx, nullptr);
101+
102+
bool published = false;
103+
SurfaceTransaction borrowed_tx(raw_tx, [&]() {
104+
// Native wrapper must release its reference before handing the transaction
105+
// back to Java for application/closing.
106+
EXPECT_FALSE(borrowed_tx.IsValid());
107+
published = true;
108+
GetProcTable().ASurfaceTransaction_apply(raw_tx);
109+
GetProcTable().ASurfaceTransaction_delete(raw_tx);
110+
});
111+
ASSERT_TRUE(borrowed_tx.IsValid());
112+
EXPECT_FALSE(published);
113+
114+
fml::AutoResetWaitableEvent on_complete;
115+
ASSERT_TRUE(
116+
borrowed_tx.Apply([&on_complete](auto) { on_complete.Signal(); }));
117+
EXPECT_TRUE(published);
118+
on_complete.Wait();
119+
}
120+
94121
TEST(ToolkitAndroidTest, SurfacControlsAreAvailable) {
95122
if (!SurfaceControl::IsAvailableOnPlatform()) {
96123
GTEST_SKIP() << "Surface controls are not supported on this platform.";

‎engine/src/flutter/shell/platform/android/BUILD.gn‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ executable("flutter_shell_native_unittests") {
5757
sources += [ "android_context_gl_unittests.cc" ]
5858
}
5959
public_configs = [ "//flutter:config" ]
60+
defines = [ "TESTING" ]
6061
deps = [
6162
":flutter_shell_native_src",
6263
"//flutter/fml",

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,10 @@ class MockPlatformViewAndroidJNI : public PlatformViewAndroidJNI {
9999
(),
100100
(override));
101101
MOCK_METHOD(void, FlutterViewDestroyOverlaySurfaces, (), (override));
102-
MOCK_METHOD(ASurfaceTransaction*, createTransaction, (), (override));
102+
MOCK_METHOD(ASurfaceTransaction*,
103+
createTransaction,
104+
(std::function<void()>&),
105+
(override));
103106
MOCK_METHOD(void, swapTransaction, (), (override));
104107
MOCK_METHOD(void, destroyOverlaySurface2, (), (override));
105108
MOCK_METHOD(std::unique_ptr<PlatformViewAndroidJNI::OverlayMetadata>,

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,11 +87,13 @@ bool AndroidSurfaceVKImpeller::SetNativeWindow(
8787

8888
impeller::CreateTransactionCB cb = [jni_facade = jni_facade]() {
8989
FML_CHECK(jni_facade) << "JNI was nullptr";
90-
ASurfaceTransaction* tx = jni_facade->createTransaction();
90+
std::function<void()> publish_callback;
91+
ASurfaceTransaction* tx = jni_facade->createTransaction(publish_callback);
9192
if (tx == nullptr) {
9293
return impeller::android::SurfaceTransaction();
9394
}
94-
return impeller::android::SurfaceTransaction(tx);
95+
return impeller::android::SurfaceTransaction(tx,
96+
std::move(publish_callback));
9597
};
9698

9799
auto swapchain = impeller::SwapchainVK::Create(

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

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1358,14 +1358,29 @@ public void maybeResizeSurfaceView(int width, int height) {
13581358

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

1361-
// Called from the raster thread for AHB swapchain presentation.
1361+
// Called from the raster thread for AHB swapchain presentation. The returned transaction is not
1362+
// yet visible to the platform thread; the caller must pass it to publishTransaction once it has
1363+
// finished writing into it.
13621364
@SuppressWarnings("unused")
13631365
@SuppressLint("NewApi")
1364-
public SurfaceControl.Transaction createTransaction() {
1366+
public SurfaceControl.Transaction createUnpublishedTransaction() {
13651367
if (platformViewsController2 == null) {
13661368
throw new RuntimeException("");
13671369
}
1368-
return platformViewsController2.createTransaction();
1370+
return platformViewsController2.createUnpublishedTransaction();
1371+
}
1372+
1373+
// Called from the raster thread once it is done writing into a transaction returned by
1374+
// createUnpublishedTransaction. If this throws, the native caller logs the exception and applies
1375+
// the transaction itself rather than dropping it.
1376+
@SuppressWarnings("unused")
1377+
@SuppressLint("NewApi")
1378+
public void publishTransaction(SurfaceControl.Transaction tx) {
1379+
if (platformViewsController2 == null) {
1380+
throw new IllegalStateException(
1381+
"publishTransaction called without a PlatformViewsController2");
1382+
}
1383+
platformViewsController2.publishTransaction(tx);
13691384
}
13701385

13711386
@SuppressWarnings("unused")

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

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -769,17 +769,40 @@ private SurfaceControl.Transaction platformTransaction() {
769769
return pendingPlatformTransaction;
770770
}
771771

772+
/**
773+
* Allocates a transaction for the raster thread without making it visible to the platform thread.
774+
*
775+
* <p>The native caller continues to write into the transaction after this returns (setting the
776+
* buffer and the completion callback). Publishing it here would let {@link #swapTransactions()}
777+
* and {@link #onEndFrame()} merge and close it while those writes are in flight. The caller must
778+
* call {@link #publishTransaction} once it is done writing.
779+
*
780+
* <p>This is only called when HCPP is active, which is gated on API 34+ in the engine (both
781+
* {@code kMinAPILevelHCPP} and the AHB swapchain's {@code CreateTransactionCB} require API 34+,
782+
* where {@code ASurfaceTransaction_fromJava} was introduced).
783+
*/
772784
// Called from the raster thread through FlutterJNI.
773785
@RequiresApi(API_LEVELS.API_34)
774-
public SurfaceControl.Transaction createTransaction() {
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.
786+
public SurfaceControl.Transaction createUnpublishedTransaction() {
787+
return newTransaction();
788+
}
789+
790+
/**
791+
* Publishes a transaction returned by {@link #createUnpublishedTransaction()} now that the caller
792+
* has finished writing into it.
793+
*
794+
* <p>Like {@link #createUnpublishedTransaction()}, this is only reachable on API 34+ because HCPP
795+
* and the native transaction callback are gated on API 34+.
796+
*/
797+
// Called from the raster thread through FlutterJNI.
798+
@RequiresApi(API_LEVELS.API_34)
799+
public void publishTransaction(SurfaceControl.Transaction tx) {
800+
if (tx == null) {
801+
return;
802+
}
779803
synchronized (transactionLock) {
780804
pendingRasterTransactions.add(tx);
781805
}
782-
return tx;
783806
}
784807

785808
/** Allocates a transaction so tests can spy on the instance retained by the controller. */

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,10 @@ class JNIMock final : public PlatformViewAndroidJNI {
123123

124124
MOCK_METHOD(void, FlutterViewDestroyOverlaySurfaces, (), (override));
125125

126-
MOCK_METHOD(ASurfaceTransaction*, createTransaction, (), (override));
126+
MOCK_METHOD(ASurfaceTransaction*,
127+
createTransaction,
128+
(std::function<void()>&),
129+
(override));
127130

128131
MOCK_METHOD(void, swapTransaction, (), (override));
129132

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,11 @@ class MockableJNIEnv : public JNIEnv {
5353
functions = &jni_;
5454
jni_.CallObjectMethod = WrapCallObjectMethod;
5555
jni_.CallObjectMethodV = WrapCallObjectMethodV;
56+
jni_.CallVoidMethod = WrapCallVoidMethod;
57+
jni_.CallVoidMethodV = WrapCallVoidMethodV;
5658
jni_.DeleteGlobalRef = WrapDeleteGlobalRef;
5759
jni_.DeleteLocalRef = WrapDeleteLocalRef;
60+
jni_.DeleteWeakGlobalRef = WrapDeleteWeakGlobalRef;
5861
jni_.ExceptionCheck = WrapExceptionCheck;
5962
jni_.ExceptionClear = WrapExceptionClear;
6063
jni_.ExceptionDescribe = WrapExceptionDescribe;
@@ -67,14 +70,17 @@ class MockableJNIEnv : public JNIEnv {
6770
jni_.GetStaticMethodID = WrapGetStaticMethodID;
6871
jni_.NewGlobalRef = WrapNewGlobalRef;
6972
jni_.NewLocalRef = WrapNewLocalRef;
73+
jni_.NewWeakGlobalRef = WrapNewWeakGlobalRef;
7074
jni_.RegisterNatives = WrapRegisterNatives;
7175
jni_.GetArrayLength = WrapGetArrayLength;
7276
jni_.GetIntArrayRegion = WrapGetIntArrayRegion;
7377
}
7478

7579
virtual jobject CallObjectMethodV(jobject, jmethodID, va_list) = 0;
80+
virtual void CallVoidMethodV(jobject, jmethodID, va_list) = 0;
7681
virtual void DeleteGlobalRef(jobject) = 0;
7782
virtual void DeleteLocalRef(jobject) = 0;
83+
virtual void DeleteWeakGlobalRef(jweak) = 0;
7884
virtual jboolean ExceptionCheck() = 0;
7985
virtual void ExceptionClear() = 0;
8086
virtual void ExceptionDescribe() = 0;
@@ -87,6 +93,7 @@ class MockableJNIEnv : public JNIEnv {
8793
virtual jmethodID GetStaticMethodID(jclass, const char*, const char*) = 0;
8894
virtual jobject NewGlobalRef(jobject) = 0;
8995
virtual jobject NewLocalRef(jobject) = 0;
96+
virtual jweak NewWeakGlobalRef(jobject) = 0;
9097
virtual jint RegisterNatives(jclass, const JNINativeMethod*, jint) = 0;
9198
virtual jsize GetArrayLength(jarray) = 0;
9299
virtual void GetIntArrayRegion(jintArray, jsize, jsize, jint*) = 0;
@@ -109,12 +116,30 @@ class MockableJNIEnv : public JNIEnv {
109116
return static_cast<MockableJNIEnv*>(env)->CallObjectMethodV(obj, methodID,
110117
args);
111118
}
119+
static void WrapCallVoidMethod(JNIEnv* env,
120+
jobject obj,
121+
jmethodID methodID,
122+
...) {
123+
va_list args;
124+
va_start(args, methodID);
125+
WrapCallVoidMethodV(env, obj, methodID, args);
126+
va_end(args);
127+
}
128+
static void WrapCallVoidMethodV(JNIEnv* env,
129+
jobject obj,
130+
jmethodID methodID,
131+
va_list args) {
132+
static_cast<MockableJNIEnv*>(env)->CallVoidMethodV(obj, methodID, args);
133+
}
112134
static void WrapDeleteGlobalRef(JNIEnv* env, jobject globalRef) {
113135
static_cast<MockableJNIEnv*>(env)->DeleteGlobalRef(globalRef);
114136
}
115137
static void WrapDeleteLocalRef(JNIEnv* env, jobject localRef) {
116138
static_cast<MockableJNIEnv*>(env)->DeleteLocalRef(localRef);
117139
}
140+
static void WrapDeleteWeakGlobalRef(JNIEnv* env, jweak weakRef) {
141+
static_cast<MockableJNIEnv*>(env)->DeleteWeakGlobalRef(weakRef);
142+
}
118143
static jboolean WrapExceptionCheck(JNIEnv* env) {
119144
return static_cast<MockableJNIEnv*>(env)->ExceptionCheck();
120145
}
@@ -165,6 +190,9 @@ class MockableJNIEnv : public JNIEnv {
165190
static jobject WrapNewLocalRef(JNIEnv* env, jobject ref) {
166191
return static_cast<MockableJNIEnv*>(env)->NewLocalRef(ref);
167192
}
193+
static jweak WrapNewWeakGlobalRef(JNIEnv* env, jobject ref) {
194+
return static_cast<MockableJNIEnv*>(env)->NewWeakGlobalRef(ref);
195+
}
168196
static jint WrapRegisterNatives(JNIEnv* env,
169197
jclass clazz,
170198
const JNINativeMethod* methods,
@@ -193,8 +221,10 @@ class MockJNIEnv : public MockableJNIEnv {
193221
CallObjectMethodV,
194222
(jobject, jmethodID, va_list),
195223
(override));
224+
MOCK_METHOD(void, CallVoidMethodV, (jobject, jmethodID, va_list), (override));
196225
MOCK_METHOD(void, DeleteGlobalRef, (jobject), (override));
197226
MOCK_METHOD(void, DeleteLocalRef, (jobject), (override));
227+
MOCK_METHOD(void, DeleteWeakGlobalRef, (jweak), (override));
198228
MOCK_METHOD(jboolean, ExceptionCheck, (), (override));
199229
MOCK_METHOD(void, ExceptionClear, (), (override));
200230
MOCK_METHOD(void, ExceptionDescribe, (), (override));
@@ -219,6 +249,7 @@ class MockJNIEnv : public MockableJNIEnv {
219249
(override));
220250
MOCK_METHOD(jobject, NewGlobalRef, (jobject), (override));
221251
MOCK_METHOD(jobject, NewLocalRef, (jobject), (override));
252+
MOCK_METHOD(jweak, NewWeakGlobalRef, (jobject), (override));
222253
MOCK_METHOD(jint,
223254
RegisterNatives,
224255
(jclass, const JNINativeMethod*, jint),

0 commit comments

Comments
 (0)