diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index 4aaa7a87bc..16a564aa2c 100755 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -962,6 +962,8 @@ FILE: ../../../flutter/runtime/dart_isolate_group_data.cc FILE: ../../../flutter/runtime/dart_isolate_group_data.h FILE: ../../../flutter/runtime/dart_isolate_unittests.cc FILE: ../../../flutter/runtime/dart_lifecycle_unittests.cc +FILE: ../../../flutter/runtime/dart_plugin_registrant.cc +FILE: ../../../flutter/runtime/dart_plugin_registrant.h FILE: ../../../flutter/runtime/dart_plugin_registrant_unittests.cc FILE: ../../../flutter/runtime/dart_service_isolate.cc FILE: ../../../flutter/runtime/dart_service_isolate.h diff --git a/engine/src/flutter/lib/ui/BUILD.gn b/engine/src/flutter/lib/ui/BUILD.gn index 22fb82dc0a..0b7219f9ac 100644 --- a/engine/src/flutter/lib/ui/BUILD.gn +++ b/engine/src/flutter/lib/ui/BUILD.gn @@ -140,6 +140,7 @@ source_set("ui") { "//flutter/common", "//flutter/display_list", "//flutter/fml", + "//flutter/runtime:dart_plugin_registrant", "//flutter/runtime:test_font", "//flutter/third_party/tonic", "//third_party/dart/runtime/bin:dart_io_api", diff --git a/engine/src/flutter/lib/ui/dart_runtime_hooks.cc b/engine/src/flutter/lib/ui/dart_runtime_hooks.cc index dd43b37d85..5cc82cb583 100644 --- a/engine/src/flutter/lib/ui/dart_runtime_hooks.cc +++ b/engine/src/flutter/lib/ui/dart_runtime_hooks.cc @@ -15,6 +15,7 @@ #include "flutter/fml/logging.h" #include "flutter/lib/ui/plugins/callback_cache.h" #include "flutter/lib/ui/ui_dart_state.h" +#include "flutter/runtime/dart_plugin_registrant.h" #include "third_party/dart/runtime/include/bin/dart_io_api.h" #include "third_party/dart/runtime/include/dart_api.h" #include "third_party/dart/runtime/include/dart_tools_api.h" @@ -37,11 +38,12 @@ namespace flutter { #define DECLARE_FUNCTION(name, count) \ extern void name(Dart_NativeArguments args); -#define BUILTIN_NATIVE_LIST(V) \ - V(Logger_PrintString, 1) \ - V(Logger_PrintDebugString, 1) \ - V(ScheduleMicrotask, 1) \ - V(GetCallbackHandle, 1) \ +#define BUILTIN_NATIVE_LIST(V) \ + V(Logger_PrintString, 1) \ + V(Logger_PrintDebugString, 1) \ + V(DartPluginRegistrant_EnsureInitialized, 0) \ + V(ScheduleMicrotask, 1) \ + V(GetCallbackHandle, 1) \ V(GetCallbackFromHandle, 1) BUILTIN_NATIVE_LIST(DECLARE_FUNCTION); @@ -304,4 +306,8 @@ void GetCallbackFromHandle(Dart_NativeArguments args) { Dart_SetReturnValue(args, DartCallbackCache::GetCallback(handle)); } +void DartPluginRegistrant_EnsureInitialized(Dart_NativeArguments args) { + FindAndInvokeDartPluginRegistrant(); +} + } // namespace flutter diff --git a/engine/src/flutter/lib/ui/natives.dart b/engine/src/flutter/lib/ui/natives.dart index 312593daea..c23456262d 100644 --- a/engine/src/flutter/lib/ui/natives.dart +++ b/engine/src/flutter/lib/ui/natives.dart @@ -4,10 +4,27 @@ // TODO(dnfield): remove unused_element ignores when https://github.com/dart-lang/sdk/issues/35164 is resolved. - // @dart = 2.12 part of dart.ui; +// ignore_for_file: avoid_classes_with_only_static_members + +/// Helper functions for Dart Plugin Registrants. +class DartPluginRegistrant { + static bool _wasInitialized = false; + + /// Makes sure the that the Dart Plugin Registrant has been called for this + /// isolate. This can safely be executed multiple times on the same isolate, + /// but should not be called on the Root isolate. + static void ensureInitialized() { + if (!_wasInitialized) { + _wasInitialized = true; + _ensureInitialized(); + } + } + static void _ensureInitialized() native 'DartPluginRegistrant_EnsureInitialized'; +} + // Corelib 'print' implementation. void _print(Object? arg) { _Logger._printString(arg.toString()); diff --git a/engine/src/flutter/lib/web_ui/lib/natives.dart b/engine/src/flutter/lib/web_ui/lib/natives.dart index 8c94e6a69e..731e36d07f 100644 --- a/engine/src/flutter/lib/web_ui/lib/natives.dart +++ b/engine/src/flutter/lib/web_ui/lib/natives.dart @@ -4,6 +4,19 @@ part of ui; +// ignore_for_file: avoid_classes_with_only_static_members + +/// Helper functions for Dart Plugin Registrants. +class DartPluginRegistrant { + /// Makes sure the that the Dart Plugin Registrant has been called for this + /// isolate. This can safely be executed multiple times on the same isolate, + /// but should not be called on the Root isolate. + static void ensureInitialized() { + throw UnimplementedError('`ensureInitialized` is not implemented on the web.'); + } +} + + List saveCompilationTrace() { if (engine.assertionsEnabled) { throw UnimplementedError('saveCompilationTrace is not implemented on the web.'); diff --git a/engine/src/flutter/runtime/BUILD.gn b/engine/src/flutter/runtime/BUILD.gn index 9e082cf308..a6f4ceb196 100644 --- a/engine/src/flutter/runtime/BUILD.gn +++ b/engine/src/flutter/runtime/BUILD.gn @@ -35,6 +35,18 @@ group("libdart") { } } +source_set("dart_plugin_registrant") { + sources = [ + "dart_plugin_registrant.cc", + "dart_plugin_registrant.h", + ] + deps = [ + "//flutter/fml", + "//flutter/third_party/tonic", + "//third_party/dart/runtime:dart_api", + ] +} + source_set("runtime") { sources = [ "dart_isolate.cc", @@ -83,6 +95,7 @@ source_set("runtime") { public_configs = [ "//flutter:config" ] deps = [ + ":dart_plugin_registrant", ":test_font", "//flutter/assets", "//flutter/common", diff --git a/engine/src/flutter/runtime/dart_isolate.cc b/engine/src/flutter/runtime/dart_isolate.cc index 244f5969de..bb62265549 100644 --- a/engine/src/flutter/runtime/dart_isolate.cc +++ b/engine/src/flutter/runtime/dart_isolate.cc @@ -14,6 +14,7 @@ #include "flutter/lib/ui/dart_runtime_hooks.h" #include "flutter/lib/ui/dart_ui.h" #include "flutter/runtime/dart_isolate_group_data.h" +#include "flutter/runtime/dart_plugin_registrant.h" #include "flutter/runtime/dart_service_isolate.h" #include "flutter/runtime/dart_vm.h" #include "flutter/runtime/dart_vm_lifecycle.h" @@ -687,57 +688,6 @@ bool DartIsolate::MarkIsolateRunnable() { return true; } -static void InvokeDartPluginRegistrantIfAvailable(Dart_Handle library_handle) { - TRACE_EVENT0("flutter", "InvokeDartPluginRegistrantIfAvailable"); - - // The Dart plugin registrant is a static method with signature `void - // register()` within the class `_PluginRegistrant` generated by the Flutter - // tool. - // - // This method binds a plugin implementation to their platform - // interface based on the configuration of the app's pubpec.yaml, and the - // plugin's pubspec.yaml. - // - // Since this method may or may not be defined, check if the class is defined - // in the default library before calling the method. - Dart_Handle plugin_registrant = - ::Dart_GetClass(library_handle, tonic::ToDart("_PluginRegistrant")); - - if (Dart_IsError(plugin_registrant)) { - return; - } - tonic::LogIfError(tonic::DartInvokeField(plugin_registrant, "register", {})); -} - -namespace { -bool EndsWith(const std::string& str, const std::string& ending) { - if (str.size() >= ending.size()) { - return (0 == - str.compare(str.size() - ending.size(), ending.size(), ending)); - } else { - return false; - } -} - -Dart_Handle FindDartPluginRegistrantLibrary() { - // TODO(99308): Instead of finding this, it could be passed down from the - // tool. - Dart_Handle libraries = Dart_GetLoadedLibraries(); - intptr_t length = 0; - Dart_ListLength(libraries, &length); - for (intptr_t i = 0; i < length; ++i) { - Dart_Handle library = Dart_ListGetAt(libraries, i); - std::string library_name = - tonic::DartConverter::FromDart(Dart_ToString(library)); - if (EndsWith(library_name, - "dart_tool/flutter_build/dart_plugin_registrant.dart'")) { - return library; - } - } - return Dart_Null(); -} -} // namespace - bool DartIsolate::RunFromLibrary(std::optional library_name, std::optional entrypoint, const std::vector& args) { @@ -756,10 +706,7 @@ bool DartIsolate::RunFromLibrary(std::optional library_name, ? tonic::ToDart(entrypoint.value().c_str()) : tonic::ToDart("main"); - auto dart_plugin_registrant_library = FindDartPluginRegistrantLibrary(); - if (!Dart_IsNull(dart_plugin_registrant_library)) { - InvokeDartPluginRegistrantIfAvailable(dart_plugin_registrant_library); - } else { + if (!FindAndInvokeDartPluginRegistrant()) { InvokeDartPluginRegistrantIfAvailable(library_handle); } diff --git a/engine/src/flutter/runtime/dart_plugin_registrant.cc b/engine/src/flutter/runtime/dart_plugin_registrant.cc new file mode 100644 index 0000000000..08916ed477 --- /dev/null +++ b/engine/src/flutter/runtime/dart_plugin_registrant.cc @@ -0,0 +1,76 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/runtime/dart_plugin_registrant.h" + +#include + +#include "flutter/fml/trace_event.h" +#include "third_party/tonic/converter/dart_converter.h" +#include "third_party/tonic/logging/dart_invoke.h" + +namespace flutter { + +namespace { +bool EndsWith(const std::string& str, const std::string& ending) { + if (str.size() >= ending.size()) { + return (0 == + str.compare(str.size() - ending.size(), ending.size(), ending)); + } else { + return false; + } +} + +Dart_Handle FindDartPluginRegistrantLibrary() { + // TODO(99308): Instead of finding this, it could be passed down from the + // tool. + Dart_Handle libraries = Dart_GetLoadedLibraries(); + intptr_t length = 0; + Dart_ListLength(libraries, &length); + for (intptr_t i = 0; i < length; ++i) { + Dart_Handle library = Dart_ListGetAt(libraries, i); + std::string library_name = + tonic::DartConverter::FromDart(Dart_ToString(library)); + if (EndsWith(library_name, + "dart_tool/flutter_build/dart_plugin_registrant.dart'")) { + return library; + } + } + return Dart_Null(); +} +} // namespace + +bool InvokeDartPluginRegistrantIfAvailable(Dart_Handle library_handle) { + TRACE_EVENT0("flutter", "InvokeDartPluginRegistrantIfAvailable"); + + // The Dart plugin registrant is a static method with signature `void + // register()` within the class `_PluginRegistrant` generated by the Flutter + // tool. + // + // This method binds a plugin implementation to their platform + // interface based on the configuration of the app's pubpec.yaml, and the + // plugin's pubspec.yaml. + // + // Since this method may or may not be defined, check if the class is defined + // in the default library before calling the method. + Dart_Handle plugin_registrant = + ::Dart_GetClass(library_handle, tonic::ToDart("_PluginRegistrant")); + + if (Dart_IsError(plugin_registrant)) { + return false; + } + tonic::LogIfError(tonic::DartInvokeField(plugin_registrant, "register", {})); + return true; +} + +bool FindAndInvokeDartPluginRegistrant() { + auto dart_plugin_registrant_library = FindDartPluginRegistrantLibrary(); + if (!Dart_IsNull(dart_plugin_registrant_library)) { + return InvokeDartPluginRegistrantIfAvailable( + dart_plugin_registrant_library); + } else { + return false; + } +} +} // namespace flutter diff --git a/engine/src/flutter/runtime/dart_plugin_registrant.h b/engine/src/flutter/runtime/dart_plugin_registrant.h new file mode 100644 index 0000000000..b6a9856d66 --- /dev/null +++ b/engine/src/flutter/runtime/dart_plugin_registrant.h @@ -0,0 +1,22 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_DART_PLUGIN_REGISTRANT_H_ +#define FLUTTER_DART_PLUGIN_REGISTRANT_H_ + +#include "third_party/dart/runtime/include/dart_api.h" + +namespace flutter { + +/// Looks for the Dart Plugin Registrant in `library_handle` and invokes it if +/// it is found. +/// @return `true` when the registrant has been invoked. +bool InvokeDartPluginRegistrantIfAvailable(Dart_Handle library_handle); + +/// @return `true` when the registrant has been invoked. +bool FindAndInvokeDartPluginRegistrant(); + +} // namespace flutter + +#endif // FLUTTER_DART_PLUGIN_REGISTRANT_H_ diff --git a/engine/src/flutter/runtime/dart_plugin_registrant_unittests.cc b/engine/src/flutter/runtime/dart_plugin_registrant_unittests.cc index 2452b1e58e..c7cb6e4e84 100644 --- a/engine/src/flutter/runtime/dart_plugin_registrant_unittests.cc +++ b/engine/src/flutter/runtime/dart_plugin_registrant_unittests.cc @@ -25,7 +25,7 @@ class DartIsolateTest : public FixtureTest { DartIsolateTest() : FixtureTest(kernel_file_name, elf_file_name, "") {} }; -TEST_F(DartIsolateTest, DartPluginRegistrantIsNotPresent) { +TEST_F(DartIsolateTest, DartPluginRegistrantIsPresent) { ASSERT_FALSE(DartVMRef::IsInstanceRunning()); std::vector messages; @@ -72,6 +72,103 @@ TEST_F(DartIsolateTest, DartPluginRegistrantIsNotPresent) { ASSERT_EQ(messages[0], "_PluginRegistrant.register() was called"); } +TEST_F(DartIsolateTest, DartPluginRegistrantFromBackgroundIsolate) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + + std::vector messages; + fml::AutoResetWaitableEvent latch; + + AddNativeCallback( + "PassMessage", + CREATE_NATIVE_ENTRY(([&latch, &messages](Dart_NativeArguments args) { + auto message = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + messages.push_back(message); + latch.Signal(); + }))); + + auto settings = CreateSettingsForFixture(); + auto did_throw_exception = false; + settings.unhandled_exception_callback = [&](const std::string& error, + const std::string& stack_trace) { + did_throw_exception = true; + return true; + }; + + auto vm_ref = DartVMRef::Create(settings); + auto thread = CreateNewThread(); + TaskRunners task_runners(GetCurrentTestName(), // + thread, // + thread, // + thread, // + thread // + ); + + auto kernel_path = + fml::paths::JoinPaths({GetFixturesPath(), kernel_file_name}); + auto isolate = RunDartCodeInIsolate( + vm_ref, settings, task_runners, + "callDartPluginRegistrantFromBackgroundIsolate", {}, kernel_path); + + ASSERT_TRUE(isolate); + ASSERT_EQ(isolate->get()->GetPhase(), DartIsolate::Phase::Running); + + latch.Wait(); + + ASSERT_EQ(messages.size(), 1u); + ASSERT_EQ(messages[0], + "_PluginRegistrant.register() was called on background isolate"); +} + +TEST_F(DartIsolateTest, DartPluginRegistrantNotFromBackgroundIsolate) { + ASSERT_FALSE(DartVMRef::IsInstanceRunning()); + + std::vector messages; + fml::AutoResetWaitableEvent latch; + + AddNativeCallback( + "PassMessage", + CREATE_NATIVE_ENTRY(([&latch, &messages](Dart_NativeArguments args) { + auto message = tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + messages.push_back(message); + latch.Signal(); + }))); + + auto settings = CreateSettingsForFixture(); + auto did_throw_exception = false; + settings.unhandled_exception_callback = [&](const std::string& error, + const std::string& stack_trace) { + did_throw_exception = true; + return true; + }; + + auto vm_ref = DartVMRef::Create(settings); + auto thread = CreateNewThread(); + TaskRunners task_runners(GetCurrentTestName(), // + thread, // + thread, // + thread, // + thread // + ); + + auto kernel_path = + fml::paths::JoinPaths({GetFixturesPath(), kernel_file_name}); + auto isolate = RunDartCodeInIsolate( + vm_ref, settings, task_runners, + "dontCallDartPluginRegistrantFromBackgroundIsolate", {}, kernel_path); + + ASSERT_TRUE(isolate); + ASSERT_EQ(isolate->get()->GetPhase(), DartIsolate::Phase::Running); + + latch.Wait(); + + ASSERT_EQ(messages.size(), 1u); + ASSERT_EQ( + messages[0], + "_PluginRegistrant.register() was not called on background isolate"); +} + } // namespace testing } // namespace flutter diff --git a/engine/src/flutter/runtime/fixtures/dart_tool/flutter_build/dart_plugin_registrant.dart b/engine/src/flutter/runtime/fixtures/dart_tool/flutter_build/dart_plugin_registrant.dart index 2a6220f1e5..a8550a04e1 100644 --- a/engine/src/flutter/runtime/fixtures/dart_tool/flutter_build/dart_plugin_registrant.dart +++ b/engine/src/flutter/runtime/fixtures/dart_tool/flutter_build/dart_plugin_registrant.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:isolate'; +import 'dart:ui'; + void passMessage(String message) native 'PassMessage'; bool didCallRegistrantBeforeEntrypoint = false; @@ -31,3 +34,38 @@ void mainForPluginRegistrantTest() { } void main() {} + +void dartPluginRegistrantIsolate(SendPort sendPort) { + DartPluginRegistrant.ensureInitialized(); + sendPort.send(didCallRegistrantBeforeEntrypoint); +} + +@pragma('vm:entry-point') +void callDartPluginRegistrantFromBackgroundIsolate() async { + ReceivePort receivePort = ReceivePort(); + Isolate isolate = await Isolate.spawn(dartPluginRegistrantIsolate, receivePort.sendPort); + bool didCallEntrypoint = await receivePort.first; + if (didCallEntrypoint) { + passMessage('_PluginRegistrant.register() was called on background isolate'); + } else { + passMessage('_PluginRegistrant.register() was not called on background isolate'); + } + isolate.kill(); +} + +void noDartPluginRegistrantIsolate(SendPort sendPort) { + sendPort.send(didCallRegistrantBeforeEntrypoint); +} + +@pragma('vm:entry-point') +void dontCallDartPluginRegistrantFromBackgroundIsolate() async { + ReceivePort receivePort = ReceivePort(); + Isolate isolate = await Isolate.spawn(noDartPluginRegistrantIsolate, receivePort.sendPort); + bool didCallEntrypoint = await receivePort.first; + if (didCallEntrypoint) { + passMessage('_PluginRegistrant.register() was called on background isolate'); + } else { + passMessage('_PluginRegistrant.register() was not called on background isolate'); + } + isolate.kill(); +}