7#include "flutter/common/graphics/persistent_cache.h"
15#include "flutter/fml/base32.h"
16#include "flutter/fml/file.h"
17#include "flutter/fml/hex_codec.h"
18#include "flutter/fml/logging.h"
19#include "flutter/fml/make_copyable.h"
20#include "flutter/fml/mapping.h"
21#include "flutter/fml/paths.h"
22#include "flutter/fml/trace_event.h"
23#include "flutter/shell/common/base64.h"
24#include "flutter/shell/version/version.h"
25#include "openssl/sha.h"
26#include "rapidjson/document.h"
31std::string PersistentCache::cache_base_path_;
33std::shared_ptr<AssetManager> PersistentCache::asset_manager_;
35std::mutex PersistentCache::instance_mutex_;
36std::unique_ptr<PersistentCache> PersistentCache::gPersistentCache;
39 if (
key.data() ==
nullptr ||
key.size() == 0) {
43 uint8_t sha_digest[SHA_DIGEST_LENGTH];
44 SHA1(
static_cast<const uint8_t*
>(
key.data()),
key.size(), sha_digest);
46 std::string_view view(
reinterpret_cast<const char*
>(sha_digest),
53std::atomic<bool> PersistentCache::cache_sksl_ =
false;
54std::atomic<bool> PersistentCache::strategy_set_ =
false;
57 if (strategy_set_ &&
value != cache_sksl_) {
58 FML_LOG(
ERROR) <<
"Cache SkSL can only be set before the "
59 "GrContextOptions::fShaderCacheStrategy is set.";
66 std::scoped_lock lock(instance_mutex_);
67 if (gPersistentCache ==
nullptr) {
70 return gPersistentCache.get();
74 std::scoped_lock lock(instance_mutex_);
76 strategy_set_ =
false;
80 cache_base_path_ = std::move(
path);
89 std::promise<bool> removed;
90 GetWorkerTaskRunner()->
PostTask([&removed,
91 cache_directory = cache_directory_]() {
92 if (cache_directory->is_valid()) {
94 FML_LOG(INFO) <<
"Purge persistent cache.";
95 fml::FileVisitor delete_file = [](const fml::UniqueFD& directory,
96 const std::string& filename) {
98 if (fml::IsDirectory(directory, filename.c_str())) {
101 return fml::UnlinkFile(directory, filename.c_str());
105 removed.set_value(
false);
108 return removed.get_future().get();
113constexpr char kEngineComponent[] =
"flutter_engine";
115static void FreeOldCacheDirectory(
const fml::UniqueFD& cache_base_dir) {
122 const std::string& filename) {
126 if (
dir.is_valid()) {
134static std::shared_ptr<fml::UniqueFD> MakeCacheDirectory(
135 const std::string& global_cache_base_path,
139 if (global_cache_base_path.length()) {
147 FreeOldCacheDirectory(cache_base_dir);
148 std::vector<std::string> components = {
151 components.push_back(PersistentCache::kSkSLSubdirName);
153 return std::make_shared<fml::UniqueFD>(
158 return std::make_shared<fml::UniqueFD>();
165 if (!decode_result.first) {
169 const std::string& data_string = decode_result.second;
200 auto known_sksls = LoadSkSLs();
202 FML_TRACE_EVENT(
"flutter",
"PersistentCache::PrecompileKnownSkSLs",
"count",
205 if (context ==
nullptr) {
209 size_t precompiled_count = 0;
210 for (
const auto& sksl : known_sksls) {
218 reinterpret_cast<int64_t
>(
this),
219 "Successful", precompiled_count);
220 return precompiled_count;
223std::vector<PersistentCache::SkSLCache> PersistentCache::LoadSkSLs()
const {
225 std::vector<PersistentCache::SkSLCache>
result;
227 const std::string& filename) {
229 if (
cache.key !=
nullptr &&
cache.value !=
nullptr) {
250 std::unique_ptr<fml::Mapping> mapping =
nullptr;
251 if (asset_manager_ !=
nullptr) {
252 mapping = asset_manager_->GetAsMapping(kAssetFileName);
254 if (mapping ==
nullptr) {
255 FML_LOG(INFO) <<
"No sksl asset found.";
257 FML_LOG(INFO) <<
"Found sksl asset. Loading SkSLs from it...";
258 rapidjson::Document json_doc;
259 rapidjson::ParseResult parse_result =
260 json_doc.Parse(
reinterpret_cast<const char*
>(mapping->GetMapping()),
262 if (parse_result.IsError()) {
263 FML_LOG(
ERROR) <<
"Failed to parse json file: " << kAssetFileName;
265 for (
auto& item : json_doc[
"data"].
GetObject()) {
268 if (
key !=
nullptr && sksl !=
nullptr) {
271 FML_LOG(
ERROR) <<
"Failed to load: " << item.name.GetString();
280PersistentCache::PersistentCache(
bool read_only)
281 : is_read_only_(read_only),
282 cache_directory_(MakeCacheDirectory(cache_base_path_, read_only,
false)),
283 sksl_cache_directory_(
284 MakeCacheDirectory(cache_base_path_, read_only,
true)) {
286 FML_LOG(WARNING) <<
"Could not acquire the persistent cache directory. "
287 "Caching of GPU resources on disk is disabled.";
293bool PersistentCache::IsValid()
const {
294 return cache_directory_ && cache_directory_->is_valid();
297PersistentCache::SkSLCache PersistentCache::LoadFile(
299 const std::string& file_name,
303 if (!
file.is_valid()) {
306 auto mapping = std::make_unique<fml::FileMapping>(
file);
307 if (mapping->GetSize() <
sizeof(CacheObjectHeader)) {
310 const CacheObjectHeader*
header =
311 reinterpret_cast<const CacheObjectHeader*
>(mapping->GetMapping());
314 FML_LOG(INFO) <<
"Persistent cache header is corrupt: " << file_name;
317 if (mapping->GetSize() <
sizeof(CacheObjectHeader) +
header->key_size) {
318 FML_LOG(INFO) <<
"Persistent cache size is corrupt: " << file_name;
323 mapping->GetMapping() +
sizeof(CacheObjectHeader),
header->key_size);
325 size_t value_offset =
sizeof(CacheObjectHeader) +
header->key_size;
327 mapping->GetSize() - value_offset);
338 if (file_name.empty()) {
342 PersistentCache::LoadFile(*cache_directory_, file_name,
false).value;
351 const std::shared_ptr<fml::UniqueFD>& cache_directory,
353 std::unique_ptr<fml::Mapping>
value) {
357 file_name = std::move(
key),
358 mapping = std::move(
value)
365 FML_LOG(WARNING) <<
"Could not write cache contents to persistent store.";
371 <<
"The persistent cache has no available workers. Performing the task "
372 "on the current thread. This slow operation is going to occur on a "
388 auto mapping = std::make_unique<fml::MallocMapping>(mapping_buf,
total_size);
393 memcpy(mapping_buf,
key.data(),
key.size());
394 mapping_buf +=
key.size();
395 memcpy(mapping_buf,
data.data(),
data.size());
402 stored_new_shaders_ =
true;
414 if (file_name.empty()) {
424 cache_sksl_ ? sksl_cache_directory_ : cache_directory_,
425 std::move(file_name), std::move(mapping));
429 if (is_read_only_ || !IsValid()) {
430 FML_LOG(
ERROR) <<
"Could not dump SKP from read-only or invalid persistent "
435 std::stringstream name_stream;
438 std::string file_name = name_stream.str();
439 FML_LOG(INFO) <<
"Dumping " << file_name;
440 auto mapping = std::make_unique<fml::DataMapping>(
441 std::vector<uint8_t>{
data.bytes(),
data.bytes() +
data.size()});
443 std::move(file_name), std::move(mapping));
448 std::scoped_lock lock(worker_task_runners_mutex_);
449 worker_task_runners_.insert(task_runner);
454 std::scoped_lock lock(worker_task_runners_mutex_);
455 auto found = worker_task_runners_.find(task_runner);
456 if (found != worker_task_runners_.end()) {
457 worker_task_runners_.erase(found);
464 std::scoped_lock lock(worker_task_runners_mutex_);
465 if (!worker_task_runners_.empty()) {
466 worker = *worker_task_runners_.begin();
474 asset_manager_ = std::move(
value);
477std::vector<std::unique_ptr<fml::Mapping>>
479 if (!asset_manager_) {
481 <<
"PersistentCache::GetSkpsFromAssetManager: Asset manager not set!";
482 return std::vector<std::unique_ptr<fml::Mapping>>();
484 return asset_manager_->GetAsMappings(
".*\\.skp$",
"shaders");
static size_t total_size(SkSBlockAllocator< N > &pool)
PersistentCache()=default
bool precompileShader(const SkData &key, const SkData &data)
static sk_sp< SkData > MakeUninitialized(size_t length)
static sk_sp< SkData > MakeWithCopy(const void *data, size_t length)
static void SetAssetManager(std::shared_ptr< AssetManager > value)
void RemoveWorkerTaskRunner(const fml::RefPtr< fml::TaskRunner > &task_runner)
std::vector< std::unique_ptr< fml::Mapping > > GetSkpsFromAssetManager() const
static void SetCacheDirectoryPath(std::string path)
sk_sp< SkData > load(const SkData &key) override
static PersistentCache * GetCacheForProcess()
void DumpSkp(const SkData &data)
static void SetCacheSkSL(bool value)
static void ResetCacheForProcess()
void AddWorkerTaskRunner(const fml::RefPtr< fml::TaskRunner > &task_runner)
~PersistentCache() override
static std::string SkKeyToFilePath(const SkData &key)
static std::unique_ptr< fml::MallocMapping > BuildCacheObject(const SkData &key, const SkData &data)
virtual void PostTask(const fml::closure &task) override
constexpr int64_t ToNanoseconds() const
TimeDelta ToEpochDelta() const
const uint8_t uint32_t uint32_t GError ** error
#define FML_LOG(severity)
#define FML_CHECK(condition)
SK_API std::unique_ptr< SkCodec > Decode(std::unique_ptr< SkStream >, SkCodec::Result *, SkCodecs::DecodeContext=nullptr)
void * malloc(size_t size)
static void GetObject(Thread *thread, JSONStream *js)
std::unique_ptr< fml::Mapping > LoadFile(int namespace_fd, const char *path, bool executable)
const char * GetSkiaVersion()
DEF_SWITCHES_START aot vmservice shared library Name of the *so containing AOT compiled Dart assets for launching the service isolate vm snapshot The VM snapshot data that will be memory mapped as read only SnapshotAssetPath must be present isolate snapshot The isolate snapshot data that will be memory mapped as read only SnapshotAssetPath must be present cache dir Path to the cache directory This is different from the persistent_cache_path in embedder which is used for Skia shader cache icu native lib Path to the library file that exports the ICU data vm service The hostname IP address on which the Dart VM Service should be served If not defaults to or::depending on whether ipv6 is specified vm service A custom Dart VM Service port The default is to pick a randomly available open port disable vm Disable the Dart VM Service The Dart VM Service is never available in release mode disable vm service Disable mDNS Dart VM Service publication Bind to the IPv6 localhost address for the Dart VM Service Ignored if vm service host is set endless trace Enable an endless trace buffer The default is a ring buffer This is useful when very old events need to viewed For during application launch Memory usage will continue to grow indefinitely however Start app with an specific route defined on the framework flutter assets Path to the Flutter assets directory enable service port Allow the VM service to fallback to automatic port selection if binding to a specified port fails trace Trace early application lifecycle Automatically switches to an endless trace buffer trace skia Filters out all Skia trace event categories except those that are specified in this comma separated list dump skp on shader Automatically dump the skp that triggers new shader compilations This is useful for writing custom ShaderWarmUp to reduce jank By this is not enabled to reduce the overhead purge persistent cache
DEF_SWITCHES_START aot vmservice shared library Name of the *so containing AOT compiled Dart assets for launching the service isolate vm snapshot The VM snapshot data that will be memory mapped as read only SnapshotAssetPath must be present isolate snapshot The isolate snapshot data that will be memory mapped as read only SnapshotAssetPath must be present cache dir path
const char * GetFlutterEngineVersion()
DEF_SWITCHES_START aot vmservice shared library Name of the *so containing AOT compiled Dart assets for launching the service isolate vm snapshot The VM snapshot data that will be memory mapped as read only SnapshotAssetPath must be present isolate snapshot The isolate snapshot data that will be memory mapped as read only SnapshotAssetPath must be present cache dir Path to the cache directory This is different from the persistent_cache_path in embedder which is used for Skia shader cache icu native lib Path to the library file that exports the ICU data vm service The hostname IP address on which the Dart VM Service should be served If not defaults to or::depending on whether ipv6 is specified vm service A custom Dart VM Service port The default is to pick a randomly available open port disable vm Disable the Dart VM Service The Dart VM Service is never available in release mode disable vm service Disable mDNS Dart VM Service publication Bind to the IPv6 localhost address for the Dart VM Service Ignored if vm service host is set endless trace Enable an endless trace buffer The default is a ring buffer This is useful when very old events need to viewed For during application launch Memory usage will continue to grow indefinitely however Start app with an specific route defined on the framework flutter assets Path to the Flutter assets directory enable service port Allow the VM service to fallback to automatic port selection if binding to a specified port fails trace Trace early application lifecycle Automatically switches to an endless trace buffer trace skia Filters out all Skia trace event categories except those that are specified in this comma separated list dump skp on shader Automatically dump the skp that triggers new shader compilations This is useful for writing custom ShaderWarmUp to reduce jank By this is not enabled to reduce the overhead purge persistent Remove all existing persistent cache This is mainly for debugging purposes such as reproducing the shader compilation jank trace to file
sk_sp< SkData > ParseBase32(const std::string &input)
DEF_SWITCHES_START aot vmservice shared library Name of the *so containing AOT compiled Dart assets for launching the service isolate vm snapshot data
DEF_SWITCHES_START aot vmservice shared library Name of the *so containing AOT compiled Dart assets for launching the service isolate vm snapshot The VM snapshot data that will be memory mapped as read only SnapshotAssetPath must be present isolate snapshot The isolate snapshot data that will be memory mapped as read only SnapshotAssetPath must be present cache dir Path to the cache directory This is different from the persistent_cache_path in embedder which is used for Skia shader cache icu native lib Path to the library file that exports the ICU data vm service The hostname IP address on which the Dart VM Service should be served If not defaults to or::depending on whether ipv6 is specified vm service A custom Dart VM Service port The default is to pick a randomly available open port disable vm Disable the Dart VM Service The Dart VM Service is never available in release mode disable vm service Disable mDNS Dart VM Service publication Bind to the IPv6 localhost address for the Dart VM Service Ignored if vm service host is set endless trace Enable an endless trace buffer The default is a ring buffer This is useful when very old events need to viewed For during application launch Memory usage will continue to grow indefinitely however Start app with an specific route defined on the framework flutter assets dir
sk_sp< SkData > ParseBase64(const std::string &input)
static void PersistentCacheStore(const fml::RefPtr< fml::TaskRunner > &worker, const std::shared_ptr< fml::UniqueFD > &cache_directory, std::string key, std::unique_ptr< fml::Mapping > value)
fml::UniqueFD GetCachesDirectory()
std::string HexEncode(std::string_view input)
fml::UniqueFD OpenFileReadOnly(const fml::UniqueFD &base_directory, const char *path)
bool VisitFiles(const fml::UniqueFD &directory, const FileVisitor &visitor)
bool WriteAtomically(const fml::UniqueFD &base_directory, const char *file_name, const Mapping &mapping)
fml::UniqueFD OpenDirectoryReadOnly(const fml::UniqueFD &base_directory, const char *path)
std::pair< bool, std::string > Base32Decode(const std::string &input)
fml::UniqueFD OpenDirectory(const char *path, bool create_if_necessary, FilePermission permission)
internal::CopyableLambda< T > MakeCopyable(T lambda)
bool RemoveDirectoryRecursively(const fml::UniqueFD &parent, const char *directory_name)
bool VisitFilesRecursively(const fml::UniqueFD &directory, const FileVisitor &visitor)
std::function< bool(const fml::UniqueFD &directory, const std::string &filename)> FileVisitor
static SkString to_string(int n)
static const char header[]
std::shared_ptr< const fml::Mapping > data
#define TRACE_EVENT0(category_group, name)
#define FML_TRACE_COUNTER(category_group, name, counter_id, arg1,...)
#define TRACE_EVENT_INSTANT0(category_group, name)
#define FML_TRACE_EVENT(category_group, name,...)