[fuchsia] Remove Dart CF v1 runner. (flutter/engine#36029)

This commit is contained in:
Alexander Biggs
2022-09-13 14:58:44 -07:00
committed by GitHub
parent 805d507d5e
commit a9dd7de3d4
22 changed files with 225 additions and 1051 deletions

View File

@@ -2111,12 +2111,10 @@ FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/builtin_libraries.cc
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/builtin_libraries.h
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/dart_component_controller.cc
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/dart_component_controller.h
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/dart_component_controller_v2.cc
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/dart_component_controller_v2.h
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/dart_runner.cc
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/dart_runner.h
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/dart_test_component_controller_v2.cc
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/dart_test_component_controller_v2.h
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/dart_test_component_controller.cc
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/dart_test_component_controller.h
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/embedder/builtin.dart
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/embedder/script_runner_snapshot.dart
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/embedder/shim.dart
@@ -2126,19 +2124,11 @@ FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/embedder/snapshot.h
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/kernel/libraries.json
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/logging.h
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/main.cc
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/meta/aot_product_runtime
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/meta/aot_runtime
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/meta/common.shard.cml
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/meta/dart_aot_product_runner.cml
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/meta/dart_aot_product_runner.cmx
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/meta/dart_aot_runner.cml
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/meta/dart_aot_runner.cmx
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/meta/dart_jit_product_runner.cml
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/meta/dart_jit_product_runner.cmx
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/meta/dart_jit_runner.cml
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/meta/dart_jit_runner.cmx
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/meta/jit_product_runtime
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/meta/jit_runtime
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/service_isolate.cc
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/service_isolate.h
FILE: ../../../flutter/shell/platform/fuchsia/dart_runner/vmservice/empty.dart

View File

@@ -20,12 +20,10 @@ template("runner_sources") {
"builtin_libraries.h",
"dart_component_controller.cc",
"dart_component_controller.h",
"dart_component_controller_v2.cc",
"dart_component_controller_v2.h",
"dart_runner.cc",
"dart_runner.h",
"dart_test_component_controller_v2.cc",
"dart_test_component_controller_v2.h",
"dart_test_component_controller.cc",
"dart_test_component_controller.h",
"logging.h",
"service_isolate.cc",
"service_isolate.h",
@@ -179,7 +177,6 @@ template("aot_runner_package") {
binary = "dart_aot${product_suffix}_runner"
cmx_file = rebase_path("meta/dart_aot${product_suffix}_runner.cmx")
cml_file = rebase_path("meta/dart_aot${product_suffix}_runner.cml")
libraries = common_libs
@@ -240,7 +237,6 @@ template("jit_runner_package") {
binary = "dart_jit${product_suffix}_runner"
cmx_file = rebase_path("meta/dart_jit${product_suffix}_runner.cmx")
cml_file = rebase_path("meta/dart_jit${product_suffix}_runner.cml")
libraries = common_libs

View File

@@ -1,3 +1,4 @@
# Dart Application Runner
An Runner that runs Dart programs.
Implements the `fuchsia::component::runner::ComponentRunner` FIDL interface to
launch and run Dart applications that don't use Flutter.

View File

@@ -5,6 +5,7 @@
#include "dart_component_controller.h"
#include <fcntl.h>
#include <fml/logging.h>
#include <lib/async-loop/loop.h>
#include <lib/async/cpp/task.h>
#include <lib/async/default.h>
@@ -43,10 +44,14 @@ using tonic::ToDart;
namespace dart_runner {
constexpr char kDataKey[] = "data";
namespace {
constexpr char kTmpPath[] = "/tmp";
constexpr zx::duration kIdleWaitDuration = zx::sec(2);
constexpr zx::duration kIdleNotifyDuration = zx::msec(500);
constexpr zx::duration kIdleSlack = zx::sec(1);
void AfterTask(async_loop_t*, void*) {
tonic::DartMicrotaskQueue* queue =
tonic::DartMicrotaskQueue::GetForCurrentThread();
@@ -67,9 +72,9 @@ constexpr async_loop_config_t kLoopConfig = {
.epilogue = &AfterTask,
};
// Find the last path component.
// Find the last path of the component.
// fuchsia-pkg://fuchsia.com/hello_dart#meta/hello_dart.cmx -> hello_dart.cmx
std::string GetLabelFromURL(const std::string& url) {
std::string GetLabelFromUrl(const std::string& url) {
for (size_t i = url.length() - 1; i > 0; i--) {
if (url[i] == '/') {
return url.substr(i + 1, url.length() - 1);
@@ -78,46 +83,60 @@ std::string GetLabelFromURL(const std::string& url) {
return url;
}
// Find the name of the component.
// fuchsia-pkg://fuchsia.com/hello_dart#meta/hello_dart.cm -> hello_dart
std::string GetComponentNameFromUrl(const std::string& url) {
const std::string label = GetLabelFromUrl(url);
for (size_t i = 0; i < label.length(); ++i) {
if (label[i] == '.') {
return label.substr(0, i);
}
}
return label;
}
} // namespace
DartComponentController::DartComponentController(
fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
fuchsia::component::runner::ComponentStartInfo start_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::sys::ComponentController> controller)
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
controller)
: loop_(new async::Loop(&kLoopConfig)),
label_(GetLabelFromURL(package.resolved_url)),
url_(std::move(package.resolved_url)),
package_(std::move(package)),
startup_info_(std::move(startup_info)),
label_(GetLabelFromUrl(start_info.resolved_url())),
url_(std::move(start_info.resolved_url())),
runner_incoming_services_(runner_incoming_services),
start_info_(std::move(start_info)),
binding_(this) {
for (size_t i = 0; i < startup_info_.program_metadata->size(); ++i) {
auto pg = startup_info_.program_metadata->at(i);
if (pg.key.compare(kDataKey) == 0) {
data_path_ = "pkg/" + pg.value;
}
}
if (data_path_.empty()) {
FX_LOGF(ERROR, LOG_TAG, "Could not find a /pkg/data directory for %s",
url_.c_str());
return;
}
// TODO(fxb/84537): This data path is configured based how we build Flutter
// applications in tree currently, but the way we build the Flutter
// application may change. We should avoid assuming the data path and let the
// CML file specify this data path instead.
const std::string component_name = GetComponentNameFromUrl(url_);
data_path_ = "pkg/data/" + component_name;
if (controller.is_valid()) {
binding_.Bind(std::move(controller));
binding_.set_error_handler([this](zx_status_t status) { Kill(); });
} else {
FX_LOG(ERROR, LOG_TAG,
"Fuchsia component controller endpoint is not valid.");
}
zx_status_t status =
zx_status_t idle_timer_status =
zx::timer::create(ZX_TIMER_SLACK_LATE, ZX_CLOCK_MONOTONIC, &idle_timer_);
if (status != ZX_OK) {
if (idle_timer_status != ZX_OK) {
FX_LOGF(INFO, LOG_TAG, "Idle timer creation failed: %s",
zx_status_get_string(status));
zx_status_get_string(idle_timer_status));
} else {
idle_wait_.set_object(idle_timer_.get());
idle_wait_.set_trigger(ZX_TIMER_SIGNALED);
idle_wait_.Begin(async_get_default_dispatcher());
}
// Close the runtime_dir channel if we don't intend to serve it. Otherwise any
// access to the runtime_dir will hang forever.
start_info_.clear_runtime_dir();
}
DartComponentController::~DartComponentController() {
@@ -125,27 +144,25 @@ DartComponentController::~DartComponentController() {
fdio_ns_destroy(namespace_);
namespace_ = nullptr;
}
close(stdoutfd_);
close(stderrfd_);
close(stdout_fd_);
close(stderr_fd_);
}
bool DartComponentController::Setup() {
bool DartComponentController::SetUp() {
// Name the thread after the url of the component being launched.
zx::thread::self()->set_property(ZX_PROP_NAME, label_.c_str(), label_.size());
Dart_SetThreadName(label_.c_str());
if (!SetupNamespace()) {
if (!CreateAndBindNamespace()) {
return false;
}
if (SetupFromAppSnapshot()) {
if (SetUpFromAppSnapshot()) {
FX_LOGF(INFO, LOG_TAG, "%s is running from an app snapshot", url_.c_str());
} else if (SetupFromKernel()) {
} else if (SetUpFromKernel()) {
FX_LOGF(INFO, LOG_TAG, "%s is running from kernel", url_.c_str());
} else {
FX_LOGF(ERROR, LOG_TAG,
"Could not find a program in %s. Was data specified"
" correctly in the component manifest?",
FX_LOGF(ERROR, LOG_TAG, "Failed to set up component controller for %s.",
url_.c_str());
return false;
}
@@ -153,40 +170,45 @@ bool DartComponentController::Setup() {
return true;
}
constexpr char kTmpPath[] = "/tmp";
constexpr char kServiceRootPath[] = "/svc";
bool DartComponentController::SetupNamespace() {
fuchsia::sys::FlatNamespace* flat = &startup_info_.flat_namespace;
zx_status_t status = fdio_ns_create(&namespace_);
if (status != ZX_OK) {
FX_LOG(ERROR, LOG_TAG, "Failed to create namespace");
bool DartComponentController::CreateAndBindNamespace() {
if (!start_info_.has_ns()) {
FX_LOG(ERROR, LOG_TAG, "Component start info does not have a namespace.");
return false;
}
const zx_status_t ns_create_status = fdio_ns_create(&namespace_);
if (ns_create_status != ZX_OK) {
FX_LOGF(ERROR, LOG_TAG, "Failed to create namespace: %s",
zx_status_get_string(ns_create_status));
}
dart_utils::RunnerTemp::SetupComponent(namespace_);
for (size_t i = 0; i < flat->paths.size(); ++i) {
if (flat->paths.at(i) == kTmpPath) {
// Bind each directory in start_info's namespace to the controller's namespace
// instance.
for (auto& ns_entry : *start_info_.mutable_ns()) {
// TODO(akbiggs): Under what circumstances does a namespace entry not have a
// path or directory? Should we log an error for these?
if (!ns_entry.has_path() || !ns_entry.has_directory()) {
continue;
}
if (ns_entry.path() == kTmpPath) {
// /tmp is covered by the local memfs.
continue;
}
zx::channel dir;
if (flat->paths.at(i) == kServiceRootPath) {
// clone /svc so component_context can still use it below
dir = zx::channel(fdio_service_clone(flat->directories.at(i).get()));
} else {
dir = std::move(flat->directories.at(i));
}
// We move ownership of the directory & path since RAII is used to keep
// the handle open.
fidl::InterfaceHandle<::fuchsia::io::Directory> dir =
std::move(*ns_entry.mutable_directory());
const std::string path = std::move(*ns_entry.mutable_path());
zx_handle_t dir_handle = dir.release();
const char* path = flat->paths.at(i).data();
status = fdio_ns_bind(namespace_, path, dir_handle);
if (status != ZX_OK) {
const zx_status_t ns_bind_status =
fdio_ns_bind(namespace_, path.c_str(), dir.TakeChannel().release());
if (ns_bind_status != ZX_OK) {
FX_LOGF(ERROR, LOG_TAG, "Failed to bind %s to namespace: %s",
flat->paths.at(i).c_str(), zx_status_get_string(status));
zx_handle_close(dir_handle);
path.c_str(), zx_status_get_string(ns_bind_status));
return false;
}
}
@@ -194,7 +216,7 @@ bool DartComponentController::SetupNamespace() {
return true;
}
bool DartComponentController::SetupFromKernel() {
bool DartComponentController::SetUpFromKernel() {
dart_utils::MappedResource manifest;
if (!dart_utils::MappedResource::LoadFromNamespace(
namespace_, data_path_ + "/app.dilplist", manifest)) {
@@ -236,13 +258,14 @@ bool DartComponentController::SetupFromKernel() {
dart_utils::MappedResource kernel;
if (!dart_utils::MappedResource::LoadFromNamespace(namespace_, path,
kernel)) {
FX_LOGF(ERROR, LOG_TAG, "Failed to find kernel: %s", path.c_str());
FX_LOGF(ERROR, LOG_TAG, "Cannot load kernel from namespace: %s",
path.c_str());
Dart_ExitScope();
return false;
}
library = Dart_LoadLibraryFromKernel(kernel.address(), kernel.size());
if (Dart_IsError(library)) {
FX_LOGF(ERROR, LOG_TAG, "Failed to load kernel: %s",
FX_LOGF(ERROR, LOG_TAG, "Cannot load library from kernel: %s",
Dart_GetError(library));
Dart_ExitScope();
return false;
@@ -263,7 +286,7 @@ bool DartComponentController::SetupFromKernel() {
return true;
}
bool DartComponentController::SetupFromAppSnapshot() {
bool DartComponentController::SetUpFromAppSnapshot() {
#if !defined(AOT_RUNTIME)
return false;
#else
@@ -292,22 +315,6 @@ bool DartComponentController::SetupFromAppSnapshot() {
#endif // defined(AOT_RUNTIME)
}
int DartComponentController::SetupFileDescriptor(
fuchsia::sys::FileDescriptorPtr fd) {
if (!fd) {
return -1;
}
// fd->handle1 and fd->handle2 are no longer used.
int outfd = -1;
zx_status_t status = fdio_fd_create(fd->handle0.release(), &outfd);
if (status != ZX_OK) {
FX_LOGF(ERROR, LOG_TAG, "Failed to extract output fd: %s",
zx_status_get_string(status));
return -1;
}
return outfd;
}
bool DartComponentController::CreateIsolate(
const uint8_t* isolate_snapshot_data,
const uint8_t* isolate_snapshot_instructions) {
@@ -316,6 +323,7 @@ bool DartComponentController::CreateIsolate(
// TODO(dart_runner): Pass if we start using tonic's loader.
intptr_t namespace_fd = -1;
// Freed in IsolateShutdownCallback.
auto state = new std::shared_ptr<tonic::DartState>(new tonic::DartState(
namespace_fd, [this](Dart_Handle result) { MessageEpilogue(result); }));
@@ -344,49 +352,49 @@ bool DartComponentController::CreateIsolate(
void DartComponentController::Run() {
async::PostTask(loop_->dispatcher(), [loop = loop_.get(), app = this] {
if (!app->Main()) {
if (!app->RunDartMain()) {
loop->Quit();
}
});
loop_->Run();
SendReturnCode();
if (binding_.is_bound()) {
// From the documentation for ComponentController, ZX_OK should be sent when
// the ComponentController receives a termination request. However, if the
// component exited with a non-zero return code, we indicate this by sending
// an INTERNAL epitaph instead.
//
// TODO(fxb/86666): Communicate return code from the ComponentController
// once v2 has support.
if (return_code_ == 0) {
binding_.Close(ZX_OK);
} else {
FML_LOG(ERROR) << "Component exited with non-zero return code: "
<< return_code_;
binding_.Close(zx_status_t(fuchsia::component::Error::INTERNAL));
}
}
}
bool DartComponentController::Main() {
bool DartComponentController::RunDartMain() {
FML_CHECK(namespace_ != nullptr);
Dart_EnterScope();
tonic::DartMicrotaskQueue::StartForCurrentThread();
std::vector<std::string> arguments =
startup_info_.launch_info.arguments.value_or(std::vector<std::string>());
stdoutfd_ = SetupFileDescriptor(std::move(startup_info_.launch_info.out));
stderrfd_ = SetupFileDescriptor(std::move(startup_info_.launch_info.err));
auto directory_request =
std::move(startup_info_.launch_info.directory_request);
auto* flat = &startup_info_.flat_namespace;
std::unique_ptr<sys::ServiceDirectory> svc;
for (size_t i = 0; i < flat->paths.size(); ++i) {
zx::channel dir;
if (flat->paths.at(i) == kServiceRootPath) {
svc = std::make_unique<sys::ServiceDirectory>(
std::move(flat->directories.at(i)));
break;
}
}
if (!svc) {
FX_LOG(ERROR, LOG_TAG, "Unable to get /svc for dart component");
return false;
}
fidl::InterfaceHandle<fuchsia::sys::Environment> environment;
svc->Connect(environment.NewRequest());
// TODO(fxb/88384): Create a file descriptor for each component that is
// launched and listen for anything that is written to the component. When
// something is written to the component, forward that message along to the
// Fuchsia logger and decorate it with the tag that it came from the
// component.
stdout_fd_ = fileno(stdout);
stderr_fd_ = fileno(stderr);
fidl::InterfaceRequest<fuchsia::io::Directory> outgoing_dir =
std::move(*start_info_.mutable_outgoing_dir());
InitBuiltinLibrariesForIsolate(
url_, namespace_, stdoutfd_, stderrfd_, std::move(environment),
std::move(directory_request), false /* service_isolate */);
namespace_ = nullptr;
url_, namespace_, stdout_fd_, stderr_fd_, nullptr /* environment */,
outgoing_dir.TakeChannel(), false /* service_isolate */);
Dart_ExitScope();
Dart_ExitIsolate();
@@ -401,12 +409,12 @@ bool DartComponentController::Main() {
Dart_EnterIsolate(isolate_);
Dart_EnterScope();
// TODO(fxb/88383): Support argument passing.
Dart_Handle corelib = Dart_LookupLibrary(ToDart("dart:core"));
Dart_Handle string_type =
Dart_GetNonNullableType(corelib, ToDart("String"), 0, NULL);
Dart_Handle dart_arguments = Dart_NewListOfTypeFilled(
string_type, Dart_EmptyString(), arguments.size());
Dart_Handle dart_arguments =
Dart_NewListOfTypeFilled(string_type, Dart_EmptyString(), 0);
if (Dart_IsError(dart_arguments)) {
FX_LOGF(ERROR, LOG_TAG, "Failed to allocate Dart arguments list: %s",
@@ -414,10 +422,6 @@ bool DartComponentController::Main() {
Dart_ExitScope();
return false;
}
for (size_t i = 0; i < arguments.size(); i++) {
tonic::CheckAndHandleError(
Dart_ListSetAt(dart_arguments, i, ToDart(arguments.at(i))));
}
Dart_Handle user_main = Dart_GetField(Dart_RootLibrary(), ToDart("main"));
@@ -478,19 +482,6 @@ void DartComponentController::Kill() {
}
}
void DartComponentController::Detach() {
binding_.set_error_handler([](zx_status_t status) {});
}
void DartComponentController::SendReturnCode() {
binding_.events().OnTerminated(return_code_,
fuchsia::sys::TerminationReason::EXITED);
}
const zx::duration kIdleWaitDuration = zx::sec(2);
const zx::duration kIdleNotifyDuration = zx::msec(500);
const zx::duration kIdleSlack = zx::sec(1);
void DartComponentController::MessageEpilogue(Dart_Handle result) {
auto dart_state = tonic::DartState::Current();
// If the Dart program has set a return code, then it is intending to shut
@@ -519,6 +510,10 @@ void DartComponentController::MessageEpilogue(Dart_Handle result) {
}
}
void DartComponentController::Stop() {
Kill();
}
void DartComponentController::OnIdleTimer(async_dispatcher_t* dispatcher,
async::WaitBase* wait,
zx_status_t status,

View File

@@ -7,6 +7,7 @@
#include <memory>
#include <fuchsia/component/runner/cpp/fidl.h>
#include <fuchsia/sys/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async/cpp/wait.h>
@@ -21,34 +22,46 @@
namespace dart_runner {
class DartComponentController : public fuchsia::sys::ComponentController {
/// Starts a Dart component written in CFv2.
class DartComponentController
: public fuchsia::component::runner::ComponentController {
public:
DartComponentController(
fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
fuchsia::component::runner::ComponentStartInfo start_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::sys::ComponentController> controller);
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
controller);
~DartComponentController() override;
bool Setup();
/// Sets up the controller.
///
/// This should be called before |Run|.
bool SetUp();
/// Runs the Dart component in a task, sending the return code back to
/// the Fuchsia component controller.
///
/// This should be called after |SetUp|.
void Run();
bool Main();
void SendReturnCode();
private:
bool SetupNamespace();
/// Helper for actually running the Dart main. Returns true if successful,
/// false otherwise.
bool RunDartMain();
bool SetupFromKernel();
bool SetupFromAppSnapshot();
/// Creates and binds the namespace for this component. Returns true if
/// successful, false otherwise.
bool CreateAndBindNamespace();
bool SetUpFromKernel();
bool SetUpFromAppSnapshot();
bool CreateIsolate(const uint8_t* isolate_snapshot_data,
const uint8_t* isolate_snapshot_instructions);
int SetupFileDescriptor(fuchsia::sys::FileDescriptorPtr fd);
// |ComponentController|
void Kill() override;
void Detach() override;
void Stop() override;
// Idle notification.
void MessageEpilogue(Dart_Handle result);
@@ -60,18 +73,20 @@ class DartComponentController : public fuchsia::sys::ComponentController {
// The loop must be the first declared member so that it gets destroyed after
// binding_ which expects the existence of a loop.
std::unique_ptr<async::Loop> loop_;
std::string label_;
std::string url_;
fuchsia::sys::Package package_;
fuchsia::sys::StartupInfo startup_info_;
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services_;
std::string data_path_;
fidl::Binding<fuchsia::sys::ComponentController> binding_;
std::unique_ptr<sys::ComponentContext> context_;
fuchsia::component::runner::ComponentStartInfo start_info_;
fidl::Binding<fuchsia::component::runner::ComponentController> binding_;
fdio_ns_t* namespace_ = nullptr;
int stdoutfd_ = -1;
int stderrfd_ = -1;
int stdout_fd_ = -1;
int stderr_fd_ = -1;
dart_utils::ElfSnapshot elf_snapshot_; // AOT snapshot
dart_utils::MappedResource isolate_snapshot_data_; // JIT snapshot
dart_utils::MappedResource isolate_snapshot_instructions_; // JIT snapshot

View File

@@ -1,546 +0,0 @@
// 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 "dart_component_controller_v2.h"
#include <fcntl.h>
#include <fml/logging.h>
#include <lib/async-loop/loop.h>
#include <lib/async/cpp/task.h>
#include <lib/async/default.h>
#include <lib/fdio/directory.h>
#include <lib/fdio/fd.h>
#include <lib/fdio/namespace.h>
#include <lib/fidl/cpp/string.h>
#include <lib/sys/cpp/service_directory.h>
#include <lib/syslog/global.h>
#include <lib/zx/clock.h>
#include <lib/zx/thread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <zircon/status.h>
#include <regex>
#include <utility>
#include "runtime/dart/utils/files.h"
#include "runtime/dart/utils/handle_exception.h"
#include "runtime/dart/utils/inlines.h"
#include "runtime/dart/utils/tempfs.h"
#include "third_party/dart/runtime/include/dart_tools_api.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_message_handler.h"
#include "third_party/tonic/dart_microtask_queue.h"
#include "third_party/tonic/dart_state.h"
#include "third_party/tonic/logging/dart_error.h"
#include "third_party/tonic/logging/dart_invoke.h"
#include "builtin_libraries.h"
#include "logging.h"
using tonic::ToDart;
namespace dart_runner {
namespace {
constexpr char kTmpPath[] = "/tmp";
constexpr zx::duration kIdleWaitDuration = zx::sec(2);
constexpr zx::duration kIdleNotifyDuration = zx::msec(500);
constexpr zx::duration kIdleSlack = zx::sec(1);
void AfterTask(async_loop_t*, void*) {
tonic::DartMicrotaskQueue* queue =
tonic::DartMicrotaskQueue::GetForCurrentThread();
// Verify that the queue exists, as this method could have been called back as
// part of the exit routine, after the destruction of the microtask queue.
if (queue) {
queue->RunMicrotasks();
}
}
constexpr async_loop_config_t kLoopConfig = {
.default_accessors =
{
.getter = async_get_default_dispatcher,
.setter = async_set_default_dispatcher,
},
.make_default_for_current_thread = true,
.epilogue = &AfterTask,
};
// Find the last path of the component.
// fuchsia-pkg://fuchsia.com/hello_dart#meta/hello_dart.cmx -> hello_dart.cmx
std::string GetLabelFromUrl(const std::string& url) {
for (size_t i = url.length() - 1; i > 0; i--) {
if (url[i] == '/') {
return url.substr(i + 1, url.length() - 1);
}
}
return url;
}
// Find the name of the component.
// fuchsia-pkg://fuchsia.com/hello_dart#meta/hello_dart.cm -> hello_dart
std::string GetComponentNameFromUrl(const std::string& url) {
const std::string label = GetLabelFromUrl(url);
for (size_t i = 0; i < label.length(); ++i) {
if (label[i] == '.') {
return label.substr(0, i);
}
}
return label;
}
} // namespace
DartComponentControllerV2::DartComponentControllerV2(
fuchsia::component::runner::ComponentStartInfo start_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
controller)
: loop_(new async::Loop(&kLoopConfig)),
label_(GetLabelFromUrl(start_info.resolved_url())),
url_(std::move(start_info.resolved_url())),
runner_incoming_services_(runner_incoming_services),
start_info_(std::move(start_info)),
binding_(this) {
// TODO(fxb/84537): This data path is configured based how we build Flutter
// applications in tree currently, but the way we build the Flutter
// application may change. We should avoid assuming the data path and let the
// CML file specify this data path instead.
const std::string component_name = GetComponentNameFromUrl(url_);
data_path_ = "pkg/data/" + component_name;
if (controller.is_valid()) {
binding_.Bind(std::move(controller));
binding_.set_error_handler([this](zx_status_t status) { Kill(); });
} else {
FX_LOG(ERROR, LOG_TAG,
"Fuchsia component controller endpoint is not valid.");
}
zx_status_t idle_timer_status =
zx::timer::create(ZX_TIMER_SLACK_LATE, ZX_CLOCK_MONOTONIC, &idle_timer_);
if (idle_timer_status != ZX_OK) {
FX_LOGF(INFO, LOG_TAG, "Idle timer creation failed: %s",
zx_status_get_string(idle_timer_status));
} else {
idle_wait_.set_object(idle_timer_.get());
idle_wait_.set_trigger(ZX_TIMER_SIGNALED);
idle_wait_.Begin(async_get_default_dispatcher());
}
// Close the runtime_dir channel if we don't intend to serve it. Otherwise any
// access to the runtime_dir will hang forever.
start_info_.clear_runtime_dir();
}
DartComponentControllerV2::~DartComponentControllerV2() {
if (namespace_) {
fdio_ns_destroy(namespace_);
namespace_ = nullptr;
}
close(stdout_fd_);
close(stderr_fd_);
}
bool DartComponentControllerV2::SetUp() {
// Name the thread after the url of the component being launched.
zx::thread::self()->set_property(ZX_PROP_NAME, label_.c_str(), label_.size());
Dart_SetThreadName(label_.c_str());
if (!CreateAndBindNamespace()) {
return false;
}
if (SetUpFromAppSnapshot()) {
FX_LOGF(INFO, LOG_TAG, "%s is running from an app snapshot", url_.c_str());
} else if (SetUpFromKernel()) {
FX_LOGF(INFO, LOG_TAG, "%s is running from kernel", url_.c_str());
} else {
FX_LOGF(ERROR, LOG_TAG, "Failed to set up component controller for %s.",
url_.c_str());
return false;
}
return true;
}
bool DartComponentControllerV2::CreateAndBindNamespace() {
if (!start_info_.has_ns()) {
FX_LOG(ERROR, LOG_TAG, "Component start info does not have a namespace.");
return false;
}
const zx_status_t ns_create_status = fdio_ns_create(&namespace_);
if (ns_create_status != ZX_OK) {
FX_LOGF(ERROR, LOG_TAG, "Failed to create namespace: %s",
zx_status_get_string(ns_create_status));
}
dart_utils::RunnerTemp::SetupComponent(namespace_);
// Bind each directory in start_info's namespace to the controller's namespace
// instance.
for (auto& ns_entry : *start_info_.mutable_ns()) {
// TODO(akbiggs): Under what circumstances does a namespace entry not have a
// path or directory? Should we log an error for these?
if (!ns_entry.has_path() || !ns_entry.has_directory()) {
continue;
}
if (ns_entry.path() == kTmpPath) {
// /tmp is covered by the local memfs.
continue;
}
// We move ownership of the directory & path since RAII is used to keep
// the handle open.
fidl::InterfaceHandle<::fuchsia::io::Directory> dir =
std::move(*ns_entry.mutable_directory());
const std::string path = std::move(*ns_entry.mutable_path());
const zx_status_t ns_bind_status =
fdio_ns_bind(namespace_, path.c_str(), dir.TakeChannel().release());
if (ns_bind_status != ZX_OK) {
FX_LOGF(ERROR, LOG_TAG, "Failed to bind %s to namespace: %s",
path.c_str(), zx_status_get_string(ns_bind_status));
return false;
}
}
return true;
}
bool DartComponentControllerV2::SetUpFromKernel() {
dart_utils::MappedResource manifest;
if (!dart_utils::MappedResource::LoadFromNamespace(
namespace_, data_path_ + "/app.dilplist", manifest)) {
return false;
}
if (!dart_utils::MappedResource::LoadFromNamespace(
nullptr, "/pkg/data/isolate_core_snapshot_data.bin",
isolate_snapshot_data_)) {
return false;
}
if (!dart_utils::MappedResource::LoadFromNamespace(
nullptr, "/pkg/data/isolate_core_snapshot_instructions.bin",
isolate_snapshot_instructions_, true /* executable */)) {
return false;
}
if (!CreateIsolate(isolate_snapshot_data_.address(),
isolate_snapshot_instructions_.address())) {
return false;
}
Dart_EnterScope();
std::string str(reinterpret_cast<const char*>(manifest.address()),
manifest.size());
Dart_Handle library = Dart_Null();
for (size_t start = 0; start < manifest.size();) {
size_t end = str.find("\n", start);
if (end == std::string::npos) {
FX_LOG(ERROR, LOG_TAG, "Malformed manifest");
Dart_ExitScope();
return false;
}
std::string path = data_path_ + "/" + str.substr(start, end - start);
start = end + 1;
dart_utils::MappedResource kernel;
if (!dart_utils::MappedResource::LoadFromNamespace(namespace_, path,
kernel)) {
FX_LOGF(ERROR, LOG_TAG, "Cannot load kernel from namespace: %s",
path.c_str());
Dart_ExitScope();
return false;
}
library = Dart_LoadLibraryFromKernel(kernel.address(), kernel.size());
if (Dart_IsError(library)) {
FX_LOGF(ERROR, LOG_TAG, "Cannot load library from kernel: %s",
Dart_GetError(library));
Dart_ExitScope();
return false;
}
kernel_peices_.emplace_back(std::move(kernel));
}
Dart_SetRootLibrary(library);
Dart_Handle result = Dart_FinalizeLoading(false);
if (Dart_IsError(result)) {
FX_LOGF(ERROR, LOG_TAG, "Failed to FinalizeLoading: %s",
Dart_GetError(result));
Dart_ExitScope();
return false;
}
return true;
}
bool DartComponentControllerV2::SetUpFromAppSnapshot() {
#if !defined(AOT_RUNTIME)
return false;
#else
// Load the ELF snapshot as available, and fall back to a blobs snapshot
// otherwise.
const uint8_t *isolate_data, *isolate_instructions;
if (elf_snapshot_.Load(namespace_, data_path_ + "/app_aot_snapshot.so")) {
isolate_data = elf_snapshot_.IsolateData();
isolate_instructions = elf_snapshot_.IsolateInstrs();
if (isolate_data == nullptr || isolate_instructions == nullptr) {
return false;
}
} else {
if (!dart_utils::MappedResource::LoadFromNamespace(
namespace_, data_path_ + "/isolate_snapshot_data.bin",
isolate_snapshot_data_)) {
return false;
}
if (!dart_utils::MappedResource::LoadFromNamespace(
namespace_, data_path_ + "/isolate_snapshot_instructions.bin",
isolate_snapshot_instructions_, true /* executable */)) {
return false;
}
}
return CreateIsolate(isolate_data, isolate_instructions);
#endif // defined(AOT_RUNTIME)
}
bool DartComponentControllerV2::CreateIsolate(
const uint8_t* isolate_snapshot_data,
const uint8_t* isolate_snapshot_instructions) {
// Create the isolate from the snapshot.
char* error = nullptr;
// TODO(dart_runner): Pass if we start using tonic's loader.
intptr_t namespace_fd = -1;
// Freed in IsolateShutdownCallback.
auto state = new std::shared_ptr<tonic::DartState>(new tonic::DartState(
namespace_fd, [this](Dart_Handle result) { MessageEpilogue(result); }));
isolate_ = Dart_CreateIsolateGroup(
url_.c_str(), label_.c_str(), isolate_snapshot_data,
isolate_snapshot_instructions, nullptr /* flags */, state, state, &error);
if (!isolate_) {
FX_LOGF(ERROR, LOG_TAG, "Dart_CreateIsolateGroup failed: %s", error);
return false;
}
state->get()->SetIsolate(isolate_);
tonic::DartMessageHandler::TaskDispatcher dispatcher =
[loop = loop_.get()](auto callback) {
async::PostTask(loop->dispatcher(), std::move(callback));
};
state->get()->message_handler().Initialize(dispatcher);
state->get()->SetReturnCodeCallback(
[this](uint32_t return_code) { return_code_ = return_code; });
return true;
}
void DartComponentControllerV2::Run() {
async::PostTask(loop_->dispatcher(), [loop = loop_.get(), app = this] {
if (!app->RunDartMain()) {
loop->Quit();
}
});
loop_->Run();
if (binding_.is_bound()) {
// From the documentation for ComponentController, ZX_OK should be sent when
// the ComponentController receives a termination request. However, if the
// component exited with a non-zero return code, we indicate this by sending
// an INTERNAL epitaph instead.
//
// TODO(fxb/86666): Communicate return code from the ComponentController
// once v2 has support.
if (return_code_ == 0) {
binding_.Close(ZX_OK);
} else {
FML_LOG(ERROR) << "Component exited with non-zero return code: "
<< return_code_;
binding_.Close(zx_status_t(fuchsia::component::Error::INTERNAL));
}
}
}
bool DartComponentControllerV2::RunDartMain() {
FML_CHECK(namespace_ != nullptr);
Dart_EnterScope();
tonic::DartMicrotaskQueue::StartForCurrentThread();
// TODO(fxb/88384): Create a file descriptor for each component that is
// launched and listen for anything that is written to the component. When
// something is written to the component, forward that message along to the
// Fuchsia logger and decorate it with the tag that it came from the
// component.
stdout_fd_ = fileno(stdout);
stderr_fd_ = fileno(stderr);
fidl::InterfaceRequest<fuchsia::io::Directory> outgoing_dir =
std::move(*start_info_.mutable_outgoing_dir());
InitBuiltinLibrariesForIsolate(
url_, namespace_, stdout_fd_, stderr_fd_, nullptr /* environment */,
outgoing_dir.TakeChannel(), false /* service_isolate */);
Dart_ExitScope();
Dart_ExitIsolate();
char* error = Dart_IsolateMakeRunnable(isolate_);
if (error != nullptr) {
Dart_EnterIsolate(isolate_);
Dart_ShutdownIsolate();
FX_LOGF(ERROR, LOG_TAG, "Unable to make isolate runnable: %s", error);
free(error);
return false;
}
Dart_EnterIsolate(isolate_);
Dart_EnterScope();
// TODO(fxb/88383): Support argument passing.
Dart_Handle corelib = Dart_LookupLibrary(ToDart("dart:core"));
Dart_Handle string_type =
Dart_GetNonNullableType(corelib, ToDart("String"), 0, NULL);
Dart_Handle dart_arguments =
Dart_NewListOfTypeFilled(string_type, Dart_EmptyString(), 0);
if (Dart_IsError(dart_arguments)) {
FX_LOGF(ERROR, LOG_TAG, "Failed to allocate Dart arguments list: %s",
Dart_GetError(dart_arguments));
Dart_ExitScope();
return false;
}
Dart_Handle user_main = Dart_GetField(Dart_RootLibrary(), ToDart("main"));
if (Dart_IsError(user_main)) {
FX_LOGF(ERROR, LOG_TAG,
"Failed to locate user_main in the root library: %s",
Dart_GetError(user_main));
Dart_ExitScope();
return false;
}
Dart_Handle fuchsia_lib = Dart_LookupLibrary(tonic::ToDart("dart:fuchsia"));
if (Dart_IsError(fuchsia_lib)) {
FX_LOGF(ERROR, LOG_TAG, "Failed to locate dart:fuchsia: %s",
Dart_GetError(fuchsia_lib));
Dart_ExitScope();
return false;
}
Dart_Handle main_result = tonic::DartInvokeField(
fuchsia_lib, "_runUserMainForDartRunner", {user_main, dart_arguments});
if (Dart_IsError(main_result)) {
auto dart_state = tonic::DartState::Current();
if (!dart_state->has_set_return_code()) {
// The program hasn't set a return code meaning this exit is unexpected.
FX_LOG(ERROR, LOG_TAG, Dart_GetError(main_result));
return_code_ = tonic::GetErrorExitCode(main_result);
dart_utils::HandleIfException(runner_incoming_services_, url_,
main_result);
}
Dart_ExitScope();
return false;
}
Dart_ExitScope();
return true;
}
void DartComponentControllerV2::Kill() {
if (Dart_CurrentIsolate()) {
tonic::DartMicrotaskQueue* queue =
tonic::DartMicrotaskQueue::GetForCurrentThread();
if (queue) {
queue->Destroy();
}
loop_->Quit();
// TODO(rosswang): The docs warn of threading issues if doing this again,
// but without this, attempting to shut down the isolate finalizes app
// contexts that can't tell a shutdown is in progress and so fatal.
Dart_SetMessageNotifyCallback(nullptr);
Dart_ShutdownIsolate();
}
}
void DartComponentControllerV2::MessageEpilogue(Dart_Handle result) {
auto dart_state = tonic::DartState::Current();
// If the Dart program has set a return code, then it is intending to shut
// down by way of a fatal error, and so there is no need to override
// return_code_.
if (dart_state->has_set_return_code()) {
Dart_ShutdownIsolate();
return;
}
dart_utils::HandleIfException(runner_incoming_services_, url_, result);
// Otherwise, see if there was any other error.
return_code_ = tonic::GetErrorExitCode(result);
if (return_code_ != 0) {
Dart_ShutdownIsolate();
return;
}
idle_start_ = zx::clock::get_monotonic();
zx_status_t status =
idle_timer_.set(idle_start_ + kIdleWaitDuration, kIdleSlack);
if (status != ZX_OK) {
FX_LOGF(INFO, LOG_TAG, "Idle timer set failed: %s",
zx_status_get_string(status));
}
}
void DartComponentControllerV2::Stop() {
Kill();
}
void DartComponentControllerV2::OnIdleTimer(async_dispatcher_t* dispatcher,
async::WaitBase* wait,
zx_status_t status,
const zx_packet_signal* signal) {
if ((status != ZX_OK) || !(signal->observed & ZX_TIMER_SIGNALED) ||
!Dart_CurrentIsolate()) {
// Timer closed or isolate shutdown.
return;
}
zx::time deadline = idle_start_ + kIdleWaitDuration;
zx::time now = zx::clock::get_monotonic();
if (now >= deadline) {
// No Dart message has been processed for kIdleWaitDuration: assume we'll
// stay idle for kIdleNotifyDuration.
Dart_NotifyIdle((now + kIdleNotifyDuration).get());
idle_start_ = zx::time(0);
idle_timer_.cancel(); // De-assert signal.
} else {
// Early wakeup or message pushed idle time forward: reschedule.
zx_status_t status = idle_timer_.set(deadline, kIdleSlack);
if (status != ZX_OK) {
FX_LOGF(INFO, LOG_TAG, "Idle timer set failed: %s",
zx_status_get_string(status));
}
}
wait->Begin(dispatcher); // ignore errors
}
} // namespace dart_runner

View File

@@ -1,112 +0,0 @@
// 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_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_COMPONENT_CONTROLLER_V2_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_COMPONENT_CONTROLLER_V2_H_
#include <memory>
#include <fuchsia/component/runner/cpp/fidl.h>
#include <fuchsia/sys/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async/cpp/wait.h>
#include <lib/fdio/namespace.h>
#include <lib/sys/cpp/component_context.h>
#include <lib/sys/cpp/service_directory.h>
#include <lib/zx/timer.h>
#include "lib/fidl/cpp/binding.h"
#include "runtime/dart/utils/mapped_resource.h"
#include "third_party/dart/runtime/include/dart_api.h"
namespace dart_runner {
/// Starts a Dart component written in CFv2.
class DartComponentControllerV2
: public fuchsia::component::runner::ComponentController {
public:
DartComponentControllerV2(
fuchsia::component::runner::ComponentStartInfo start_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
controller);
~DartComponentControllerV2() override;
/// Sets up the controller.
///
/// This should be called before |Run|.
bool SetUp();
/// Runs the Dart component in a task, sending the return code back to
/// the Fuchsia component controller.
///
/// This should be called after |SetUp|.
void Run();
private:
/// Helper for actually running the Dart main. Returns true if successful,
/// false otherwise.
bool RunDartMain();
/// Creates and binds the namespace for this component. Returns true if
/// successful, false otherwise.
bool CreateAndBindNamespace();
bool SetUpFromKernel();
bool SetUpFromAppSnapshot();
bool CreateIsolate(const uint8_t* isolate_snapshot_data,
const uint8_t* isolate_snapshot_instructions);
// |ComponentController|
void Kill() override;
void Stop() override;
// Idle notification.
void MessageEpilogue(Dart_Handle result);
void OnIdleTimer(async_dispatcher_t* dispatcher,
async::WaitBase* wait,
zx_status_t status,
const zx_packet_signal* signal);
// The loop must be the first declared member so that it gets destroyed after
// binding_ which expects the existence of a loop.
std::unique_ptr<async::Loop> loop_;
std::string label_;
std::string url_;
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services_;
std::string data_path_;
std::unique_ptr<sys::ComponentContext> context_;
fuchsia::component::runner::ComponentStartInfo start_info_;
fidl::Binding<fuchsia::component::runner::ComponentController> binding_;
fdio_ns_t* namespace_ = nullptr;
int stdout_fd_ = -1;
int stderr_fd_ = -1;
dart_utils::ElfSnapshot elf_snapshot_; // AOT snapshot
dart_utils::MappedResource isolate_snapshot_data_; // JIT snapshot
dart_utils::MappedResource isolate_snapshot_instructions_; // JIT snapshot
std::vector<dart_utils::MappedResource> kernel_peices_;
Dart_Isolate isolate_;
int32_t return_code_ = 0;
zx::time idle_start_{0};
zx::timer idle_timer_;
async::WaitMethod<DartComponentControllerV2,
&DartComponentControllerV2::OnIdleTimer>
idle_wait_{this};
// Disallow copy and assignment.
DartComponentControllerV2(const DartComponentControllerV2&) = delete;
DartComponentControllerV2& operator=(const DartComponentControllerV2&) =
delete;
};
} // namespace dart_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_COMPONENT_CONTROLLER_V2_H_

View File

@@ -17,8 +17,6 @@
#include <utility>
#include "dart_component_controller.h"
#include "dart_component_controller_v2.h"
#include "dart_test_component_controller_v2.h"
#include "flutter/fml/command_line.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/trace_event.h"
@@ -104,20 +102,20 @@ void IsolateGroupCleanupCallback(void* isolate_group_data) {
delete static_cast<std::shared_ptr<tonic::DartState>*>(isolate_group_data);
}
// Runs the application for a V1 component.
void RunApplicationV1(
// Runs the application for a Dart component.
void RunApplication(
DartRunner* runner,
fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
fuchsia::component::runner::ComponentStartInfo start_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
::fidl::InterfaceRequest<fuchsia::sys::ComponentController> controller) {
int64_t start = Dart_TimelineGetMicros();
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
controller) {
const int64_t start = Dart_TimelineGetMicros();
DartComponentController app(std::move(package), std::move(startup_info),
runner_incoming_services, std::move(controller));
bool success = app.Setup();
DartComponentController app(std::move(start_info), runner_incoming_services,
std::move(controller));
const bool success = app.SetUp();
int64_t end = Dart_TimelineGetMicros();
const int64_t end = Dart_TimelineGetMicros();
Dart_TimelineEvent("DartComponentController::SetUp", start, end,
Dart_Timeline_Event_Duration, 0, NULL, NULL);
if (success) {
@@ -129,43 +127,18 @@ void RunApplicationV1(
}
}
// Runs the application for a V2 component.
void RunApplicationV2(
DartRunner* runner,
fuchsia::component::runner::ComponentStartInfo start_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
controller) {
const int64_t start = Dart_TimelineGetMicros();
DartComponentControllerV2 app(std::move(start_info), runner_incoming_services,
std::move(controller));
const bool success = app.SetUp();
const int64_t end = Dart_TimelineGetMicros();
Dart_TimelineEvent("DartComponentControllerV2::SetUp", start, end,
Dart_Timeline_Event_Duration, 0, NULL, NULL);
if (success) {
app.Run();
}
if (Dart_CurrentIsolate()) {
Dart_ShutdownIsolate();
}
}
void RunTestApplicationV2(
void RunTestApplication(
DartRunner* runner,
fuchsia::component::runner::ComponentStartInfo start_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
controller,
fit::function<void(std::shared_ptr<DartTestComponentControllerV2>)>
fit::function<void(std::shared_ptr<DartTestComponentController>)>
component_created_callback,
fit::function<void(DartTestComponentControllerV2*)> done_callback) {
fit::function<void(DartTestComponentController*)> done_callback) {
const int64_t start = Dart_TimelineGetMicros();
auto test_component = std::make_shared<DartTestComponentControllerV2>(
auto test_component = std::make_shared<DartTestComponentController>(
std::move(start_info), runner_incoming_services, std::move(controller),
std::move(done_callback));
@@ -175,7 +148,7 @@ void RunTestApplicationV2(
test_component->SetUp();
const int64_t end = Dart_TimelineGetMicros();
Dart_TimelineEvent("DartTestComponentControllerV2::SetUp", start, end,
Dart_TimelineEvent("DartTestComponentController::SetUp", start, end,
Dart_Timeline_Event_Duration, 0, NULL, NULL);
}
@@ -214,11 +187,6 @@ bool IsTestProgram(const fuchsia::data::Dictionary& program_metadata) {
}
DartRunner::DartRunner(sys::ComponentContext* context) : context_(context) {
context_->outgoing()->AddPublicService<fuchsia::sys::Runner>(
[this](fidl::InterfaceRequest<fuchsia::sys::Runner> request) {
bindings_.AddBinding(this, std::move(request));
});
context_->outgoing()
->AddPublicService<fuchsia::component::runner::ComponentRunner>(
[this](fidl::InterfaceRequest<
@@ -280,43 +248,25 @@ DartRunner::~DartRunner() {
FX_LOGF(FATAL, LOG_TAG, "Dart_Cleanup failed: %s", error);
}
void DartRunner::StartComponent(
fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
fidl::InterfaceRequest<fuchsia::sys::ComponentController> controller) {
// TRACE_DURATION currently requires that the string data does not change
// in the traced scope. Since |package| gets moved in the construction of
// |thread| below, we cannot ensure that |package.resolved_url| does not
// move or change, so we make a copy to pass to TRACE_DURATION.
// TODO(PT-169): Remove this copy when TRACE_DURATION reads string arguments
// eagerly.
std::string url_copy = package.resolved_url;
TRACE_EVENT1("dart", "StartComponent", "url", url_copy.c_str());
std::thread thread(RunApplicationV1, this, std::move(package),
std::move(startup_info), context_->svc(),
std::move(controller));
thread.detach();
}
void DartRunner::Start(
fuchsia::component::runner::ComponentStartInfo start_info,
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
controller) {
// Parse the program field of the component's cml and check if it is a test
// component. If so, serve the |fuchsia.test.Suite| protocol from the
// component's outgoing directory, via DartTestComponentControllerV2.
// component's outgoing directory, via DartTestComponentController.
if (IsTestProgram(start_info.program())) {
std::string url_copy = start_info.resolved_url();
TRACE_EVENT1("dart", "Start", "url", url_copy.c_str());
std::thread thread(
RunTestApplicationV2, this, std::move(start_info), context_->svc(),
RunTestApplication, this, std::move(start_info), context_->svc(),
std::move(controller),
// component_created_callback
[this](std::shared_ptr<DartTestComponentControllerV2> ptr) {
[this](std::shared_ptr<DartTestComponentController> ptr) {
test_components_.emplace(ptr.get(), std::move(ptr));
},
// done_callback
[this](DartTestComponentControllerV2* ptr) {
[this](DartTestComponentController* ptr) {
auto it = test_components_.find(ptr);
if (it != test_components_.end()) {
test_components_.erase(it);
@@ -326,7 +276,7 @@ void DartRunner::Start(
} else {
std::string url_copy = start_info.resolved_url();
TRACE_EVENT1("dart", "Start", "url", url_copy.c_str());
std::thread thread(RunApplicationV2, this, std::move(start_info),
std::thread thread(RunApplication, this, std::move(start_info),
context_->svc(), std::move(controller));
thread.detach();
}

View File

@@ -10,24 +10,17 @@
#include <lib/fidl/cpp/binding_set.h>
#include <lib/sys/cpp/component_context.h>
#include "dart_test_component_controller_v2.h"
#include "dart_test_component_controller.h"
#include "runtime/dart/utils/mapped_resource.h"
namespace dart_runner {
class DartRunner : public fuchsia::sys::Runner,
public fuchsia::component::runner::ComponentRunner {
class DartRunner : public fuchsia::component::runner::ComponentRunner {
public:
explicit DartRunner(sys::ComponentContext* context);
~DartRunner() override;
private:
// |fuchsia::sys::Runner| implementation:
void StartComponent(fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
fidl::InterfaceRequest<fuchsia::sys::ComponentController>
controller) override;
// |fuchsia::component::runner::ComponentRunner| implementation:
void Start(
fuchsia::component::runner::ComponentStartInfo start_info,
@@ -36,13 +29,12 @@ class DartRunner : public fuchsia::sys::Runner,
// Add test components to this map to ensure it is kept alive in memory for
// the duration of test execution and retrieval of exit code.
std::map<DartTestComponentControllerV2*,
std::shared_ptr<DartTestComponentControllerV2>>
std::map<DartTestComponentController*,
std::shared_ptr<DartTestComponentController>>
test_components_;
// Not owned by DartRunner.
sys::ComponentContext* context_;
fidl::BindingSet<fuchsia::sys::Runner> bindings_;
fidl::BindingSet<fuchsia::component::runner::ComponentRunner>
component_runner_bindings_;

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "dart_test_component_controller_v2.h"
#include "dart_test_component_controller.h"
#include <fcntl.h>
#include <fml/logging.h>
@@ -101,7 +101,7 @@ std::string GetComponentNameFromUrl(const std::string& url) {
} // namespace
DartTestComponentControllerV2::DartTestComponentControllerV2(
DartTestComponentController::DartTestComponentController(
fuchsia::component::runner::ComponentStartInfo start_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
@@ -146,7 +146,7 @@ DartTestComponentControllerV2::DartTestComponentControllerV2(
start_info_.clear_runtime_dir();
}
DartTestComponentControllerV2::~DartTestComponentControllerV2() {
DartTestComponentController::~DartTestComponentController() {
if (namespace_) {
fdio_ns_destroy(namespace_);
namespace_ = nullptr;
@@ -155,7 +155,7 @@ DartTestComponentControllerV2::~DartTestComponentControllerV2() {
close(stderr_fd_);
}
void DartTestComponentControllerV2::SetUp() {
void DartTestComponentController::SetUp() {
// Name the thread after the url of the component being launched.
zx::thread::self()->set_property(ZX_PROP_NAME, label_.c_str(), label_.size());
Dart_SetThreadName(label_.c_str());
@@ -183,7 +183,7 @@ void DartTestComponentControllerV2::SetUp() {
loop_->Run();
}
bool DartTestComponentControllerV2::CreateAndBindNamespace() {
bool DartTestComponentController::CreateAndBindNamespace() {
if (!start_info_.has_ns()) {
FX_LOG(ERROR, LOG_TAG, "Component start info does not have a namespace.");
return false;
@@ -229,7 +229,7 @@ bool DartTestComponentControllerV2::CreateAndBindNamespace() {
return true;
}
bool DartTestComponentControllerV2::SetUpFromKernel() {
bool DartTestComponentController::SetUpFromKernel() {
dart_utils::MappedResource manifest;
if (!dart_utils::MappedResource::LoadFromNamespace(
namespace_, data_path_ + "/app.dilplist", manifest)) {
@@ -299,7 +299,7 @@ bool DartTestComponentControllerV2::SetUpFromKernel() {
return true;
}
bool DartTestComponentControllerV2::SetUpFromAppSnapshot() {
bool DartTestComponentController::SetUpFromAppSnapshot() {
#if !defined(AOT_RUNTIME)
return false;
#else
@@ -328,7 +328,7 @@ bool DartTestComponentControllerV2::SetUpFromAppSnapshot() {
#endif // defined(AOT_RUNTIME)
}
bool DartTestComponentControllerV2::CreateIsolate(
bool DartTestComponentController::CreateIsolate(
const uint8_t* isolate_snapshot_data,
const uint8_t* isolate_snapshot_instructions) {
// Create the isolate from the snapshot.
@@ -370,7 +370,7 @@ bool DartTestComponentControllerV2::CreateIsolate(
}
// |fuchsia::test::CaseIterator|
DartTestComponentControllerV2::CaseIterator::CaseIterator(
DartTestComponentController::CaseIterator::CaseIterator(
fidl::InterfaceRequest<fuchsia::test::CaseIterator> request,
async_dispatcher_t* dispatcher,
std::string test_component_name,
@@ -380,7 +380,7 @@ DartTestComponentControllerV2::CaseIterator::CaseIterator(
done_callback_(std::move(done_callback)) {}
// |fuchsia::test::CaseIterator|
void DartTestComponentControllerV2::CaseIterator::GetNext(
void DartTestComponentController::CaseIterator::GetNext(
GetNextCallback callback) {
// Dart test suites run as multiple tests behind one
// test case. Flip flag once the one test case has been retrieved.
@@ -402,12 +402,10 @@ void DartTestComponentControllerV2::CaseIterator::GetNext(
}
// |fuchsia::test::CaseIterator|
std::unique_ptr<DartTestComponentControllerV2::CaseIterator>
DartTestComponentControllerV2::RemoveCaseInterator(
CaseIterator* case_iterator) {
std::unique_ptr<DartTestComponentController::CaseIterator>
DartTestComponentController::RemoveCaseInterator(CaseIterator* case_iterator) {
auto it = case_iterators_.find(case_iterator);
std::unique_ptr<DartTestComponentControllerV2::CaseIterator>
case_iterator_ptr;
std::unique_ptr<DartTestComponentController::CaseIterator> case_iterator_ptr;
if (it != case_iterators_.end()) {
case_iterator_ptr = std::move(it->second);
case_iterators_.erase(it);
@@ -416,7 +414,7 @@ DartTestComponentControllerV2::RemoveCaseInterator(
}
// |fuchsia::test::Suite|
void DartTestComponentControllerV2::GetTests(
void DartTestComponentController::GetTests(
fidl::InterfaceRequest<fuchsia::test::CaseIterator> iterator) {
auto case_iterator = std::make_unique<CaseIterator>(
std::move(iterator), loop_->dispatcher(), test_component_name_,
@@ -427,7 +425,7 @@ void DartTestComponentControllerV2::GetTests(
}
// |fuchsia::test::Suite|
void DartTestComponentControllerV2::Run(
void DartTestComponentController::Run(
std::vector<fuchsia::test::Invocation> tests,
fuchsia::test::RunOptions options,
fidl::InterfaceHandle<fuchsia::test::RunListener> listener) {
@@ -517,7 +515,7 @@ void DartTestComponentControllerV2::Run(
Stop();
}
fpromise::promise<> DartTestComponentControllerV2::RunDartMain() {
fpromise::promise<> DartTestComponentController::RunDartMain() {
FML_CHECK(namespace_ != nullptr);
Dart_EnterScope();
@@ -596,7 +594,7 @@ fpromise::promise<> DartTestComponentControllerV2::RunDartMain() {
return fpromise::make_ok_promise();
}
void DartTestComponentControllerV2::Kill() {
void DartTestComponentController::Kill() {
done_callback_(this);
close(stdout_fd_);
close(stderr_fd_);
@@ -619,7 +617,7 @@ void DartTestComponentControllerV2::Kill() {
}
}
void DartTestComponentControllerV2::MessageEpilogue(Dart_Handle result) {
void DartTestComponentController::MessageEpilogue(Dart_Handle result) {
auto dart_state = tonic::DartState::Current();
// If the Dart program has set a return code, then it is intending to shut
// down by way of a fatal error, and so there is no need to override
@@ -647,15 +645,14 @@ void DartTestComponentControllerV2::MessageEpilogue(Dart_Handle result) {
}
}
void DartTestComponentControllerV2::Stop() {
void DartTestComponentController::Stop() {
Kill();
}
void DartTestComponentControllerV2::OnIdleTimer(
async_dispatcher_t* dispatcher,
async::WaitBase* wait,
zx_status_t status,
const zx_packet_signal* signal) {
void DartTestComponentController::OnIdleTimer(async_dispatcher_t* dispatcher,
async::WaitBase* wait,
zx_status_t status,
const zx_packet_signal* signal) {
if ((status != ZX_OK) || !(signal->observed & ZX_TIMER_SIGNALED) ||
!Dart_CurrentIsolate()) {
// Timer closed or isolate shutdown.

View File

@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_TEST_COMPONENT_CONTROLLER_V2_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_TEST_COMPONENT_CONTROLLER_V2_H_
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_TEST_COMPONENT_CONTROLLER_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_TEST_COMPONENT_CONTROLLER_H_
#include <memory>
@@ -26,27 +26,27 @@
namespace dart_runner {
/// Starts a Dart test component written in CFv2. It's different from
/// DartComponentControllerV2 in that it must implement the
/// DartComponentController in that it must implement the
/// |fuchsia.test.Suite| protocol. It was forked to avoid a naming clash
/// between the two classes' methods as the Suite protocol requires a Run()
/// method for the test_manager to call on. This way, we avoid an extra layer
/// between the test_manager and actual test execution.
/// TODO(fxb/98369): Look into combining the two component classes once dart
/// testing is stable.
class DartTestComponentControllerV2
class DartTestComponentController
: public fuchsia::component::runner::ComponentController,
public fuchsia::test::Suite {
using DoneCallback = fit::function<void(DartTestComponentControllerV2*)>;
using DoneCallback = fit::function<void(DartTestComponentController*)>;
public:
DartTestComponentControllerV2(
DartTestComponentController(
fuchsia::component::runner::ComponentStartInfo start_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
controller,
DoneCallback done_callback);
~DartTestComponentControllerV2() override;
~DartTestComponentController() override;
/// Sets up the controller.
///
@@ -153,16 +153,16 @@ class DartTestComponentControllerV2
zx::time idle_start_{0};
zx::timer idle_timer_;
async::WaitMethod<DartTestComponentControllerV2,
&DartTestComponentControllerV2::OnIdleTimer>
async::WaitMethod<DartTestComponentController,
&DartTestComponentController::OnIdleTimer>
idle_wait_{this};
// Disallow copy and assignment.
DartTestComponentControllerV2(const DartTestComponentControllerV2&) = delete;
DartTestComponentControllerV2& operator=(
const DartTestComponentControllerV2&) = delete;
DartTestComponentController(const DartTestComponentController&) = delete;
DartTestComponentController& operator=(const DartTestComponentController&) =
delete;
};
} // namespace dart_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_TEST_COMPONENT_CONTROLLER_V2_H_
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_TEST_COMPONENT_CONTROLLER_H_

View File

@@ -1,3 +0,0 @@
{
"runner": "fuchsia-pkg://fuchsia.com/dart_aot_product_runner#meta/dart_aot_product_runner.cmx"
}

View File

@@ -1,3 +0,0 @@
{
"runner": "fuchsia-pkg://fuchsia.com/dart_aot_runner#meta/dart_aot_runner.cmx"
}

View File

@@ -1,20 +0,0 @@
{
"program": {
"data": "data"
},
"sandbox": {
"features": [
"config-data",
"root-ssl-certificates"
],
"services": [
"fuchsia.device.NameProvider",
"fuchsia.feedback.CrashReporter",
"fuchsia.intl.PropertyProvider",
"fuchsia.logger.LogSink",
"fuchsia.net.name.Lookup",
"fuchsia.posix.socket.Provider",
"fuchsia.tracing.provider.Registry"
]
}
}

View File

@@ -1,20 +0,0 @@
{
"program": {
"data": "data"
},
"sandbox": {
"features": [
"config-data",
"root-ssl-certificates"
],
"services": [
"fuchsia.device.NameProvider",
"fuchsia.feedback.CrashReporter",
"fuchsia.intl.PropertyProvider",
"fuchsia.logger.LogSink",
"fuchsia.net.name.Lookup",
"fuchsia.posix.socket.Provider",
"fuchsia.tracing.provider.Registry"
]
}
}

View File

@@ -1,23 +0,0 @@
{
"program": {
"data": "data"
},
"sandbox": {
"features": [
"config-data",
"deprecated-ambient-replace-as-executable",
"root-ssl-certificates"
],
"services": [
"fuchsia.device.NameProvider",
"fuchsia.feedback.CrashReporter",
"fuchsia.intl.PropertyProvider",
"fuchsia.logger.LogSink",
"fuchsia.net.name.Lookup",
"fuchsia.posix.socket.Provider",
"fuchsia.process.Launcher",
"fuchsia.process.Resolver",
"fuchsia.tracing.provider.Registry"
]
}
}

View File

@@ -1,23 +0,0 @@
{
"program": {
"data": "data"
},
"sandbox": {
"features": [
"config-data",
"deprecated-ambient-replace-as-executable",
"root-ssl-certificates"
],
"services": [
"fuchsia.device.NameProvider",
"fuchsia.feedback.CrashReporter",
"fuchsia.intl.PropertyProvider",
"fuchsia.logger.LogSink",
"fuchsia.net.name.Lookup",
"fuchsia.posix.socket.Provider",
"fuchsia.process.Launcher",
"fuchsia.process.Resolver",
"fuchsia.tracing.provider.Registry"
]
}
}

View File

@@ -1,3 +0,0 @@
{
"runner": "fuchsia-pkg://fuchsia.com/dart_jit_product_runner#meta/dart_jit_product_runner.cmx"
}

View File

@@ -1,3 +0,0 @@
{
"runner": "fuchsia-pkg://fuchsia.com/dart_jit_runner#meta/dart_jit_runner.cmx"
}

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "dart_runner/dart_test_component_controller_v2.h"
#include "dart_runner/dart_test_component_controller.h"
#include "gtest/gtest.h"

View File

@@ -1,4 +1,5 @@
Flutter Application Runner
==========================
Implements the `fuchsia::sys::Runner` FIDL interface to launch and run multiple Flutter applications within the same process.
Implements the `fuchsia::component::runner::ComponentRunner` FIDL interface to
launch and run multiple Flutter applications within the same process in Fuchsia.

View File

@@ -7,7 +7,6 @@ import("//flutter/common/config.gni")
# Builds the component in a non-product JIT build. This will
# launch the vm service in the runner.
dart_debug_build_cfg = {
runtime_meta = "//flutter/shell/platform/fuchsia/dart_runner/meta/jit_runtime"
runner_dep = "//flutter/shell/platform/fuchsia/dart_runner:dart_jit_runner"
platform_name = "dart_runner"
is_aot = false
@@ -20,7 +19,6 @@ dart_debug_build_cfg = {
# This configuration is not compatible with a --release build since the
# profile aot runner is built without asserts.
dart_aot_debug_build_cfg = {
runtime_meta = "//flutter/shell/platform/fuchsia/dart_runner/meta/aot_runtime"
runner_dep = "//flutter/shell/platform/fuchsia/dart_runner:dart_aot_runner"
platform_name = "dart_runner"
is_aot = true
@@ -31,7 +29,6 @@ dart_aot_debug_build_cfg = {
# Builds the component in a non-product AOT build. This will
# launch the vm service in the runner.
dart_profile_build_cfg = {
runtime_meta = "//flutter/shell/platform/fuchsia/dart_runner/meta/aot_runtime"
runner_dep = "//flutter/shell/platform/fuchsia/dart_runner:dart_aot_runner"
platform_name = "dart_runner"
is_aot = true
@@ -42,8 +39,6 @@ dart_profile_build_cfg = {
# Builds the component in a product JIT build. This will
# not launch the vm service in the runner.
dart_jit_release_build_cfg = {
runtime_meta =
"//flutter/shell/platform/fuchsia/dart_runner/meta/jit_product_runtime"
runner_dep =
"//flutter/shell/platform/fuchsia/dart_runner:dart_jit_product_runner"
platform_name = "dart_runner"
@@ -55,8 +50,6 @@ dart_jit_release_build_cfg = {
# Builds the component in a product AOT build. This will
# not launch the vm service in the runner.
dart_release_build_cfg = {
runtime_meta =
"//flutter/shell/platform/fuchsia/dart_runner/meta/aot_product_runtime"
runner_dep =
"//flutter/shell/platform/fuchsia/dart_runner:dart_aot_product_runner"
platform_name = "dart_runner"