Add Dart entrypoint to execute the dart plugin registrant. (flutter/engine#31720)

* Adds Dart entrypoint to execute the dart plugin registrant.

* added negative test and added web ui interface

* removed linter warning
This commit is contained in:
gaaclarke
2022-03-02 17:50:23 -08:00
committed by GitHub
parent 194fb3fc3f
commit 70271f2263
11 changed files with 294 additions and 62 deletions

View File

@@ -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

View File

@@ -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",

View File

@@ -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

View File

@@ -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());

View File

@@ -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<int> saveCompilationTrace() {
if (engine.assertionsEnabled) {
throw UnimplementedError('saveCompilationTrace is not implemented on the web.');

View File

@@ -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",

View File

@@ -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<std::string>::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<std::string> library_name,
std::optional<std::string> entrypoint,
const std::vector<std::string>& args) {
@@ -756,10 +706,7 @@ bool DartIsolate::RunFromLibrary(std::optional<std::string> 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);
}

View File

@@ -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 <string>
#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<std::string>::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

View File

@@ -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_

View File

@@ -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<std::string> 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<std::string> messages;
fml::AutoResetWaitableEvent latch;
AddNativeCallback(
"PassMessage",
CREATE_NATIVE_ENTRY(([&latch, &messages](Dart_NativeArguments args) {
auto message = tonic::DartConverter<std::string>::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<std::string> messages;
fml::AutoResetWaitableEvent latch;
AddNativeCallback(
"PassMessage",
CREATE_NATIVE_ENTRY(([&latch, &messages](Dart_NativeArguments args) {
auto message = tonic::DartConverter<std::string>::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

View File

@@ -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();
}