Skip to content

Commit e7224df

Browse files
[android]: removes RegisterExternalTexture race condition (flutter#192951)
fixes flutter#192776 ## 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]. - [x] 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 --------- Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
1 parent aae258a commit e7224df

6 files changed

Lines changed: 200 additions & 11 deletions

File tree

‎engine/src/flutter/fml/logging.h‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,10 @@ constexpr bool ShouldCreateLogMessageConstexpr(LogSeverity severity,
117117
#define FML_VLOG(verbose_level) \
118118
FML_LAZY_STREAM(FML_VLOG_STREAM(verbose_level), FML_VLOG_IS_ON(verbose_level))
119119

120+
#ifndef NDEBUG
121+
#define FML_DCHECK_IS_ON 1
122+
#endif
123+
120124
#ifndef NDEBUG
121125
#define FML_DLOG(severity) FML_LOG(severity)
122126
#define FML_DCHECK(condition) FML_CHECK(condition)

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ executable("flutter_shell_native_unittests") {
4343
visibility = [ "*" ]
4444
testonly = true
4545
sources = [
46+
"android_context_dynamic_impeller_unittests.cc",
4647
"android_context_gl_impeller_unittests.cc",
4748
"android_image_generator_unittests.cc",
4849
"android_shell_holder_unittests.cc",

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,9 @@ AndroidContextDynamicImpeller::AndroidContextDynamicImpeller(
149149
AndroidContextDynamicImpeller::~AndroidContextDynamicImpeller() = default;
150150

151151
AndroidRenderingAPI AndroidContextDynamicImpeller::RenderingApi() const {
152+
// Block until the raster thread has chosen a backend. Without this, callers
153+
// on the platform thread can observe kImpellerAutoselect during startup.
154+
WaitForSetup();
152155
if (vk_context_) {
153156
return AndroidRenderingAPI::kImpellerVulkan;
154157
}
@@ -183,13 +186,42 @@ void AndroidContextDynamicImpeller::SetupImpellerContext() {
183186
if (vk_context_ || gl_context_) {
184187
return;
185188
}
189+
// Recorded before the probe below, which is the slow part and therefore the
190+
// window in which a re-entrant |WaitForSetup| would deadlock. Wrapped in a
191+
// DCHECK so this bookkeeping compiles out of release builds along with the
192+
// assert that consumes it. The store always evaluates to true.
193+
#ifdef FML_DCHECK_IS_ON
194+
setup_thread_id_.store(std::this_thread::get_id(), std::memory_order_relaxed);
195+
#endif
186196
vk_context_ = GetActualRenderingAPIForImpeller(android_get_device_api_level(),
187197
settings_);
188198
if (!vk_context_) {
189199
gl_context_ = std::make_shared<AndroidContextGLImpeller>(
190200
std::make_unique<impeller::egl::Display>(),
191201
settings_.enable_gpu_tracing, io_task_runner_);
192202
}
203+
// The id is only meaningful while setup is in flight. Cleared before the
204+
// signal so a waiter can never observe a completed setup alongside a stale
205+
// id and trip the assert in |WaitForSetup| spuriously. After this point the
206+
// raster thread may freely call |RenderingApi|, which no longer blocks.
207+
#ifdef FML_DCHECK_IS_ON
208+
setup_thread_id_.store(std::thread::id(), std::memory_order_relaxed);
209+
#endif
210+
// Publish the backend selection to any thread blocked in |WaitForSetup|.
211+
setup_complete_.Signal();
212+
}
213+
214+
void AndroidContextDynamicImpeller::WaitForSetup() const {
215+
// The thread performing setup cannot wait for setup to finish. Compiled out
216+
// of release builds.
217+
#ifdef FML_DCHECK_IS_ON
218+
FML_DCHECK(setup_thread_id_.load(std::memory_order_relaxed) !=
219+
std::this_thread::get_id())
220+
<< "Deadlock: the thread running SetupImpellerContext() called "
221+
"RenderingApi(), which waits on that same setup. Read GetGLContext() "
222+
"or GetVKContext() directly from the raster thread instead.";
223+
#endif
224+
setup_complete_.Wait();
193225
}
194226

195227
} // namespace flutter

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

Lines changed: 55 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,12 @@
55
#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_CONTEXT_DYNAMIC_IMPELLER_H_
66
#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_CONTEXT_DYNAMIC_IMPELLER_H_
77

8-
#include <mutex>
8+
#include <atomic>
9+
#include <thread>
910

1011
#include "flutter/fml/macros.h"
1112
#include "flutter/fml/native_library.h"
13+
#include "flutter/fml/synchronization/waitable_event.h"
1214
#include "flutter/shell/platform/android/android_context_gl_impeller.h"
1315
#include "flutter/shell/platform/android/android_context_vk_impeller.h"
1416
#include "flutter/shell/platform/android/context/android_context.h"
@@ -17,9 +19,6 @@ namespace flutter {
1719

1820
/// @brief An Impeller Android context that dynamically creates either an
1921
/// [AndroidContextGLImpeller] or an [AndroidContextVKImpeller].
20-
///
21-
/// The construction of these objects is deferred until [GetImpellerContext] is
22-
/// invoked. Up to this point, the reported backend will be kImpellerAutoselect.
2322
class AndroidContextDynamicImpeller : public AndroidContext {
2423
public:
2524
explicit AndroidContextDynamicImpeller(
@@ -34,25 +33,77 @@ class AndroidContextDynamicImpeller : public AndroidContext {
3433
// |AndroidContext|
3534
bool IsDynamicSelection() const override { return true; }
3635

36+
/// @brief Returns the selected rendering backend, blocking if the selection
37+
/// is still in flight.
38+
///
39+
/// The backend is chosen lazily by [SetupImpellerContext] on the
40+
/// raster thread, which can take 100+ ms while probing for Vulkan.
41+
/// Callers on other threads would otherwise observe
42+
/// kImpellerAutoselect during early startup, so this blocks until the
43+
/// choice is made. Waiting also publishes the raster thread's writes,
44+
/// making it safe to then read [GetImpellerContext], [GetGLContext]
45+
/// and [GetVKContext] without further synchronization.
46+
///
47+
/// Once setup has completed this is just an uncontended mutex
48+
/// acquisition, so it is not worth avoiding on non-hot paths.
49+
///
50+
/// @attention Must never be called from the thread that executes
51+
/// [SetupImpellerContext] before that setup has completed, as
52+
/// the signal being waited on could then never be delivered.
53+
/// In practice that is the raster thread, but note it is not
54+
/// always a distinct thread: while a |fml::RasterThreadMerger|
55+
/// lease is active, raster tasks run on the platform thread.
56+
///
3757
// |AndroidContext|
3858
AndroidRenderingAPI RenderingApi() const override;
3959

4060
/// @brief Retrieve the GL Context if it was created, or nullptr.
61+
///
62+
/// Does not block. Only meaningful after [RenderingApi] has returned.
4163
std::shared_ptr<AndroidContextGLImpeller> GetGLContext() const;
4264

4365
/// @brief Retrieve the VK context if it was created, or nullptr.
66+
///
67+
/// Does not block. Only meaningful after [RenderingApi] has returned.
4468
std::shared_ptr<AndroidContextVKImpeller> GetVKContext() const;
4569

4670
// |AndroidContext|
4771
void SetupImpellerContext() override;
4872

73+
/// @brief Retrieve the Impeller context, or nullptr if setup has not run.
74+
///
75+
/// Does not block. Callers on threads other than the raster thread
76+
/// should read [RenderingApi] first, which both waits for setup and
77+
/// publishes the writes read here.
78+
///
79+
// |AndroidContext|
4980
std::shared_ptr<impeller::Context> GetImpellerContext() const override;
5081

5182
private:
83+
/// @brief Blocks until [SetupImpellerContext] has completed on the raster
84+
/// thread. Returns immediately once it has.
85+
///
86+
/// Debug builds assert that the caller is not the thread running
87+
/// setup, which would deadlock. Note the assert can only fire once
88+
/// setup has begun; a thread that waits before setup is ever
89+
/// scheduled still hangs undiagnosed.
90+
void WaitForSetup() const;
91+
5292
const AndroidContext::ContextSettings settings_;
93+
// These are written once on the raster thread by |SetupImpellerContext| and
94+
// only read by other threads after |setup_complete_| has been signalled.
5395
std::shared_ptr<AndroidContextGLImpeller> gl_context_;
5496
std::shared_ptr<AndroidContextVKImpeller> vk_context_;
5597
std::shared_ptr<fml::BasicTaskRunner> io_task_runner_;
98+
// Signalled by |SetupImpellerContext| once a backend has been chosen.
99+
// Mutable so the const accessors above can wait on it.
100+
mutable fml::ManualResetWaitableEvent setup_complete_;
101+
#ifdef FML_DCHECK_IS_ON
102+
// The thread running |SetupImpellerContext|, recorded so |WaitForSetup| can
103+
// assert it is not being called from that same thread. Atomic because it is
104+
// read by waiters concurrently with the setup thread writing it.
105+
std::atomic<std::thread::id> setup_thread_id_;
106+
#endif
56107

57108
FML_DISALLOW_COPY_AND_ASSIGN(AndroidContextDynamicImpeller);
58109
};
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
// Copyright 2013 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
#include "flutter/shell/platform/android/android_context_dynamic_impeller.h"
6+
7+
#include <atomic>
8+
#include <chrono>
9+
#include <thread>
10+
11+
#include "flutter/shell/platform/android/android_rendering_selector.h"
12+
#include "gtest/gtest.h"
13+
14+
namespace flutter {
15+
namespace testing {
16+
17+
TEST(AndroidContextDynamicImpellerTest, ContextsAreNullBeforeSetup) {
18+
auto context = std::make_shared<AndroidContextDynamicImpeller>(
19+
AndroidContext::ContextSettings{}, /*io_task_runner=*/nullptr);
20+
21+
EXPECT_TRUE(context->IsDynamicSelection());
22+
// These accessors never block, so they are safe to read before setup has
23+
// run. They simply report that no backend exists yet.
24+
EXPECT_EQ(context->GetImpellerContext(), nullptr);
25+
EXPECT_EQ(context->GetGLContext(), nullptr);
26+
EXPECT_EQ(context->GetVKContext(), nullptr);
27+
}
28+
29+
TEST(AndroidContextDynamicImpellerTest, RenderingApiBlocksUntilBackendChosen) {
30+
auto context = std::make_shared<AndroidContextDynamicImpeller>(
31+
AndroidContext::ContextSettings{}, /*io_task_runner=*/nullptr);
32+
33+
fml::AutoResetWaitableEvent waiter_started;
34+
std::atomic<bool> waiter_returned = false;
35+
36+
std::thread waiter_thread([context, &waiter_started, &waiter_returned]() {
37+
waiter_started.Signal();
38+
context->RenderingApi();
39+
waiter_returned.store(true);
40+
});
41+
42+
waiter_started.Wait();
43+
// Give the waiter thread a moment to enter RenderingApi() and block.
44+
std::this_thread::sleep_for(std::chrono::milliseconds(10));
45+
46+
// Verify that the waiter thread is indeed blocked and hasn't returned yet.
47+
EXPECT_FALSE(waiter_returned);
48+
49+
// Now run setup, which should unblock the waiter.
50+
context->SetupImpellerContext();
51+
52+
waiter_thread.join();
53+
EXPECT_TRUE(waiter_returned.load());
54+
EXPECT_NE(context->RenderingApi(), AndroidRenderingAPI::kImpellerAutoselect);
55+
}
56+
57+
TEST(AndroidContextDynamicImpellerTest, RenderingApiDoesNotBlockAfterSetup) {
58+
auto context = std::make_shared<AndroidContextDynamicImpeller>(
59+
AndroidContext::ContextSettings{}, /*io_task_runner=*/nullptr);
60+
61+
context->SetupImpellerContext();
62+
63+
// The latch stays signalled, so repeated reads do not block and stay stable.
64+
const AndroidRenderingAPI first = context->RenderingApi();
65+
const AndroidRenderingAPI second = context->RenderingApi();
66+
EXPECT_NE(first, AndroidRenderingAPI::kImpellerAutoselect);
67+
EXPECT_EQ(first, second);
68+
EXPECT_NE(context->GetImpellerContext(), nullptr);
69+
}
70+
71+
TEST(AndroidContextDynamicImpellerTest, SetupIsIdempotent) {
72+
auto context = std::make_shared<AndroidContextDynamicImpeller>(
73+
AndroidContext::ContextSettings{}, /*io_task_runner=*/nullptr);
74+
75+
context->SetupImpellerContext();
76+
const AndroidRenderingAPI first = context->RenderingApi();
77+
78+
// A second call is a no-op and must not reset the backend selection.
79+
context->SetupImpellerContext();
80+
EXPECT_EQ(context->RenderingApi(), first);
81+
}
82+
83+
TEST(AndroidContextDynamicImpellerTest, SetupThreadCanReadBackendAfterSetup) {
84+
auto context = std::make_shared<AndroidContextDynamicImpeller>(
85+
AndroidContext::ContextSettings{}, /*io_task_runner=*/nullptr);
86+
87+
// Mirrors the raster thread running setup and then reading the backend later
88+
// in a frame, as AndroidExternalViewEmbedderWrapper::EnsureInitialized does.
89+
// The debug assert guarding against a deadlocking self-wait must not fire
90+
// here, because the wait completes immediately once setup is done.
91+
std::thread raster_thread([context]() {
92+
context->SetupImpellerContext();
93+
EXPECT_NE(context->RenderingApi(),
94+
AndroidRenderingAPI::kImpellerAutoselect);
95+
EXPECT_NE(context->GetImpellerContext(), nullptr);
96+
});
97+
raster_thread.join();
98+
}
99+
100+
} // namespace testing
101+
} // namespace flutter

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

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,13 @@ std::unique_ptr<Surface> AndroidSurfaceDynamicImpeller::CreateGPUSurface(
4646
}
4747

4848
void AndroidSurfaceDynamicImpeller::SetupImpellerSurface() {
49-
AndroidRenderingAPI api = android_context_->RenderingApi();
50-
if (api == AndroidRenderingAPI::kImpellerVulkan) {
51-
vulkan_surface_ = std::make_unique<AndroidSurfaceVKImpeller>(
52-
android_context_->GetVKContext());
53-
} else if (api == AndroidRenderingAPI::kImpellerOpenGLES) {
54-
gl_surface_ = std::make_unique<AndroidSurfaceGLImpeller>(
55-
android_context_->GetGLContext());
49+
// This runs on the raster thread as part of |SetupImpellerContext|, so the
50+
// contexts are read directly instead of going through |RenderingApi|, which
51+
// blocks until that very setup completes.
52+
if (auto vk_context = android_context_->GetVKContext()) {
53+
vulkan_surface_ = std::make_unique<AndroidSurfaceVKImpeller>(vk_context);
54+
} else if (auto gl_context = android_context_->GetGLContext()) {
55+
gl_surface_ = std::make_unique<AndroidSurfaceGLImpeller>(gl_context);
5656
} else {
5757
FML_UNREACHABLE();
5858
}

0 commit comments

Comments
 (0)