25#include "openssl/sha.h"
26#include "rapidjson/document.h"
27#include "third_party/skia/include/gpu/ganesh/GrDirectContext.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());
103 removed.set_value(VisitFilesRecursively(*cache_directory, delete_file));
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;
170 return SkData::MakeWithCopy(data_string.data(), data_string.length());
177 error = Base64::Decode(
input.c_str(),
input.length(),
nullptr, &output_len);
178 if (
error != Base64::Error::kNone) {
179 FML_LOG(ERROR) <<
"Base64 decode error: " <<
static_cast<int>(
error);
184 sk_sp<SkData>
data = SkData::MakeUninitialized(output_len);
185 void* output =
data->writable_data();
186 error = Base64::Decode(
input.c_str(),
input.length(), output, &output_len);
187 if (
error != Base64::Error::kNone) {
188 FML_LOG(ERROR) <<
"Base64 decode error: " <<
static_cast<int>(
error);
196size_t PersistentCache::PrecompileKnownSkSLs(GrDirectContext* context)
const {
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) {
212 if (context->precompileShader(*sksl.key, *sksl.value)) {
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) {
228 SkSLCache cache = LoadFile(directory, filename,
true);
229 if (cache.
key !=
nullptr && cache.
value !=
nullptr) {
230 result.push_back(cache);
232 FML_LOG(ERROR) <<
"Failed to load: " << filename;
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()) {
267 sk_sp<SkData> sksl =
ParseBase64(item.value.GetString());
268 if (
key !=
nullptr && sksl !=
nullptr) {
269 result.push_back({
key, sksl});
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;
322 result.key = SkData::MakeWithCopy(
323 mapping->GetMapping() +
sizeof(CacheObjectHeader), header->key_size);
325 size_t value_offset =
sizeof(CacheObjectHeader) + header->key_size;
326 result.value = SkData::MakeWithCopy(mapping->GetMapping() + value_offset,
327 mapping->GetSize() - value_offset);
338 if (file_name.empty()) {
342 PersistentCache::LoadFile(*cache_directory_, file_name,
false).value;
343 if (result !=
nullptr) {
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 "
376 worker->PostTask(std::move(task));
382 const SkData&
data) {
384 uint8_t* mapping_buf =
reinterpret_cast<uint8_t*
>(malloc(total_size));
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());
401void PersistentCache::store(
const SkData&
key,
const SkData&
data) {
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;
437 name_stream <<
"shader_dump_" << std::to_string(ticks) <<
".skp";
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 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
constexpr TimeDelta ToEpochDelta() const
const uint8_t uint32_t uint32_t GError ** error
#define FML_LOG(severity)
#define FML_CHECK(condition)
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
const char * GetFlutterEngineVersion()
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
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)
std::function< bool(const fml::UniqueFD &directory, const std::string &filename)> FileVisitor
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,...)