From 171221580e8f73ddc814db50988aa69a051060a3 Mon Sep 17 00:00:00 2001 From: Jason Simmons Date: Fri, 22 Mar 2024 07:33:03 -0700 Subject: [PATCH] Post Dart message handling tasks directly to the platform task runner for isolates running on the platform thread (flutter/engine#51573) Some embedders use a custom platform task runner that does not support fml::MessageLoopTaskQueues and may not have an fml::MessageLoop. To support those embedders, DartIsolate::SetMessageHandlingTaskRunner will not use fml::MessageLoopTaskQueues for platform isolates. See https://github.com/flutter/engine/pull/48551#issuecomment-1962190896 --- engine/src/flutter/runtime/dart_isolate.cc | 52 +++++++++------ engine/src/flutter/runtime/dart_isolate.h | 3 +- .../platform/embedder/fixtures/main.dart | 9 +++ .../embedder/tests/embedder_unittests.cc | 66 +++++++++++++++++++ 4 files changed, 110 insertions(+), 20 deletions(-) diff --git a/engine/src/flutter/runtime/dart_isolate.cc b/engine/src/flutter/runtime/dart_isolate.cc index ab63db5e9c..9d063bedbe 100644 --- a/engine/src/flutter/runtime/dart_isolate.cc +++ b/engine/src/flutter/runtime/dart_isolate.cc @@ -504,9 +504,12 @@ bool DartIsolate::Initialize(Dart_Isolate dart_isolate) { Dart_SetCurrentUserTag(Dart_NewUserTag("AppStartUp")); } - SetMessageHandlingTaskRunner(is_platform_isolate_ - ? GetTaskRunners().GetPlatformTaskRunner() - : GetTaskRunners().GetUITaskRunner()); + if (is_platform_isolate_) { + SetMessageHandlingTaskRunner(GetTaskRunners().GetPlatformTaskRunner(), + true); + } else { + SetMessageHandlingTaskRunner(GetTaskRunners().GetUITaskRunner(), false); + } if (tonic::CheckAndHandleError( Dart_SetLibraryTagHandler(tonic::DartState::HandleLibraryTag))) { @@ -562,30 +565,41 @@ void DartIsolate::LoadLoadingUnitError(intptr_t loading_unit_id, } void DartIsolate::SetMessageHandlingTaskRunner( - const fml::RefPtr& runner) { + const fml::RefPtr& runner, + bool post_directly_to_runner) { if (!runner) { return; } message_handling_task_runner_ = runner; - message_handler().Initialize([runner](std::function task) { + tonic::DartMessageHandler::TaskDispatcher dispatcher; + #ifdef OS_FUCHSIA - runner->PostTask([task = std::move(task)]() { - TRACE_EVENT0("flutter", "DartIsolate::HandleMessage"); - task(); - }); -#else - auto task_queues = fml::MessageLoopTaskQueues::GetInstance(); - task_queues->RegisterTask( - runner->GetTaskQueueId(), - [task = std::move(task)]() { - TRACE_EVENT0("flutter", "DartIsolate::HandleMessage"); - task(); - }, - fml::TimePoint::Now(), fml::TaskSourceGrade::kDartEventLoop); + post_directly_to_runner = true; #endif - }); + + if (post_directly_to_runner) { + dispatcher = [runner](std::function task) { + runner->PostTask([task = std::move(task)]() { + TRACE_EVENT0("flutter", "DartIsolate::HandleMessage"); + task(); + }); + }; + } else { + dispatcher = [runner](std::function task) { + auto task_queues = fml::MessageLoopTaskQueues::GetInstance(); + task_queues->RegisterTask( + runner->GetTaskQueueId(), + [task = std::move(task)]() { + TRACE_EVENT0("flutter", "DartIsolate::HandleMessage"); + task(); + }, + fml::TimePoint::Now(), fml::TaskSourceGrade::kDartEventLoop); + }; + } + + message_handler().Initialize(dispatcher); } // Updating thread names here does not change the underlying OS thread names. diff --git a/engine/src/flutter/runtime/dart_isolate.h b/engine/src/flutter/runtime/dart_isolate.h index e5f1ca576a..e8facb468e 100644 --- a/engine/src/flutter/runtime/dart_isolate.h +++ b/engine/src/flutter/runtime/dart_isolate.h @@ -470,7 +470,8 @@ class DartIsolate : public UIDartState { /// [[nodiscard]] bool Initialize(Dart_Isolate dart_isolate); - void SetMessageHandlingTaskRunner(const fml::RefPtr& runner); + void SetMessageHandlingTaskRunner(const fml::RefPtr& runner, + bool post_directly_to_runner); bool LoadKernel(const std::shared_ptr& mapping, bool last_piece); diff --git a/engine/src/flutter/shell/platform/embedder/fixtures/main.dart b/engine/src/flutter/shell/platform/embedder/fixtures/main.dart index b5ddfac585..d5758ffd92 100644 --- a/engine/src/flutter/shell/platform/embedder/fixtures/main.dart +++ b/engine/src/flutter/shell/platform/embedder/fixtures/main.dart @@ -60,6 +60,12 @@ void invokePlatformTaskRunner() { PlatformDispatcher.instance.sendPlatformMessage('OhHi', null, null); } +@pragma('vm:entry-point') +void invokePlatformThreadIsolate() { + signalNativeTest(); + runOnPlatformThread(ffiSignalNativeTest); +} + Float64List kTestTransform = () { final Float64List values = Float64List(16); values[0] = 1.0; // scaleX @@ -87,6 +93,9 @@ external void notifyAccessibilityFeatures(bool reduceMotion); @pragma('vm:external-name', 'NotifySemanticsAction') external void notifySemanticsAction(int nodeId, int action, List data); +@ffi.Native(symbol: 'FFISignalNativeTest') +external void ffiSignalNativeTest(); + /// Returns a future that completes when /// `PlatformDispatcher.instance.onSemanticsEnabledChanged` fires. Future get semanticsChanged { diff --git a/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests.cc b/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests.cc index 9c2b5779b5..b573b1db6c 100644 --- a/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests.cc +++ b/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests.cc @@ -3009,6 +3009,72 @@ TEST_F(EmbedderTest, RegisterChannelListener) { ASSERT_TRUE(listening); } +TEST_F(EmbedderTest, PlatformThreadIsolatesWithCustomPlatformTaskRunner) { + auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); + static fml::AutoResetWaitableEvent latch; + + static std::thread::id ffi_call_thread_id; + static void (*ffi_signal_native_test)() = []() -> void { + ffi_call_thread_id = std::this_thread::get_id(); + latch.Signal(); + }; + + Dart_FfiNativeResolver ffi_resolver = [](const char* name, + uintptr_t args_n) -> void* { + if (std::string_view(name) == "FFISignalNativeTest") { + return reinterpret_cast(ffi_signal_native_test); + } + return nullptr; + }; + + // The test's Dart code will call this native function which overrides the + // FFI resolver. After that, the Dart code will invoke the FFI function + // using runOnPlatformThread. + context.AddNativeCallback( + "SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { + Dart_SetFfiNativeResolver(Dart_RootLibrary(), ffi_resolver); + })); + + auto platform_task_runner = CreateNewThread("test_platform_thread"); + + UniqueEngine engine; + + EmbedderTestTaskRunner test_task_runner( + platform_task_runner, [&](FlutterTask task) { + if (!engine.is_valid()) { + return; + } + FlutterEngineRunTask(engine.get(), &task); + }); + + std::thread::id platform_thread_id; + platform_task_runner->PostTask([&]() { + platform_thread_id = std::this_thread::get_id(); + + EmbedderConfigBuilder builder(context); + const auto task_runner_description = + test_task_runner.GetFlutterTaskRunnerDescription(); + builder.SetSoftwareRendererConfig(); + builder.SetPlatformTaskRunner(&task_runner_description); + builder.SetDartEntrypoint("invokePlatformThreadIsolate"); + engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + }); + + latch.Wait(); + + fml::AutoResetWaitableEvent kill_latch; + platform_task_runner->PostTask(fml::MakeCopyable([&]() mutable { + engine.reset(); + + platform_task_runner->PostTask([&kill_latch] { kill_latch.Signal(); }); + })); + kill_latch.Wait(); + + // Check that the FFI call was executed on the platform thread. + ASSERT_EQ(platform_thread_id, ffi_call_thread_id); +} + } // namespace testing } // namespace flutter