Skip to content

Commit

Permalink
Support multiple shells in a single process.
Browse files Browse the repository at this point in the history
The Flutter Engine currently works by initializing a singleton shell
instance. This shell has to be created on the platform thread. The shell
is responsible for creating the 3 main threads used by Flutter (UI, IO,
GPU) as well as initializing the Dart VM. The shell, references to task
runners of the main threads as well as all snapshots used for VM
initialization are stored in singleton objects. The Flutter shell only
creates the threads, rasterizers, contexts, etc. to fully support a
single Flutter application. Current support for multiple Flutter
applications is achieved by making multiple applications share the same
resources (via the platform views mechanism).

This scheme has the following limitations:

* The shell is a singleton and there is no way to tear it down. Once you
  run a Flutter application in a process, all resources managed by it
  will remain referenced till process termination.
* The threads on which the shell performs its operations are all
  singletons. These threads are never torn down and multiple Flutter
  applications (if present) have to compete with one another on these
  threads.
* Resources referenced by the Dart VM are leaked because the VM isn't
  shutdown even when there are no more Flutter views.
* The shell as a target does not compile on Fuchsia. The Fuchsia content
  handler uses specific dependencies of the shell to rebuild all the
  shell dependencies on its own. This leads to differences in frame
  scheduling, VM setup, service protocol endpoint setup, tracing, etc..
  Fuchsia is very much a second class citizen in this world.
* Since threads and message loops are managed by the engine, the engine
  has to know about threading and platform message loop interop on each
  supported platform.

Specific updates in this patch:

* The shell is no longer a singleton and the embedder holds the unique
  reference to the shell.
* Shell setup and teardown is deterministic.
* Threads are no longer managed by the shell. Instead, the shell is
  given a task runner configuration by the embedder.
* Since the shell does not own its threads, the embedder can control
  threads and the message loops operating on these threads. The shell is
  only given references to the task runners that execute tasks on these
  threads.
* The shell only needs task runner references. These references can be
  to the same task runner. So, if the embedder thinks that a particular
  Flutter application would not need all the threads, it can pass
  references to the same task runner. This effectively makes Flutter
  application run in single threaded mode. There are some places in the
  shell that make synchronous calls, these sites have been updated to
  ensure that they don’t deadlock.
* The test runner and the headless Dart code runner are now Flutter
  applications that are effectively single threaded (since they don’t
  have rendering concerns of big-boy Flutter application).
* The embedder has to guarantee that the threads and outlive the shell.
  It is easy for the embedder to make that guarantee because shell
  termination is deterministic.
* The embedder can create as many shell as it wants. Typically it
  creates a shell per Flutter application with its own task runner
  configuration. Most embedders obtain these task runners from threads
  dedicated to the shell. But, it is entirely possible that the embedder
  can obtain these task runners from a thread pool.
* There can only be one Dart VM in the process. The numerous shell
  interact with one another to manage the VM lifecycle. Once the last
  shell goes away, the VM does as well and hence all resources
  associated with the VM are collected.
* The shell as a target can now compile and run on Fuchsia. The current
  content handler has been removed from the Flutter engine source tree
  and a new implementation has been written that uses the new shell
  target.
* Isolate management has been significantly overhauled. There are no
  owning references to Dart isolates within the shell. The VM owns the
  only strong reference to the Dart isolate. The isolate that has window
  bindings is now called the root isolate. Child isolates can now be
  created from the root isolate and their bindings and thread
  configurations are now inherited from the root isolate.
* Terminating the shell terminates its root isolates as well as all the
  isolates spawned by this isolate. This is necessary be shell shutdown
  is deterministic and the embedder is free to collect the threads on
  which the isolates execute their tasks (and listen for mircrotasks
  flushes on).
* Launching the root isolate is now significantly overhauled. The shell
  side (non-owning) reference to an isolate is now a little state
  machine and illegal state transitions should be impossible (barring
  construction issues). This is the only way to manage Dart isolates in
  the shell (the shell does not use the C API is dart_api.h anymore).
* Once an isolate is launched, it must be prepared (and hence move to
  the ready phase) by associating a snapshot with the same. This
  snapshot can either be a precompiled snapshot, kernel snapshot, script
  snapshot or source file. Depending on the kind of data specified as a
  snapshot as well as the capabilities of the VM running in the process,
  isolate preparation can fail preparation with the right message.
* Asset management has been significantly overhauled. All asset
  resolution goes through an abstract asset resolver interface. An asset
  manager implements this interface and manages one or more child asset
  resolvers. These asset resolvers typically resolve assets from
  directories, ZIP files (legacy FLX assets if provided), APK bundles,
  FDIO namespaces, etc…
* Each launch of the shell requires a separate and fully configured
  asset resolver. This is necessary because launching isolates for the
  engine may require resolving snapshots as assets from the asset
  resolver. Asset resolvers can be shared by multiple launch instances
  in multiple shells and need to be thread safe.
* References to the command line object have been removed from the
  shell. Instead, the shell only takes a settings object that may be
  configured from the command line. This makes it easy for embedders and
  platforms that don’t have a command line (Fuchsia) to configure the
  shell. Consequently, there is only one spot where the various switches
  are read from the command line (by the embedder and not the shell) to
  form the settings object.
* All platform now respect the log tag (this was done only by Android
  till now) and each shell instance have its own log tag. This makes
  logs from multiple Flutter application in the same process (mainly
  Fuchsia) more easily decipherable.
* The per shell IO task runner now has a new component that is
  unfortunately named the IOManager. This component manages the IO
  GrContext (used for asynchronous texture uploads) that cooperates with
  the GrContext on the GPU task runner associated with the shell. The
  IOManager is also responsible for flushing tasks that collect Skia
  objects that reference GPU resources during deterministic shell
  shutdown.
* The embedder now has to be careful to only enable Blink on a single
  instance of the shell. Launching the legacy text layout and rendering
  engine multiple times is will trip assertions. The entirety of this
  runtime has been separated out into a separate object and can be
  removed in one go when the migration to libtxt is complete.
* There is a new test target for the various C++ objects that the shell
  uses to interact with the Dart VM (the shell no longer use the C API
  in dart_api.h). This allows engine developers to test VM/Isolate
  initialization and teardown without having the setup a full shell
  instance.
* There is a new test target for the testing a single shell instances
  without having to configure and launch an entire VM and associated
  root isolate.
* Mac, Linux & Windows used to have different target that created the
  flutter_tester referenced by the tool. This has now been converted
  into a single target that compiles on all platforms.
* WeakPointers vended by the fml::WeakPtrFactory(notice the difference
  between the same class in the fxl namespace) add threading checks on
  each use. This is enabled by getting rid of the “re-origination”
  feature of the WeakPtrFactory in the fxl namespace. The side effect of
  this is that all non-thread safe components have to be created, used
  and destroyed on the same thread. Numerous thread safety issues were
  caught by this extra assertion and have now been fixed.
  * Glossary of components that are only safe on a specific thread (and
    have the fml variants of the WeakPtrFactory):
    * Platform Thread: Shell
    * UI Thread: Engine, RuntimeDelegate, DartIsolate, Animator
    * GPU Thread: Rasterizer, Surface
    * IO Thread: IOManager

This patch was reviewed in smaller chunks in the following pull
requests. All comments from the pulls requests has been incorporated
into this patch:

* flutter/assets: flutter#4829
* flutter/common: flutter#4830
* flutter/content_handler: flutter#4831
* flutter/flow: flutter#4832
* flutter/fml: flutter#4833
* flutter/lib/snapshot: flutter#4834
* flutter/lib/ui: flutter#4835
* flutter/runtime: flutter#4836
* flutter/shell: flutter#4837
* flutter/synchronization: flutter#4838
* flutter/testing: flutter#4839
  • Loading branch information
chinmaygarde committed Apr 10, 2018
1 parent c8e4c69 commit c50158f
Show file tree
Hide file tree
Showing 345 changed files with 12,543 additions and 11,072 deletions.
74 changes: 32 additions & 42 deletions BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,12 @@ group("flutter") {
public_deps = [
"$flutter_root/lib/snapshot:generate_snapshot_bin",
"$flutter_root/lib/snapshot:kernel_platform_files",
"$flutter_root/shell/testing",
"$flutter_root/sky",
"$flutter_root/third_party/txt",
]

if (flutter_runtime_mode != "debug") {
public_deps += [
"$flutter_root/lib/snapshot:entry_points_json_files",
]
public_deps += [ "$flutter_root/lib/snapshot:entry_points_json_files" ]
}

if (!is_fuchsia && !is_fuchsia_host) {
Expand Down Expand Up @@ -45,20 +43,24 @@ group("flutter") {
"$flutter_root/shell/platform/embedder:flutter_embedder_framework",
]
}
if (!is_win) {
public_deps += [
"$flutter_root/shell/platform/embedder:embedder_unittests",
"$flutter_root/shell/platform/embedder:flutter_engine",
]
}

public_deps += [
"$flutter_root/flow:flow_unittests",
"$flutter_root/fml:fml_unittests",
"$flutter_root/runtime:runtime_unittests",
"$flutter_root/shell/common:shell_unittests",
"$flutter_root/sky/engine/wtf:wtf_unittests",
"$flutter_root/synchronization:synchronization_unittests",
"$flutter_root/third_party/txt:txt_unittests",
"//garnet/public/lib/fxl:fxl_unittests",
]

if (!is_win) {
public_deps += [
"$flutter_root/shell/platform/embedder:embedder_unittests",
"$flutter_root/shell/platform/embedder:flutter_engine",
]
}
}
}

Expand All @@ -74,59 +76,47 @@ if (is_fuchsia) {
"$flutter_root/content_handler:aot",
]
if (flutter_runtime_mode != "release") {
deps += [
"//third_party/dart/runtime/observatory:embedded_archive_observatory",
]
deps += [ "//third_party/dart/runtime/observatory:embedded_archive_observatory" ]
}

binary = "flutter_aot_runner"

if (flutter_runtime_mode != "release") {
resources = [
{
path = rebase_path(
"$root_gen_dir/observatory/embedded_archive_observatory.tar")
dest = "observatory.tar"
},
]
resources = [ {
path = rebase_path(
"$root_gen_dir/observatory/embedded_archive_observatory.tar")
dest = "observatory.tar"
} ]
}

meta = [
{
path = rebase_path("content_handler/meta/sandbox")
dest = "sandbox"
},
]
meta = [ {
path = rebase_path("content_handler/meta/sandbox")
dest = "sandbox"
} ]
}

package("flutter_jit_runner") {
deps = [
"$flutter_root/content_handler:jit",
]
if (flutter_runtime_mode != "release") {
deps += [
"//third_party/dart/runtime/observatory:embedded_archive_observatory",
]
deps += [ "//third_party/dart/runtime/observatory:embedded_archive_observatory" ]
}

binary = "flutter_jit_runner"

if (flutter_runtime_mode != "release") {
resources = [
{
path = rebase_path(
"$root_gen_dir/observatory/embedded_archive_observatory.tar")
dest = "observatory.tar"
},
]
resources = [ {
path = rebase_path(
"$root_gen_dir/observatory/embedded_archive_observatory.tar")
dest = "observatory.tar"
} ]
}

meta = [
{
path = rebase_path("content_handler/meta/sandbox")
dest = "sandbox"
},
]
meta = [ {
path = rebase_path("content_handler/meta/sandbox")
dest = "sandbox"
} ]
}
} else {
group("dist") {
Expand Down
2 changes: 1 addition & 1 deletion DEPS
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ allowed_hosts = [
]

deps = {
'src': 'https://github.com/flutter/buildroot.git' + '@' + '8dddd90bf943a8174913564353b30a3b11ee0f7a',
'src': 'https://github.com/flutter/buildroot.git' + '@' + '3cf97e01cdbd4bb920fa3d40282a56c4b2d62a58',

# Fuchsia compatibility
#
Expand Down
12 changes: 6 additions & 6 deletions assets/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,18 @@

source_set("assets") {
sources = [
"asset_provider.h",
"asset_manager.cc",
"asset_manager.h",
"asset_resolver.h",
"directory_asset_bundle.cc",
"directory_asset_bundle.h",
"unzipper_provider.cc",
"unzipper_provider.h",
"zip_asset_store.cc",
"zip_asset_store.h",
]

deps = [
"$flutter_root/common",
"$flutter_root/fml",
"$flutter_root/glue",
"//garnet/public/lib/fxl",
"//garnet/public/lib/zip",
Expand All @@ -23,7 +25,5 @@ source_set("assets") {
"//third_party/zlib:minizip",
]

public_configs = [
"$flutter_root:config",
]
public_configs = [ "$flutter_root:config" ]
}
55 changes: 55 additions & 0 deletions assets/asset_manager.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright 2017 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "flutter/assets/asset_manager.h"

#include "flutter/assets/directory_asset_bundle.h"
#include "flutter/assets/zip_asset_store.h"
#include "flutter/glue/trace_event.h"
#include "lib/fxl/files/path.h"

namespace blink {

AssetManager::AssetManager() = default;

AssetManager::~AssetManager() = default;

void AssetManager::PushFront(std::unique_ptr<AssetResolver> resolver) {
if (resolver == nullptr || !resolver->IsValid()) {
return;
}

resolvers_.push_front(std::move(resolver));
}

void AssetManager::PushBack(std::unique_ptr<AssetResolver> resolver) {
if (resolver == nullptr || !resolver->IsValid()) {
return;
}

resolvers_.push_back(std::move(resolver));
}

// |blink::AssetResolver|
bool AssetManager::GetAsBuffer(const std::string& asset_name,
std::vector<uint8_t>* data) const {
if (asset_name.size() == 0) {
return false;
}
TRACE_EVENT0("flutter", "AssetManager::GetAsBuffer");
for (const auto& resolver : resolvers_) {
if (resolver->GetAsBuffer(asset_name, data)) {
return true;
}
}
FXL_DLOG(ERROR) << "Could not find asset: " << asset_name;
return false;
}

// |blink::AssetResolver|
bool AssetManager::IsValid() const {
return resolvers_.size() > 0;
}

} // namespace blink
47 changes: 47 additions & 0 deletions assets/asset_manager.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright 2017 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_ASSETS_ASSET_MANAGER_H_
#define FLUTTER_ASSETS_ASSET_MANAGER_H_

#include <deque>
#include <memory>
#include <string>

#include "flutter/assets/asset_resolver.h"
#include "lib/fxl/files/unique_fd.h"
#include "lib/fxl/macros.h"
#include "lib/fxl/memory/ref_counted.h"

namespace blink {

class AssetManager final : public AssetResolver,
public fxl::RefCountedThreadSafe<AssetManager> {
public:
void PushFront(std::unique_ptr<AssetResolver> resolver);

void PushBack(std::unique_ptr<AssetResolver> resolver);

// |blink::AssetResolver|
bool IsValid() const override;

// |blink::AssetResolver|
bool GetAsBuffer(const std::string& asset_name,
std::vector<uint8_t>* data) const override;

private:
std::deque<std::unique_ptr<AssetResolver>> resolvers_;

AssetManager();

~AssetManager();

FXL_DISALLOW_COPY_AND_ASSIGN(AssetManager);
FRIEND_MAKE_REF_COUNTED(AssetManager);
FRIEND_REF_COUNTED_THREAD_SAFE(AssetManager);
};

} // namespace blink

#endif // FLUTTER_ASSETS_ASSET_MANAGER_H_
25 changes: 0 additions & 25 deletions assets/asset_provider.h

This file was deleted.

32 changes: 32 additions & 0 deletions assets/asset_resolver.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright 2017 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_ASSETS_ASSET_RESOLVER_H_
#define FLUTTER_ASSETS_ASSET_RESOLVER_H_

#include <string>
#include <vector>

#include "lib/fxl/macros.h"

namespace blink {

class AssetResolver {
public:
AssetResolver() = default;

virtual ~AssetResolver() = default;

virtual bool IsValid() const = 0;

virtual bool GetAsBuffer(const std::string& asset_name,
std::vector<uint8_t>* data) const = 0;

private:
FXL_DISALLOW_COPY_AND_ASSIGN(AssetResolver);
};

} // namespace blink

#endif // FLUTTER_ASSETS_ASSET_RESOLVER_H_
Loading

0 comments on commit c50158f

Please sign in to comment.