Experimental platform isolates API (flutter/engine#48551)

This is a prototype of the [PlatformIsolate
API](https://github.com/flutter/flutter/issues/136314).

**UPDATE (Jan 25):** The PR is ready for review. PTAL.

The `PlatformIsolate` creation flow is:

1. `PlatformIsolate.spawn` running on parent isolate
(platform_isolate.dart)
    a. Create `isolateReadyPort`
    b. `PlatformIsolateNativeApi::Spawn` (platform_isolate.cc)
    c. `DartIsolate::CreatePlatformIsolate` (dart_isolate.cc)
d. Isolate created. Entry point invocation task dispatched to platform
thread
    e. `PlatformIsolate.spawn` returns a `Future<Isolate>`
2. On the platform thread, `_platformIsolateMain` is invoked in the
platform isolate
    a. Create `entryPointPort`
b. Send `Isolate.current` metadata and `entryPointPort` back to the
parent isolate via `isolateReadyPort`
3. Back in the parent isolate, `isolateReadyPort.handler` is invoked
a. Send the user's `entryPoint` and `message` to the platform isolate
via `entryPointPort`
b. Use received isolate metadata to create a new `Isolate` representing
the platform isolate and complete the `Future<Isolate>`
4. In the platform isolate, `entryPointPort.handler` is invoked
    a. Run the user's `entryPoint(message)`

The engine shutdown flow is handled by `PlatformIsolateManager`, which
maintains a set of running platform isolates.
This commit is contained in:
Liam Appelbe
2024-03-03 19:47:41 -08:00
committed by GitHub
parent 614df9461d
commit 27ca389132
36 changed files with 1775 additions and 16 deletions

View File

@@ -245,6 +245,7 @@
../../../flutter/runtime/dart_vm_unittests.cc
../../../flutter/runtime/fixtures
../../../flutter/runtime/no_dart_plugin_registrant_unittests.cc
../../../flutter/runtime/platform_isolate_manager_unittests.cc
../../../flutter/runtime/type_conversions_unittests.cc
../../../flutter/shell/common/animator_unittests.cc
../../../flutter/shell/common/base64_unittests.cc

View File

@@ -35635,6 +35635,7 @@ ORIGIN: ../../../flutter/lib/ui/painting/single_frame_codec.h + ../../../flutter
ORIGIN: ../../../flutter/lib/ui/painting/vertices.cc + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/ui/painting/vertices.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/ui/platform_dispatcher.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/ui/platform_isolate.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/ui/plugins.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/ui/plugins/callback_cache.cc + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/ui/plugins/callback_cache.h + ../../../flutter/LICENSE
@@ -35675,6 +35676,8 @@ ORIGIN: ../../../flutter/lib/ui/window/key_data_packet.cc + ../../../flutter/LIC
ORIGIN: ../../../flutter/lib/ui/window/key_data_packet.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/ui/window/platform_configuration.cc + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/ui/window/platform_configuration.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/ui/window/platform_isolate.cc + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/ui/window/platform_isolate.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/ui/window/platform_message.cc + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/ui/window/platform_message.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/ui/window/platform_message_response.cc + ../../../flutter/LICENSE
@@ -35716,6 +35719,7 @@ ORIGIN: ../../../flutter/lib/web_ui/lib/painting.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/path.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/path_metrics.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/platform_dispatcher.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/platform_isolate.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/pointer.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/semantics.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine.dart + ../../../flutter/LICENSE
@@ -36015,6 +36019,8 @@ ORIGIN: ../../../flutter/runtime/isolate_configuration.cc + ../../../flutter/LIC
ORIGIN: ../../../flutter/runtime/isolate_configuration.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/runtime/platform_data.cc + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/runtime/platform_data.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/runtime/platform_isolate_manager.cc + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/runtime/platform_isolate_manager.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/runtime/ptrace_check.cc + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/runtime/ptrace_check.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/runtime/runtime_controller.cc + ../../../flutter/LICENSE
@@ -38475,6 +38481,7 @@ FILE: ../../../flutter/lib/ui/painting/single_frame_codec.h
FILE: ../../../flutter/lib/ui/painting/vertices.cc
FILE: ../../../flutter/lib/ui/painting/vertices.h
FILE: ../../../flutter/lib/ui/platform_dispatcher.dart
FILE: ../../../flutter/lib/ui/platform_isolate.dart
FILE: ../../../flutter/lib/ui/plugins.dart
FILE: ../../../flutter/lib/ui/plugins/callback_cache.cc
FILE: ../../../flutter/lib/ui/plugins/callback_cache.h
@@ -38515,6 +38522,8 @@ FILE: ../../../flutter/lib/ui/window/key_data_packet.cc
FILE: ../../../flutter/lib/ui/window/key_data_packet.h
FILE: ../../../flutter/lib/ui/window/platform_configuration.cc
FILE: ../../../flutter/lib/ui/window/platform_configuration.h
FILE: ../../../flutter/lib/ui/window/platform_isolate.cc
FILE: ../../../flutter/lib/ui/window/platform_isolate.h
FILE: ../../../flutter/lib/ui/window/platform_message.cc
FILE: ../../../flutter/lib/ui/window/platform_message.h
FILE: ../../../flutter/lib/ui/window/platform_message_response.cc
@@ -38557,6 +38566,7 @@ FILE: ../../../flutter/lib/web_ui/lib/painting.dart
FILE: ../../../flutter/lib/web_ui/lib/path.dart
FILE: ../../../flutter/lib/web_ui/lib/path_metrics.dart
FILE: ../../../flutter/lib/web_ui/lib/platform_dispatcher.dart
FILE: ../../../flutter/lib/web_ui/lib/platform_isolate.dart
FILE: ../../../flutter/lib/web_ui/lib/pointer.dart
FILE: ../../../flutter/lib/web_ui/lib/semantics.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine.dart
@@ -38856,6 +38866,8 @@ FILE: ../../../flutter/runtime/isolate_configuration.cc
FILE: ../../../flutter/runtime/isolate_configuration.h
FILE: ../../../flutter/runtime/platform_data.cc
FILE: ../../../flutter/runtime/platform_data.h
FILE: ../../../flutter/runtime/platform_isolate_manager.cc
FILE: ../../../flutter/runtime/platform_isolate_manager.h
FILE: ../../../flutter/runtime/ptrace_check.cc
FILE: ../../../flutter/runtime/ptrace_check.h
FILE: ../../../flutter/runtime/runtime_controller.cc

View File

@@ -10,4 +10,5 @@
Spawn;
LoadLibraryFromKernel;
LookupEntryPoint;
ForceShutdownIsolate;
};

View File

@@ -9,3 +9,4 @@ _kInternalFlutterGpu*
_Spawn
_LoadLibraryFromKernel
_LookupEntryPoint
_ForceShutdownIsolate

View File

@@ -138,6 +138,8 @@ source_set("ui") {
"window/key_data_packet.h",
"window/platform_configuration.cc",
"window/platform_configuration.h",
"window/platform_isolate.cc",
"window/platform_isolate.h",
"window/platform_message.cc",
"window/platform_message.h",
"window/platform_message_response.cc",

View File

@@ -38,6 +38,7 @@
#include "flutter/lib/ui/text/paragraph.h"
#include "flutter/lib/ui/text/paragraph_builder.h"
#include "flutter/lib/ui/window/platform_configuration.h"
#include "flutter/lib/ui/window/platform_isolate.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_args.h"
#include "third_party/tonic/logging/dart_error.h"
@@ -113,6 +114,8 @@ typedef CanvasPath Path;
V(PlatformConfigurationNativeApi::SendPortPlatformMessage) \
V(PlatformConfigurationNativeApi::SendChannelUpdate) \
V(PlatformConfigurationNativeApi::GetScaledFontSize) \
V(PlatformIsolateNativeApi::IsRunningOnPlatformThread) \
V(PlatformIsolateNativeApi::Spawn) \
V(DartRuntimeHooks::Logger_PrintDebugString) \
V(DartRuntimeHooks::Logger_PrintString) \
V(DartRuntimeHooks::ScheduleMicrotask) \

View File

@@ -17,7 +17,13 @@ import 'dart:convert';
import 'dart:developer' as developer;
import 'dart:ffi';
import 'dart:io';
import 'dart:isolate' show SendPort;
import 'dart:isolate'
show
Isolate,
IsolateSpawnException,
RawReceivePort,
RemoteError,
SendPort;
import 'dart:math' as math;
import 'dart:nativewrappers';
import 'dart:typed_data';
@@ -35,6 +41,7 @@ part '../math.dart';
part '../natives.dart';
part '../painting.dart';
part '../platform_dispatcher.dart';
part '../platform_isolate.dart';
part '../plugins.dart';
part '../pointer.dart';
part '../semantics.dart';

View File

@@ -0,0 +1,189 @@
// 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.
part of dart.ui;
/// Runs [computation] on the platform thread and returns the result.
///
/// This may run the computation on a separate isolate. That isolate will be
/// reused for subsequent [runOnPlatformThread] calls. This means that global
/// state is maintained in that isolate between calls.
///
/// The [computation] and any state it captures may be sent to that isolate.
/// See [SendPort.send] for information about what types can be sent.
///
/// If [computation] is asynchronous (returns a `Future<R>`) then
/// that future is awaited in the new isolate, completing the entire
/// asynchronous computation, before returning the result.
///
/// If [computation] throws, the `Future` returned by this function completes
/// with that error.
///
/// The [computation] function and its result (or error) must be
/// sendable between isolates. Objects that cannot be sent include open
/// files and sockets (see [SendPort.send] for details).
///
/// This method can only be invoked from the main isolate.
///
/// This API is currently experimental.
Future<R> runOnPlatformThread<R>(FutureOr<R> Function() computation) {
if (isRunningOnPlatformThread) {
return Future<R>(computation);
}
final SendPort? sendPort = _platformRunnerSendPort;
if (sendPort != null) {
return _sendComputation(sendPort, computation);
} else {
return (_platformRunnerSendPortFuture ??= _spawnPlatformIsolate())
.then((SendPort port) => _sendComputation(port, computation));
}
}
SendPort? _platformRunnerSendPort;
Future<SendPort>? _platformRunnerSendPortFuture;
final Map<int, Completer<Object?>> _pending = <int, Completer<Object?>>{};
int _nextId = 0;
Future<SendPort> _spawnPlatformIsolate() {
final Completer<SendPort> sendPortCompleter = Completer<SendPort>();
final RawReceivePort receiver = RawReceivePort()..keepIsolateAlive = false;
receiver.handler = (Object? message) {
if (message == null) {
// This is the platform isolate's onExit handler.
// This shouldn't really happen, since Isolate.exit is disabled, the
// pause and terminate capabilities aren't provided to the parent
// isolate, and errors are fatal is false. But if the isolate does
// shutdown unexpectedly, clear the singleton so we can create another.
for (final Completer<Object?> completer in _pending.values) {
completer.completeError(RemoteError(
'PlatformIsolate shutdown unexpectedly',
StackTrace.empty.toString()));
}
_pending.clear();
_platformRunnerSendPort = null;
_platformRunnerSendPortFuture = null;
} else if (message is _PlatformIsolateReadyMessage) {
_platformRunnerSendPort = message.computationPort;
sendPortCompleter.complete(message.computationPort);
} else if (message is _ComputationResult) {
final Completer<Object?> resultCompleter = _pending.remove(message.id)!;
final Object? remoteStack = message.remoteStack;
final Object? remoteError = message.remoteError;
if (remoteStack != null) {
if (remoteStack is StackTrace) {
// Typed error.
resultCompleter.completeError(remoteError!, remoteStack);
} else {
// onError handler message, uncaught async error.
// Both values are strings, so calling `toString` is efficient.
final RemoteError error =
RemoteError(remoteError!.toString(), remoteStack.toString());
resultCompleter.completeError(error, error.stackTrace);
}
} else {
resultCompleter.complete(message.result);
}
} else {
// We encountered an error while starting the new isolate.
if (!sendPortCompleter.isCompleted) {
sendPortCompleter.completeError(
IsolateSpawnException('Unable to spawn isolate: $message'));
return;
}
// This shouldn't happen.
throw IsolateSpawnException(
"Internal error: unexpected message: '$message'");
}
};
final Isolate parentIsolate = Isolate.current;
final SendPort sendPort = receiver.sendPort;
try {
_nativeSpawn(() => _platformIsolateMain(parentIsolate, sendPort));
} on Object {
receiver.close();
rethrow;
}
return sendPortCompleter.future;
}
Future<R> _sendComputation<R>(
SendPort port, FutureOr<R> Function() computation) {
final int id = ++_nextId;
final Completer<R> resultCompleter = Completer<R>();
_pending[id] = resultCompleter;
port.send(_ComputationRequest(id, computation));
return resultCompleter.future;
}
void _safeSend(SendPort sendPort, int id, Object? result, Object? error,
Object? stackTrace) {
try {
sendPort.send(_ComputationResult(id, result, error, stackTrace));
} catch (sendError, sendStack) {
sendPort.send(_ComputationResult(id, null, sendError, sendStack));
}
}
void _platformIsolateMain(Isolate parentIsolate, SendPort sendPort) {
final RawReceivePort computationPort = RawReceivePort();
computationPort.handler = (_ComputationRequest? message) {
if (message == null) {
// The parent isolate has shutdown. Allow this isolate to shutdown.
computationPort.keepIsolateAlive = false;
return;
}
late final FutureOr<Object?> potentiallyAsyncResult;
try {
potentiallyAsyncResult = message.computation();
} catch (e, s) {
_safeSend(sendPort, message.id, null, e, s);
return;
}
if (potentiallyAsyncResult is Future<Object?>) {
potentiallyAsyncResult.then((Object? result) {
_safeSend(sendPort, message.id, result, null, null);
}, onError: (Object? e, Object? s) {
_safeSend(sendPort, message.id, null, e, s ?? StackTrace.empty);
});
} else {
_safeSend(sendPort, message.id, potentiallyAsyncResult, null, null);
}
};
Isolate.current.addOnExitListener(sendPort);
parentIsolate.addOnExitListener(computationPort.sendPort);
sendPort.send(_PlatformIsolateReadyMessage(computationPort.sendPort));
}
@Native<Void Function(Handle)>(symbol: 'PlatformIsolateNativeApi::Spawn')
external void _nativeSpawn(Function entryPoint);
/// Whether the current isolate is running on the platform thread.
final bool isRunningOnPlatformThread = _isRunningOnPlatformThread();
@Native<Bool Function()>(
symbol: 'PlatformIsolateNativeApi::IsRunningOnPlatformThread', isLeaf: true)
external bool _isRunningOnPlatformThread();
class _PlatformIsolateReadyMessage {
_PlatformIsolateReadyMessage(this.computationPort);
final SendPort computationPort;
}
class _ComputationRequest {
_ComputationRequest(this.id, this.computation);
final int id;
final FutureOr<Object?> Function() computation;
}
class _ComputationResult {
_ComputationResult(this.id, this.result, this.remoteError, this.remoteStack);
final int id;
final Object? result;
final Object? remoteError;
final Object? remoteStack;
}

View File

@@ -17,7 +17,13 @@ import 'dart:convert';
import 'dart:developer' as developer;
import 'dart:ffi';
import 'dart:io';
import 'dart:isolate' show SendPort;
import 'dart:isolate'
show
Isolate,
IsolateSpawnException,
RawReceivePort,
RemoteError,
SendPort;
import 'dart:math' as math;
import 'dart:nativewrappers';
import 'dart:typed_data';
@@ -35,6 +41,7 @@ part 'math.dart';
part 'natives.dart';
part 'painting.dart';
part 'platform_dispatcher.dart';
part 'platform_isolate.dart';
part 'plugins.dart';
part 'pointer.dart';
part 'semantics.dart';

View File

@@ -262,4 +262,10 @@ int64_t UIDartState::GetRootIsolateToken() const {
return IsRootIsolate() ? reinterpret_cast<int64_t>(this) : 0;
}
Dart_Isolate UIDartState::CreatePlatformIsolate(Dart_Handle entry_point,
char** error) {
FML_UNREACHABLE();
return nullptr;
}
} // namespace flutter

View File

@@ -171,6 +171,9 @@ class UIDartState : public tonic::DartState {
/// The expected type for runtime stage shaders.
impeller::RuntimeStageBackend GetRuntimeStageBackend() const;
virtual Dart_Isolate CreatePlatformIsolate(Dart_Handle entry_point,
char** error);
protected:
UIDartState(TaskObserverAdd add_callback,
TaskObserverRemove remove_callback,

View File

@@ -25,6 +25,7 @@ namespace flutter {
class FontCollection;
class PlatformMessage;
class PlatformMessageHandler;
class PlatformIsolateManager;
class Scene;
//--------------------------------------------------------------------------
@@ -247,6 +248,9 @@ class PlatformConfigurationClient {
virtual double GetScaledFontSize(double unscaled_font_size,
int configuration_id) const = 0;
virtual std::shared_ptr<PlatformIsolateManager>
GetPlatformIsolateManager() = 0;
protected:
virtual ~PlatformConfigurationClient();
};

View File

@@ -0,0 +1,47 @@
// 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 <iostream>
#include <thread>
#include "flutter/fml/macros.h"
#include "flutter/fml/task_runner.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "flutter/lib/ui/window/platform_isolate.h"
#include "third_party/tonic/converter/dart_converter.h"
namespace flutter {
void PlatformIsolateNativeApi::Spawn(Dart_Handle entry_point) {
UIDartState* current_state = UIDartState::Current();
FML_DCHECK(current_state != nullptr);
if (!current_state->IsRootIsolate()) {
// TODO(flutter/flutter#136314): Remove this restriction.
Dart_EnterScope();
Dart_ThrowException(tonic::ToDart(
"PlatformIsolates can only be spawned on the root isolate."));
}
char* error = nullptr;
current_state->CreatePlatformIsolate(entry_point, &error);
if (error) {
Dart_EnterScope();
Dart_Handle error_handle = tonic::ToDart<const char*>(error);
::free(error);
Dart_ThrowException(error_handle);
}
}
bool PlatformIsolateNativeApi::IsRunningOnPlatformThread() {
UIDartState* current_state = UIDartState::Current();
FML_DCHECK(current_state != nullptr);
fml::RefPtr<fml::TaskRunner> platform_task_runner =
current_state->GetTaskRunners().GetPlatformTaskRunner();
if (!platform_task_runner) {
return false;
}
return platform_task_runner->RunsTasksOnCurrentThread();
}
} // namespace flutter

View File

@@ -0,0 +1,21 @@
// 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_LIB_UI_WINDOW_PLATFORM_ISOLATE_H_
#define FLUTTER_LIB_UI_WINDOW_PLATFORM_ISOLATE_H_
#include "third_party/dart/runtime/include/dart_api.h"
namespace flutter {
class PlatformIsolateNativeApi {
public:
static void Spawn(Dart_Handle entry_point);
static bool IsRunningOnPlatformThread();
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_WINDOW_PLATFORM_ISOLATE_H_

View File

@@ -0,0 +1,34 @@
// 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.
part of ui;
/// Runs [computation] on the platform thread and returns the result.
///
/// This may run the computation on a separate isolate. That isolate will be
/// reused for subsequent [runOnPlatformThread] calls. This means that global
/// state is maintained in that isolate between calls.
///
/// The [computation] and any state it captures may be sent to that isolate.
/// See [SendPort.send] for information about what types can be sent.
///
/// If [computation] is asynchronous (returns a `Future<R>`) then
/// that future is awaited in the new isolate, completing the entire
/// asynchronous computation, before returning the result.
///
/// If [computation] throws, the `Future` returned by this function completes
/// with that error.
///
/// The [computation] function and its result (or error) must be
/// sendable between isolates. Objects that cannot be sent include open
/// files and sockets (see [SendPort.send] for details).
///
/// This method can only be invoked from the main isolate.
///
/// This API is currently experimental.
Future<R> runOnPlatformThread<R>(FutureOr<R> Function() computation) =>
Future<R>(computation);
/// Returns whether the current isolate is running on the platform thread.
bool isRunningOnPlatformThread = true;

View File

@@ -31,6 +31,7 @@ part 'painting.dart';
part 'path.dart';
part 'path_metrics.dart';
part 'platform_dispatcher.dart';
part 'platform_isolate.dart';
part 'pointer.dart';
part 'semantics.dart';
part 'text.dart';

View File

@@ -76,6 +76,8 @@ source_set("runtime") {
"isolate_configuration.h",
"platform_data.cc",
"platform_data.h",
"platform_isolate_manager.cc",
"platform_isolate_manager.h",
"ptrace_check.h",
"runtime_controller.cc",
"runtime_controller.h",
@@ -136,6 +138,7 @@ if (enable_unittests) {
"dart_lifecycle_unittests.cc",
"dart_service_isolate_unittests.cc",
"dart_vm_unittests.cc",
"platform_isolate_manager_unittests.cc",
"type_conversions_unittests.cc",
]

View File

@@ -14,12 +14,14 @@
#include "flutter/lib/io/dart_io.h"
#include "flutter/lib/ui/dart_runtime_hooks.h"
#include "flutter/lib/ui/dart_ui.h"
#include "flutter/lib/ui/window/platform_isolate.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"
#include "flutter/runtime/isolate_configuration.h"
#include "flutter/runtime/runtime_controller.h"
#include "fml/message_loop_task_queues.h"
#include "fml/task_source.h"
#include "fml/time/time_point.h"
@@ -280,6 +282,150 @@ std::weak_ptr<DartIsolate> DartIsolate::CreateRootIsolate(
return (*root_isolate_data)->GetWeakIsolatePtr();
}
Dart_Isolate DartIsolate::CreatePlatformIsolate(Dart_Handle entry_point,
char** error) {
*error = nullptr;
PlatformConfiguration* platform_config = platform_configuration();
FML_DCHECK(platform_config != nullptr);
std::shared_ptr<PlatformIsolateManager> platform_isolate_manager =
platform_config->client()->GetPlatformIsolateManager();
std::weak_ptr<PlatformIsolateManager> weak_platform_isolate_manager =
platform_isolate_manager;
if (platform_isolate_manager->HasShutdownMaybeFalseNegative()) {
// Don't set the error string. We want to silently ignore this error,
// because the engine is shutting down.
FML_LOG(INFO) << "CreatePlatformIsolate called after shutdown";
return nullptr;
}
Dart_Isolate parent_isolate = isolate();
Dart_ExitIsolate(); // Exit parent_isolate.
const TaskRunners& task_runners = GetTaskRunners();
fml::RefPtr<fml::TaskRunner> platform_task_runner =
task_runners.GetPlatformTaskRunner();
FML_DCHECK(platform_task_runner);
auto isolate_group_data = std::shared_ptr<DartIsolateGroupData>(
*static_cast<std::shared_ptr<DartIsolateGroupData>*>(
Dart_IsolateGroupData(parent_isolate)));
Settings settings(isolate_group_data->GetSettings());
// PlatformIsolate.spawn should behave like Isolate.spawn when unhandled
// exceptions happen (log the exception, but don't terminate the app). But the
// default unhandled_exception_callback may terminate the app, because it is
// only called for the root isolate (child isolates are managed by the VM and
// have a different error code path). So override it to simply log the error.
settings.unhandled_exception_callback = [](const std::string& error,
const std::string& stack_trace) {
FML_LOG(ERROR) << "Unhandled exception:\n" << error << "\n" << stack_trace;
return true;
};
// The platform isolate task observer must be added on the platform thread. So
// schedule the add function on the platform task runner.
TaskObserverAdd old_task_observer_add = settings.task_observer_add;
settings.task_observer_add = [old_task_observer_add, platform_task_runner,
weak_platform_isolate_manager](
intptr_t key, const fml::closure& callback) {
platform_task_runner->PostTask([old_task_observer_add,
weak_platform_isolate_manager, key,
callback]() {
std::shared_ptr<PlatformIsolateManager> platform_isolate_manager =
weak_platform_isolate_manager.lock();
if (platform_isolate_manager == nullptr ||
platform_isolate_manager->HasShutdown()) {
// Shutdown happened in between this task being posted, and it running.
// platform_isolate has already been shut down. Do nothing.
FML_LOG(INFO) << "Shutdown before platform isolate task observer added";
return;
}
old_task_observer_add(key, callback);
});
};
UIDartState::Context context(task_runners);
context.advisory_script_uri = isolate_group_data->GetAdvisoryScriptURI();
context.advisory_script_entrypoint =
isolate_group_data->GetAdvisoryScriptEntrypoint();
auto isolate_data = std::make_unique<std::shared_ptr<DartIsolate>>(
std::shared_ptr<DartIsolate>(
new DartIsolate(settings, context, platform_isolate_manager)));
IsolateMaker isolate_maker =
[parent_isolate](
std::shared_ptr<DartIsolateGroupData>* unused_isolate_group_data,
std::shared_ptr<DartIsolate>* isolate_data, Dart_IsolateFlags* flags,
char** error) {
return Dart_CreateIsolateInGroup(
/*group_member=*/parent_isolate,
/*name=*/"PlatformIsolate",
/*shutdown_callback=*/
reinterpret_cast<Dart_IsolateShutdownCallback>(
DartIsolate::SpawnIsolateShutdownCallback),
/*cleanup_callback=*/
reinterpret_cast<Dart_IsolateCleanupCallback>(
DartIsolateCleanupCallback),
/*child_isolate_data=*/isolate_data,
/*error=*/error);
};
Dart_Isolate platform_isolate = CreateDartIsolateGroup(
nullptr, std::move(isolate_data), nullptr, error, isolate_maker);
Dart_EnterIsolate(parent_isolate);
if (*error) {
return nullptr;
}
if (!platform_isolate_manager->RegisterPlatformIsolate(platform_isolate)) {
// The PlatformIsolateManager was shutdown while we were creating the
// isolate. This means that we're shutting down the engine. We need to
// shutdown the platform isolate.
FML_LOG(INFO) << "Shutdown during platform isolate creation";
tonic::DartIsolateScope isolate_scope(platform_isolate);
Dart_ShutdownIsolate();
return nullptr;
}
tonic::DartApiScope api_scope;
Dart_PersistentHandle entry_point_handle =
Dart_NewPersistentHandle(entry_point);
platform_task_runner->PostTask([entry_point_handle, platform_isolate,
weak_platform_isolate_manager]() {
std::shared_ptr<PlatformIsolateManager> platform_isolate_manager =
weak_platform_isolate_manager.lock();
if (platform_isolate_manager == nullptr ||
platform_isolate_manager->HasShutdown()) {
// Shutdown happened in between this task being posted, and it running.
// platform_isolate has already been shut down. Do nothing.
FML_LOG(INFO) << "Shutdown before platform isolate entry point";
return;
}
tonic::DartIsolateScope isolate_scope(platform_isolate);
tonic::DartApiScope api_scope;
Dart_Handle entry_point = Dart_HandleFromPersistent(entry_point_handle);
Dart_DeletePersistentHandle(entry_point_handle);
// Disable Isolate.exit().
Dart_Handle isolate_lib = Dart_LookupLibrary(tonic::ToDart("dart:isolate"));
FML_CHECK(!tonic::CheckAndHandleError(isolate_lib));
Dart_Handle isolate_type = Dart_GetNonNullableType(
isolate_lib, tonic::ToDart("Isolate"), 0, nullptr);
FML_CHECK(!tonic::CheckAndHandleError(isolate_type));
Dart_Handle result =
Dart_SetField(isolate_type, tonic::ToDart("_mayExit"), Dart_False());
FML_CHECK(!tonic::CheckAndHandleError(result));
tonic::DartInvokeVoid(entry_point);
});
return platform_isolate;
}
DartIsolate::DartIsolate(const Settings& settings,
bool is_root_isolate,
const UIDartState::Context& context,
@@ -294,8 +440,30 @@ DartIsolate::DartIsolate(const Settings& settings,
context),
may_insecurely_connect_to_all_domains_(
settings.may_insecurely_connect_to_all_domains),
is_platform_isolate_(false),
is_spawning_in_group_(is_spawning_in_group),
domain_network_policy_(settings.domain_network_policy) {
phase_ = Phase::Uninitialized;
}
DartIsolate::DartIsolate(
const Settings& settings,
const UIDartState::Context& context,
std::shared_ptr<PlatformIsolateManager> platform_isolate_manager)
: UIDartState(settings.task_observer_add,
settings.task_observer_remove,
settings.log_tag,
settings.unhandled_exception_callback,
settings.log_message_callback,
DartVMRef::GetIsolateNameServer(),
false, // is_root_isolate
context),
may_insecurely_connect_to_all_domains_(
settings.may_insecurely_connect_to_all_domains),
is_platform_isolate_(true),
is_spawning_in_group_(false),
domain_network_policy_(settings.domain_network_policy),
is_spawning_in_group_(is_spawning_in_group) {
platform_isolate_manager_(std::move(platform_isolate_manager)) {
phase_ = Phase::Uninitialized;
}
@@ -336,7 +504,9 @@ bool DartIsolate::Initialize(Dart_Isolate dart_isolate) {
Dart_SetCurrentUserTag(Dart_NewUserTag("AppStartUp"));
}
SetMessageHandlingTaskRunner(GetTaskRunners().GetUITaskRunner());
SetMessageHandlingTaskRunner(is_platform_isolate_
? GetTaskRunners().GetPlatformTaskRunner()
: GetTaskRunners().GetUITaskRunner());
if (tonic::CheckAndHandleError(
Dart_SetLibraryTagHandler(tonic::DartState::HandleLibraryTag))) {
@@ -393,7 +563,7 @@ void DartIsolate::LoadLoadingUnitError(intptr_t loading_unit_id,
void DartIsolate::SetMessageHandlingTaskRunner(
const fml::RefPtr<fml::TaskRunner>& runner) {
if (!IsRootIsolate() || !runner) {
if (!runner) {
return;
}
@@ -1108,6 +1278,11 @@ void DartIsolate::OnShutdownCallback() {
}
}
if (is_platform_isolate_) {
FML_DCHECK(platform_isolate_manager_ != nullptr);
platform_isolate_manager_->RemovePlatformIsolate(isolate());
}
shutdown_callbacks_.clear();
const fml::closure& isolate_shutdown_callback =
@@ -1124,7 +1299,7 @@ Dart_Handle DartIsolate::OnDartLoadLibrary(intptr_t loading_unit_id) {
return Dart_Null();
}
const std::string error_message =
"Platform Configuration was null. Deferred library load request"
"Platform Configuration was null. Deferred library load request "
"for loading unit id " +
std::to_string(loading_unit_id) + " was not sent.";
FML_LOG(ERROR) << error_message;

View File

@@ -379,6 +379,25 @@ class DartIsolate : public UIDartState {
///
fml::RefPtr<fml::TaskRunner> GetMessageHandlingTaskRunner() const;
//----------------------------------------------------------------------------
/// @brief Creates a new isolate in the same group as this isolate, which
/// runs on the platform thread. This method can only be invoked
/// on the root isolate.
///
/// @param[in] entry_point The entrypoint to invoke once the isolate is
/// spawned. Will be run on the platform thread.
/// @param[out] error If spawning fails inside the Dart VM, this is
/// set to the error string. The error should be
/// reported to the user. Otherwise it is set to
/// null. It's possible for spawning to fail, but
/// this error still be null. In that case the
/// failure should not be reported to the user.
///
/// @return The newly created isolate, or null if spawning failed.
///
Dart_Isolate CreatePlatformIsolate(Dart_Handle entry_point,
char** error) override;
bool LoadLoadingUnit(
intptr_t loading_unit_id,
std::unique_ptr<const fml::Mapping> snapshot_data,
@@ -416,8 +435,10 @@ class DartIsolate : public UIDartState {
std::unordered_set<fml::RefPtr<DartSnapshot>> loading_unit_snapshots_;
fml::RefPtr<fml::TaskRunner> message_handling_task_runner_;
const bool may_insecurely_connect_to_all_domains_;
std::string domain_network_policy_;
const bool is_platform_isolate_;
const bool is_spawning_in_group_;
std::string domain_network_policy_;
std::shared_ptr<PlatformIsolateManager> platform_isolate_manager_;
static std::weak_ptr<DartIsolate> CreateRootIsolate(
const Settings& settings,
@@ -434,6 +455,10 @@ class DartIsolate : public UIDartState {
const UIDartState::Context& context,
bool is_spawning_in_group = false);
DartIsolate(const Settings& settings,
const UIDartState::Context& context,
std::shared_ptr<PlatformIsolateManager> platform_isolate_manager);
//----------------------------------------------------------------------------
/// @brief Initializes the given (current) isolate.
///

View File

@@ -2,14 +2,15 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/runtime/dart_isolate.h"
#include "flutter/fml/mapping.h"
#include "flutter/fml/synchronization/count_down_latch.h"
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/lib/ui/window/platform_message.h"
#include "flutter/runtime/dart_isolate.h"
#include "flutter/runtime/dart_vm.h"
#include "flutter/runtime/dart_vm_lifecycle.h"
#include "flutter/runtime/isolate_configuration.h"
#include "flutter/runtime/platform_isolate_manager.h"
#include "flutter/testing/dart_isolate_runner.h"
#include "flutter/testing/fixture_test.h"
#include "flutter/testing/testing.h"
@@ -695,6 +696,498 @@ TEST_F(DartIsolateTest, SpawningAnIsolateDoesNotReloadKernel) {
ASSERT_TRUE(root_isolate->Shutdown());
}
class FakePlatformConfigurationClient : public PlatformConfigurationClient {
public:
std::shared_ptr<PlatformIsolateManager> mgr =
std::shared_ptr<PlatformIsolateManager>(new PlatformIsolateManager());
std::shared_ptr<PlatformIsolateManager> GetPlatformIsolateManager() override {
return mgr;
}
std::string DefaultRouteName() override { return ""; }
void ScheduleFrame() override {}
void EndWarmUpFrame() override {}
void Render(Scene* scene, double width, double height) override {}
void UpdateSemantics(SemanticsUpdate* update) override {}
void HandlePlatformMessage(
std::unique_ptr<PlatformMessage> message) override {}
FontCollection& GetFontCollection() override {
FML_UNREACHABLE();
return *(FontCollection*)(this);
}
std::shared_ptr<AssetManager> GetAssetManager() override { return nullptr; }
void UpdateIsolateDescription(const std::string isolate_name,
int64_t isolate_port) override {}
void SetNeedsReportTimings(bool value) override {}
std::shared_ptr<const fml::Mapping> GetPersistentIsolateData() override {
return nullptr;
}
std::unique_ptr<std::vector<std::string>> ComputePlatformResolvedLocale(
const std::vector<std::string>& supported_locale_data) override {
return nullptr;
}
void RequestDartDeferredLibrary(intptr_t loading_unit_id) override {}
void SendChannelUpdate(std::string name, bool listening) override {}
double GetScaledFontSize(double unscaled_font_size,
int configuration_id) const override {
return 0;
}
};
TEST_F(DartIsolateTest, PlatformIsolateCreationAndShutdown) {
fml::AutoResetWaitableEvent message_latch;
AddNativeCallback(
"PassMessage",
CREATE_NATIVE_ENTRY(([&message_latch](Dart_NativeArguments args) {
auto message = tonic::DartConverter<std::string>::FromDart(
Dart_GetNativeArgument(args, 0));
ASSERT_EQ("Platform isolate is ready", message);
message_latch.Signal();
})));
FakePlatformConfigurationClient client;
auto platform_configuration =
std::make_unique<PlatformConfiguration>(&client);
Dart_Isolate platform_isolate = nullptr;
{
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
auto settings = CreateSettingsForFixture();
auto vm_ref = DartVMRef::Create(settings);
ASSERT_TRUE(vm_ref);
auto vm_data = vm_ref.GetVMData();
ASSERT_TRUE(vm_data);
auto platform_thread = CreateNewThread();
auto ui_thread = CreateNewThread();
TaskRunners task_runners(GetCurrentTestName(), // label
platform_thread, // platform
ui_thread, // raster
ui_thread, // ui
ui_thread // io
);
auto isolate =
RunDartCodeInIsolate(vm_ref, settings, task_runners, "emptyMain", {},
GetDefaultKernelFilePath(), {}, nullptr,
std::move(platform_configuration));
ASSERT_TRUE(isolate);
auto root_isolate = isolate->get();
ASSERT_EQ(root_isolate->GetPhase(), DartIsolate::Phase::Running);
EXPECT_FALSE(
client.mgr->IsRegisteredForTestingOnly(root_isolate->isolate()));
// Post a task to the platform_thread that just waits, to delay execution of
// the platform isolate until we're ready.
fml::AutoResetWaitableEvent platform_thread_latch;
fml::TaskRunner::RunNowOrPostTask(
platform_thread, fml::MakeCopyable([&platform_thread_latch]() mutable {
platform_thread_latch.Wait();
}));
fml::AutoResetWaitableEvent ui_thread_latch;
fml::TaskRunner::RunNowOrPostTask(
ui_thread, fml::MakeCopyable([&]() mutable {
ASSERT_TRUE(
isolate->RunInIsolateScope([root_isolate, &platform_isolate]() {
Dart_Handle lib = Dart_RootLibrary();
Dart_Handle entry_point = Dart_GetField(
lib, tonic::ToDart("mainForPlatformIsolates"));
char* error = nullptr;
platform_isolate =
root_isolate->CreatePlatformIsolate(entry_point, &error);
EXPECT_FALSE(error);
EXPECT_TRUE(platform_isolate);
EXPECT_EQ(Dart_CurrentIsolate(), root_isolate->isolate());
return true;
}));
ui_thread_latch.Signal();
}));
ui_thread_latch.Wait();
ASSERT_TRUE(platform_isolate);
EXPECT_TRUE(client.mgr->IsRegisteredForTestingOnly(platform_isolate));
// Allow the platform isolate to run.
platform_thread_latch.Signal();
// Wait for a message from the platform isolate.
message_latch.Wait();
// root isolate will be auto-shutdown
}
EXPECT_FALSE(client.mgr->IsRegisteredForTestingOnly(platform_isolate));
}
TEST_F(DartIsolateTest, PlatformIsolateEarlyShutdown) {
FakePlatformConfigurationClient client;
auto platform_configuration =
std::make_unique<PlatformConfiguration>(&client);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
auto settings = CreateSettingsForFixture();
auto vm_ref = DartVMRef::Create(settings);
ASSERT_TRUE(vm_ref);
auto vm_data = vm_ref.GetVMData();
ASSERT_TRUE(vm_data);
auto platform_thread = CreateNewThread();
auto ui_thread = CreateNewThread();
TaskRunners task_runners(GetCurrentTestName(), // label
platform_thread, // platform
ui_thread, // raster
ui_thread, // ui
ui_thread // io
);
auto isolate =
RunDartCodeInIsolate(vm_ref, settings, task_runners, "emptyMain", {},
GetDefaultKernelFilePath(), {}, nullptr,
std::move(platform_configuration));
ASSERT_TRUE(isolate);
auto root_isolate = isolate->get();
ASSERT_EQ(root_isolate->GetPhase(), DartIsolate::Phase::Running);
EXPECT_FALSE(client.mgr->IsRegisteredForTestingOnly(root_isolate->isolate()));
fml::AutoResetWaitableEvent ui_thread_latch;
Dart_Isolate platform_isolate = nullptr;
fml::TaskRunner::RunNowOrPostTask(
ui_thread, fml::MakeCopyable([&]() mutable {
ASSERT_TRUE(
isolate->RunInIsolateScope([root_isolate, &platform_isolate]() {
Dart_Handle lib = Dart_RootLibrary();
Dart_Handle entry_point =
Dart_GetField(lib, tonic::ToDart("emptyMain"));
char* error = nullptr;
platform_isolate =
root_isolate->CreatePlatformIsolate(entry_point, &error);
EXPECT_FALSE(error);
EXPECT_TRUE(platform_isolate);
EXPECT_EQ(Dart_CurrentIsolate(), root_isolate->isolate());
return true;
}));
ui_thread_latch.Signal();
}));
ui_thread_latch.Wait();
ASSERT_TRUE(platform_isolate);
EXPECT_TRUE(client.mgr->IsRegisteredForTestingOnly(platform_isolate));
// Post a task to the platform thread to shut down the platform isolate.
fml::AutoResetWaitableEvent platform_thread_latch;
fml::TaskRunner::RunNowOrPostTask(
platform_thread,
fml::MakeCopyable([&platform_thread_latch, platform_isolate]() mutable {
Dart_EnterIsolate(platform_isolate);
Dart_ShutdownIsolate();
platform_thread_latch.Signal();
}));
platform_thread_latch.Wait();
// The platform isolate should be shut down.
EXPECT_FALSE(client.mgr->IsRegisteredForTestingOnly(platform_isolate));
// root isolate will be auto-shutdown
}
TEST_F(DartIsolateTest, PlatformIsolateSendAndReceive) {
fml::AutoResetWaitableEvent message_latch;
AddNativeCallback(
"PassMessage",
CREATE_NATIVE_ENTRY(([&message_latch](Dart_NativeArguments args) {
auto message = tonic::DartConverter<std::string>::FromDart(
Dart_GetNativeArgument(args, 0));
ASSERT_EQ("Platform isolate received: Hello from root isolate!",
message);
message_latch.Signal();
})));
FakePlatformConfigurationClient client;
auto platform_configuration =
std::make_unique<PlatformConfiguration>(&client);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
auto settings = CreateSettingsForFixture();
auto vm_ref = DartVMRef::Create(settings);
ASSERT_TRUE(vm_ref);
auto vm_data = vm_ref.GetVMData();
ASSERT_TRUE(vm_data);
auto platform_thread = CreateNewThread();
auto ui_thread = CreateNewThread();
TaskRunners task_runners(GetCurrentTestName(), // label
platform_thread, // platform
ui_thread, // raster
ui_thread, // ui
ui_thread // io
);
auto isolate =
RunDartCodeInIsolate(vm_ref, settings, task_runners, "emptyMain", {},
GetDefaultKernelFilePath(), {}, nullptr,
std::move(platform_configuration));
ASSERT_TRUE(isolate);
auto root_isolate = isolate->get();
ASSERT_EQ(root_isolate->GetPhase(), DartIsolate::Phase::Running);
fml::AutoResetWaitableEvent ui_thread_latch;
Dart_Isolate platform_isolate = nullptr;
fml::TaskRunner::RunNowOrPostTask(
ui_thread, fml::MakeCopyable([&]() mutable {
ASSERT_TRUE(isolate->RunInIsolateScope([root_isolate,
&platform_isolate]() {
Dart_Handle lib = Dart_RootLibrary();
Dart_Handle entry_point = Dart_Invoke(
lib, tonic::ToDart("createEntryPointForPlatIsoSendAndRecvTest"),
0, nullptr);
char* error = nullptr;
platform_isolate =
root_isolate->CreatePlatformIsolate(entry_point, &error);
EXPECT_FALSE(error);
return true;
}));
ui_thread_latch.Signal();
}));
ui_thread_latch.Wait();
// Wait for a message from the platform isolate.
message_latch.Wait();
// Post a task to the platform_thread that runs after the platform isolate's
// entry point and all messages, and wait for it to run.
fml::AutoResetWaitableEvent epilogue_latch;
fml::TaskRunner::RunNowOrPostTask(
platform_thread, fml::MakeCopyable([&epilogue_latch]() mutable {
epilogue_latch.Signal();
}));
epilogue_latch.Wait();
// root isolate will be auto-shutdown
}
TEST_F(DartIsolateTest, PlatformIsolateCreationAfterManagerShutdown) {
AddNativeCallback("PassMessage",
CREATE_NATIVE_ENTRY((
[](Dart_NativeArguments args) { FML_UNREACHABLE(); })));
FakePlatformConfigurationClient client;
auto platform_configuration =
std::make_unique<PlatformConfiguration>(&client);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
auto settings = CreateSettingsForFixture();
auto vm_ref = DartVMRef::Create(settings);
ASSERT_TRUE(vm_ref);
auto vm_data = vm_ref.GetVMData();
ASSERT_TRUE(vm_data);
auto platform_thread = CreateNewThread();
auto ui_thread = CreateNewThread();
TaskRunners task_runners(GetCurrentTestName(), // label
platform_thread, // platform
ui_thread, // raster
ui_thread, // ui
ui_thread // io
);
auto isolate =
RunDartCodeInIsolate(vm_ref, settings, task_runners, "emptyMain", {},
GetDefaultKernelFilePath(), {}, nullptr,
std::move(platform_configuration));
ASSERT_TRUE(isolate);
auto root_isolate = isolate->get();
ASSERT_EQ(root_isolate->GetPhase(), DartIsolate::Phase::Running);
// Shut down the manager on the platform thread.
fml::AutoResetWaitableEvent manager_shutdown_latch;
fml::TaskRunner::RunNowOrPostTask(
platform_thread,
fml::MakeCopyable([&manager_shutdown_latch, &client]() mutable {
client.mgr->ShutdownPlatformIsolates();
manager_shutdown_latch.Signal();
}));
manager_shutdown_latch.Wait();
fml::AutoResetWaitableEvent ui_thread_latch;
fml::TaskRunner::RunNowOrPostTask(
ui_thread, fml::MakeCopyable([&]() mutable {
ASSERT_TRUE(isolate->RunInIsolateScope([root_isolate]() {
Dart_Handle lib = Dart_RootLibrary();
Dart_Handle entry_point =
Dart_GetField(lib, tonic::ToDart("mainForPlatformIsolates"));
char* error = nullptr;
Dart_Isolate platform_isolate =
root_isolate->CreatePlatformIsolate(entry_point, &error);
// Failed to create a platform isolate, but we've still re-entered the
// root isolate.
EXPECT_FALSE(error);
EXPECT_FALSE(platform_isolate);
EXPECT_EQ(Dart_CurrentIsolate(), root_isolate->isolate());
return true;
}));
ui_thread_latch.Signal();
}));
ui_thread_latch.Wait();
// root isolate will be auto-shutdown
}
TEST_F(DartIsolateTest, PlatformIsolateManagerShutdownBeforeMainRuns) {
AddNativeCallback("PassMessage",
CREATE_NATIVE_ENTRY((
[](Dart_NativeArguments args) { FML_UNREACHABLE(); })));
FakePlatformConfigurationClient client;
auto platform_configuration =
std::make_unique<PlatformConfiguration>(&client);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
auto settings = CreateSettingsForFixture();
auto vm_ref = DartVMRef::Create(settings);
ASSERT_TRUE(vm_ref);
auto vm_data = vm_ref.GetVMData();
ASSERT_TRUE(vm_data);
auto platform_thread = CreateNewThread();
auto ui_thread = CreateNewThread();
TaskRunners task_runners(GetCurrentTestName(), // label
platform_thread, // platform
ui_thread, // raster
ui_thread, // ui
ui_thread // io
);
auto isolate =
RunDartCodeInIsolate(vm_ref, settings, task_runners, "emptyMain", {},
GetDefaultKernelFilePath(), {}, nullptr,
std::move(platform_configuration));
ASSERT_TRUE(isolate);
auto root_isolate = isolate->get();
ASSERT_EQ(root_isolate->GetPhase(), DartIsolate::Phase::Running);
Dart_Isolate platform_isolate = nullptr;
// Post a task to the platform_thread that just waits, to delay execution of
// the platform isolate until we're ready, and shutdown the manager just
// before it runs.
fml::AutoResetWaitableEvent platform_thread_latch;
fml::TaskRunner::RunNowOrPostTask(
platform_thread, fml::MakeCopyable([&platform_thread_latch, &client,
&platform_isolate]() mutable {
platform_thread_latch.Wait();
client.mgr->ShutdownPlatformIsolates();
EXPECT_TRUE(platform_isolate);
EXPECT_FALSE(client.mgr->IsRegisteredForTestingOnly(platform_isolate));
}));
fml::AutoResetWaitableEvent ui_thread_latch;
fml::TaskRunner::RunNowOrPostTask(
ui_thread, fml::MakeCopyable([&]() mutable {
ASSERT_TRUE(
isolate->RunInIsolateScope([root_isolate, &platform_isolate]() {
Dart_Handle lib = Dart_RootLibrary();
Dart_Handle entry_point =
Dart_GetField(lib, tonic::ToDart("mainForPlatformIsolates"));
char* error = nullptr;
platform_isolate =
root_isolate->CreatePlatformIsolate(entry_point, &error);
EXPECT_FALSE(error);
EXPECT_TRUE(platform_isolate);
EXPECT_EQ(Dart_CurrentIsolate(), root_isolate->isolate());
return true;
}));
ui_thread_latch.Signal();
}));
ui_thread_latch.Wait();
ASSERT_TRUE(platform_isolate);
EXPECT_TRUE(client.mgr->IsRegisteredForTestingOnly(platform_isolate));
// Allow the platform isolate to run, but its main is never run.
platform_thread_latch.Signal();
// Post a task to the platform_thread that runs after the platform isolate's
// entry point, and wait for it to run.
fml::AutoResetWaitableEvent epilogue_latch;
fml::TaskRunner::RunNowOrPostTask(
platform_thread, fml::MakeCopyable([&epilogue_latch]() mutable {
epilogue_latch.Signal();
}));
epilogue_latch.Wait();
// root isolate will be auto-shutdown
}
TEST_F(DartIsolateTest, PlatformIsolateMainThrowsError) {
AddNativeCallback("PassMessage",
CREATE_NATIVE_ENTRY((
[](Dart_NativeArguments args) { FML_UNREACHABLE(); })));
FakePlatformConfigurationClient client;
auto platform_configuration =
std::make_unique<PlatformConfiguration>(&client);
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
auto settings = CreateSettingsForFixture();
auto vm_ref = DartVMRef::Create(settings);
ASSERT_TRUE(vm_ref);
auto vm_data = vm_ref.GetVMData();
ASSERT_TRUE(vm_data);
auto platform_thread = CreateNewThread();
auto ui_thread = CreateNewThread();
TaskRunners task_runners(GetCurrentTestName(), // label
platform_thread, // platform
ui_thread, // raster
ui_thread, // ui
ui_thread // io
);
auto isolate =
RunDartCodeInIsolate(vm_ref, settings, task_runners, "emptyMain", {},
GetDefaultKernelFilePath(), {}, nullptr,
std::move(platform_configuration));
ASSERT_TRUE(isolate);
auto root_isolate = isolate->get();
ASSERT_EQ(root_isolate->GetPhase(), DartIsolate::Phase::Running);
Dart_Isolate platform_isolate = nullptr;
fml::AutoResetWaitableEvent ui_thread_latch;
fml::TaskRunner::RunNowOrPostTask(
ui_thread, fml::MakeCopyable([&]() mutable {
ASSERT_TRUE(
isolate->RunInIsolateScope([root_isolate, &platform_isolate]() {
Dart_Handle lib = Dart_RootLibrary();
Dart_Handle entry_point = Dart_GetField(
lib, tonic::ToDart("mainForPlatformIsolatesThrowError"));
char* error = nullptr;
platform_isolate =
root_isolate->CreatePlatformIsolate(entry_point, &error);
EXPECT_FALSE(error);
EXPECT_TRUE(platform_isolate);
EXPECT_EQ(Dart_CurrentIsolate(), root_isolate->isolate());
return true;
}));
ui_thread_latch.Signal();
}));
ui_thread_latch.Wait();
ASSERT_TRUE(platform_isolate);
EXPECT_TRUE(client.mgr->IsRegisteredForTestingOnly(platform_isolate));
// Post a task to the platform_thread that runs after the platform isolate's
// entry point, and wait for it to run.
fml::AutoResetWaitableEvent epilogue_latch;
fml::TaskRunner::RunNowOrPostTask(
platform_thread, fml::MakeCopyable([&epilogue_latch]() mutable {
epilogue_latch.Signal();
}));
epilogue_latch.Wait();
// root isolate will be auto-shutdown
}
} // namespace testing
} // namespace flutter

View File

@@ -188,3 +188,34 @@ void mainForPluginRegistrantTest() {
passMessage('_PluginRegistrant.register() was not called');
}
}
@pragma('vm:entry-point')
void mainForPlatformIsolates() {
passMessage('Platform isolate is ready');
}
@pragma('vm:entry-point')
void emptyMain(args) {}
@pragma('vm:entry-point')
Function createEntryPointForPlatIsoSendAndRecvTest() {
final port = RawReceivePort();
port.handler = (message) {
port.close();
(message as SendPort).send('Hello from root isolate!');
};
final SendPort sendPort = port.sendPort;
return () {
final replyPort = RawReceivePort();
replyPort.handler = (message) {
replyPort.close();
passMessage('Platform isolate received: $message');
};
sendPort.send(replyPort.sendPort);
};
}
@pragma('vm:entry-point')
void mainForPlatformIsolatesThrowError() {
throw 'Error from platform isolate';
}

View File

@@ -0,0 +1,70 @@
// 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/platform_isolate_manager.h"
#include "flutter/runtime/dart_isolate.h"
namespace flutter {
bool PlatformIsolateManager::HasShutdown() {
// TODO(flutter/flutter#136314): Assert that we're on the platform thread.
std::scoped_lock lock(lock_);
return is_shutdown_;
}
bool PlatformIsolateManager::HasShutdownMaybeFalseNegative() {
std::scoped_lock lock(lock_);
return is_shutdown_;
}
bool PlatformIsolateManager::RegisterPlatformIsolate(Dart_Isolate isolate) {
std::scoped_lock lock(lock_);
if (is_shutdown_) {
// It's possible shutdown occured while we were trying to aquire the lock.
return false;
}
FML_DCHECK(platform_isolates_.find(isolate) == platform_isolates_.end());
platform_isolates_.insert(isolate);
return true;
}
void PlatformIsolateManager::RemovePlatformIsolate(Dart_Isolate isolate) {
// This method is only called by DartIsolate::OnShutdownCallback() during
// isolate shutdown. This can happen either during the ordinary platform
// isolate shutdown, or during ShutdownPlatformIsolates(). In either case
// we're on the platform thread.
// TODO(flutter/flutter#136314): Assert that we're on the platform thread.
// Need a method that works for ShutdownPlatformIsolates() too.
std::scoped_lock lock(lock_);
if (is_shutdown_) {
// Removal during ShutdownPlatformIsolates. Ignore, to avoid modifying
// platform_isolates_ during iteration.
FML_DCHECK(platform_isolates_.empty());
return;
}
FML_DCHECK(platform_isolates_.find(isolate) != platform_isolates_.end());
platform_isolates_.erase(isolate);
}
void PlatformIsolateManager::ShutdownPlatformIsolates() {
// TODO(flutter/flutter#136314): Assert that we're on the platform thread.
// There's no current UIDartState here, so platform_isolate.cc's method won't
// work.
std::scoped_lock lock(lock_);
is_shutdown_ = true;
std::unordered_set<Dart_Isolate> platform_isolates;
std::swap(platform_isolates_, platform_isolates);
for (Dart_Isolate isolate : platform_isolates) {
Dart_EnterIsolate(isolate);
Dart_ShutdownIsolate();
}
}
bool PlatformIsolateManager::IsRegisteredForTestingOnly(Dart_Isolate isolate) {
std::scoped_lock lock(lock_);
return platform_isolates_.find(isolate) != platform_isolates_.end();
}
} // namespace flutter

View File

@@ -0,0 +1,56 @@
// 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_RUNTIME_PLATFORM_ISOLATE_MANAGER_H_
#define FLUTTER_RUNTIME_PLATFORM_ISOLATE_MANAGER_H_
#include <atomic>
#include <mutex>
#include <unordered_set>
#include "third_party/dart/runtime/include/dart_api.h"
namespace flutter {
/// Maintains a list of registered platform isolates, so that they can be
/// proactively shutdown as a group during shell shutdown.
class PlatformIsolateManager {
public:
/// Returns whether the PlatformIsolateManager is shutdown. New isolates
/// cannot be registered after the manager is shutdown. Must be called on the
/// platform thread.
bool HasShutdown();
/// Returns whether the PlatformIsolateManager is shutdown. New isolates
/// cannot be registered after the manager is shutdown. Callable from any
/// thread. The result may be obsolete immediately after the call.
bool HasShutdownMaybeFalseNegative();
/// Register an isolate in the list of platform isolates. Callable from any
/// thread.
bool RegisterPlatformIsolate(Dart_Isolate isolate);
/// Remove an isolate from the list of platform isolates. Must be called from
/// the platform thread.
void RemovePlatformIsolate(Dart_Isolate isolate);
/// Shuts down all registered isolates, and the manager itself. Must be called
/// from the platform thread.
void ShutdownPlatformIsolates();
/// Returns whether an isolate is registered. For testing only. Callable from
/// any thread.
bool IsRegisteredForTestingOnly(Dart_Isolate isolate);
private:
// This lock must be recursive because ShutdownPlatformIsolates indirectly
// calls RemovePlatformIsolate.
std::recursive_mutex lock_;
std::unordered_set<Dart_Isolate> platform_isolates_;
bool is_shutdown_ = false;
};
} // namespace flutter
#endif // FLUTTER_RUNTIME_PLATFORM_ISOLATE_MANAGER_H_

View File

@@ -0,0 +1,278 @@
// 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_vm.h"
#include "flutter/runtime/dart_vm_lifecycle.h"
#include "flutter/runtime/platform_isolate_manager.h"
#include "flutter/testing/fixture_test.h"
#include "flutter/testing/testing.h"
namespace flutter {
namespace testing {
struct IsolateData {
PlatformIsolateManager* mgr;
Dart_Isolate isolate = nullptr;
bool is_shutdown = false;
bool is_registered = false;
explicit IsolateData(PlatformIsolateManager* _mgr) : mgr(_mgr) {}
};
// The IsolateDataMap is a map from Dart_Isolate to a *vector* of IsolateData,
// because Dart_Isolates are frequently reused after shutdown, and we want the
// IsolateData objects to live as long as the map itself. The last element of
// the vector is always the currently active IsolateData, and the other elements
// refer to isolates that have been shutdown.
using IsolateDataMap =
std::unordered_map<Dart_Isolate, std::vector<std::unique_ptr<IsolateData>>>;
// Using a thread local isolate data map so that MultithreadedCreation test
// can avoid using locks while creating isolates on multiple threads. A lock
// would sync up the threads, so would defeat the purpose of the test.
static thread_local std::unique_ptr<IsolateDataMap> isolate_data_map_;
class PlatformIsolateManagerTest : public FixtureTest {
public:
PlatformIsolateManagerTest() {}
void TestWithRootIsolate(const std::function<void()>& test) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
auto settings = CreateSettingsForFixture();
auto vm_ref = DartVMRef::Create(settings);
ASSERT_TRUE(vm_ref);
auto vm_data = vm_ref.GetVMData();
ASSERT_TRUE(vm_data);
TaskRunners task_runners(GetCurrentTestName(), //
GetCurrentTaskRunner(), //
GetCurrentTaskRunner(), //
GetCurrentTaskRunner(), //
GetCurrentTaskRunner() //
);
auto isolate_configuration =
IsolateConfiguration::InferFromSettings(settings);
UIDartState::Context context(task_runners);
context.advisory_script_uri = "main.dart";
context.advisory_script_entrypoint = "main";
auto weak_isolate = DartIsolate::CreateRunningRootIsolate(
vm_data->GetSettings(), // settings
vm_data->GetIsolateSnapshot(), // isolate snapshot
nullptr, // platform configuration
DartIsolate::Flags{}, // flags
nullptr, // root_isolate_create_callback
settings.isolate_create_callback, // isolate create callback
settings.isolate_shutdown_callback, // isolate shutdown callback
"main", // dart entrypoint
std::nullopt, // dart entrypoint library
{}, // dart entrypoint arguments
std::move(isolate_configuration), // isolate configuration
context // engine context
);
root_isolate_ = weak_isolate.lock()->isolate();
ASSERT_TRUE(root_isolate_);
test();
Dart_EnterIsolate(root_isolate_);
Dart_ShutdownIsolate();
}
Dart_Isolate CreateAndRegisterIsolate(PlatformIsolateManager* mgr) {
if (isolate_data_map_.get() == nullptr) {
isolate_data_map_.reset(new IsolateDataMap());
}
IsolateData* isolate_data = new IsolateData(mgr);
char* error = nullptr;
Dart_Isolate isolate =
Dart_CreateIsolateInGroup(root_isolate_, "TestIsolate", OnShutdown,
nullptr, isolate_data, &error);
isolate_data->isolate = isolate;
EXPECT_TRUE(isolate);
Dart_ExitIsolate();
(*isolate_data_map_.get())[isolate].push_back(
std::unique_ptr<IsolateData>(isolate_data));
isolate_data->is_registered = mgr->RegisterPlatformIsolate(isolate);
return isolate;
}
bool IsolateIsShutdown(Dart_Isolate isolate) {
EXPECT_EQ(1u, isolate_data_map_.get()->count(isolate));
EXPECT_LT(0u, (*isolate_data_map_.get())[isolate].size());
return (*isolate_data_map_.get())[isolate].back()->is_shutdown;
}
bool IsolateIsRegistered(Dart_Isolate isolate) {
EXPECT_EQ(1u, isolate_data_map_.get()->count(isolate));
EXPECT_LT(0u, (*isolate_data_map_.get())[isolate].size());
return (*isolate_data_map_.get())[isolate].back()->is_registered;
}
private:
Dart_Isolate root_isolate_ = nullptr;
static void OnShutdown(void*, void* raw_isolate_data) {
IsolateData* isolate_data =
reinterpret_cast<IsolateData*>(raw_isolate_data);
EXPECT_TRUE(isolate_data->isolate);
EXPECT_FALSE(isolate_data->is_shutdown);
isolate_data->is_shutdown = true;
if (isolate_data->is_registered) {
isolate_data->mgr->RemovePlatformIsolate(isolate_data->isolate);
isolate_data->is_registered = false;
}
}
FML_DISALLOW_COPY_AND_ASSIGN(PlatformIsolateManagerTest);
};
TEST_F(PlatformIsolateManagerTest, OrdinaryFlow) {
TestWithRootIsolate([this]() {
PlatformIsolateManager mgr;
EXPECT_FALSE(mgr.HasShutdown());
EXPECT_FALSE(mgr.HasShutdownMaybeFalseNegative());
Dart_Isolate isolateA = CreateAndRegisterIsolate(&mgr);
ASSERT_TRUE(isolateA);
EXPECT_FALSE(IsolateIsShutdown(isolateA));
EXPECT_TRUE(IsolateIsRegistered(isolateA));
EXPECT_TRUE(mgr.IsRegisteredForTestingOnly(isolateA));
Dart_Isolate isolateB = CreateAndRegisterIsolate(&mgr);
ASSERT_TRUE(isolateB);
EXPECT_FALSE(IsolateIsShutdown(isolateB));
EXPECT_TRUE(IsolateIsRegistered(isolateB));
EXPECT_TRUE(mgr.IsRegisteredForTestingOnly(isolateB));
mgr.ShutdownPlatformIsolates();
EXPECT_TRUE(mgr.HasShutdown());
EXPECT_TRUE(mgr.HasShutdownMaybeFalseNegative());
EXPECT_TRUE(IsolateIsShutdown(isolateA));
EXPECT_FALSE(IsolateIsRegistered(isolateA));
EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateA));
EXPECT_TRUE(IsolateIsShutdown(isolateB));
EXPECT_FALSE(IsolateIsRegistered(isolateB));
EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateB));
});
}
TEST_F(PlatformIsolateManagerTest, EarlyShutdown) {
TestWithRootIsolate([this]() {
PlatformIsolateManager mgr;
EXPECT_FALSE(mgr.HasShutdown());
Dart_Isolate isolateA = CreateAndRegisterIsolate(&mgr);
ASSERT_TRUE(isolateA);
EXPECT_FALSE(IsolateIsShutdown(isolateA));
EXPECT_TRUE(IsolateIsRegistered(isolateA));
EXPECT_TRUE(mgr.IsRegisteredForTestingOnly(isolateA));
Dart_Isolate isolateB = CreateAndRegisterIsolate(&mgr);
ASSERT_TRUE(isolateB);
EXPECT_FALSE(IsolateIsShutdown(isolateB));
EXPECT_TRUE(IsolateIsRegistered(isolateB));
EXPECT_TRUE(mgr.IsRegisteredForTestingOnly(isolateB));
Dart_EnterIsolate(isolateA);
Dart_ShutdownIsolate();
EXPECT_TRUE(IsolateIsShutdown(isolateA));
EXPECT_FALSE(IsolateIsRegistered(isolateA));
EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateA));
Dart_EnterIsolate(isolateB);
Dart_ShutdownIsolate();
EXPECT_TRUE(IsolateIsShutdown(isolateB));
EXPECT_FALSE(IsolateIsRegistered(isolateB));
EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateB));
mgr.ShutdownPlatformIsolates();
EXPECT_TRUE(mgr.HasShutdown());
EXPECT_TRUE(IsolateIsShutdown(isolateA));
EXPECT_FALSE(IsolateIsRegistered(isolateA));
EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateA));
EXPECT_TRUE(IsolateIsShutdown(isolateB));
EXPECT_FALSE(IsolateIsRegistered(isolateB));
EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateB));
});
}
TEST_F(PlatformIsolateManagerTest, RegistrationAfterShutdown) {
TestWithRootIsolate([this]() {
PlatformIsolateManager mgr;
EXPECT_FALSE(mgr.HasShutdown());
Dart_Isolate isolateA = CreateAndRegisterIsolate(&mgr);
ASSERT_TRUE(isolateA);
EXPECT_FALSE(IsolateIsShutdown(isolateA));
EXPECT_TRUE(IsolateIsRegistered(isolateA));
EXPECT_TRUE(mgr.IsRegisteredForTestingOnly(isolateA));
mgr.ShutdownPlatformIsolates();
EXPECT_TRUE(mgr.HasShutdown());
EXPECT_TRUE(IsolateIsShutdown(isolateA));
EXPECT_FALSE(IsolateIsRegistered(isolateA));
EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateA));
Dart_Isolate isolateB = CreateAndRegisterIsolate(&mgr);
ASSERT_TRUE(isolateB);
EXPECT_FALSE(IsolateIsShutdown(isolateB));
EXPECT_FALSE(IsolateIsRegistered(isolateB));
EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateB));
Dart_EnterIsolate(isolateB);
Dart_ShutdownIsolate();
EXPECT_TRUE(IsolateIsShutdown(isolateB));
EXPECT_FALSE(IsolateIsRegistered(isolateB));
EXPECT_FALSE(mgr.IsRegisteredForTestingOnly(isolateB));
});
}
TEST_F(PlatformIsolateManagerTest, MultithreadedCreation) {
// Try to generate race conditions by creating Isolates on multiple threads,
// while shutting down the manager.
TestWithRootIsolate([this]() {
PlatformIsolateManager mgr;
EXPECT_FALSE(mgr.HasShutdown());
std::atomic<bool> test_finished = false;
std::vector<std::thread> threads;
threads.reserve(10);
for (int i = 0; i < 10; ++i) {
threads.push_back(std::thread([this, &mgr, &test_finished]() {
for (int j = 0; j < 100; ++j) {
Dart_Isolate isolate = CreateAndRegisterIsolate(&mgr);
ASSERT_TRUE(isolate);
EXPECT_FALSE(IsolateIsShutdown(isolate));
if (!IsolateIsRegistered(isolate)) {
Dart_EnterIsolate(isolate);
Dart_ShutdownIsolate();
}
}
while (!test_finished.load()) {
// Wait for the test to finish, to avoid prematurely destroying thread
// local isolate_data_map_.
}
}));
}
mgr.ShutdownPlatformIsolates();
EXPECT_TRUE(mgr.HasShutdown());
test_finished = true;
for (auto& thread : threads) {
thread.join();
}
});
}
} // namespace testing
} // namespace flutter

View File

@@ -559,6 +559,10 @@ double RuntimeController::GetScaledFontSize(double unscaled_font_size,
return client_.GetScaledFontSize(unscaled_font_size, configuration_id);
}
void RuntimeController::ShutdownPlatformIsolates() {
platform_isolate_manager_->ShutdownPlatformIsolates();
}
RuntimeController::Locale::Locale(std::string language_code_,
std::string country_code_,
std::string script_code_,

View File

@@ -22,6 +22,7 @@
#include "flutter/lib/ui/window/pointer_data_packet.h"
#include "flutter/runtime/dart_vm.h"
#include "flutter/runtime/platform_data.h"
#include "flutter/runtime/platform_isolate_manager.h"
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
@@ -614,6 +615,16 @@ class RuntimeController : public PlatformConfigurationClient {
return root_isolate_;
}
std::shared_ptr<PlatformIsolateManager> GetPlatformIsolateManager() override {
return platform_isolate_manager_;
}
//--------------------------------------------------------------------------
/// @brief Shuts down all registered platform isolates. Must be called
/// from the platform thread.
///
void ShutdownPlatformIsolates();
protected:
/// Constructor for Mocks.
RuntimeController(RuntimeDelegate& p_client, const TaskRunners& task_runners);
@@ -645,6 +656,8 @@ class RuntimeController : public PlatformConfigurationClient {
const fml::closure isolate_shutdown_callback_;
std::shared_ptr<const fml::Mapping> persistent_isolate_data_;
UIDartState::Context context_;
std::shared_ptr<PlatformIsolateManager> platform_isolate_manager_ =
std::shared_ptr<PlatformIsolateManager>(new PlatformIsolateManager());
bool has_flushed_runtime_state_ = false;
PlatformConfiguration* GetPlatformConfigurationIfAvailable();

View File

@@ -615,4 +615,8 @@ void Engine::SetDisplays(const std::vector<DisplayData>& displays) {
ScheduleFrame();
}
void Engine::ShutdownPlatformIsolates() {
runtime_controller_->ShutdownPlatformIsolates();
}
} // namespace flutter

View File

@@ -961,6 +961,12 @@ class Engine final : public RuntimeDelegate, PointerDataDispatcher::Delegate {
const std::weak_ptr<VsyncWaiter> GetVsyncWaiter() const;
//--------------------------------------------------------------------------
/// @brief Shuts down all registered platform isolates. Must be called
/// from the platform thread.
///
void ShutdownPlatformIsolates();
private:
// |RuntimeDelegate|
std::string DefaultRouteName() override;

View File

@@ -522,7 +522,16 @@ Shell::~Shell() {
vm_->GetServiceProtocol()->RemoveHandler(this);
fml::AutoResetWaitableEvent ui_latch, gpu_latch, platform_latch, io_latch;
fml::AutoResetWaitableEvent platiso_latch, ui_latch, gpu_latch,
platform_latch, io_latch;
fml::TaskRunner::RunNowOrPostTask(
task_runners_.GetPlatformTaskRunner(),
fml::MakeCopyable([this, &platiso_latch]() mutable {
engine_->ShutdownPlatformIsolates();
platiso_latch.Signal();
}));
platiso_latch.Wait();
fml::TaskRunner::RunNowOrPostTask(
task_runners_.GetUITaskRunner(),

View File

@@ -601,6 +601,19 @@ EXPORTED void Spawn(const char* entrypoint, const char* route) {
Dart_EnterIsolate(isolate);
}
EXPORTED void ForceShutdownIsolate() {
// Enable Isolate.exit().
FML_DCHECK(Dart_CurrentIsolate() != nullptr);
Dart_Handle isolate_lib = Dart_LookupLibrary(tonic::ToDart("dart:isolate"));
FML_CHECK(!tonic::CheckAndHandleError(isolate_lib));
Dart_Handle isolate_type = Dart_GetNonNullableType(
isolate_lib, tonic::ToDart("Isolate"), 0, nullptr);
FML_CHECK(!tonic::CheckAndHandleError(isolate_type));
Dart_Handle result =
Dart_SetField(isolate_type, tonic::ToDart("_mayExit"), Dart_True());
FML_CHECK(!tonic::CheckAndHandleError(result));
}
}
} // namespace flutter

View File

@@ -40,6 +40,8 @@ tests = [
"picture_test.dart",
"platform_dispatcher_test.dart",
"platform_view_test.dart",
"platform_isolate_test.dart",
"platform_isolate_shutdown_test.dart",
"plugin_utilities_test.dart",
"semantics_test.dart",
"serial_gc_test.dart",

View File

@@ -0,0 +1,40 @@
// Copyright 2024 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:async';
import 'dart:ffi';
import 'dart:isolate';
import 'dart:ui';
import 'package:litetest/litetest.dart';
void main() {
test('PlatformIsolate runOnPlatformThread, cancels pending jobs if shutdown', () async {
final Future<int> slowTask = runOnPlatformThread(() async {
await Future<void>.delayed(const Duration(seconds: 10));
return 123;
});
await runOnPlatformThread(() {
_forceShutdownIsolate();
Future<void>(() => Isolate.exit());
});
bool throws = false;
try {
await slowTask;
} catch (error) {
expect(error.toString(), contains('PlatformIsolate shutdown unexpectedly'));
throws = true;
}
expect(throws, true);
// Platform isolate automatically restarts.
final int result = await runOnPlatformThread(() => 123);
expect(result, 123);
});
}
@Native<Void Function()>(symbol: 'ForceShutdownIsolate')
external void _forceShutdownIsolate();

View File

@@ -0,0 +1,187 @@
// Copyright 2024 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:async';
import 'dart:isolate';
import 'dart:ui';
import 'package:litetest/litetest.dart';
int counter = 0;
void main() {
test('PlatformIsolate isRunningOnPlatformThread, false cases', () async {
final bool isPlatThread =
await Isolate.run(() => isRunningOnPlatformThread);
expect(isPlatThread, isFalse);
});
test('PlatformIsolate runOnPlatformThread', () async {
final bool isPlatThread =
await runOnPlatformThread(() => isRunningOnPlatformThread);
expect(isPlatThread, isTrue);
});
test('PlatformIsolate runOnPlatformThread, async operations', () async {
final bool isPlatThread = await runOnPlatformThread(() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
await Future<void>.delayed(const Duration(milliseconds: 100));
await Future<void>.delayed(const Duration(milliseconds: 100));
return isRunningOnPlatformThread;
});
expect(isPlatThread, isTrue);
});
test('PlatformIsolate runOnPlatformThread, retains state', () async {
await runOnPlatformThread(() => ++counter);
await Future<void>.delayed(const Duration(milliseconds: 100));
await runOnPlatformThread(() => ++counter);
await Future<void>.delayed(const Duration(milliseconds: 100));
await runOnPlatformThread(() => ++counter);
await Future<void>.delayed(const Duration(milliseconds: 100));
final int counterValue = await runOnPlatformThread(() => counter);
expect(counterValue, 3);
});
test('PlatformIsolate runOnPlatformThread, concurrent jobs', () async {
final Future<int> future1 = runOnPlatformThread(() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
return 1;
});
final Future<int> future2 = runOnPlatformThread(() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
return 2;
});
final Future<int> future3 = runOnPlatformThread(() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
return 3;
});
expect(await future1, 1);
expect(await future2, 2);
expect(await future3, 3);
});
test('PlatformIsolate runOnPlatformThread, send and receive messages',
() async {
// Send numbers 1 to 10 to the platform isolate. The platform isolate
// multiplies them by 100 and sends them back.
int sum = 0;
final RawReceivePort recvPort = RawReceivePort((Object message) {
if (message is SendPort) {
for (int i = 1; i <= 10; ++i) {
message.send(i);
}
} else {
sum += message as int;
}
});
final SendPort sendPort = recvPort.sendPort;
await runOnPlatformThread(() async {
final Completer<void> completer = Completer<void>();
final RawReceivePort recvPort = RawReceivePort((Object message) {
sendPort.send((message as int) * 100);
if (message == 10) {
completer.complete();
}
});
sendPort.send(recvPort.sendPort);
await completer.future;
recvPort.close();
});
expect(sum, 5500); // sum(1 to 10) * 100
recvPort.close();
});
test('PlatformIsolate runOnPlatformThread, throws', () async {
bool throws = false;
try {
await runOnPlatformThread(() => throw 'Oh no!');
} catch (error) {
expect(error, 'Oh no!');
throws = true;
}
expect(throws, true);
});
test('PlatformIsolate runOnPlatformThread, async throws', () async {
bool throws = false;
try {
await runOnPlatformThread(() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
await Future<void>.delayed(const Duration(milliseconds: 100));
await Future<void>.delayed(const Duration(milliseconds: 100));
throw 'Oh no!';
});
} catch (error) {
expect(error, 'Oh no!');
throws = true;
}
expect(throws, true);
});
test('PlatformIsolate runOnPlatformThread, disabled on helper isolates',
() async {
await Isolate.run(() {
expect(() => runOnPlatformThread(() => print('Unreachable')), throws);
});
});
test('PlatformIsolate runOnPlatformThread, on platform isolate', () async {
final int result = await runOnPlatformThread(() => runOnPlatformThread(
() => runOnPlatformThread(() => runOnPlatformThread(() => 123))));
expect(result, 123);
});
test('PlatformIsolate runOnPlatformThread, exit disabled', () async {
await runOnPlatformThread(() => expect(() => Isolate.exit(), throws));
});
test('PlatformIsolate runOnPlatformThread, unsendable object', () async {
bool throws = false;
try {
await runOnPlatformThread(() => ReceivePort());
} catch (error) {
throws = true;
}
expect(throws, true);
});
test('PlatformIsolate runOnPlatformThread, unsendable object async',
() async {
bool throws = false;
try {
await runOnPlatformThread(() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
return ReceivePort();
});
} catch (error) {
throws = true;
}
expect(throws, true);
});
test('PlatformIsolate runOnPlatformThread, throws unsendable', () async {
bool throws = false;
try {
await runOnPlatformThread(() => throw ReceivePort());
} catch (error) {
throws = true;
}
expect(throws, true);
});
test('PlatformIsolate runOnPlatformThread, throws unsendable async',
() async {
bool throws = false;
try {
await runOnPlatformThread(() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
throw ReceivePort();
});
} catch (error) {
throws = true;
}
expect(throws, true);
});
}

View File

@@ -72,7 +72,8 @@ std::unique_ptr<AutoIsolateShutdown> RunDartCodeInIsolateOnUITaskRunner(
const std::vector<std::string>& args,
const std::string& kernel_file_path,
fml::WeakPtr<IOManager> io_manager,
const std::shared_ptr<VolatilePathTracker>& volatile_path_tracker) {
const std::shared_ptr<VolatilePathTracker>& volatile_path_tracker,
std::unique_ptr<PlatformConfiguration> platform_configuration) {
FML_CHECK(task_runners.GetUITaskRunner()->RunsTasksOnCurrentThread());
if (!vm_ref) {
@@ -129,7 +130,7 @@ std::unique_ptr<AutoIsolateShutdown> RunDartCodeInIsolateOnUITaskRunner(
DartIsolate::CreateRunningRootIsolate(
settings, // settings
vm_data->GetIsolateSnapshot(), // isolate snapshot
nullptr, // platform configuration
std::move(platform_configuration), // platform configuration
DartIsolate::Flags{}, // flags
nullptr, // root isolate create callback
settings.isolate_create_callback, // isolate create callback
@@ -159,14 +160,16 @@ std::unique_ptr<AutoIsolateShutdown> RunDartCodeInIsolate(
const std::vector<std::string>& args,
const std::string& kernel_file_path,
fml::WeakPtr<IOManager> io_manager,
std::shared_ptr<VolatilePathTracker> volatile_path_tracker) {
std::shared_ptr<VolatilePathTracker> volatile_path_tracker,
std::unique_ptr<PlatformConfiguration> platform_configuration) {
std::unique_ptr<AutoIsolateShutdown> result;
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(
task_runners.GetUITaskRunner(), fml::MakeCopyable([&]() mutable {
result = RunDartCodeInIsolateOnUITaskRunner(
vm_ref, settings, task_runners, entrypoint, args, kernel_file_path,
io_manager, volatile_path_tracker);
io_manager, volatile_path_tracker,
std::move(platform_configuration));
latch.Signal();
}));
latch.Wait();

View File

@@ -54,7 +54,8 @@ void RunDartCodeInIsolate(
const std::vector<std::string>& args,
const std::string& fixtures_path,
fml::WeakPtr<IOManager> io_manager = {},
std::shared_ptr<VolatilePathTracker> volatile_path_tracker = nullptr);
std::shared_ptr<VolatilePathTracker> volatile_path_tracker = nullptr,
std::unique_ptr<PlatformConfiguration> platform_configuration = nullptr);
std::unique_ptr<AutoIsolateShutdown> RunDartCodeInIsolate(
DartVMRef& vm_ref,
@@ -64,7 +65,8 @@ std::unique_ptr<AutoIsolateShutdown> RunDartCodeInIsolate(
const std::vector<std::string>& args,
const std::string& fixtures_path,
fml::WeakPtr<IOManager> io_manager = {},
std::shared_ptr<VolatilePathTracker> volatile_path_tracker = nullptr);
std::shared_ptr<VolatilePathTracker> volatile_path_tracker = nullptr,
std::unique_ptr<PlatformConfiguration> platform_configuration = nullptr);
} // namespace testing
} // namespace flutter

View File

@@ -39,6 +39,12 @@ bool CheckAndHandleError(Dart_Handle handle) {
ReportUnhandledException(exception_handle, stack_trace_handle);
return true;
} else if (Dart_IsFatalError(handle)) {
// An UnwindError designed to shutdown isolates. This is thrown by
// Isolate.exit. This is ordinary API usage, not actually an error, so
// silently shut down the isolate. The actual isolate shutdown happens in
// DartMessageHandler::UnhandledError.
return true;
} else if (Dart_IsError(handle)) {
tonic::Log("Dart Error: %s", Dart_GetError(handle));
return true;