Flutter Engine
 
Loading...
Searching...
No Matches
persistent_cache.cc
Go to the documentation of this file.
1// Copyright 2013 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#if !SLIMPELLER
6
8
9#include <future>
10#include <memory>
11#include <string>
12#include <string_view>
13#include <utility>
14
15#include "flutter/fml/base32.h"
16#include "flutter/fml/file.h"
18#include "flutter/fml/logging.h"
20#include "flutter/fml/mapping.h"
21#include "flutter/fml/paths.h"
25#include "openssl/sha.h"
26#include "rapidjson/document.h"
27#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h"
28
29namespace flutter {
30
31std::string PersistentCache::cache_base_path_;
32
33std::shared_ptr<AssetManager> PersistentCache::asset_manager_;
34
35std::mutex PersistentCache::instance_mutex_;
36std::unique_ptr<PersistentCache> PersistentCache::gPersistentCache;
37
38std::string PersistentCache::SkKeyToFilePath(const SkData& key) {
39 if (key.data() == nullptr || key.size() == 0) {
40 return "";
41 }
42
43 uint8_t sha_digest[SHA_DIGEST_LENGTH];
44 SHA1(static_cast<const uint8_t*>(key.data()), key.size(), sha_digest);
45
46 std::string_view view(reinterpret_cast<const char*>(sha_digest),
47 SHA_DIGEST_LENGTH);
48 return fml::HexEncode(view);
49}
50
52
53std::atomic<bool> PersistentCache::cache_sksl_ = false;
54std::atomic<bool> PersistentCache::strategy_set_ = false;
55
57 if (strategy_set_ && value != cache_sksl_) {
58 FML_LOG(ERROR) << "Cache SkSL can only be set before the "
59 "GrContextOptions::fShaderCacheStrategy is set.";
60 return;
61 }
62 cache_sksl_ = value;
63}
64
66 std::scoped_lock lock(instance_mutex_);
67 if (gPersistentCache == nullptr) {
68 gPersistentCache.reset(new PersistentCache(gIsReadOnly));
69 }
70 return gPersistentCache.get();
71}
72
74 std::scoped_lock lock(instance_mutex_);
75 gPersistentCache.reset(new PersistentCache(gIsReadOnly));
76 strategy_set_ = false;
77}
78
80 cache_base_path_ = std::move(path);
81}
82
84 // Make sure that this is called after the worker task runner setup so all the
85 // file system modifications would happen on that single thread to avoid
86 // racing.
87 FML_CHECK(GetWorkerTaskRunner());
88
89 std::promise<bool> removed;
90 GetWorkerTaskRunner()->PostTask([&removed,
91 cache_directory = cache_directory_]() {
92 if (cache_directory->is_valid()) {
93 // Only remove files but not directories.
94 FML_LOG(INFO) << "Purge persistent cache.";
95 fml::FileVisitor delete_file = [](const fml::UniqueFD& directory,
96 const std::string& filename) {
97 // Do not delete directories. Return true to continue with other files.
98 if (fml::IsDirectory(directory, filename.c_str())) {
99 return true;
100 }
101 return fml::UnlinkFile(directory, filename.c_str());
102 };
103 removed.set_value(VisitFilesRecursively(*cache_directory, delete_file));
104 } else {
105 removed.set_value(false);
106 }
107 });
108 return removed.get_future().get();
109}
110
111namespace {
112
113constexpr char kEngineComponent[] = "flutter_engine";
114
115static void FreeOldCacheDirectory(const fml::UniqueFD& cache_base_dir) {
116 fml::UniqueFD engine_dir =
117 fml::OpenDirectoryReadOnly(cache_base_dir, kEngineComponent);
118 if (!engine_dir.is_valid()) {
119 return;
120 }
121 fml::VisitFiles(engine_dir, [](const fml::UniqueFD& directory,
122 const std::string& filename) {
123 if (filename != GetFlutterEngineVersion()) {
124 auto dir = fml::OpenDirectory(directory, filename.c_str(), false,
126 if (dir.is_valid()) {
127 fml::RemoveDirectoryRecursively(directory, filename.c_str());
128 }
129 }
130 return true;
131 });
132}
133
134static std::shared_ptr<fml::UniqueFD> MakeCacheDirectory(
135 const std::string& global_cache_base_path,
136 bool read_only,
137 bool cache_sksl) {
138 fml::UniqueFD cache_base_dir;
139 if (global_cache_base_path.length()) {
140 cache_base_dir = fml::OpenDirectory(global_cache_base_path.c_str(), false,
142 } else {
143 cache_base_dir = fml::paths::GetCachesDirectory();
144 }
145
146 if (cache_base_dir.is_valid()) {
147 FreeOldCacheDirectory(cache_base_dir);
148 std::vector<std::string> components = {
149 kEngineComponent, GetFlutterEngineVersion(), "skia", GetSkiaVersion()};
150 if (cache_sksl) {
151 components.push_back(PersistentCache::kSkSLSubdirName);
152 }
153 return std::make_shared<fml::UniqueFD>(
154 CreateDirectory(cache_base_dir, components,
157 } else {
158 return std::make_shared<fml::UniqueFD>();
159 }
160}
161} // namespace
162
163sk_sp<SkData> ParseBase32(const std::string& input) {
164 std::pair<bool, std::string> decode_result = fml::Base32Decode(input);
165 if (!decode_result.first) {
166 FML_LOG(ERROR) << "Base32 can't decode: " << input;
167 return nullptr;
168 }
169 const std::string& data_string = decode_result.second;
170 return SkData::MakeWithCopy(data_string.data(), data_string.length());
171}
172
173sk_sp<SkData> ParseBase64(const std::string& input) {
175
176 size_t output_len;
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);
180 FML_LOG(ERROR) << "Base64 can't decode: " << input;
181 return nullptr;
182 }
183
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);
189 FML_LOG(ERROR) << "Base64 can't decode: " << input;
190 return nullptr;
191 }
192
193 return data;
194}
195
196size_t PersistentCache::PrecompileKnownSkSLs(GrDirectContext* context) const {
197 // clang-tidy has trouble reasoning about some of the complicated array and
198 // pointer-arithmetic code in rapidjson.
199 // NOLINTNEXTLINE(clang-analyzer-cplusplus.PlacementNew)
200 auto known_sksls = LoadSkSLs();
201 // A trace must be present even if no precompilations have been completed.
202 FML_TRACE_EVENT("flutter", "PersistentCache::PrecompileKnownSkSLs", "count",
203 known_sksls.size());
204
205 if (context == nullptr) {
206 return 0;
207 }
208
209 size_t precompiled_count = 0;
210 for (const auto& sksl : known_sksls) {
211 TRACE_EVENT0("flutter", "PrecompilingSkSL");
212 if (context->precompileShader(*sksl.key, *sksl.value)) {
213 precompiled_count++;
214 }
215 }
216
217 FML_TRACE_COUNTER("flutter", "PersistentCache::PrecompiledSkSLs",
218 reinterpret_cast<int64_t>(this), // Trace Counter ID
219 "Successful", precompiled_count);
220 return precompiled_count;
221}
222
223std::vector<PersistentCache::SkSLCache> PersistentCache::LoadSkSLs() const {
224 TRACE_EVENT0("flutter", "PersistentCache::LoadSkSLs");
225 std::vector<PersistentCache::SkSLCache> result;
226 fml::FileVisitor visitor = [&result](const fml::UniqueFD& directory,
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);
231 } else {
232 FML_LOG(ERROR) << "Failed to load: " << filename;
233 }
234 return true;
235 };
236
237 // Only visit sksl_cache_directory_ if this persistent cache is valid.
238 // However, we'd like to continue visit the asset dir even if this persistent
239 // cache is invalid.
240 if (IsValid()) {
241 // In case `rewinddir` doesn't work reliably, load SkSLs from a freshly
242 // opened directory (https://github.com/flutter/flutter/issues/65258).
243 fml::UniqueFD fresh_dir =
244 fml::OpenDirectoryReadOnly(*cache_directory_, kSkSLSubdirName);
245 if (fresh_dir.is_valid()) {
246 fml::VisitFiles(fresh_dir, visitor);
247 }
248 }
249
250 std::unique_ptr<fml::Mapping> mapping = nullptr;
251 if (asset_manager_ != nullptr) {
252 mapping = asset_manager_->GetAsMapping(kAssetFileName);
253 }
254 if (mapping == nullptr) {
255 FML_LOG(INFO) << "No sksl asset found.";
256 } else {
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()),
261 mapping->GetSize());
262 if (parse_result.IsError()) {
263 FML_LOG(ERROR) << "Failed to parse json file: " << kAssetFileName;
264 } else {
265 for (auto& item : json_doc["data"].GetObject()) {
266 sk_sp<SkData> key = ParseBase32(item.name.GetString());
267 sk_sp<SkData> sksl = ParseBase64(item.value.GetString());
268 if (key != nullptr && sksl != nullptr) {
269 result.push_back({key, sksl});
270 } else {
271 FML_LOG(ERROR) << "Failed to load: " << item.name.GetString();
272 }
273 }
274 }
275 }
276
277 return result;
278}
279
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)) {
285 if (!IsValid()) {
286 FML_LOG(WARNING) << "Could not acquire the persistent cache directory. "
287 "Caching of GPU resources on disk is disabled.";
288 }
289}
290
292
293bool PersistentCache::IsValid() const {
294 return cache_directory_ && cache_directory_->is_valid();
295}
296
297PersistentCache::SkSLCache PersistentCache::LoadFile(
298 const fml::UniqueFD& dir,
299 const std::string& file_name,
300 bool need_key) {
301 SkSLCache result;
302 auto file = fml::OpenFileReadOnly(dir, file_name.c_str());
303 if (!file.is_valid()) {
304 return result;
305 }
306 auto mapping = std::make_unique<fml::FileMapping>(file);
307 if (mapping->GetSize() < sizeof(CacheObjectHeader)) {
308 return result;
309 }
310 const CacheObjectHeader* header =
311 reinterpret_cast<const CacheObjectHeader*>(mapping->GetMapping());
312 if (header->signature != CacheObjectHeader::kSignature ||
313 header->version != CacheObjectHeader::kVersion1) {
314 FML_LOG(INFO) << "Persistent cache header is corrupt: " << file_name;
315 return result;
316 }
317 if (mapping->GetSize() < sizeof(CacheObjectHeader) + header->key_size) {
318 FML_LOG(INFO) << "Persistent cache size is corrupt: " << file_name;
319 return result;
320 }
321 if (need_key) {
322 result.key = SkData::MakeWithCopy(
323 mapping->GetMapping() + sizeof(CacheObjectHeader), header->key_size);
324 }
325 size_t value_offset = sizeof(CacheObjectHeader) + header->key_size;
326 result.value = SkData::MakeWithCopy(mapping->GetMapping() + value_offset,
327 mapping->GetSize() - value_offset);
328 return result;
329}
330
331// |GrContextOptions::PersistentCache|
332sk_sp<SkData> PersistentCache::load(const SkData& key) {
333 TRACE_EVENT0("flutter", "PersistentCacheLoad");
334 if (!IsValid()) {
335 return nullptr;
336 }
337 auto file_name = SkKeyToFilePath(key);
338 if (file_name.empty()) {
339 return nullptr;
340 }
341 auto result =
342 PersistentCache::LoadFile(*cache_directory_, file_name, false).value;
343 if (result != nullptr) {
344 TRACE_EVENT0("flutter", "PersistentCacheLoadHit");
345 }
346 return result;
347}
348
350 const fml::RefPtr<fml::TaskRunner>& worker,
351 const std::shared_ptr<fml::UniqueFD>& cache_directory,
352 std::string key,
353 std::unique_ptr<fml::Mapping> value) {
354 // The static leak checker gets confused by the use of fml::MakeCopyable.
355 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
356 auto task = fml::MakeCopyable([cache_directory, //
357 file_name = std::move(key), //
358 mapping = std::move(value) //
359 ]() mutable {
360 TRACE_EVENT0("flutter", "PersistentCacheStore");
361 if (!fml::WriteAtomically(*cache_directory, //
362 file_name.c_str(), //
363 *mapping) //
364 ) {
365 FML_LOG(WARNING) << "Could not write cache contents to persistent store.";
366 }
367 });
368
369 if (!worker) {
370 FML_LOG(WARNING)
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 "
373 "frame workload.";
374 task();
375 } else {
376 worker->PostTask(std::move(task));
377 }
378}
379
380std::unique_ptr<fml::MallocMapping> PersistentCache::BuildCacheObject(
381 const SkData& key,
382 const SkData& data) {
383 size_t total_size = sizeof(CacheObjectHeader) + key.size() + data.size();
384 uint8_t* mapping_buf = reinterpret_cast<uint8_t*>(malloc(total_size));
385 if (!mapping_buf) {
386 return nullptr;
387 }
388 auto mapping = std::make_unique<fml::MallocMapping>(mapping_buf, total_size);
389
390 CacheObjectHeader header(key.size());
391 memcpy(mapping_buf, &header, sizeof(CacheObjectHeader));
392 mapping_buf += sizeof(CacheObjectHeader);
393 memcpy(mapping_buf, key.data(), key.size());
394 mapping_buf += key.size();
395 memcpy(mapping_buf, data.data(), data.size());
396
397 return mapping;
398}
399
400// |GrContextOptions::PersistentCache|
401void PersistentCache::store(const SkData& key, const SkData& data) {
402 stored_new_shaders_ = true;
403
404 if (is_read_only_) {
405 return;
406 }
407
408 if (!IsValid()) {
409 return;
410 }
411
412 auto file_name = SkKeyToFilePath(key);
413
414 if (file_name.empty()) {
415 return;
416 }
417
418 std::unique_ptr<fml::MallocMapping> mapping = BuildCacheObject(key, data);
419 if (!mapping) {
420 return;
421 }
422
423 PersistentCacheStore(GetWorkerTaskRunner(),
424 cache_sksl_ ? sksl_cache_directory_ : cache_directory_,
425 std::move(file_name), std::move(mapping));
426}
427
428void PersistentCache::DumpSkp(const SkData& data) {
429 if (is_read_only_ || !IsValid()) {
430 FML_LOG(ERROR) << "Could not dump SKP from read-only or invalid persistent "
431 "cache.";
432 return;
433 }
434
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()});
442 PersistentCacheStore(GetWorkerTaskRunner(), cache_directory_,
443 std::move(file_name), std::move(mapping));
444}
445
447 const fml::RefPtr<fml::TaskRunner>& task_runner) {
448 std::scoped_lock lock(worker_task_runners_mutex_);
449 worker_task_runners_.insert(task_runner);
450}
451
453 const fml::RefPtr<fml::TaskRunner>& 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);
458 }
459}
460
461fml::RefPtr<fml::TaskRunner> PersistentCache::GetWorkerTaskRunner() const {
463
464 std::scoped_lock lock(worker_task_runners_mutex_);
465 if (!worker_task_runners_.empty()) {
466 worker = *worker_task_runners_.begin();
467 }
468
469 return worker;
470}
471
472void PersistentCache::SetAssetManager(std::shared_ptr<AssetManager> value) {
473 TRACE_EVENT_INSTANT0("flutter", "PersistentCache::SetAssetManager");
474 asset_manager_ = std::move(value);
475}
476
477std::vector<std::unique_ptr<fml::Mapping>>
479 if (!asset_manager_) {
480 FML_LOG(ERROR)
481 << "PersistentCache::GetSkpsFromAssetManager: Asset manager not set!";
482 return std::vector<std::unique_ptr<fml::Mapping>>();
483 }
484 return asset_manager_->GetAsMappings(".*\\.skp$", "shaders");
485}
486
487} // namespace flutter
488
489#endif // !SLIMPELLER
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)
void AddWorkerTaskRunner(const fml::RefPtr< fml::TaskRunner > &task_runner)
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
Definition time_delta.h:61
constexpr TimeDelta ToEpochDelta() const
Definition time_point.h:52
static TimePoint Now()
Definition time_point.cc:49
bool is_valid() const
static int input(yyscan_t yyscanner)
int32_t value
FlView * view
const uint8_t uint32_t uint32_t GError ** error
#define FML_LOG(severity)
Definition logging.h:101
#define FML_CHECK(condition)
Definition logging.h:104
const char * GetSkiaVersion()
Definition version.cc:19
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
Definition switch_defs.h:52
const char * GetFlutterEngineVersion()
Definition version.cc:11
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
Definition switch_defs.h:36
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)
Definition hex_codec.cc:14
fml::UniqueFD OpenFileReadOnly(const fml::UniqueFD &base_directory, const char *path)
Definition file.cc:92
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)
Definition file.cc:97
std::pair< bool, std::string > Base32Decode(const std::string &input)
Definition base32.cc:55
fml::UniqueFD OpenDirectory(const char *path, bool create_if_necessary, FilePermission permission)
Definition file_posix.cc:97
internal::CopyableLambda< T > MakeCopyable(T lambda)
bool RemoveDirectoryRecursively(const fml::UniqueFD &parent, const char *directory_name)
Definition file.cc:120
FilePermission
Definition file.h:24
std::function< bool(const fml::UniqueFD &directory, const std::string &filename)> FileVisitor
Definition file.h:98
Definition ref_ptr.h:261
std::shared_ptr< const fml::Mapping > data
#define TRACE_EVENT0(category_group, name)
#define FML_TRACE_COUNTER(category_group, name, counter_id, arg1,...)
Definition trace_event.h:85
#define TRACE_EVENT_INSTANT0(category_group, name)
#define FML_TRACE_EVENT(category_group, name,...)
#define CreateDirectory