Allow spawning additional UI isolates in flutter_tester (flutter/engine#48706)

This enables work ongoing by @derekxu16 to improve performance in flutter_tester when running multiple files from large test suites.

Specifically, it:

- Exposes a `Spawn` C symbol from flutter_tester that runs the current kernel in a new UI isolate with a different entrypoint and/or route name
- Exposes two symbols from flutter_tester to allow a test harness to more efficiently load particular kernel files or to lookup an entrypoint from an imported source file.
- Avoids re-loading the kernel file completely when spawning a new UI isolate

Googlers can look at go/flutter-tester-isolates for some more context. If anyone wants I'm happy to create a public version of that doc.
This commit is contained in:
Dan Field
2024-01-05 09:13:59 -08:00
committed by GitHub
parent b98cd15293
commit 3078ba7036
17 changed files with 329 additions and 30 deletions

View File

@@ -53,6 +53,23 @@ config("export_dynamic_symbols") {
}
}
config("export_dynamic_test_symbols") {
# See comment in :export_dynamic_symbols.
# This config exposes an additional symbol meant for flutter_tester.
if (is_linux || is_fuchsia) {
inputs = [ "//flutter/common/exported_test_symbols.sym" ]
ldflags = [ "-Wl,--dynamic-list=" + rebase_path(inputs[0], root_build_dir) ]
} else if (is_mac) {
inputs = [ "//flutter/common/exported_test_symbols_mac.sym" ]
ldflags = [
"-Xlinker",
"-exported_symbols_list",
"-Xlinker",
rebase_path(inputs[0], root_build_dir),
]
}
}
group("flutter") {
testonly = true

View File

@@ -7414,6 +7414,8 @@ FILE: ../../../flutter/benchmarking/library.h
FILE: ../../../flutter/common/constants.h
FILE: ../../../flutter/common/exported_symbols.sym
FILE: ../../../flutter/common/exported_symbols_mac.sym
FILE: ../../../flutter/common/exported_test_symbols.sym
FILE: ../../../flutter/common/exported_test_symbols_mac.sym
FILE: ../../../flutter/common/graphics/gl_context_switch.cc
FILE: ../../../flutter/common/graphics/gl_context_switch.h
FILE: ../../../flutter/common/graphics/msaa_sample_count.h

View File

@@ -0,0 +1,13 @@
# These symbols are looked up from within the executable at runtime and must
# be exported in the dynamic symbol table.
{
kDartVmSnapshotData;
kDartVmSnapshotInstructions;
kDartIsolateSnapshotData;
kDartIsolateSnapshotInstructions;
InternalFlutterGpu*;
kInternalFlutterGpu*;
Spawn;
LoadLibraryFromKernel;
LookupEntryPoint;
};

View File

@@ -0,0 +1,11 @@
# These symbols are looked up from within the executable at runtime and must
# be exported in the dynamic symbol table.
_kDartVmSnapshotData
_kDartVmSnapshotInstructions
_kDartIsolateSnapshotData
_kDartIsolateSnapshotInstructions
_InternalFlutterGpu*
_kInternalFlutterGpu*
_Spawn
_LoadLibraryFromKernel
_LookupEntryPoint

View File

@@ -522,8 +522,8 @@ bool DartIsolate::LoadKernel(const std::shared_ptr<const fml::Mapping>& mapping,
return false;
}
// Mapping must be retained until isolate shutdown.
kernel_buffers_.push_back(mapping);
// Mapping must be retained until isolate group shutdown.
GetIsolateGroupData().AddKernelBuffer(mapping);
Dart_Handle library =
Dart_LoadLibraryFromKernel(mapping->GetMapping(), mapping->GetSize());
@@ -589,7 +589,8 @@ bool DartIsolate::LoadKernel(const std::shared_ptr<const fml::Mapping>& mapping,
// executed leads to crashes.
if (GetIsolateGroupData().GetChildIsolatePreparer() == nullptr) {
GetIsolateGroupData().SetChildIsolatePreparer(
[buffers = kernel_buffers_](DartIsolate* isolate) {
[buffers =
GetIsolateGroupData().GetKernelBuffers()](DartIsolate* isolate) {
for (uint64_t i = 0; i < buffers.size(); i++) {
bool last_piece = i + 1 == buffers.size();
const std::shared_ptr<const fml::Mapping>& buffer = buffers.at(i);
@@ -1130,6 +1131,30 @@ Dart_Handle DartIsolate::OnDartLoadLibrary(intptr_t loading_unit_id) {
return Dart_NewApiError(error_message.c_str());
}
Dart_Handle DartIsolate::LoadLibraryFromKernel(
const std::shared_ptr<const fml::Mapping>& mapping) {
if (DartVM::IsRunningPrecompiledCode()) {
return Dart_Null();
}
auto* isolate_group_data =
static_cast<std::shared_ptr<DartIsolateGroupData>*>(
Dart_CurrentIsolateGroupData());
// Mapping must be retained until isolate shutdown.
(*isolate_group_data)->AddKernelBuffer(mapping);
auto lib =
Dart_LoadLibraryFromKernel(mapping->GetMapping(), mapping->GetSize());
if (tonic::CheckAndHandleError(lib)) {
return Dart_Null();
}
auto result = Dart_FinalizeLoading(false);
if (Dart_IsError(result)) {
return result;
}
return Dart_GetField(lib, Dart_NewStringFromCString("main"));
}
DartIsolate::AutoFireClosure::AutoFireClosure(const fml::closure& closure)
: closure_(closure) {}

View File

@@ -392,6 +392,11 @@ class DartIsolate : public UIDartState {
const DartIsolateGroupData& GetIsolateGroupData() const;
/// Returns the "main" entrypoint of the library contained in the kernel
/// data in `mapping`.
static Dart_Handle LoadLibraryFromKernel(
const std::shared_ptr<const fml::Mapping>& mapping);
private:
friend class IsolateConfiguration;
class AutoFireClosure {
@@ -407,7 +412,6 @@ class DartIsolate : public UIDartState {
friend class DartVM;
Phase phase_ = Phase::Unknown;
std::vector<std::shared_ptr<const fml::Mapping>> kernel_buffers_;
std::vector<std::unique_ptr<AutoFireClosure>> shutdown_callbacks_;
std::unordered_set<fml::RefPtr<DartSnapshot>> loading_unit_snapshots_;
fml::RefPtr<fml::TaskRunner> message_handling_task_runner_;

View File

@@ -83,4 +83,14 @@ DartIsolateGroupData::GetPlatformMessageHandler(
: it->second;
}
void DartIsolateGroupData::AddKernelBuffer(
const std::shared_ptr<const fml::Mapping>& buffer) {
kernel_buffers_.push_back(buffer);
}
std::vector<std::shared_ptr<const fml::Mapping>>
DartIsolateGroupData::GetKernelBuffers() const {
return kernel_buffers_;
}
} // namespace flutter

View File

@@ -56,6 +56,13 @@ class DartIsolateGroupData : public PlatformMessageHandlerStorage {
void SetChildIsolatePreparer(const ChildIsolatePreparer& value);
/// Adds a kernel buffer mapping to the kernels loaded for this isolate group.
void AddKernelBuffer(const std::shared_ptr<const fml::Mapping>& buffer);
/// A copy of the mappings for all kernel buffer objects loaded into this
/// isolate group.
std::vector<std::shared_ptr<const fml::Mapping>> GetKernelBuffers() const;
// |PlatformMessageHandlerStorage|
void SetPlatformMessageHandler(
int64_t root_isolate_token,
@@ -66,6 +73,7 @@ class DartIsolateGroupData : public PlatformMessageHandlerStorage {
int64_t root_isolate_token) const override;
private:
std::vector<std::shared_ptr<const fml::Mapping>> kernel_buffers_;
const Settings settings_;
const fml::RefPtr<const DartSnapshot> isolate_snapshot_;
const std::string advisory_script_uri_;

View File

@@ -12,12 +12,14 @@
#include "flutter/fml/file.h"
#include "flutter/fml/unique_fd.h"
#include "flutter/runtime/dart_vm.h"
#include "runtime/isolate_configuration.h"
namespace flutter {
RunConfiguration RunConfiguration::InferFromSettings(
const Settings& settings,
const fml::RefPtr<fml::TaskRunner>& io_worker) {
const fml::RefPtr<fml::TaskRunner>& io_worker,
IsolateLaunchType launch_type) {
auto asset_manager = std::make_shared<AssetManager>();
if (fml::UniqueFD::traits_type::IsValid(settings.assets_dir)) {
@@ -31,7 +33,7 @@ RunConfiguration RunConfiguration::InferFromSettings(
true));
return {IsolateConfiguration::InferFromSettings(settings, asset_manager,
io_worker),
io_worker, launch_type),
asset_manager};
}

View File

@@ -51,13 +51,16 @@ class RunConfiguration {
/// serial worker is kept alive for the lifetime of the
/// shell associated with the engine that this run
/// configuration is given to.
/// @param[in] launch_type Whether to launch the new isolate into an existing
/// group or a new one.
///
/// @return A run configuration. Depending on the completeness of the
/// settings, This object may potentially be invalid.
///
static RunConfiguration InferFromSettings(
const Settings& settings,
const fml::RefPtr<fml::TaskRunner>& io_worker = nullptr);
const fml::RefPtr<fml::TaskRunner>& io_worker = nullptr,
IsolateLaunchType launch_type = IsolateLaunchType::kNewGroup);
//----------------------------------------------------------------------------
/// @brief Creates a run configuration with only an isolate

View File

@@ -18,7 +18,7 @@ executable("testing") {
public_configs = [
"//flutter:config",
"//flutter:export_dynamic_symbols",
"//flutter:export_dynamic_test_symbols",
]
sources = [ "tester_main.cc" ]
@@ -42,6 +42,7 @@ executable("testing") {
"//flutter/shell/gpu:gpu_surface_software",
"//flutter/skia",
"//flutter/third_party/tonic",
"//third_party/abseil-cpp/absl/base:no_destructor",
"//third_party/dart/runtime:libdart_jit",
"//third_party/dart/runtime/bin:dart_io_api",
]

View File

@@ -25,6 +25,7 @@
#include "flutter/shell/common/thread_host.h"
#include "flutter/shell/gpu/gpu_surface_software.h"
#include "third_party/abseil-cpp/absl/base/no_destructor.h"
#include "third_party/dart/runtime/include/bin/dart_io_api.h"
#include "third_party/dart/runtime/include/dart_api.h"
#include "third_party/skia/include/core/SkSurface.h"
@@ -131,8 +132,28 @@ struct ImpellerVulkanContextHolder {};
namespace flutter {
static absl::NoDestructor<std::unique_ptr<Shell>> g_shell;
static constexpr int64_t kImplicitViewId = 0ll;
static void ConfigureShell(Shell* shell) {
auto device_pixel_ratio = 3.0;
auto physical_width = 2400.0; // 800 at 3x resolution.
auto physical_height = 1800.0; // 600 at 3x resolution.
std::vector<std::unique_ptr<Display>> displays;
displays.push_back(std::make_unique<Display>(
0, 60, physical_width, physical_height, device_pixel_ratio));
shell->OnDisplayUpdates(std::move(displays));
flutter::ViewportMetrics metrics{};
metrics.device_pixel_ratio = device_pixel_ratio;
metrics.physical_width = physical_width;
metrics.physical_height = physical_height;
metrics.display_id = 0;
shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId, metrics);
}
class TesterExternalViewEmbedder : public ExternalViewEmbedder {
// |ExternalViewEmbedder|
DlCanvas* GetRootCanvas() override { return nullptr; }
@@ -384,12 +405,14 @@ int RunTester(const flutter::Settings& settings,
shell, Rasterizer::MakeGpuImageBehavior::kBitmap);
};
auto shell = Shell::Create(flutter::PlatformData(), //
task_runners, //
settings, //
on_create_platform_view, //
on_create_rasterizer //
);
g_shell->reset(Shell::Create(flutter::PlatformData(), //
task_runners, //
settings, //
on_create_platform_view, //
on_create_rasterizer //
)
.release());
auto shell = g_shell->get();
if (!shell || !shell->IsSetup()) {
FML_LOG(ERROR) << "Could not set up the shell.";
@@ -479,21 +502,7 @@ int RunTester(const flutter::Settings& settings,
}
});
auto device_pixel_ratio = 3.0;
auto physical_width = 2400.0; // 800 at 3x resolution.
auto physical_height = 1800.0; // 600 at 3x resolution.
std::vector<std::unique_ptr<Display>> displays;
displays.push_back(std::make_unique<Display>(
0, 60, physical_width, physical_height, device_pixel_ratio));
shell->OnDisplayUpdates(std::move(displays));
flutter::ViewportMetrics metrics{};
metrics.device_pixel_ratio = device_pixel_ratio;
metrics.physical_width = physical_width;
metrics.physical_height = physical_height;
metrics.display_id = 0;
shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId, metrics);
ConfigureShell(shell);
// Run the message loop and wait for the script to do its thing.
fml::MessageLoop::GetCurrent().Run();
@@ -503,6 +512,8 @@ int RunTester(const flutter::Settings& settings,
fml::TaskRunner::RunNowOrPostTask(ui_task_runner, task_observer_remove);
latch.Wait();
delete g_shell->release();
if (!engine_did_run) {
// If the engine itself didn't have a chance to run, there is no point in
// asking it if there was an error. Signal a failure unconditionally.
@@ -512,6 +523,94 @@ int RunTester(const flutter::Settings& settings,
return completion_observer.GetExitCodeForLastError();
}
#ifdef _WIN32
#define EXPORTED __declspec(dllexport)
#else
#define EXPORTED __attribute__((visibility("default")))
#endif
extern "C" {
EXPORTED Dart_Handle LoadLibraryFromKernel(const char* path) {
std::shared_ptr<fml::FileMapping> mapping =
fml::FileMapping::CreateReadOnly(path);
if (!mapping) {
return Dart_Null();
}
return DartIsolate::LoadLibraryFromKernel(mapping);
}
EXPORTED Dart_Handle LookupEntryPoint(const char* uri, const char* name) {
if (!uri || !name) {
return Dart_Null();
}
Dart_Handle lib = Dart_LookupLibrary(Dart_NewStringFromCString(uri));
if (Dart_IsError(lib)) {
return lib;
}
return Dart_GetField(lib, Dart_NewStringFromCString(name));
}
EXPORTED void Spawn(const char* entrypoint, const char* route) {
auto shell = g_shell->get();
auto isolate = Dart_CurrentIsolate();
auto spawn_task = [shell, entrypoint = std::string(entrypoint),
route = std::string(route)]() {
auto configuration = RunConfiguration::InferFromSettings(
shell->GetSettings(), /*io_worker=*/nullptr,
/*launch_type=*/IsolateLaunchType::kExistingGroup);
configuration.SetEntrypoint(entrypoint);
Shell::CreateCallback<PlatformView> on_create_platform_view =
fml::MakeCopyable([](Shell& shell) mutable {
ImpellerVulkanContextHolder impeller_context_holder;
return std::make_unique<TesterPlatformView>(
shell, shell.GetTaskRunners(),
std::move(impeller_context_holder));
});
Shell::CreateCallback<Rasterizer> on_create_rasterizer = [](Shell& shell) {
return std::make_unique<Rasterizer>(
shell, Rasterizer::MakeGpuImageBehavior::kBitmap);
};
// Spawn a shell, and keep it running until it has no live ports, then
// delete it on the platform thread.
auto spawned_shell =
shell
->Spawn(std::move(configuration), route, on_create_platform_view,
on_create_rasterizer)
.release();
ConfigureShell(spawned_shell);
fml::TaskRunner::RunNowOrPostTask(
spawned_shell->GetTaskRunners().GetUITaskRunner(), [spawned_shell]() {
fml::MessageLoop::GetCurrent().AddTaskObserver(
reinterpret_cast<intptr_t>(spawned_shell), [spawned_shell]() {
if (spawned_shell->EngineHasLivePorts()) {
return;
}
fml::MessageLoop::GetCurrent().RemoveTaskObserver(
reinterpret_cast<intptr_t>(spawned_shell));
// Shell must be deleted on the platform task runner.
fml::TaskRunner::RunNowOrPostTask(
spawned_shell->GetTaskRunners().GetPlatformTaskRunner(),
[spawned_shell]() { delete spawned_shell; });
});
});
};
Dart_ExitIsolate();
// The global shell pointer is never deleted, short of application exit.
// This UI task runner cannot be latched because it will block spawning a new
// shell in the case where flutter_tester is running multithreaded.
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(), spawn_task);
Dart_EnterIsolate(isolate);
}
}
} // namespace flutter
int main(int argc, char* argv[]) {

View File

@@ -43,6 +43,8 @@ tests = [
"plugin_utilities_test.dart",
"semantics_test.dart",
"serial_gc_test.dart",
"spawn_helper.dart",
"spawn_test.dart",
"task_order_test.dart",
"text_test.dart",
"window_test.dart",
@@ -50,11 +52,13 @@ tests = [
foreach(test, tests) {
flutter_build_dir = rebase_path("$root_gen_dir")
flutter_src_dir = rebase_path("$root_out_dir/../../flutter")
skia_gold_work_dir = rebase_path("$root_gen_dir/skia_gold_$test")
flutter_frontend_server("compile_$test") {
main_dart = test
kernel_output = "$root_gen_dir/$test.dill"
extra_args = [
"-DkFlutterSrcDirectory=$flutter_src_dir",
"-DkFlutterBuildDirectory=$flutter_build_dir",
"-DkSkiaGoldWorkDirectory=$skia_gold_work_dir",
]

View File

@@ -17,6 +17,7 @@ environment:
sdk: '>=3.2.0-0 <4.0.0'
dependencies:
ffi: any
litetest: any
path: any
skia_gold_client: any
@@ -38,6 +39,8 @@ dependency_overrides:
path: ../../../third_party/dart/pkg/expect
file:
path: ../../../third_party/dart/third_party/pkg/file/packages/file
ffi:
path: ../../../third_party/dart/third_party/pkg/ffi
fixnum:
path: ../../../third_party/dart/third_party/pkg/fixnum
litetest:

View File

@@ -0,0 +1,10 @@
// 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.
void main() {}
@pragma('vm:entry-point')
int echoInt(int echo) {
return echo;
}

View File

@@ -0,0 +1,87 @@
// 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.
import 'dart:ffi';
import 'dart:isolate';
import 'dart:ui';
import 'package:ffi/ffi.dart';
import 'package:litetest/litetest.dart';
// This import is used in a test, but not in a way that the analyzer can understand.
// ignore: unused_import
import 'spawn_helper.dart';
@Native<Handle Function(Pointer<Utf8>)>(symbol: 'LoadLibraryFromKernel')
external Object _loadLibraryFromKernel(Pointer<Utf8> path);
@Native<Handle Function(Pointer<Utf8>, Pointer<Utf8>)>(symbol: 'LookupEntryPoint')
external Object _lookupEntryPoint(Pointer<Utf8> library, Pointer<Utf8> name);
@Native<Void Function(Pointer<Utf8>, Pointer<Utf8>)>(symbol: 'Spawn')
external void _spawn(Pointer<Utf8> entrypoint, Pointer<Utf8> route);
void spawn({
required SendPort port,
String entrypoint = 'main',
String route = '/',
}) {
assert(
entrypoint != 'main' || route != '/',
'Spawn should not be used to spawn main with the default route name',
);
IsolateNameServer.registerPortWithName(port, route);
final Pointer<Utf8> nativeEntrypoint = entrypoint.toNativeUtf8();
final Pointer<Utf8> nativeRoute = route.toNativeUtf8();
_spawn(nativeEntrypoint, nativeRoute);
malloc.free(nativeEntrypoint);
malloc.free(nativeRoute);
}
const String kTestEntrypointRouteName = 'testEntrypoint';
@pragma('vm:entry-point')
void testEntrypoint() {
expect(PlatformDispatcher.instance.defaultRouteName, kTestEntrypointRouteName);
IsolateNameServer.lookupPortByName(kTestEntrypointRouteName)!.send(null);
}
void main() {
const bool kReleaseMode = bool.fromEnvironment('dart.vm.product');
const bool kProfileMode = bool.fromEnvironment('dart.vm.profile');
test('Spawn a different entrypoint with a special route name', () async {
final ReceivePort port = ReceivePort();
spawn(port: port.sendPort, entrypoint: 'testEntrypoint', route: kTestEntrypointRouteName);
expect(await port.first, isNull);
port.close();
});
test('Lookup entrypoint and execute', () {
final Pointer<Utf8> libraryPath = 'file://${const String.fromEnvironment('kFlutterSrcDirectory')}/testing/dart/spawn_helper.dart'.toNativeUtf8();
final Pointer<Utf8> entryPoint = 'echoInt'.toNativeUtf8();
expect(
(_lookupEntryPoint(
libraryPath,
entryPoint,
) as int Function(int))(42),
42,
);
malloc.free(libraryPath);
malloc.free(entryPoint);
});
test('Load from kernel', () {
final Pointer<Utf8> kernelPath = '${const String.fromEnvironment('kFlutterBuildDirectory')}/spawn_helper.dart.dill'.toNativeUtf8();
expect(
_loadLibraryFromKernel(kernelPath) is void Function(),
true,
);
malloc.free(kernelPath);
final Pointer<Utf8> fakePath = 'fake-path'.toNativeUtf8();
expect(_loadLibraryFromKernel(fakePath), null);
malloc.free(fakePath);
}, skip: kProfileMode || kReleaseMode); // ignore: avoid_redundant_argument_values
}

View File

@@ -1058,7 +1058,7 @@ def run_engine_tasks_in_parallel(tasks):
if len(failures) > 0:
logger.error('The following commands failed:')
for task, exn in failures:
logger.error('%s\n', str(task))
logger.error('%s\n %s\n\n', str(task), str(exn))
return False
return True