[fuchsia] Rename, move some CF v1 runner code. (flutter/engine#29072)

Bug: fxb/50694
Tested: Ran Spinning Square with the JIT runner.

Some small non-destructive cleanups that should make the CF v2
Flutter runner easier to read in a follow-up PR. No logic is
changed, only naming and location.

Renames Application -> Component. This matches the filename and
Fuchsia's naming.
Moves FileInNamespaceBuffer and related utilities into a separate
file from component.cc. This will enable reusing these utilities
in the CF v2 FLutter runner. Also adds documentation for them.
Renames CreateWithContentsOfFile helper -> LoadFile since that's
what the FML_EVENT_TRACE calls it.
Removes undefined UnregisterApplication method. There are no
usages of this method in our codebase.
Move fields after methods to follow the C++ style guide.
This commit is contained in:
Alexander Biggs
2021-10-08 15:01:15 -04:00
committed by GitHub
parent 59b2fa56cd
commit 069625d26a
9 changed files with 311 additions and 240 deletions

View File

@@ -1418,6 +1418,8 @@ FILE: ../../../flutter/shell/platform/fuchsia/flutter/component.h
FILE: ../../../flutter/shell/platform/fuchsia/flutter/component_unittest.cc
FILE: ../../../flutter/shell/platform/fuchsia/flutter/engine.cc
FILE: ../../../flutter/shell/platform/fuchsia/flutter/engine.h
FILE: ../../../flutter/shell/platform/fuchsia/flutter/file_in_namespace_buffer.cc
FILE: ../../../flutter/shell/platform/fuchsia/flutter/file_in_namespace_buffer.h
FILE: ../../../flutter/shell/platform/fuchsia/flutter/flatland_connection.cc
FILE: ../../../flutter/shell/platform/fuchsia/flutter/flatland_connection.h
FILE: ../../../flutter/shell/platform/fuchsia/flutter/flatland_external_view_embedder.cc

View File

@@ -61,6 +61,8 @@ template("runner_sources") {
"component.h",
"engine.cc",
"engine.h",
"file_in_namespace_buffer.cc",
"file_in_namespace_buffer.h",
"flatland_connection.cc",
"flatland_connection.h",
"flatland_external_view_embedder.cc",

View File

@@ -26,6 +26,7 @@
#include <regex>
#include <sstream>
#include "file_in_namespace_buffer.h"
#include "flutter/fml/mapping.h"
#include "flutter/fml/platform/fuchsia/task_observers.h"
#include "flutter/fml/synchronization/waitable_event.h"
@@ -38,13 +39,6 @@
#include "runtime/dart/utils/tempfs.h"
#include "runtime/dart/utils/vmo.h"
// TODO(kaushikiska): Use these constants from ::llcpp::fuchsia::io
// Can read from target object.
constexpr uint32_t OPEN_RIGHT_READABLE = 1u;
// Connection can map target object executable.
constexpr uint32_t OPEN_RIGHT_EXECUTABLE = 8u;
namespace flutter_runner {
namespace {
@@ -54,99 +48,7 @@ constexpr char kTmpPath[] = "/tmp";
constexpr char kServiceRootPath[] = "/svc";
constexpr char kRunnerConfigPath[] = "/config/data/flutter_runner_config";
class FileInNamespaceBuffer final : public fml::Mapping {
public:
FileInNamespaceBuffer(int namespace_fd, const char* path, bool executable)
: address_(nullptr), size_(0) {
fuchsia::mem::Buffer buffer;
if (!dart_utils::VmoFromFilenameAt(namespace_fd, path, executable,
&buffer)) {
return;
}
if (buffer.size == 0) {
return;
}
uint32_t flags = ZX_VM_PERM_READ;
if (executable) {
flags |= ZX_VM_PERM_EXECUTE;
}
uintptr_t addr;
zx_status_t status =
zx::vmar::root_self()->map(flags, 0, buffer.vmo, 0, buffer.size, &addr);
if (status != ZX_OK) {
FML_LOG(FATAL) << "Failed to map " << path << ": "
<< zx_status_get_string(status);
}
address_ = reinterpret_cast<void*>(addr);
size_ = buffer.size;
}
~FileInNamespaceBuffer() {
if (address_ != nullptr) {
zx::vmar::root_self()->unmap(reinterpret_cast<uintptr_t>(address_),
size_);
address_ = nullptr;
size_ = 0;
}
}
// |fml::Mapping|
const uint8_t* GetMapping() const override {
return reinterpret_cast<const uint8_t*>(address_);
}
// |fml::Mapping|
size_t GetSize() const override { return size_; }
private:
void* address_;
size_t size_;
FML_DISALLOW_COPY_AND_ASSIGN(FileInNamespaceBuffer);
};
std::unique_ptr<fml::Mapping> CreateWithContentsOfFile(int namespace_fd,
const char* file_path,
bool executable) {
FML_TRACE_EVENT("flutter", "LoadFile", "path", file_path);
return std::make_unique<FileInNamespaceBuffer>(namespace_fd, file_path,
executable);
}
std::unique_ptr<fml::FileMapping> MakeFileMapping(const char* path,
bool executable) {
uint32_t flags = OPEN_RIGHT_READABLE;
if (executable) {
flags |= OPEN_RIGHT_EXECUTABLE;
}
int fd = 0;
// The returned file descriptor is compatible with standard posix operations
// such as close, mmap, etc. We only need to treat open/open_at specially.
zx_status_t status = fdio_open_fd(path, flags, &fd);
if (status != ZX_OK) {
return nullptr;
}
using Protection = fml::FileMapping::Protection;
std::initializer_list<Protection> protection_execute = {Protection::kRead,
Protection::kExecute};
std::initializer_list<Protection> protection_read = {Protection::kRead};
auto mapping = std::make_unique<fml::FileMapping>(
fml::UniqueFD{fd}, executable ? protection_execute : protection_read);
if (!mapping->IsValid()) {
return nullptr;
}
return mapping;
}
std::string DebugLabelForURL(const std::string& url) {
std::string DebugLabelForUrl(const std::string& url) {
auto found = url.rfind("/");
if (found == std::string::npos) {
return url;
@@ -157,7 +59,7 @@ std::string DebugLabelForURL(const std::string& url) {
} // namespace
void Application::ParseProgramMetadata(
void Component::ParseProgramMetadata(
const fidl::VectorPtr<fuchsia::sys::ProgramMetadata>& program_metadata,
std::string* data_path,
std::string* assets_path) {
@@ -178,43 +80,43 @@ void Application::ParseProgramMetadata(
}
}
ActiveApplication Application::Create(
ActiveComponent Component::Create(
TerminationCallback termination_callback,
fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::sys::ComponentController> controller) {
auto thread = std::make_unique<fml::Thread>();
std::unique_ptr<Application> application;
std::unique_ptr<Component> component;
fml::AutoResetWaitableEvent latch;
thread->GetTaskRunner()->PostTask([&]() mutable {
application.reset(
new Application(std::move(termination_callback), std::move(package),
std::move(startup_info), runner_incoming_services,
std::move(controller)));
component.reset(new Component(std::move(termination_callback),
std::move(package), std::move(startup_info),
runner_incoming_services,
std::move(controller)));
latch.Signal();
});
latch.Wait();
return {.platform_thread = std::move(thread),
.application = std::move(application)};
.component = std::move(component)};
}
Application::Application(
Component::Component(
TerminationCallback termination_callback,
fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::sys::ComponentController>
application_controller_request)
component_controller_request)
: termination_callback_(std::move(termination_callback)),
debug_label_(DebugLabelForURL(startup_info.launch_info.url)),
application_controller_(this),
debug_label_(DebugLabelForUrl(startup_info.launch_info.url)),
component_controller_(this),
outgoing_dir_(new vfs::PseudoDir()),
runner_incoming_services_(runner_incoming_services),
weak_factory_(this) {
application_controller_.set_error_handler(
component_controller_.set_error_handler(
[this](zx_status_t status) { Kill(); });
FML_DCHECK(fdio_ns_.is_valid());
@@ -269,13 +171,13 @@ Application::Application(
constexpr mode_t mode = O_RDONLY | O_DIRECTORY;
application_assets_directory_.reset(
component_assets_directory_.reset(
openat(ns_fd.get(), assets_path.c_str(), mode));
FML_DCHECK(application_assets_directory_.is_valid());
FML_DCHECK(component_assets_directory_.is_valid());
application_data_directory_.reset(
component_data_directory_.reset(
openat(ns_fd.get(), data_path.c_str(), mode));
FML_DCHECK(application_data_directory_.is_valid());
FML_DCHECK(component_data_directory_.is_valid());
}
// TODO: LaunchInfo::out.
@@ -330,7 +232,7 @@ Application::Application(
dir_str, std::make_unique<vfs::RemoteDir>(dir.TakeChannel()));
} else {
FML_LOG(ERROR) << "could not add out directory entry(" << dir_str
<< ") for flutter app(" << debug_label_
<< ") for flutter component(" << debug_label_
<< "): " << zx_status_get_string(status);
}
}
@@ -343,7 +245,7 @@ Application::Application(
// All launch arguments have been read. Perform service binding and
// final settings configuration. The next call will be to create a view
// for this application.
// for this component.
composed_service_dir->AddService(
fuchsia::ui::app::ViewProvider::Name_,
std::make_unique<vfs::Service>(
@@ -355,9 +257,9 @@ Application::Application(
outgoing_dir_->AddEntry("svc", std::move(composed_service_dir));
// Setup the application controller binding.
if (application_controller_request) {
application_controller_.Bind(std::move(application_controller_request));
// Setup the component controller binding.
if (component_controller_request) {
component_controller_.Bind(std::move(component_controller_request));
}
// Load and use runner-specific configuration, if it exists.
@@ -371,13 +273,13 @@ Application::Application(
<< kRunnerConfigPath << "; using default config values.";
}
// Load VM and application bytecode.
// Load VM and component bytecode.
// For AOT, compare with flutter_aot_app in flutter_app.gni.
// For JIT, compare flutter_jit_runner in BUILD.gn.
if (flutter::DartVM::IsRunningPrecompiledCode()) {
std::shared_ptr<dart_utils::ElfSnapshot> snapshot =
std::make_shared<dart_utils::ElfSnapshot>();
if (snapshot->Load(application_data_directory_.get(),
if (snapshot->Load(component_data_directory_.get(),
"app_aot_snapshot.so")) {
const uint8_t* isolate_data = snapshot->IsolateData();
const uint8_t* isolate_instructions = snapshot->IsolateInstrs();
@@ -412,38 +314,41 @@ Application::Application(
std::make_shared<fml::NonOwnedMapping>(isolate_instructions, 0,
hold_snapshot));
} else {
const int namespace_fd = application_data_directory_.get();
const int namespace_fd = component_data_directory_.get();
settings_.vm_snapshot_data = [namespace_fd]() {
return CreateWithContentsOfFile(namespace_fd, "vm_snapshot_data.bin",
false);
return LoadFile(namespace_fd, "vm_snapshot_data.bin",
false /* executable */);
};
settings_.vm_snapshot_instr = [namespace_fd]() {
return CreateWithContentsOfFile(namespace_fd,
"vm_snapshot_instructions.bin", true);
return LoadFile(namespace_fd, "vm_snapshot_instructions.bin",
true /* executable */);
};
settings_.isolate_snapshot_data = [namespace_fd]() {
return CreateWithContentsOfFile(namespace_fd,
"isolate_snapshot_data.bin", false);
return LoadFile(namespace_fd, "isolate_snapshot_data.bin",
false /* executable */);
};
settings_.isolate_snapshot_instr = [namespace_fd]() {
return CreateWithContentsOfFile(
namespace_fd, "isolate_snapshot_instructions.bin", true);
return LoadFile(namespace_fd, "isolate_snapshot_instructions.bin",
true /* executable */);
};
}
} else {
settings_.vm_snapshot_data = []() {
return MakeFileMapping("/pkg/data/vm_snapshot_data.bin", false);
return MakeFileMapping("/pkg/data/vm_snapshot_data.bin",
false /* executable */);
};
settings_.vm_snapshot_instr = []() {
return MakeFileMapping("/pkg/data/vm_snapshot_instructions.bin", true);
return MakeFileMapping("/pkg/data/vm_snapshot_instructions.bin",
true /* executable */);
};
settings_.isolate_snapshot_data = []() {
return MakeFileMapping("/pkg/data/isolate_core_snapshot_data.bin", false);
return MakeFileMapping("/pkg/data/isolate_core_snapshot_data.bin",
false /* executable */);
};
settings_.isolate_snapshot_instr = [] {
return MakeFileMapping("/pkg/data/isolate_core_snapshot_instructions.bin",
true);
true /* executable */);
};
}
@@ -467,7 +372,7 @@ Application::Application(
settings_.icu_data_path = "";
settings_.assets_dir = application_assets_directory_.get();
settings_.assets_dir = component_assets_directory_.get();
// Compare flutter_jit_app in flutter_app.gni.
settings_.application_kernel_list_asset = "app.dilplist";
@@ -515,26 +420,24 @@ Application::Application(
settings_.dart_flags.push_back("--profile_period=10000");
#endif // defined(__aarch64__)
auto weak_application = weak_factory_.GetWeakPtr();
auto platform_task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner();
const std::string component_url = package.resolved_url;
settings_.unhandled_exception_callback = [weak_application,
settings_.unhandled_exception_callback = [weak = weak_factory_.GetWeakPtr(),
platform_task_runner,
runner_incoming_services,
component_url](
const std::string& error,
const std::string& stack_trace) {
if (weak_application) {
if (weak) {
// TODO(cbracken): unsafe. The above check and the PostTask below are
// happening on the UI thread. If the Application dtor and thread
// happening on the UI thread. If the Component dtor and thread
// termination happen (on the platform thread) between the previous
// line and the next line, a crash will occur since we'll be posting
// to a dead thread. See Runner::OnApplicationTerminate() in
// to a dead thread. See Runner::OnComponentTerminate() in
// runner.cc.
platform_task_runner->PostTask([weak_application,
runner_incoming_services, component_url,
error, stack_trace]() {
if (weak_application) {
platform_task_runner->PostTask([weak, runner_incoming_services,
component_url, error, stack_trace]() {
if (weak) {
dart_utils::HandleException(runner_incoming_services, component_url,
error, stack_trace);
} else {
@@ -555,14 +458,14 @@ Application::Application(
};
}
Application::~Application() = default;
Component::~Component() = default;
const std::string& Application::GetDebugLabel() const {
const std::string& Component::GetDebugLabel() const {
return debug_label_;
}
void Application::Kill() {
application_controller_.events().OnTerminated(
void Component::Kill() {
component_controller_.events().OnTerminated(
last_return_code_.second, fuchsia::sys::TerminationReason::EXITED);
termination_callback_(this);
@@ -570,11 +473,11 @@ void Application::Kill() {
// collected.
}
void Application::Detach() {
application_controller_.set_error_handler(nullptr);
void Component::Detach() {
component_controller_.set_error_handler(nullptr);
}
void Application::OnEngineTerminate(const Engine* shell_holder) {
void Component::OnEngineTerminate(const Engine* shell_holder) {
auto found = std::find_if(shell_holders_.begin(), shell_holders_.end(),
[shell_holder](const auto& holder) {
return holder.get() == shell_holder;
@@ -584,9 +487,9 @@ void Application::OnEngineTerminate(const Engine* shell_holder) {
return;
}
// We may launch multiple shell in this application. However, we will
// We may launch multiple shell in this component. However, we will
// terminate when the last shell goes away. The error code return to the
// application controller will be the last isolate that had an error.
// component controller will be the last isolate that had an error.
auto return_code = shell_holder->GetEngineReturnCode();
if (return_code.has_value()) {
last_return_code_ = {true, return_code.value()};
@@ -601,7 +504,7 @@ void Application::OnEngineTerminate(const Engine* shell_holder) {
}
}
void Application::CreateView(
void Component::CreateView(
zx::eventpair token,
fidl::InterfaceRequest<fuchsia::sys::ServiceProvider> /*incoming_services*/,
fidl::InterfaceHandle<
@@ -611,7 +514,7 @@ void Application::CreateView(
std::move(view_ref_pair.view_ref));
}
void Application::CreateViewWithViewRef(
void Component::CreateViewWithViewRef(
zx::eventpair view_token,
fuchsia::ui::views::ViewRefControl control_ref,
fuchsia::ui::views::ViewRef view_ref) {
@@ -639,7 +542,7 @@ void Application::CreateViewWithViewRef(
));
}
void Application::CreateView2(fuchsia::ui::app::CreateView2Args view_args) {
void Component::CreateView2(fuchsia::ui::app::CreateView2Args view_args) {
if (!svc_) {
FML_DLOG(ERROR)
<< "Component incoming services was invalid when attempting to "
@@ -663,7 +566,7 @@ void Application::CreateView2(fuchsia::ui::app::CreateView2Args view_args) {
}
#if !defined(DART_PRODUCT)
void Application::WriteProfileToTrace() const {
void Component::WriteProfileToTrace() const {
for (const auto& engine : shell_holders_) {
engine->WriteProfileToTrace();
}

View File

@@ -30,35 +30,35 @@
namespace flutter_runner {
class Application;
class Component;
struct ActiveApplication {
struct ActiveComponent {
std::unique_ptr<fml::Thread> platform_thread;
std::unique_ptr<Application> application;
std::unique_ptr<Component> component;
ActiveApplication& operator=(ActiveApplication&& other) noexcept {
ActiveComponent& operator=(ActiveComponent&& other) noexcept {
if (this != &other) {
this->platform_thread.reset(other.platform_thread.release());
this->application.reset(other.application.release());
this->component.reset(other.component.release());
}
return *this;
}
~ActiveApplication() = default;
~ActiveComponent() = default;
};
// Represents an instance of a Flutter application that contains one of more
// Represents an instance of a Flutter component that contains one of more
// Flutter engine instances.
class Application final : public Engine::Delegate,
public fuchsia::sys::ComponentController,
public fuchsia::ui::app::ViewProvider {
class Component final : public Engine::Delegate,
public fuchsia::sys::ComponentController,
public fuchsia::ui::app::ViewProvider {
public:
using TerminationCallback = fit::function<void(const Application*)>;
using TerminationCallback = fit::function<void(const Component*)>;
// Creates a dedicated thread to run the application and constructions the
// application on it. The application can be accessed only on this thread.
// Creates a dedicated thread to run the component and creates the
// component on it. The component can be accessed only on this thread.
// This is a synchronous operation.
static ActiveApplication Create(
static ActiveComponent Create(
TerminationCallback termination_callback,
fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
@@ -67,7 +67,7 @@ class Application final : public Engine::Delegate,
// Must be called on the same thread returned from the create call. The thread
// may be collected after.
~Application();
~Component();
static void ParseProgramMetadata(
const fidl::VectorPtr<fuchsia::sys::ProgramMetadata>& program_metadata,
@@ -86,10 +86,10 @@ class Application final : public Engine::Delegate,
TerminationCallback termination_callback_;
const std::string debug_label_;
UniqueFDIONS fdio_ns_ = UniqueFDIONSCreate();
fml::UniqueFD application_data_directory_;
fml::UniqueFD application_assets_directory_;
fml::UniqueFD component_data_directory_;
fml::UniqueFD component_assets_directory_;
fidl::Binding<fuchsia::sys::ComponentController> application_controller_;
fidl::Binding<fuchsia::sys::ComponentController> component_controller_;
fuchsia::io::DirectoryPtr directory_ptr_;
fuchsia::io::NodePtr cloned_directory_ptr_;
fidl::InterfaceRequest<fuchsia::io::Directory> directory_request_;
@@ -101,9 +101,9 @@ class Application final : public Engine::Delegate,
fml::RefPtr<flutter::DartSnapshot> isolate_snapshot_;
std::set<std::unique_ptr<Engine>> shell_holders_;
std::pair<bool, uint32_t> last_return_code_;
fml::WeakPtrFactory<Application> weak_factory_;
fml::WeakPtrFactory<Component> weak_factory_;
Application(
Component(
TerminationCallback termination_callback,
fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
@@ -134,7 +134,7 @@ class Application final : public Engine::Delegate,
// |flutter::Engine::Delegate|
void OnEngineTerminate(const Engine* holder) override;
FML_DISALLOW_COPY_AND_ASSIGN(Application);
FML_DISALLOW_COPY_AND_ASSIGN(Component);
};
} // namespace flutter_runner

View File

@@ -15,7 +15,7 @@ TEST(Component, ParseProgramMetadata) {
// The ProgramMetadata field may be null. We should parse this as if no
// fields were specified.
Application::ParseProgramMetadata(nullptr, &data_path, &assets_path);
Component::ParseProgramMetadata(nullptr, &data_path, &assets_path);
EXPECT_EQ(data_path, "");
EXPECT_EQ(assets_path, "");
@@ -23,7 +23,7 @@ TEST(Component, ParseProgramMetadata) {
// The ProgramMetadata field may be empty. Treat this the same as null.
fidl::VectorPtr<fuchsia::sys::ProgramMetadata> program_metadata(size_t{0});
Application::ParseProgramMetadata(program_metadata, &data_path, &assets_path);
Component::ParseProgramMetadata(program_metadata, &data_path, &assets_path);
EXPECT_EQ(data_path, "");
EXPECT_EQ(assets_path, "");
@@ -31,7 +31,7 @@ TEST(Component, ParseProgramMetadata) {
// The assets_path defaults to the "data" value if unspecified
program_metadata = {{"data", "foobar"}};
Application::ParseProgramMetadata(program_metadata, &data_path, &assets_path);
Component::ParseProgramMetadata(program_metadata, &data_path, &assets_path);
EXPECT_EQ(data_path, "pkg/foobar");
EXPECT_EQ(assets_path, "pkg/foobar");
@@ -41,7 +41,7 @@ TEST(Component, ParseProgramMetadata) {
program_metadata = {{"not_data", "foo"}, {"data", "bar"}, {"assets", "baz"}};
Application::ParseProgramMetadata(program_metadata, &data_path, &assets_path);
Component::ParseProgramMetadata(program_metadata, &data_path, &assets_path);
EXPECT_EQ(data_path, "pkg/bar");
EXPECT_EQ(assets_path, "pkg/baz");

View File

@@ -0,0 +1,110 @@
// 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 "file_in_namespace_buffer.h"
#include <lib/fdio/directory.h>
#include <zircon/status.h>
#include "flutter/fml/trace_event.h"
#include "runtime/dart/utils/files.h"
#include "runtime/dart/utils/handle_exception.h"
#include "runtime/dart/utils/mapped_resource.h"
#include "runtime/dart/utils/tempfs.h"
#include "runtime/dart/utils/vmo.h"
namespace flutter_runner {
namespace {
// TODO(kaushikiska): Use these constants from ::llcpp::fuchsia::io
// Can read from target object.
constexpr uint32_t OPEN_RIGHT_READABLE = 1u;
// Connection can map target object executable.
constexpr uint32_t OPEN_RIGHT_EXECUTABLE = 8u;
} // namespace
FileInNamespaceBuffer::FileInNamespaceBuffer(int namespace_fd,
const char* path,
bool executable)
: address_(nullptr), size_(0) {
fuchsia::mem::Buffer buffer;
if (!dart_utils::VmoFromFilenameAt(namespace_fd, path, executable, &buffer) ||
buffer.size == 0) {
return;
}
uint32_t flags = ZX_VM_PERM_READ;
if (executable) {
flags |= ZX_VM_PERM_EXECUTE;
}
uintptr_t addr;
const zx_status_t status =
zx::vmar::root_self()->map(flags, 0, buffer.vmo, 0, buffer.size, &addr);
if (status != ZX_OK) {
FML_LOG(FATAL) << "Failed to map " << path << ": "
<< zx_status_get_string(status);
}
address_ = reinterpret_cast<void*>(addr);
size_ = buffer.size;
}
FileInNamespaceBuffer::~FileInNamespaceBuffer() {
if (address_ != nullptr) {
zx::vmar::root_self()->unmap(reinterpret_cast<uintptr_t>(address_), size_);
address_ = nullptr;
size_ = 0;
}
}
const uint8_t* FileInNamespaceBuffer::GetMapping() const {
return reinterpret_cast<const uint8_t*>(address_);
}
size_t FileInNamespaceBuffer::GetSize() const {
return size_;
}
std::unique_ptr<fml::Mapping> LoadFile(int namespace_fd,
const char* path,
bool executable) {
FML_TRACE_EVENT("flutter", "LoadFile", "path", path);
return std::make_unique<FileInNamespaceBuffer>(namespace_fd, path,
executable);
}
std::unique_ptr<fml::FileMapping> MakeFileMapping(const char* path,
bool executable) {
uint32_t flags = OPEN_RIGHT_READABLE;
if (executable) {
flags |= OPEN_RIGHT_EXECUTABLE;
}
// The returned file descriptor is compatible with standard posix operations
// such as close, mmap, etc. We only need to treat open/open_at specially.
int fd;
const zx_status_t status = fdio_open_fd(path, flags, &fd);
if (status != ZX_OK) {
return nullptr;
}
using Protection = fml::FileMapping::Protection;
std::initializer_list<Protection> protection_execute = {Protection::kRead,
Protection::kExecute};
std::initializer_list<Protection> protection_read = {Protection::kRead};
auto mapping = std::make_unique<fml::FileMapping>(
fml::UniqueFD{fd}, executable ? protection_execute : protection_read);
if (!mapping->IsValid()) {
return nullptr;
}
return mapping;
}
} // namespace flutter_runner

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_SHELL_PLATFORM_FUCHSIA_FILE_IN_NAMESPACE_BUFFER_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FILE_IN_NAMESPACE_BUFFER_H_
#include "flutter/fml/mapping.h"
namespace flutter_runner {
/// A mapping to a buffer for a file that has been loaded into a namespace.
class FileInNamespaceBuffer final : public fml::Mapping {
public:
/// Loads the file at |path| into the namespace |namespace_fd|, creating
/// a mapping to the loaded buffer.
///
/// The file will be loaded with the readable permission. If |executable| is
/// true, the file will also be loaded with the executable permission.
FileInNamespaceBuffer(int namespace_fd, const char* path, bool executable);
~FileInNamespaceBuffer();
// |fml::Mapping|
const uint8_t* GetMapping() const override;
// |fml::Mapping|
size_t GetSize() const override;
private:
/// The address that was mapped to the buffer.
void* address_;
/// The size of the buffer.
size_t size_;
FML_DISALLOW_COPY_AND_ASSIGN(FileInNamespaceBuffer);
};
/// Loads a file from |file_path| into the namespace |namespace_fd|, returning
/// the mapping for that file.
///
/// The file will be loaded with the readable permission. If |executable| is
/// true, the file will be also be loaded with the executable permission.
std::unique_ptr<fml::Mapping> LoadFile(int namespace_fd,
const char* path,
bool executable);
/// Opens the file at |path| and creates a file mapping for the file.
///
/// The file will be opened with the readable permission. If |executable| is
/// true, the file will also be opened with the executable permission.
std::unique_ptr<fml::FileMapping> MakeFileMapping(const char* path,
bool executable);
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FILE_IN_NAMESPACE_BUFFER_H_

View File

@@ -188,7 +188,7 @@ Runner::Runner(fml::RefPtr<fml::TaskRunner> task_runner,
SetThreadName("io.flutter.runner.main");
context_->outgoing()->AddPublicService<fuchsia::sys::Runner>(
std::bind(&Runner::RegisterApplication, this, std::placeholders::_1));
std::bind(&Runner::RegisterComponent, this, std::placeholders::_1));
#if !defined(DART_PRODUCT)
if (Dart_IsPrecompiledRuntime()) {
@@ -209,9 +209,9 @@ Runner::~Runner() {
#endif // !defined(DART_PRODUCT)
}
void Runner::RegisterApplication(
void Runner::RegisterComponent(
fidl::InterfaceRequest<fuchsia::sys::Runner> request) {
active_applications_bindings_.AddBinding(this, std::move(request));
active_components_bindings_.AddBinding(this, std::move(request));
}
void Runner::StartComponent(
@@ -219,66 +219,68 @@ void Runner::StartComponent(
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 Application::Create
// in the traced scope. Since |package| gets moved in the Component::Create
// call 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("flutter", "StartComponent", "url", url_copy.c_str());
// Notes on application termination: Application typically terminate on the
// Notes on component termination: Components typically terminate on the
// thread on which they were created. This usually means the thread was
// specifically created to host the application. But we want to ensure that
// access to the active applications collection is made on the same thread. So
// specifically created to host the component. But we want to ensure that
// access to the active components collection is made on the same thread. So
// we capture the runner in the termination callback. There is no risk of
// there being multiple application runner instance in the process at the same
// there being multiple component runner instances in the process at the same
// time. So it is safe to use the raw pointer.
Application::TerminationCallback termination_callback =
[application_runner = this](const Application* application) {
application_runner->task_runner_->PostTask(
[application_runner, application]() {
application_runner->OnApplicationTerminate(application);
Component::TerminationCallback termination_callback =
[component_runner = this](const Component* component) {
component_runner->task_runner_->PostTask(
[component_runner, component]() {
component_runner->OnComponentTerminate(component);
});
};
auto active_application = Application::Create(
ActiveComponent active_component = Component::Create(
std::move(termination_callback), // termination callback
std::move(package), // application package
std::move(package), // component package
std::move(startup_info), // startup info
context_->svc(), // runner incoming services
std::move(controller) // controller request
);
auto key = active_application.application.get();
active_applications_[key] = std::move(active_application);
auto key = active_component.component.get();
active_components_[key] = std::move(active_component);
}
void Runner::OnApplicationTerminate(const Application* application) {
auto app = active_applications_.find(application);
if (app == active_applications_.end()) {
void Runner::OnComponentTerminate(const Component* component) {
auto app = active_components_.find(component);
if (app == active_components_.end()) {
FML_LOG(INFO)
<< "The remote end of the application runner tried to terminate an "
"application that has already been terminated, possibly because we "
<< "The remote end of the component runner tried to terminate an "
"component that has already been terminated, possibly because we "
"initiated the termination";
return;
}
auto& active_application = app->second;
ActiveComponent& active_component = app->second;
// Grab the items out of the entry because we will have to rethread the
// destruction.
auto application_to_destroy = std::move(active_application.application);
auto application_thread = std::move(active_application.platform_thread);
std::unique_ptr<Component> component_to_destroy =
std::move(active_component.component);
std::unique_ptr<fml::Thread> component_thread =
std::move(active_component.platform_thread);
// Delegate the entry.
active_applications_.erase(application);
// Delete the entry.
active_components_.erase(component);
// Post the task to destroy the application and quit its message loop.
application_thread->GetTaskRunner()->PostTask(fml::MakeCopyable(
[instance = std::move(application_to_destroy),
thread = application_thread.get()]() mutable { instance.reset(); }));
// Post the task to destroy the component and quit its message loop.
component_thread->GetTaskRunner()->PostTask(fml::MakeCopyable(
[instance = std::move(component_to_destroy),
thread = component_thread.get()]() mutable { instance.reset(); }));
// Terminate and join the thread's message loop.
application_thread->Join();
component_thread->Join();
}
void Runner::SetupICU() {
@@ -315,11 +317,11 @@ void Runner::SetupTraceObserver() {
runner->prolonged_context_ = trace_acquire_prolonged_context();
Dart_StartProfiling();
} else if (trace_state() == TRACE_STOPPING) {
for (auto& it : runner->active_applications_) {
for (auto& it : runner->active_components_) {
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(
it.second.platform_thread->GetTaskRunner(), [&]() {
it.second.application->WriteProfileToTrace();
it.second.component->WriteProfileToTrace();
latch.Signal();
});
latch.Wait();

View File

@@ -23,7 +23,7 @@
namespace flutter_runner {
// Publishes the |fuchsia::sys::Runner| service and runs applications on
// Publishes the |fuchsia::sys::Runner| service and runs components on
// their own threads.
class Runner final : public fuchsia::sys::Runner {
public:
@@ -34,33 +34,15 @@ class Runner final : public fuchsia::sys::Runner {
~Runner();
private:
fml::RefPtr<fml::TaskRunner> task_runner_;
sys::ComponentContext* context_;
fidl::BindingSet<fuchsia::sys::Runner> active_applications_bindings_;
std::unordered_map<const Application*, ActiveApplication>
active_applications_;
#if !defined(DART_PRODUCT)
// The connection between the Dart VM service and The Hub.
std::unique_ptr<dart_utils::VMServiceObject> vmservice_object_;
std::unique_ptr<trace::TraceObserver> trace_observer_;
trace_prolonged_context_t* prolonged_context_;
#endif // !defined(DART_PRODUCT)
// |fuchsia::sys::Runner|
void StartComponent(fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
fidl::InterfaceRequest<fuchsia::sys::ComponentController>
controller) override;
void RegisterApplication(
fidl::InterfaceRequest<fuchsia::sys::Runner> request);
void RegisterComponent(fidl::InterfaceRequest<fuchsia::sys::Runner> request);
void UnregisterApplication(const Application* application);
void OnApplicationTerminate(const Application* application);
void OnComponentTerminate(const Component* component);
void SetupICU();
@@ -77,6 +59,20 @@ class Runner final : public fuchsia::sys::Runner {
FRIEND_TEST(RunnerTZDataTest, LoadsWithoutTZDataPresent);
#endif // defined(FRIEND_TEST)
fml::RefPtr<fml::TaskRunner> task_runner_;
sys::ComponentContext* context_;
fidl::BindingSet<fuchsia::sys::Runner> active_components_bindings_;
std::unordered_map<const Component*, ActiveComponent> active_components_;
#if !defined(DART_PRODUCT)
// The connection between the Dart VM service and The Hub.
std::unique_ptr<dart_utils::VMServiceObject> vmservice_object_;
std::unique_ptr<trace::TraceObserver> trace_observer_;
trace_prolonged_context_t* prolonged_context_;
#endif // !defined(DART_PRODUCT)
FML_DISALLOW_COPY_AND_ASSIGN(Runner);
};