Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- flutter/engine/src/flutter/fml/memory/ref_counted.hAdded+137
- flutter/engine/src/flutter/fml/memory/ref_counted_internal.hAdded+106
- flutter/engine/src/flutter/fml/memory/ref_counted_unittest.ccAdded+647
- flutter/engine/src/flutter/fml/memory/ref_ptr.hAdded+272
- flutter/engine/src/flutter/fml/memory/ref_ptr_internal.hAdded+38
- flutter/engine/src/flutter/fml/memory/task_runner_checker.ccAdded+52
- flutter/engine/src/flutter/fml/memory/task_runner_checker.hAdded+41
- flutter/engine/src/flutter/fml/memory/task_runner_checker_unittest.ccAdded+173
- flutter/engine/src/flutter/fml/memory/thread_checker.ccAdded+11
- flutter/engine/src/flutter/fml/memory/thread_checker.hAdded+104
- flutter/engine/src/flutter/fml/memory/weak_ptr.hAdded+328
- flutter/engine/src/flutter/fml/memory/weak_ptr_internal.ccAdded+26
- flutter/engine/src/flutter/fml/memory/weak_ptr_internal.hAdded+41
- flutter/engine/src/flutter/fml/memory/weak_ptr_unittest.ccAdded+241
- flutter/engine/src/flutter/fml/synchronization/atomic_object.hAdded+36
- flutter/engine/src/flutter/fml/synchronization/count_down_latch.ccAdded+29
- flutter/engine/src/flutter/fml/synchronization/count_down_latch.hAdded+34
- flutter/engine/src/flutter/fml/synchronization/count_down_latch_unittests.ccAdded+41
- flutter/engine/src/flutter/fml/synchronization/semaphore.ccAdded+193
- flutter/engine/src/flutter/impeller/base/BUILD.gnAdded+47
- flutter/engine/src/flutter/impeller/base/README.mdAdded+4
- flutter/engine/src/flutter/impeller/base/allocation.ccAdded+118
- flutter/engine/src/flutter/impeller/base/allocation.hAdded+152
- flutter/engine/src/flutter/impeller/base/allocation_size.ccAdded+11
- flutter/engine/src/flutter/impeller/base/allocation_size.hAdded+202
- flutter/engine/src/flutter/impeller/base/allocation_size_unittests.ccAdded+125
- flutter/engine/src/flutter/impeller/base/backend_cast.hAdded+28
- flutter/engine/src/flutter/impeller/base/base_unittests.ccAdded+449
- flutter/engine/src/flutter/impeller/base/comparable.ccAdded+14
- flutter/engine/src/flutter/impeller/base/comparable.hAdded+114
- flutter/engine/src/flutter/impeller/base/config.hAdded+40
- flutter/engine/src/flutter/impeller/base/flags.hAdded+18
- flutter/engine/src/flutter/impeller/base/mask.hAdded+230
- flutter/engine/src/flutter/impeller/base/promise.ccAdded+11
- flutter/engine/src/flutter/impeller/base/promise.hAdded+50
- flutter/engine/src/flutter/impeller/base/strings.ccAdded+50
- flutter/engine/src/flutter/impeller/base/strings.hAdded+25
- flutter/engine/src/flutter/impeller/base/thread.ccAdded+11
- flutter/engine/src/flutter/impeller/base/thread.hAdded+270
- flutter/engine/src/flutter/impeller/base/thread_safety.ccAdded+11
- flutter/engine/src/flutter/impeller/base/thread_safety.hAdded+72
- flutter/engine/src/flutter/impeller/base/timing.hAdded+19
- flutter/engine/src/flutter/impeller/base/validation.ccAdded+75
- flutter/engine/src/flutter/impeller/base/validation.hAdded+93
- flutter/engine/src/flutter/impeller/base/version.ccAdded+33
- flutter/engine/src/flutter/impeller/base/version.hAdded+42
- flutter/engine/src/flutter/impeller/compiler/BUILD.gnAdded+118
- flutter/engine/src/flutter/impeller/compiler/README.mdAdded+7
- flutter/engine/src/flutter/impeller/compiler/code_gen_template.hAdded+259
- flutter/engine/src/flutter/impeller/compiler/compiler.ccAdded+547
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137// 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.
// Provides a base class for reference-counted classes.
#ifndef FLUTTER_FML_MEMORY_REF_COUNTED_H_#define FLUTTER_FML_MEMORY_REF_COUNTED_H_
#include "flutter/fml/macros.h"#include "flutter/fml/memory/ref_counted_internal.h"#include "flutter/fml/memory/ref_ptr.h"
namespace fml {
// A base class for (thread-safe) reference-counted classes. Use like://// class Foo : public RefCountedThreadSafe<Foo> {// ...// };//// |~Foo()| *may* be made private (e.g., to avoid accidental deletion of objects// while there are still references to them), |Foo| should friend// |RefCountedThreadSafe<Foo>|; use |FML_FRIEND_REF_COUNTED_THREAD_SAFE()|// for this://// class Foo : public RefCountedThreadSafe<Foo> {// ...// private:// FML_FRIEND_REF_COUNTED_THREAD_SAFE(Foo);// ~Foo();// ...// };//// Similarly, |Foo(...)| may be made private. In this case, there should either// be a static factory method performing the requisite adoption://// class Foo : public RefCountedThreadSafe<Foo> {// ...// public:// inline static RefPtr<Foo> Create() { return AdoptRef(new Foo()); }// ...// private:// Foo();// ...// };//// Or, to allow |MakeRefCounted()| to be used, use// |FML_FRIEND_MAKE_REF_COUNTED()|://// class Foo : public RefCountedThreadSafe<Foo> {// ...// private:// FML_FRIEND_MAKE_REF_COUNTED(Foo);// Foo();// Foo(const Bar& bar, bool maybe);// ...// };//// For now, we only have thread-safe reference counting, since that's all we// need. It's easy enough to add thread-unsafe versions if necessary.template <typename T>class RefCountedThreadSafe : public internal::RefCountedThreadSafeBase { public: // Adds a reference to this object. // Inherited from the internal superclass: // void AddRef() const;
// Releases a reference to this object. This will destroy this object once the // last reference is released. void Release() const { if (internal::RefCountedThreadSafeBase::Release()) { delete static_cast<const T*>(this); } }
// Returns true if there is exactly one reference to this object. Use of this // is subtle, and should usually be avoided. To assert that there is only one // reference (typically held by the calling thread, possibly in a local // variable), use |AssertHasOneRef()| instead. However, a use is: // // if (foo->HasOneRef()) { // // Do something "fast", since |foo| is the only reference and no other // // thread can get another reference. // ... // } else { // // Do something slower, but still valid even if there were only one // // reference. // ... // } // // Inherited from the internal superclass: // bool HasOneRef();
// Asserts that there is exactly one reference to this object; does nothing in // Release builds (when |NDEBUG| is defined). // Inherited from the internal superclass: // void AssertHasOneRef();
protected: // Constructor. Note that the object is constructed with a reference count of // 1, and then must be adopted (see |AdoptRef()| in ref_ptr.h). RefCountedThreadSafe() {}
// Destructor. Note that this object should only be destroyed via |Release()| // (see above), or something that calls |Release()| (see, e.g., |RefPtr<>| in // ref_ptr.h). ~RefCountedThreadSafe() {}
private:#ifndef NDEBUG template <typename U> friend RefPtr<U> AdoptRef(U*); // Marks the initial reference (assumed on construction) as adopted. This is // only required for Debug builds (when |NDEBUG| is not defined). // TODO(vtl): Should this really be private? This makes manual ref-counting // and also writing one's own ref pointer class impossible. void Adopt() { internal::RefCountedThreadSafeBase::Adopt(); }#endif
FML_DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafe);};
// If you subclass |RefCountedThreadSafe| and want to keep your destructor// private, use this. (See the example above |RefCountedThreadSafe|.)#define FML_FRIEND_REF_COUNTED_THREAD_SAFE(T) \ friend class ::fml::RefCountedThreadSafe<T>
// If you want to keep your constructor(s) private and still want to use// |MakeRefCounted<T>()|, use this. (See the example above// |RefCountedThreadSafe|.)#define FML_FRIEND_MAKE_REF_COUNTED(T) \ friend class ::fml::internal::MakeRefCountedHelper<T>
} // namespace fml
#endif // FLUTTER_FML_MEMORY_REF_COUNTED_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106// 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.
// Internal implementation details for ref_counted.h.
#ifndef FLUTTER_FML_MEMORY_REF_COUNTED_INTERNAL_H_#define FLUTTER_FML_MEMORY_REF_COUNTED_INTERNAL_H_
#include <atomic>
#include "flutter/fml/logging.h"#include "flutter/fml/macros.h"
namespace fml {namespace internal {
// See ref_counted.h for comments on the public methods.class RefCountedThreadSafeBase { public: void AddRef() const {#ifndef NDEBUG FML_DCHECK(!adoption_required_); FML_DCHECK(!destruction_started_);#endif ref_count_.fetch_add(1u, std::memory_order_relaxed); }
bool HasOneRef() const { return ref_count_.load(std::memory_order_acquire) == 1u; }
void AssertHasOneRef() const { FML_DCHECK(HasOneRef()); }
protected: RefCountedThreadSafeBase(); ~RefCountedThreadSafeBase();
// Returns true if the object should self-delete. bool Release() const {#ifndef NDEBUG FML_DCHECK(!adoption_required_); FML_DCHECK(!destruction_started_);#endif FML_DCHECK(ref_count_.load(std::memory_order_acquire) != 0u); // TODO(vtl): We could add the following: // if (ref_count_.load(std::memory_order_relaxed) == 1u) { // #ifndef NDEBUG // destruction_started_= true; // #endif // return true; // } // This would be correct. On ARM (an Nexus 4), in *single-threaded* tests, // this seems to make the destruction case marginally faster (barely // measurable), and while the non-destruction case remains about the same // (possibly marginally slower, but my measurements aren't good enough to // have any confidence in that). I should try multithreaded/multicore tests. if (ref_count_.fetch_sub(1u, std::memory_order_release) == 1u) { std::atomic_thread_fence(std::memory_order_acquire);#ifndef NDEBUG destruction_started_ = true;#endif return true; } return false; }
#ifndef NDEBUG void Adopt() { FML_DCHECK(adoption_required_); adoption_required_ = false; }#endif
private: mutable std::atomic_uint_fast32_t ref_count_;
#ifndef NDEBUG mutable bool adoption_required_ = false; mutable bool destruction_started_ = false;#endif
FML_DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafeBase);};
inline RefCountedThreadSafeBase::RefCountedThreadSafeBase() : ref_count_(1u)#ifndef NDEBUG , adoption_required_(true)#endif{}
inline RefCountedThreadSafeBase::~RefCountedThreadSafeBase() {#ifndef NDEBUG FML_DCHECK(!adoption_required_); // Should only be destroyed as a result of |Release()|. FML_DCHECK(destruction_started_);#endif}
} // namespace internal} // namespace fml
#endif // FLUTTER_FML_MEMORY_REF_COUNTED_INTERNAL_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647// 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.
// This file tests both ref_counted.h and ref_ptr.h (which the former includes).// TODO(vtl): Possibly we could separate these tests out better, since a lot of// it is actually testing |RefPtr|.
#include "flutter/fml/memory/ref_counted.h"
#include "flutter/fml/macros.h"#include "gtest/gtest.h"
// NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks)
#if defined(__clang__)#define ALLOW_PESSIMIZING_MOVE(code_line) \ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Wpessimizing-move\"") code_line; \ _Pragma("clang diagnostic pop")#else#define ALLOW_PESSIMIZING_MOVE(code_line) code_line;#endif
#if defined(__clang__)#define ALLOW_SELF_MOVE(code_line) \ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Wself-move\"") code_line; \ _Pragma("clang diagnostic pop")#else#define ALLOW_SELF_MOVE(code_line) code_line;#endif
#if defined(__clang__)#define ALLOW_SELF_ASSIGN_OVERLOADED(code_line) \ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Wself-assign-overloaded\"") \ code_line; \ _Pragma("clang diagnostic pop")#else#define ALLOW_SELF_ASSIGN_OVERLOADED(code_line) code_line;#endif
namespace fml {namespace {
class MyClass : public RefCountedThreadSafe<MyClass> { protected: MyClass(MyClass** created, bool* was_destroyed) : was_destroyed_(was_destroyed) { if (created) { *created = this; } } virtual ~MyClass() { if (was_destroyed_) { *was_destroyed_ = true; } }
private: FML_FRIEND_REF_COUNTED_THREAD_SAFE(MyClass); FML_FRIEND_MAKE_REF_COUNTED(MyClass);
bool* was_destroyed_;
FML_DISALLOW_COPY_AND_ASSIGN(MyClass);};
class MySubclass final : public MyClass { private: FML_FRIEND_REF_COUNTED_THREAD_SAFE(MySubclass); FML_FRIEND_MAKE_REF_COUNTED(MySubclass);
MySubclass(MySubclass** created, bool* was_destroyed) : MyClass(nullptr, was_destroyed) { if (created) { *created = this; } } ~MySubclass() override {}
FML_DISALLOW_COPY_AND_ASSIGN(MySubclass);};
TEST(RefCountedTest, Constructors) { bool was_destroyed;
{ // Default. RefPtr<MyClass> r; EXPECT_TRUE(r.get() == nullptr); EXPECT_FALSE(r); }
{ // Nullptr. RefPtr<MyClass> r(nullptr); EXPECT_TRUE(r.get() == nullptr); EXPECT_FALSE(r); }
{ MyClass* created = nullptr; was_destroyed = false; // Adopt, then RVO. RefPtr<MyClass> r(MakeRefCounted<MyClass>(&created, &was_destroyed)); EXPECT_TRUE(created); EXPECT_EQ(created, r.get()); EXPECT_TRUE(r); EXPECT_FALSE(was_destroyed); } EXPECT_TRUE(was_destroyed);
{ MyClass* created = nullptr; was_destroyed = false; // Adopt, then move. ALLOW_PESSIMIZING_MOVE(RefPtr<MyClass> r( std::move(MakeRefCounted<MyClass>(&created, &was_destroyed)))) EXPECT_TRUE(created); EXPECT_EQ(created, r.get()); EXPECT_TRUE(r); EXPECT_FALSE(was_destroyed); } EXPECT_TRUE(was_destroyed);
{ MyClass* created = nullptr; was_destroyed = false; RefPtr<MyClass> r1(MakeRefCounted<MyClass>(&created, &was_destroyed)); // Copy. // NOLINTNEXTLINE(performance-unnecessary-copy-initialization) RefPtr<MyClass> r2(r1); EXPECT_TRUE(created); EXPECT_EQ(created, r1.get()); EXPECT_EQ(created, r2.get()); EXPECT_TRUE(r1); EXPECT_TRUE(r2); EXPECT_FALSE(was_destroyed); } EXPECT_TRUE(was_destroyed);
{ MyClass* created = nullptr; was_destroyed = false; RefPtr<MyClass> r1(MakeRefCounted<MyClass>(&created, &was_destroyed)); // From raw pointer. RefPtr<MyClass> r2(created); EXPECT_TRUE(created); EXPECT_EQ(created, r1.get()); EXPECT_EQ(created, r2.get()); EXPECT_TRUE(r1); EXPECT_TRUE(r2); EXPECT_FALSE(was_destroyed); } EXPECT_TRUE(was_destroyed);
{ MySubclass* created = nullptr; was_destroyed = false; // Adopt, then "move". RefPtr<MyClass> r(MakeRefCounted<MySubclass>(&created, &was_destroyed)); EXPECT_TRUE(created); EXPECT_EQ(static_cast<MyClass*>(created), r.get()); EXPECT_TRUE(r); EXPECT_FALSE(was_destroyed); } EXPECT_TRUE(was_destroyed);
{ MySubclass* created = nullptr; was_destroyed = false; // Adopt, then "move". ALLOW_PESSIMIZING_MOVE(RefPtr<MyClass> r( std::move(MakeRefCounted<MySubclass>(&created, &was_destroyed)))) EXPECT_TRUE(created); EXPECT_EQ(static_cast<MyClass*>(created), r.get()); EXPECT_TRUE(r); EXPECT_FALSE(was_destroyed); } EXPECT_TRUE(was_destroyed);
{ MySubclass* created = nullptr; was_destroyed = false; RefPtr<MySubclass> r1(MakeRefCounted<MySubclass>(&created, &was_destroyed)); // "Copy". RefPtr<MyClass> r2(r1); EXPECT_TRUE(created); EXPECT_EQ(static_cast<MyClass*>(created), r1.get()); EXPECT_EQ(static_cast<MyClass*>(created), r2.get()); EXPECT_TRUE(r1); EXPECT_TRUE(r2); EXPECT_FALSE(was_destroyed); } EXPECT_TRUE(was_destroyed);
{ MySubclass* created = nullptr; was_destroyed = false; RefPtr<MySubclass> r1(MakeRefCounted<MySubclass>(&created, &was_destroyed)); // From raw pointer. RefPtr<MyClass> r2(created); EXPECT_TRUE(created); EXPECT_EQ(static_cast<MyClass*>(created), r1.get()); EXPECT_EQ(static_cast<MyClass*>(created), r2.get()); EXPECT_TRUE(r1); EXPECT_TRUE(r2); EXPECT_FALSE(was_destroyed); } EXPECT_TRUE(was_destroyed);}
TEST(RefCountedTest, NullAssignmentToNull) { RefPtr<MyClass> r1; // No-op null assignment using |nullptr|. r1 = nullptr; EXPECT_TRUE(r1.get() == nullptr); EXPECT_FALSE(r1);
RefPtr<MyClass> r2; // No-op null assignment using copy constructor. r1 = r2; EXPECT_TRUE(r1.get() == nullptr); EXPECT_TRUE(r2.get() == nullptr); EXPECT_FALSE(r1); EXPECT_FALSE(r2);
// No-op null assignment using move constructor. r1 = std::move(r2); EXPECT_TRUE(r1.get() == nullptr); // The clang linter flags the method called on the moved-from reference, but // this is testing the move implementation, so it is marked NOLINT. EXPECT_TRUE(r2.get() == nullptr); // NOLINT(clang-analyzer-cplusplus.Move, // bugprone-use-after-move) EXPECT_FALSE(r1); EXPECT_FALSE(r2);
RefPtr<MySubclass> r3; // No-op null assignment using "copy" constructor. r1 = r3; EXPECT_TRUE(r1.get() == nullptr); EXPECT_TRUE(r3.get() == nullptr); EXPECT_FALSE(r1); EXPECT_FALSE(r3);
// No-op null assignment using "move" constructor. r1 = std::move(r3); EXPECT_TRUE(r1.get() == nullptr); EXPECT_TRUE(r3.get() == nullptr); // NOLINT(bugprone-use-after-move) EXPECT_FALSE(r1); EXPECT_FALSE(r3);}
TEST(RefCountedTest, NonNullAssignmentToNull) { bool was_destroyed;
{ MyClass* created = nullptr; was_destroyed = false; RefPtr<MyClass> r1(MakeRefCounted<MyClass>(&created, &was_destroyed)); RefPtr<MyClass> r2; // Copy assignment (to null ref pointer). r2 = r1; EXPECT_EQ(created, r1.get()); EXPECT_EQ(created, r2.get()); EXPECT_TRUE(r1); EXPECT_TRUE(r2); EXPECT_FALSE(was_destroyed); } EXPECT_TRUE(was_destroyed);
{ MyClass* created = nullptr; was_destroyed = false; RefPtr<MyClass> r1(MakeRefCounted<MyClass>(&created, &was_destroyed)); RefPtr<MyClass> r2; // Move assignment (to null ref pointer). r2 = std::move(r1); // The clang linter flags the method called on the moved-from reference, but // this is testing the move implementation, so it is marked NOLINT. EXPECT_TRUE(r1.get() == nullptr); // NOLINT(clang-analyzer-cplusplus.Move, // bugprone-use-after-move) EXPECT_EQ(created, r2.get()); EXPECT_FALSE(r1); EXPECT_TRUE(r2); EXPECT_FALSE(was_destroyed); } EXPECT_TRUE(was_destroyed);
{ MySubclass* created = nullptr; was_destroyed = false; RefPtr<MySubclass> r1(MakeRefCounted<MySubclass>(&created, &was_destroyed)); RefPtr<MyClass> r2; // "Copy" assignment (to null ref pointer). r2 = r1; EXPECT_EQ(created, r1.get()); EXPECT_EQ(static_cast<MyClass*>(created), r2.get()); EXPECT_TRUE(r1); EXPECT_TRUE(r2); EXPECT_FALSE(was_destroyed); } EXPECT_TRUE(was_destroyed);
{ MySubclass* created = nullptr; was_destroyed = false; RefPtr<MySubclass> r1(MakeRefCounted<MySubclass>(&created, &was_destroyed)); RefPtr<MyClass> r2; // "Move" assignment (to null ref pointer). r2 = std::move(r1); EXPECT_TRUE(r1.get() == nullptr); // NOLINT(bugprone-use-after-move) EXPECT_EQ(static_cast<MyClass*>(created), r2.get()); EXPECT_FALSE(r1); EXPECT_TRUE(r2); EXPECT_FALSE(was_destroyed); } EXPECT_TRUE(was_destroyed);}
TEST(RefCountedTest, NullAssignmentToNonNull) { bool was_destroyed = false; RefPtr<MyClass> r1(MakeRefCounted<MyClass>(nullptr, &was_destroyed)); // Null assignment (to non-null ref pointer) using |nullptr|. r1 = nullptr; EXPECT_TRUE(r1.get() == nullptr); EXPECT_FALSE(r1); EXPECT_TRUE(was_destroyed);
was_destroyed = false; r1 = MakeRefCounted<MyClass>(nullptr, &was_destroyed); RefPtr<MyClass> r2; // Null assignment (to non-null ref pointer) using copy constructor. r1 = r2; EXPECT_TRUE(r1.get() == nullptr); EXPECT_TRUE(r2.get() == nullptr); EXPECT_FALSE(r1); EXPECT_FALSE(r2); EXPECT_TRUE(was_destroyed);
was_destroyed = false; r1 = MakeRefCounted<MyClass>(nullptr, &was_destroyed); // Null assignment using move constructor. r1 = std::move(r2); EXPECT_TRUE(r1.get() == nullptr); // The clang linter flags the method called on the moved-from reference, but // this is testing the move implementation, so it is marked NOLINT. EXPECT_TRUE(r2.get() == nullptr); // NOLINT(clang-analyzer-cplusplus.Move, // bugprone-use-after-move) EXPECT_FALSE(r1); EXPECT_FALSE(r2); EXPECT_TRUE(was_destroyed);
was_destroyed = false; r1 = MakeRefCounted<MyClass>(nullptr, &was_destroyed); RefPtr<MySubclass> r3; // Null assignment (to non-null ref pointer) using "copy" constructor. r1 = r3; EXPECT_TRUE(r1.get() == nullptr); EXPECT_TRUE(r3.get() == nullptr); EXPECT_FALSE(r1); EXPECT_FALSE(r3); EXPECT_TRUE(was_destroyed);
was_destroyed = false; r1 = MakeRefCounted<MyClass>(nullptr, &was_destroyed); // Null assignment (to non-null ref pointer) using "move" constructor. r1 = std::move(r3); EXPECT_TRUE(r1.get() == nullptr); EXPECT_TRUE(r3.get() == nullptr); // NOLINT(bugprone-use-after-move) EXPECT_FALSE(r1); EXPECT_FALSE(r3); EXPECT_TRUE(was_destroyed);}
TEST(RefCountedTest, NonNullAssignmentToNonNull) { bool was_destroyed1; bool was_destroyed2;
{ was_destroyed1 = false; was_destroyed2 = false; RefPtr<MyClass> r1(MakeRefCounted<MyClass>(nullptr, &was_destroyed1)); RefPtr<MyClass> r2(MakeRefCounted<MyClass>(nullptr, &was_destroyed2)); // Copy assignment (to non-null ref pointer). r2 = r1; EXPECT_EQ(r1.get(), r2.get()); EXPECT_TRUE(r1); EXPECT_TRUE(r2); EXPECT_FALSE(was_destroyed1); EXPECT_TRUE(was_destroyed2); } EXPECT_TRUE(was_destroyed1);
{ was_destroyed1 = false; was_destroyed2 = false; RefPtr<MyClass> r1(MakeRefCounted<MyClass>(nullptr, &was_destroyed1)); RefPtr<MyClass> r2(MakeRefCounted<MyClass>(nullptr, &was_destroyed2)); // Move assignment (to non-null ref pointer). r2 = std::move(r1); // The clang linter flags the method called on the moved-from reference, but // this is testing the move implementation, so it is marked NOLINT. EXPECT_TRUE(r1.get() == nullptr); // NOLINT(clang-analyzer-cplusplus.Move, // bugprone-use-after-move) EXPECT_FALSE(r2.get() == nullptr); EXPECT_FALSE(r1); EXPECT_TRUE(r2); EXPECT_FALSE(was_destroyed1); EXPECT_TRUE(was_destroyed2); } EXPECT_TRUE(was_destroyed1);
{ was_destroyed1 = false; was_destroyed2 = false; RefPtr<MySubclass> r1(MakeRefCounted<MySubclass>(nullptr, &was_destroyed1)); RefPtr<MyClass> r2(MakeRefCounted<MyClass>(nullptr, &was_destroyed2)); // "Copy" assignment (to non-null ref pointer). r2 = r1; EXPECT_EQ(r1.get(), r2.get()); EXPECT_TRUE(r1); EXPECT_TRUE(r2); EXPECT_FALSE(was_destroyed1); EXPECT_TRUE(was_destroyed2); } EXPECT_TRUE(was_destroyed1);
{ was_destroyed1 = false; was_destroyed2 = false; RefPtr<MySubclass> r1(MakeRefCounted<MySubclass>(nullptr, &was_destroyed1)); RefPtr<MyClass> r2(MakeRefCounted<MyClass>(nullptr, &was_destroyed2)); // Move assignment (to non-null ref pointer). r2 = std::move(r1); EXPECT_TRUE(r1.get() == nullptr); // NOLINT(bugprone-use-after-move) EXPECT_FALSE(r2.get() == nullptr); EXPECT_FALSE(r1); EXPECT_TRUE(r2); EXPECT_FALSE(was_destroyed1); EXPECT_TRUE(was_destroyed2); } EXPECT_TRUE(was_destroyed1);}
TEST(RefCountedTest, SelfAssignment) { bool was_destroyed;
{ MyClass* created = nullptr; was_destroyed = false; // This line is marked NOLINT because the clang linter does not reason about // the value of the reference count. In particular, the self-assignment // below is handled in the copy constructor by a refcount increment then // decrement. The linter sees only that the decrement might destroy the // object. RefPtr<MyClass> r(MakeRefCounted<MyClass>( // NOLINT &created, &was_destroyed)); // Copy. ALLOW_SELF_ASSIGN_OVERLOADED(r = r); EXPECT_EQ(created, r.get()); EXPECT_FALSE(was_destroyed); } EXPECT_TRUE(was_destroyed);
{ MyClass* created = nullptr; was_destroyed = false; RefPtr<MyClass> r(MakeRefCounted<MyClass>(&created, &was_destroyed)); // Move. ALLOW_SELF_MOVE(r = std::move(r)) EXPECT_EQ(created, r.get()); EXPECT_FALSE(was_destroyed); } EXPECT_TRUE(was_destroyed);}
TEST(RefCountedTest, Swap) { MyClass* created1 = nullptr; static bool was_destroyed1; was_destroyed1 = false; RefPtr<MyClass> r1(MakeRefCounted<MyClass>(&created1, &was_destroyed1)); EXPECT_TRUE(created1); EXPECT_EQ(created1, r1.get());
MyClass* created2 = nullptr; static bool was_destroyed2; was_destroyed2 = false; RefPtr<MyClass> r2(MakeRefCounted<MyClass>(&created2, &was_destroyed2)); EXPECT_TRUE(created2); EXPECT_EQ(created2, r2.get()); EXPECT_NE(created1, created2);
r1.swap(r2); EXPECT_EQ(created2, r1.get()); EXPECT_EQ(created1, r2.get());}
TEST(RefCountedTest, GetAndDereferenceOperators) { // Note: We check here that .get(), operator*, and operator-> are const, but // return non-const pointers/refs.
MyClass* created = nullptr; const RefPtr<MyClass> r(MakeRefCounted<MyClass>(&created, nullptr)); MyClass* ptr = r.get(); // Assign to non-const pointer. EXPECT_EQ(created, ptr); ptr = r.operator->(); // Assign to non-const pointer. EXPECT_EQ(created, ptr); MyClass& ref = *r; // "Assign" to non-const reference. EXPECT_EQ(created, &ref);}
// You can manually call |AddRef()| and |Release()| if you want.TEST(RefCountedTest, AddRefRelease) { MyClass* created = nullptr; bool was_destroyed = false; { RefPtr<MyClass> r(MakeRefCounted<MyClass>(&created, &was_destroyed)); EXPECT_EQ(created, r.get()); created->AddRef(); } EXPECT_FALSE(was_destroyed); created->Release(); EXPECT_TRUE(was_destroyed);}
TEST(RefCountedTest, Mix) { MySubclass* created = nullptr; bool was_destroyed = false; RefPtr<MySubclass> r1(MakeRefCounted<MySubclass>(&created, &was_destroyed)); ASSERT_FALSE(was_destroyed); EXPECT_TRUE(created->HasOneRef()); created->AssertHasOneRef();
RefPtr<MySubclass> r2 = r1; ASSERT_FALSE(was_destroyed); EXPECT_FALSE(created->HasOneRef());
r1 = nullptr; ASSERT_FALSE(was_destroyed); created->AssertHasOneRef();
{ RefPtr<MyClass> r3 = r2; EXPECT_FALSE(created->HasOneRef()); { // NOLINTNEXTLINE(performance-unnecessary-copy-initialization) RefPtr<MyClass> r4(r3); r2 = nullptr; ASSERT_FALSE(was_destroyed); EXPECT_FALSE(created->HasOneRef()); } ASSERT_FALSE(was_destroyed); EXPECT_TRUE(created->HasOneRef()); created->AssertHasOneRef();
r1 = RefPtr<MySubclass>(static_cast<MySubclass*>(r3.get())); ASSERT_FALSE(was_destroyed); EXPECT_FALSE(created->HasOneRef()); } ASSERT_FALSE(was_destroyed); EXPECT_TRUE(created->HasOneRef()); created->AssertHasOneRef();
EXPECT_EQ(created, r1.get());
r1 = nullptr; EXPECT_TRUE(was_destroyed);}
class MyPublicClass : public RefCountedThreadSafe<MyPublicClass> { public: // Overloaded constructors work with |MakeRefCounted()|. MyPublicClass() : has_num_(false), num_(0) {} explicit MyPublicClass(int num) : has_num_(true), num_(num) {}
~MyPublicClass() {}
bool has_num() const { return has_num_; } int num() const { return num_; }
private: bool has_num_; int num_;
FML_DISALLOW_COPY_AND_ASSIGN(MyPublicClass);};
// You can also just keep constructors and destructors public. Make sure that// works (mostly that it compiles).TEST(RefCountedTest, PublicCtorAndDtor) { RefPtr<MyPublicClass> r1 = MakeRefCounted<MyPublicClass>(); ASSERT_TRUE(r1); EXPECT_FALSE(r1->has_num());
RefPtr<MyPublicClass> r2 = MakeRefCounted<MyPublicClass>(123); ASSERT_TRUE(r2); EXPECT_TRUE(r2->has_num()); EXPECT_EQ(123, r2->num()); EXPECT_NE(r1.get(), r2.get());
r1 = r2; EXPECT_TRUE(r1->has_num()); EXPECT_EQ(123, r1->num()); EXPECT_EQ(r1.get(), r2.get());
r2 = nullptr; EXPECT_FALSE(r2); EXPECT_TRUE(r1->has_num()); EXPECT_EQ(123, r1->num());
r1 = nullptr; EXPECT_FALSE(r1);}
// The danger with having a public constructor or destructor is that certain// things will compile. You should get some protection by assertions in Debug// builds.#ifndef NDEBUGTEST(RefCountedTest, DebugChecks) { { MyPublicClass* p = new MyPublicClass(); EXPECT_DEATH_IF_SUPPORTED( // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks) delete p, "!adoption_required_"); }
{ MyPublicClass* p = new MyPublicClass(); EXPECT_DEATH_IF_SUPPORTED( // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks) RefPtr<MyPublicClass> r(p), "!adoption_required_"); }
{ RefPtr<MyPublicClass> r(MakeRefCounted<MyPublicClass>()); EXPECT_DEATH_IF_SUPPORTED(delete r.get(), "destruction_started_"); }}#endif
// TODO(vtl): Add (threaded) stress tests.
} // namespace} // namespace fml
// NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272// 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.
// Provides a smart pointer class for intrusively reference-counted objects.
#ifndef FLUTTER_FML_MEMORY_REF_PTR_H_#define FLUTTER_FML_MEMORY_REF_PTR_H_
#include <cstddef>#include <functional>#include <utility>
#include "flutter/fml/logging.h"#include "flutter/fml/macros.h"#include "flutter/fml/memory/ref_ptr_internal.h"
namespace fml {
// A smart pointer class for intrusively reference-counted objects (e.g., those// subclassing |RefCountedThreadSafe| -- see ref_counted.h).//// Such objects require *adoption* to obtain the first |RefPtr|, which is// accomplished using |AdoptRef| (see below). (This is due to such objects being// constructed with a reference count of 1. The adoption requirement is// enforced, at least in Debug builds, by assertions.)//// E.g., if |Foo| is an intrusively reference-counted class://// // The |AdoptRef| may be put in a static factory method (e.g., if |Foo|'s// // constructor is private).// RefPtr<Foo> my_foo_ptr(AdoptRef(new Foo()));//// // Now OK, since "my Foo" has been adopted ...// RefPtr<Foo> another_ptr_to_my_foo(my_foo_ptr.get());//// // ... though this would preferable in this situation.// RefPtr<Foo> yet_another_ptr_to_my_foo(my_foo_ptr);//// Unlike Chromium's |scoped_refptr|, |RefPtr| is only explicitly constructible// from a plain pointer (and not assignable). It is however implicitly// constructible from |nullptr|. So://// RefPtr<Foo> foo(plain_ptr_to_adopted_foo); // OK.// foo = plain_ptr_to_adopted_foo; // Not OK (doesn't compile).// foo = RefPtr<Foo>(plain_ptr_to_adopted_foo); // OK.// foo = nullptr; // OK.//// And if we have |void MyFunction(RefPtr<Foo> foo)|, calling it using// |MyFunction(nullptr)| is also valid.//// Implementation note: For copy/move constructors/operator=s, we often have// templated versions, so that the operation can be done on a |RefPtr<U>|, where// |U| is a subclass of |T|. However, we also have non-templated versions with// |U = T|, since the templated versions don't count as copy/move// constructors/operator=s for the purposes of causing the default copy// constructor/operator= to be deleted. E.g., if we didn't declare any// non-templated versions, we'd get the default copy constructor/operator= (we'd// only not get the default move constructor/operator= by virtue of having a// destructor)! (In fact, it'd suffice to only declare a non-templated move// constructor or move operator=, which would cause the copy// constructor/operator= to be deleted, but for clarity we include explicit// non-templated versions of everything.)template <typename T>class RefPtr final { public: RefPtr() : ptr_(nullptr) {} RefPtr(std::nullptr_t) // NOLINT(google-explicit-constructor) : ptr_(nullptr) {}
// Explicit constructor from a plain pointer (to an object that must have // already been adopted). (Note that in |T::T()|, references to |this| cannot // be taken, since the object being constructed will not have been adopted // yet.) template <typename U> explicit RefPtr(U* p) : ptr_(p) { if (ptr_) { ptr_->AddRef(); } }
// Copy constructor. RefPtr(const RefPtr<T>& r) // NOLINT(google-explicit-constructor) : ptr_(r.ptr_) { if (ptr_) { ptr_->AddRef(); } }
template <typename U> RefPtr(const RefPtr<U>& r) // NOLINT(google-explicit-constructor) : ptr_(r.ptr_) { if (ptr_) { ptr_->AddRef(); } }
// Move constructor. RefPtr(RefPtr<T>&& r) : ptr_(r.ptr_) { // NOLINT(google-explicit-constructor) r.ptr_ = nullptr; }
template <typename U> RefPtr(RefPtr<U>&& r) : ptr_(r.ptr_) { // NOLINT(google-explicit-constructor) r.ptr_ = nullptr; }
// Destructor. ~RefPtr() { if (ptr_) { // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDelete) ptr_->Release(); } }
T* get() const { return ptr_; }
T& operator*() const { FML_DCHECK(ptr_); return *ptr_; }
T* operator->() const { FML_DCHECK(ptr_); return ptr_; }
// Copy assignment. RefPtr<T>& operator=(const RefPtr<T>& r) { // Handle self-assignment. if (r.ptr_ == ptr_) { return *this; } if (r.ptr_) { r.ptr_->AddRef(); } T* old_ptr = ptr_; ptr_ = r.ptr_; if (old_ptr) { old_ptr->Release(); } // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) return *this; }
template <typename U> RefPtr<T>& operator=(const RefPtr<U>& r) { if (reinterpret_cast<T*>(r.ptr_) == ptr_) { return *this; } if (r.ptr_) { r.ptr_->AddRef(); } T* old_ptr = ptr_; ptr_ = r.ptr_; if (old_ptr) { old_ptr->Release(); } // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) return *this; }
// Move assignment. // Note: Like |std::shared_ptr|, we support self-move and move assignment is // equivalent to |RefPtr<T>(std::move(r)).swap(*this)|. RefPtr<T>& operator=(RefPtr<T>&& r) { RefPtr<T>(std::move(r)).swap(*this); // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) return *this; }
template <typename U> RefPtr<T>& operator=(RefPtr<U>&& r) { RefPtr<T>(std::move(r)).swap(*this); // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) return *this; }
void swap(RefPtr<T>& r) { T* p = ptr_; ptr_ = r.ptr_; r.ptr_ = p; }
// Returns a new |RefPtr<T>| with the same contents as this pointer. Useful // when a function takes a |RefPtr<T>&&| argument and the caller wants to // retain its reference (rather than moving it). RefPtr<T> Clone() const { return *this; }
explicit operator bool() const { return !!ptr_; }
template <typename U> bool operator==(const RefPtr<U>& rhs) const { return ptr_ == rhs.ptr_; }
template <typename U> bool operator!=(const RefPtr<U>& rhs) const { return !operator==(rhs); }
template <typename U> bool operator<(const RefPtr<U>& rhs) const { return ptr_ < rhs.ptr_; }
private: template <typename U> friend class RefPtr;
friend RefPtr<T> AdoptRef<T>(T*);
enum AdoptTag { kAdopt }; RefPtr(T* ptr, AdoptTag) : ptr_(ptr) { FML_DCHECK(ptr_); }
T* ptr_;};
// Adopts a newly-created |T|. Typically used in a static factory method, like://// // static// RefPtr<Foo> Foo::Create() {// return AdoptRef(new Foo());// }template <typename T>inline RefPtr<T> AdoptRef(T* ptr) {#ifndef NDEBUG ptr->Adopt();#endif return RefPtr<T>(ptr, RefPtr<T>::kAdopt);}
// Constructs a |RefPtr<T>| from a plain pointer (to an object that must// have already been adoped). Avoids having to spell out the full type name.//// Foo* foo = ...;// auto foo_ref = Ref(foo);//// (|foo_ref| will be of type |RefPtr<Foo>|.)template <typename T>inline RefPtr<T> Ref(T* ptr) { return RefPtr<T>(ptr);}
// Creates an intrusively reference counted |T|, producing a |RefPtr<T>| (and// performing the required adoption). Use like://// auto my_foo = MakeRefCounted<Foo>(ctor_arg1, ctor_arg2);//// (|my_foo| will be of type |RefPtr<Foo>|.)template <typename T, typename... Args>RefPtr<T> MakeRefCounted(Args&&... args) { return internal::MakeRefCountedHelper<T>::MakeRefCounted( std::forward<Args>(args)...);}
} // namespace fml
// Inject custom std::hash<> function object for |RefPtr<T>|.namespace std {template <typename T>struct hash<fml::RefPtr<T>> { using argument_type = fml::RefPtr<T>; using result_type = std::size_t;
result_type operator()(const argument_type& ptr) const { return std::hash<T*>()(ptr.get()); }};} // namespace std
#endif // FLUTTER_FML_MEMORY_REF_PTR_H_1234567891011121314151617181920212223242526272829303132333435363738// 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_FML_MEMORY_REF_PTR_INTERNAL_H_#define FLUTTER_FML_MEMORY_REF_PTR_INTERNAL_H_
#include <utility>
#include "flutter/fml/macros.h"
namespace fml {
template <typename T>class RefPtr;
template <typename T>RefPtr<T> AdoptRef(T* ptr);
namespace internal {
// This is a wrapper class that can be friended for a particular |T|, if you// want to make |T|'s constructor private, but still use |MakeRefCounted()|// (below). (You can't friend partial specializations.) See |MakeRefCounted()|// and |FML_FRIEND_MAKE_REF_COUNTED()|.template <typename T>class MakeRefCountedHelper final { public: template <typename... Args> static RefPtr<T> MakeRefCounted(Args&&... args) { return AdoptRef<T>(new T(std::forward<Args>(args)...)); }};
} // namespace internal} // namespace fml
#endif // FLUTTER_FML_MEMORY_REF_PTR_INTERNAL_H_12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152// 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 "flutter/fml/memory/task_runner_checker.h"
namespace fml {
TaskRunnerChecker::TaskRunnerChecker() : initialized_queue_id_(InitTaskQueueId()), subsumed_queue_ids_( MessageLoopTaskQueues::GetInstance()->GetSubsumedTaskQueueId( initialized_queue_id_)){};
TaskRunnerChecker::~TaskRunnerChecker() = default;
bool TaskRunnerChecker::RunsOnCreationTaskRunner() const { FML_CHECK(fml::MessageLoop::IsInitializedForCurrentThread()); const auto current_queue_id = MessageLoop::GetCurrentTaskQueueId(); if (RunsOnTheSameThread(current_queue_id, initialized_queue_id_)) { return true; } for (auto& subsumed : subsumed_queue_ids_) { if (RunsOnTheSameThread(current_queue_id, subsumed)) { return true; } } return false;};
bool TaskRunnerChecker::RunsOnTheSameThread(TaskQueueId queue_a, TaskQueueId queue_b) { if (queue_a == queue_b) { return true; }
auto queues = MessageLoopTaskQueues::GetInstance(); if (queues->Owns(queue_a, queue_b)) { return true; } if (queues->Owns(queue_b, queue_a)) { return true; } return false;};
TaskQueueId TaskRunnerChecker::InitTaskQueueId() { MessageLoop::EnsureInitializedForCurrentThread(); return MessageLoop::GetCurrentTaskQueueId();};
} // namespace fml1234567891011121314151617181920212223242526272829303132333435363738394041// 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_FML_MEMORY_TASK_RUNNER_CHECKER_H_#define FLUTTER_FML_MEMORY_TASK_RUNNER_CHECKER_H_
#include "flutter/fml/message_loop.h"#include "flutter/fml/task_runner.h"
namespace fml {
class TaskRunnerChecker final { public: TaskRunnerChecker();
~TaskRunnerChecker();
bool RunsOnCreationTaskRunner() const;
static bool RunsOnTheSameThread(TaskQueueId queue_a, TaskQueueId queue_b);
private: TaskQueueId initialized_queue_id_; std::set<TaskQueueId> subsumed_queue_ids_;
TaskQueueId InitTaskQueueId();};
#if !defined(NDEBUG)#define FML_DECLARE_TASK_RUNNER_CHECKER(c) fml::TaskRunnerChecker c#define FML_DCHECK_TASK_RUNNER_IS_CURRENT(c) \ FML_DCHECK((c).RunsOnCreationTaskRunner())#else#define FML_DECLARE_TASK_RUNNER_CHECKER(c)#define FML_DCHECK_TASK_RUNNER_IS_CURRENT(c) ((void)0)#endif
} // namespace fml
#endif // FLUTTER_FML_MEMORY_TASK_RUNNER_CHECKER_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173// 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.
#define FML_USED_ON_EMBEDDER
#include "flutter/fml/memory/task_runner_checker.h"
#include <thread>
#include "flutter/fml/message_loop.h"#include "flutter/fml/raster_thread_merger.h"#include "flutter/fml/synchronization/count_down_latch.h"#include "flutter/fml/synchronization/waitable_event.h"#include "gtest/gtest.h"
namespace fml {namespace testing {
TEST(TaskRunnerCheckerTests, RunsOnCurrentTaskRunner) { TaskRunnerChecker checker; EXPECT_EQ(checker.RunsOnCreationTaskRunner(), true);}
TEST(TaskRunnerCheckerTests, FailsTheCheckIfOnDifferentTaskRunner) { TaskRunnerChecker checker; EXPECT_EQ(checker.RunsOnCreationTaskRunner(), true); fml::MessageLoop* loop = nullptr; fml::AutoResetWaitableEvent latch; std::thread another_thread([&]() { fml::MessageLoop::EnsureInitializedForCurrentThread(); loop = &fml::MessageLoop::GetCurrent(); loop->GetTaskRunner()->PostTask([&]() { EXPECT_EQ(checker.RunsOnCreationTaskRunner(), false); latch.Signal(); }); loop->Run(); }); latch.Wait(); loop->Terminate(); another_thread.join(); EXPECT_EQ(checker.RunsOnCreationTaskRunner(), true);}
TEST(TaskRunnerCheckerTests, SameTaskRunnerRunsOnTheSameThread) { fml::MessageLoop::EnsureInitializedForCurrentThread(); fml::MessageLoop& loop1 = fml::MessageLoop::GetCurrent(); fml::MessageLoop& loop2 = fml::MessageLoop::GetCurrent(); TaskQueueId a = loop1.GetTaskRunner()->GetTaskQueueId(); TaskQueueId b = loop2.GetTaskRunner()->GetTaskQueueId(); EXPECT_EQ(TaskRunnerChecker::RunsOnTheSameThread(a, b), true);}
TEST(TaskRunnerCheckerTests, RunsOnDifferentThreadsReturnsFalse) { fml::MessageLoop::EnsureInitializedForCurrentThread(); fml::MessageLoop& loop1 = fml::MessageLoop::GetCurrent(); TaskQueueId a = loop1.GetTaskRunner()->GetTaskQueueId(); fml::AutoResetWaitableEvent latch; std::thread another_thread([&]() { fml::MessageLoop::EnsureInitializedForCurrentThread(); fml::MessageLoop& loop2 = fml::MessageLoop::GetCurrent(); TaskQueueId b = loop2.GetTaskRunner()->GetTaskQueueId(); EXPECT_EQ(TaskRunnerChecker::RunsOnTheSameThread(a, b), false); latch.Signal(); }); latch.Wait(); another_thread.join();}
TEST(TaskRunnerCheckerTests, MergedTaskRunnersRunsOnTheSameThread) { fml::MessageLoop* loop1 = nullptr; fml::AutoResetWaitableEvent latch1; fml::AutoResetWaitableEvent term1; std::thread thread1([&loop1, &latch1, &term1]() { fml::MessageLoop::EnsureInitializedForCurrentThread(); loop1 = &fml::MessageLoop::GetCurrent(); latch1.Signal(); term1.Wait(); });
fml::MessageLoop* loop2 = nullptr; fml::AutoResetWaitableEvent latch2; fml::AutoResetWaitableEvent term2; std::thread thread2([&loop2, &latch2, &term2]() { fml::MessageLoop::EnsureInitializedForCurrentThread(); loop2 = &fml::MessageLoop::GetCurrent(); latch2.Signal(); term2.Wait(); });
latch1.Wait(); latch2.Wait(); fml::TaskQueueId qid1 = loop1->GetTaskRunner()->GetTaskQueueId(); fml::TaskQueueId qid2 = loop2->GetTaskRunner()->GetTaskQueueId(); const auto raster_thread_merger = fml::MakeRefCounted<fml::RasterThreadMerger>(qid1, qid2); const size_t kNumFramesMerged = 5;
raster_thread_merger->MergeWithLease(kNumFramesMerged);
// merged, running on the same thread EXPECT_EQ(TaskRunnerChecker::RunsOnTheSameThread(qid1, qid2), true);
for (size_t i = 0; i < kNumFramesMerged; i++) { ASSERT_TRUE(raster_thread_merger->IsMerged()); raster_thread_merger->DecrementLease(); }
ASSERT_FALSE(raster_thread_merger->IsMerged());
// un-merged, not running on the same thread EXPECT_EQ(TaskRunnerChecker::RunsOnTheSameThread(qid1, qid2), false);
term1.Signal(); term2.Signal(); thread1.join(); thread2.join();}
TEST(TaskRunnerCheckerTests, PassesRunsOnCreationTaskRunnerIfOnDifferentTaskRunner) { fml::MessageLoop* loop1 = nullptr; fml::AutoResetWaitableEvent latch1; std::thread thread1([&]() { fml::MessageLoop::EnsureInitializedForCurrentThread(); loop1 = &fml::MessageLoop::GetCurrent(); latch1.Signal(); loop1->Run(); });
fml::MessageLoop* loop2 = nullptr; fml::AutoResetWaitableEvent latch2; std::thread thread2([&]() { fml::MessageLoop::EnsureInitializedForCurrentThread(); loop2 = &fml::MessageLoop::GetCurrent(); latch2.Signal(); loop2->Run(); });
latch1.Wait(); latch2.Wait();
fml::TaskQueueId qid1 = loop1->GetTaskRunner()->GetTaskQueueId(); fml::TaskQueueId qid2 = loop2->GetTaskRunner()->GetTaskQueueId(); fml::MessageLoopTaskQueues::GetInstance()->Merge(qid1, qid2);
std::unique_ptr<TaskRunnerChecker> checker;
fml::AutoResetWaitableEvent latch3; loop2->GetTaskRunner()->PostTask([&]() { checker = std::make_unique<TaskRunnerChecker>(); EXPECT_EQ(checker->RunsOnCreationTaskRunner(), true); latch3.Signal(); }); latch3.Wait();
fml::MessageLoopTaskQueues::GetInstance()->Unmerge(qid1, qid2);
fml::AutoResetWaitableEvent latch4; loop2->GetTaskRunner()->PostTask([&]() { EXPECT_EQ(checker->RunsOnCreationTaskRunner(), true); latch4.Signal(); }); latch4.Wait();
loop1->Terminate(); loop2->Terminate(); thread1.join(); thread2.join();}
} // namespace testing} // namespace fml1234567891011// 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 "flutter/fml/memory/thread_checker.h"
namespace fml {
thread_local bool ThreadChecker::disable_next_failure_ = false;
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104// 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.
// A class for checking that the current thread is/isn't the same as an initial// thread.
#ifndef FLUTTER_FML_MEMORY_THREAD_CHECKER_H_#define FLUTTER_FML_MEMORY_THREAD_CHECKER_H_
#include "flutter/fml/build_config.h"#include "flutter/fml/logging.h"#include "flutter/fml/macros.h"
#if defined(FML_OS_WIN)#include <windows.h>#else#include <pthread.h>#endif
namespace fml {
// A simple class that records the identity of the thread that it was created// on, and at later points can tell if the current thread is the same as its// creation thread. This class is thread-safe.//// Note: Unlike Chromium's |base::ThreadChecker|, this is *not* Debug-only (so// #ifdef it out if you want something Debug-only). (Rationale: Having a// |CalledOnValidThread()| that lies in Release builds seems bad. Moreover,// there's a small space cost to having even an empty class. )class ThreadChecker final { public: static void DisableNextThreadCheckFailure() { disable_next_failure_ = true; }
private: static thread_local bool disable_next_failure_;
public:#if defined(FML_OS_WIN) ThreadChecker() : self_(GetCurrentThreadId()) {} ~ThreadChecker() {}
bool IsCreationThreadCurrent() const { bool result = GetCurrentThreadId() == self_; if (!result && disable_next_failure_) { disable_next_failure_ = false; return true; } return result; }
private: DWORD self_;
#else ThreadChecker() : self_(pthread_self()) {} ~ThreadChecker() {}
// Returns true if the current thread is the thread this object was created // on and false otherwise. bool IsCreationThreadCurrent() const { pthread_t current_thread = pthread_self(); bool is_creation_thread_current = !!pthread_equal(current_thread, self_); if (disable_next_failure_ && !is_creation_thread_current) { disable_next_failure_ = false; return true; }#ifdef __APPLE__ // TODO(https://github.com/flutter/flutter/issues/45272): Implement for // other platforms. if (!is_creation_thread_current) { static const int buffer_length = 128; char expected_thread[buffer_length]; char actual_thread[buffer_length]; if (0 == pthread_getname_np(current_thread, actual_thread, buffer_length) && 0 == pthread_getname_np(self_, expected_thread, buffer_length)) { FML_DLOG(ERROR) << "Object referenced on a thread other than the one " "on which it was created. Expected thread: '" << expected_thread << "'. Actual thread: '" << actual_thread << "'."; } }#endif // __APPLE__ return is_creation_thread_current; }
private: pthread_t self_;#endif};
#if !defined(NDEBUG)#define FML_DECLARE_THREAD_CHECKER(c) fml::ThreadChecker c#define FML_DCHECK_CREATION_THREAD_IS_CURRENT(c) \ FML_DCHECK((c).IsCreationThreadCurrent())#else#define FML_DECLARE_THREAD_CHECKER(c)#define FML_DCHECK_CREATION_THREAD_IS_CURRENT(c) ((void)0)#endif
} // namespace fml
#endif // FLUTTER_FML_MEMORY_THREAD_CHECKER_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328// 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.
// This file provides weak pointers and weak pointer factories that work like// Chromium's |base::WeakPtr<T>| and |base::WeakPtrFactory<T>|.
#ifndef FLUTTER_FML_MEMORY_WEAK_PTR_H_#define FLUTTER_FML_MEMORY_WEAK_PTR_H_
#include <utility>
#include "flutter/fml/logging.h"#include "flutter/fml/memory/ref_counted.h"#include "flutter/fml/memory/task_runner_checker.h"#include "flutter/fml/memory/thread_checker.h"#include "flutter/fml/memory/weak_ptr_internal.h"
namespace fml {
struct DebugThreadChecker { FML_DECLARE_THREAD_CHECKER(checker);};
struct DebugTaskRunnerChecker { FML_DECLARE_TASK_RUNNER_CHECKER(checker);};
// Forward declaration, so |WeakPtr<T>| can friend it.template <typename T>class WeakPtrFactory;
// Class for "weak pointers" that can be invalidated. Valid weak pointers// can only originate from a |WeakPtrFactory| (see below), though weak// pointers are copyable and movable.//// Weak pointers are not in general thread-safe. They may only be *used* on// a single thread, namely the same thread as the "originating"// |WeakPtrFactory| (which can invalidate the weak pointers that it// generates).//// However, weak pointers may be passed to other threads, reset on other// threads, or destroyed on other threads. They may also be reassigned on// other threads (in which case they should then only be used on the thread// corresponding to the new "originating" |WeakPtrFactory|).template <typename T>class WeakPtr { public: WeakPtr() : ptr_(nullptr) {}
// Copy constructor. // NOLINTNEXTLINE(google-explicit-constructor) WeakPtr(const WeakPtr<T>& r) = default;
template <typename U> WeakPtr(const WeakPtr<U>& r) // NOLINT(google-explicit-constructor) : ptr_(static_cast<T*>(r.ptr_)), flag_(r.flag_), checker_(r.checker_) {}
// Move constructor. WeakPtr(WeakPtr<T>&& r) = default;
template <typename U> WeakPtr(WeakPtr<U>&& r) // NOLINT(google-explicit-constructor) : ptr_(static_cast<T*>(r.ptr_)), flag_(std::move(r.flag_)), checker_(r.checker_) {}
// The following methods are thread-friendly, in the sense that they may be // called subject to additional synchronization.
// Copy assignment. WeakPtr<T>& operator=(const WeakPtr<T>& r) = default;
// Move assignment. WeakPtr<T>& operator=(WeakPtr<T>&& r) = default;
void reset() { flag_ = nullptr; }
// The following methods should only be called on the same thread as the // "originating" |WeakPtrFactory|.
explicit operator bool() const { CheckThreadSafety(); return flag_ && flag_->is_valid(); }
T* get() const { CheckThreadSafety(); return *this ? ptr_ : nullptr; }
T& operator*() const { CheckThreadSafety(); FML_DCHECK(*this); return *get(); }
T* operator->() const { CheckThreadSafety(); FML_DCHECK(*this); return get(); }
protected: explicit WeakPtr(T* ptr, fml::RefPtr<fml::internal::WeakPtrFlag>&& flag) : ptr_(ptr), flag_(std::move(flag)) {}
void CheckThreadSafety() const { FML_DCHECK_CREATION_THREAD_IS_CURRENT(checker_.checker); }
private: template <typename U> friend class WeakPtr;
friend class WeakPtrFactory<T>;
explicit WeakPtr(T* ptr, fml::RefPtr<fml::internal::WeakPtrFlag>&& flag, const DebugThreadChecker& checker) : ptr_(ptr), flag_(std::move(flag)), checker_(checker) {} T* ptr_; fml::RefPtr<fml::internal::WeakPtrFlag> flag_; DebugThreadChecker checker_;
// Copy/move construction/assignment supported.};
// Forward declaration, so |TaskRunnerAffineWeakPtr<T>| can friend it.template <typename T>class TaskRunnerAffineWeakPtrFactory;
// A weak pointer that can be used in different threads as long as// the threads are belong to the same |TaskRunner|.//// It is still not in general thread safe as |WeakPtr|.template <typename T>class TaskRunnerAffineWeakPtr { public: TaskRunnerAffineWeakPtr() : ptr_(nullptr) {}
TaskRunnerAffineWeakPtr(const TaskRunnerAffineWeakPtr<T>& r) = default;
template <typename U> // NOLINTNEXTLINE(google-explicit-constructor) TaskRunnerAffineWeakPtr(const TaskRunnerAffineWeakPtr<U>& r) : ptr_(static_cast<T*>(r.ptr_)), flag_(r.flag_), checker_(r.checker_) {}
TaskRunnerAffineWeakPtr(TaskRunnerAffineWeakPtr<T>&& r) = default;
template <typename U> // NOLINTNEXTLINE(google-explicit-constructor) TaskRunnerAffineWeakPtr(TaskRunnerAffineWeakPtr<U>&& r) : ptr_(static_cast<T*>(r.ptr_)), flag_(std::move(r.flag_)), checker_(r.checker_) {}
~TaskRunnerAffineWeakPtr() = default;
TaskRunnerAffineWeakPtr<T>& operator=(const TaskRunnerAffineWeakPtr<T>& r) = default;
TaskRunnerAffineWeakPtr<T>& operator=(TaskRunnerAffineWeakPtr<T>&& r) = default;
void reset() { flag_ = nullptr; }
// The following methods should only be called on the same thread as the // "originating" |TaskRunnerAffineWeakPtrFactory|.
explicit operator bool() const { CheckThreadSafety(); return flag_ && flag_->is_valid(); }
T* get() const { CheckThreadSafety(); return *this ? ptr_ : nullptr; }
T& operator*() const { CheckThreadSafety(); FML_DCHECK(*this); return *get(); }
T* operator->() const { CheckThreadSafety(); FML_DCHECK(*this); return get(); }
protected: void CheckThreadSafety() const { FML_DCHECK_TASK_RUNNER_IS_CURRENT(checker_.checker); }
private: template <typename U> friend class TaskRunnerAffineWeakPtr; friend class TaskRunnerAffineWeakPtrFactory<T>;
explicit TaskRunnerAffineWeakPtr( T* ptr, fml::RefPtr<fml::internal::WeakPtrFlag>&& flag, const DebugTaskRunnerChecker& checker) : ptr_(ptr), flag_(std::move(flag)), checker_(checker) {}
T* ptr_; fml::RefPtr<fml::internal::WeakPtrFlag> flag_; DebugTaskRunnerChecker checker_;};
// Class that produces (valid) |WeakPtr<T>|s. Typically, this is used as a// member variable of |T| (preferably the last one -- see below), and |T|'s// methods control how weak pointers to it are vended. This class is not// thread-safe, and should only be created, destroyed and used on a single// thread.//// Example://// class Controller {// public:// Controller() : ..., weak_factory_(this) {}// ...//// void SpawnWorker() { Worker::StartNew(weak_factory_.GetWeakPtr()); }// void WorkComplete(const Result& result) { ... }//// private:// ...//// // Member variables should appear before the |WeakPtrFactory|, to ensure// // that any |WeakPtr|s to |Controller| are invalidated before its member// // variables' destructors are executed.// WeakPtrFactory<Controller> weak_factory_;// };//// class Worker {// public:// static void StartNew(const WeakPtr<Controller>& controller) {// Worker* worker = new Worker(controller);// // Kick off asynchronous processing....// }//// private:// Worker(const WeakPtr<Controller>& controller) : controller_(controller) {}//// void DidCompleteAsynchronousProcessing(const Result& result) {// if (controller_)// controller_->WorkComplete(result);// }//// WeakPtr<Controller> controller_;// };template <typename T>class WeakPtrFactory { public: explicit WeakPtrFactory(T* ptr) : ptr_(ptr), flag_(fml::MakeRefCounted<fml::internal::WeakPtrFlag>()) { FML_DCHECK(ptr_); }
~WeakPtrFactory() { CheckThreadSafety(); flag_->Invalidate(); }
// Gets a new weak pointer, which will be valid until this object is // destroyed. WeakPtr<T> GetWeakPtr() const { return WeakPtr<T>(ptr_, flag_.Clone(), checker_); }
private: // Note: See weak_ptr_internal.h for an explanation of why we store the // pointer here, instead of in the "flag". T* const ptr_; fml::RefPtr<fml::internal::WeakPtrFlag> flag_;
void CheckThreadSafety() const { FML_DCHECK_CREATION_THREAD_IS_CURRENT(checker_.checker); }
DebugThreadChecker checker_;
FML_DISALLOW_COPY_AND_ASSIGN(WeakPtrFactory);};
// A type of |WeakPtrFactory| that produces |TaskRunnerAffineWeakPtr| instead of// |WeakPtr|.template <typename T>class TaskRunnerAffineWeakPtrFactory { public: explicit TaskRunnerAffineWeakPtrFactory(T* ptr) : ptr_(ptr), flag_(fml::MakeRefCounted<fml::internal::WeakPtrFlag>()) { FML_DCHECK(ptr_); }
~TaskRunnerAffineWeakPtrFactory() { CheckThreadSafety(); flag_->Invalidate(); }
// Gets a new weak pointer, which will be valid until this object is // destroyed. TaskRunnerAffineWeakPtr<T> GetWeakPtr() const { return TaskRunnerAffineWeakPtr<T>(ptr_, flag_.Clone(), checker_); }
private: // Note: See weak_ptr_internal.h for an explanation of why we store the // pointer here, instead of in the "flag". T* const ptr_; fml::RefPtr<fml::internal::WeakPtrFlag> flag_;
void CheckThreadSafety() const { FML_DCHECK_TASK_RUNNER_IS_CURRENT(checker_.checker); }
DebugTaskRunnerChecker checker_;
FML_DISALLOW_COPY_AND_ASSIGN(TaskRunnerAffineWeakPtrFactory);};
} // namespace fml
#endif // FLUTTER_FML_MEMORY_WEAK_PTR_H_1234567891011121314151617181920212223242526// 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 "flutter/fml/memory/weak_ptr_internal.h"
#include "flutter/fml/logging.h"
namespace fml {namespace internal {
WeakPtrFlag::WeakPtrFlag() : is_valid_(true) {}
WeakPtrFlag::~WeakPtrFlag() { // Should be invalidated before destruction. FML_DCHECK(!is_valid_);}
void WeakPtrFlag::Invalidate() { // Invalidation should happen exactly once. FML_DCHECK(is_valid_); is_valid_ = false;}
} // namespace internal} // namespace fml1234567891011121314151617181920212223242526272829303132333435363738394041// 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_FML_MEMORY_WEAK_PTR_INTERNAL_H_#define FLUTTER_FML_MEMORY_WEAK_PTR_INTERNAL_H_
#include "flutter/fml/macros.h"#include "flutter/fml/memory/ref_counted.h"
namespace fml {namespace internal {
// |WeakPtr<T>|s have a reference to a |WeakPtrFlag| to determine whether they// are valid (non-null) or not. We do not store a |T*| in this object since// there may also be |WeakPtr<U>|s to the same object, where |U| is a superclass// of |T|.//// This class in not thread-safe, though references may be released on any// thread (allowing weak pointers to be destroyed/reset/reassigned on any// thread).class WeakPtrFlag : public fml::RefCountedThreadSafe<WeakPtrFlag> { public: WeakPtrFlag();
~WeakPtrFlag();
bool is_valid() const { return is_valid_; }
void Invalidate();
private: bool is_valid_ = false;
FML_DISALLOW_COPY_AND_ASSIGN(WeakPtrFlag);};
} // namespace internal} // namespace fml
#endif // FLUTTER_FML_MEMORY_WEAK_PTR_INTERNAL_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241// 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.
#define FML_USED_ON_EMBEDDER
#include "flutter/fml/memory/weak_ptr.h"
#include <thread>#include <utility>
#include "flutter/fml/message_loop.h"#include "flutter/fml/raster_thread_merger.h"#include "flutter/fml/synchronization/count_down_latch.h"#include "gtest/gtest.h"
namespace fml {namespace {
TEST(WeakPtrTest, Basic) { int data = 0; WeakPtrFactory<int> factory(&data); WeakPtr<int> ptr = factory.GetWeakPtr(); EXPECT_EQ(&data, ptr.get());}
TEST(WeakPtrTest, CopyConstruction) { int data = 0; WeakPtrFactory<int> factory(&data); WeakPtr<int> ptr = factory.GetWeakPtr(); const WeakPtr<int>& ptr2(ptr); EXPECT_EQ(&data, ptr.get()); EXPECT_EQ(&data, ptr2.get());}
TEST(WeakPtrTest, MoveConstruction) { int data = 0; WeakPtrFactory<int> factory(&data); WeakPtr<int> ptr = factory.GetWeakPtr(); WeakPtr<int> ptr2(std::move(ptr)); // The clang linter flags the method called on the moved-from reference, but // this is testing the move implementation, so it is marked NOLINT. EXPECT_EQ(nullptr, ptr.get()); // NOLINT EXPECT_EQ(&data, ptr2.get());}
TEST(WeakPtrTest, CopyAssignment) { int data = 0; WeakPtrFactory<int> factory(&data); WeakPtr<int> ptr = factory.GetWeakPtr(); WeakPtr<int> ptr2; EXPECT_EQ(nullptr, ptr2.get()); ptr2 = ptr; EXPECT_EQ(&data, ptr.get()); EXPECT_EQ(&data, ptr2.get());}
TEST(WeakPtrTest, MoveAssignment) { int data = 0; WeakPtrFactory<int> factory(&data); WeakPtr<int> ptr = factory.GetWeakPtr(); WeakPtr<int> ptr2; EXPECT_EQ(nullptr, ptr2.get()); ptr2 = std::move(ptr); // The clang linter flags the method called on the moved-from reference, but // this is testing the move implementation, so it is marked NOLINT. EXPECT_EQ(nullptr, ptr.get()); // NOLINT EXPECT_EQ(&data, ptr2.get());}
TEST(WeakPtrTest, Testable) { int data = 0; WeakPtrFactory<int> factory(&data); WeakPtr<int> ptr; EXPECT_EQ(nullptr, ptr.get()); EXPECT_FALSE(ptr); ptr = factory.GetWeakPtr(); EXPECT_EQ(&data, ptr.get()); EXPECT_TRUE(ptr);}
TEST(WeakPtrTest, OutOfScope) { WeakPtr<int> ptr; EXPECT_EQ(nullptr, ptr.get()); { int data = 0; WeakPtrFactory<int> factory(&data); ptr = factory.GetWeakPtr(); } EXPECT_EQ(nullptr, ptr.get());}
TEST(WeakPtrTest, Multiple) { WeakPtr<int> a; WeakPtr<int> b; { int data = 0; WeakPtrFactory<int> factory(&data); a = factory.GetWeakPtr(); b = factory.GetWeakPtr(); EXPECT_EQ(&data, a.get()); EXPECT_EQ(&data, b.get()); } EXPECT_EQ(nullptr, a.get()); EXPECT_EQ(nullptr, b.get());}
TEST(WeakPtrTest, MultipleStaged) { WeakPtr<int> a; { int data = 0; WeakPtrFactory<int> factory(&data); a = factory.GetWeakPtr(); { WeakPtr<int> b = factory.GetWeakPtr(); } EXPECT_NE(a.get(), nullptr); } EXPECT_EQ(nullptr, a.get());}
struct Base { double member = 0.;};struct Derived : public Base {};
TEST(WeakPtrTest, Dereference) { Base data; data.member = 123456.; WeakPtrFactory<Base> factory(&data); WeakPtr<Base> ptr = factory.GetWeakPtr(); EXPECT_EQ(&data, ptr.get()); EXPECT_EQ(data.member, (*ptr).member); EXPECT_EQ(data.member, ptr->member);}
TEST(WeakPtrTest, UpcastCopyConstruction) { Derived data; WeakPtrFactory<Derived> factory(&data); WeakPtr<Derived> ptr = factory.GetWeakPtr(); WeakPtr<Base> ptr2(ptr); EXPECT_EQ(&data, ptr.get()); EXPECT_EQ(&data, ptr2.get());}
TEST(WeakPtrTest, UpcastMoveConstruction) { Derived data; WeakPtrFactory<Derived> factory(&data); WeakPtr<Derived> ptr = factory.GetWeakPtr(); WeakPtr<Base> ptr2(std::move(ptr)); // The clang linter flags the method called on the moved-from reference, but // this is testing the move implementation, so it is marked NOLINT. EXPECT_EQ(nullptr, ptr.get()); // NOLINT EXPECT_EQ(&data, ptr2.get());}
TEST(WeakPtrTest, UpcastCopyAssignment) { Derived data; WeakPtrFactory<Derived> factory(&data); WeakPtr<Derived> ptr = factory.GetWeakPtr(); WeakPtr<Base> ptr2; EXPECT_EQ(nullptr, ptr2.get()); ptr2 = ptr; EXPECT_EQ(&data, ptr.get()); EXPECT_EQ(&data, ptr2.get());}
TEST(WeakPtrTest, UpcastMoveAssignment) { Derived data; WeakPtrFactory<Derived> factory(&data); WeakPtr<Derived> ptr = factory.GetWeakPtr(); WeakPtr<Base> ptr2; EXPECT_EQ(nullptr, ptr2.get()); ptr2 = std::move(ptr); // The clang linter flags the method called on the moved-from reference, but // this is testing the move implementation, so it is marked NOLINT. EXPECT_EQ(nullptr, ptr.get()); // NOLINT EXPECT_EQ(&data, ptr2.get());}
TEST(TaskRunnerAffineWeakPtrTest, ShouldNotCrashIfRunningOnTheSameTaskRunner) { fml::MessageLoop* loop1 = nullptr; fml::AutoResetWaitableEvent latch1; fml::AutoResetWaitableEvent term1; std::thread thread1([&loop1, &latch1, &term1]() { fml::MessageLoop::EnsureInitializedForCurrentThread(); loop1 = &fml::MessageLoop::GetCurrent(); latch1.Signal(); term1.Wait(); });
fml::MessageLoop* loop2 = nullptr; fml::AutoResetWaitableEvent latch2; fml::AutoResetWaitableEvent term2; fml::AutoResetWaitableEvent loop2_task_finish_latch; fml::AutoResetWaitableEvent loop2_task_start_latch; std::thread thread2([&loop2, &latch2, &term2, &loop2_task_finish_latch, &loop2_task_start_latch]() { fml::MessageLoop::EnsureInitializedForCurrentThread(); int data = 0; TaskRunnerAffineWeakPtrFactory<int> factory(&data); loop2 = &fml::MessageLoop::GetCurrent();
loop2->GetTaskRunner()->PostTask([&]() { latch2.Signal(); loop2_task_start_latch.Wait(); TaskRunnerAffineWeakPtr<int> ptr = factory.GetWeakPtr(); EXPECT_EQ(*ptr, data); loop2_task_finish_latch.Signal(); }); loop2->Run(); term2.Wait(); });
latch1.Wait(); latch2.Wait(); fml::TaskQueueId qid1 = loop1->GetTaskRunner()->GetTaskQueueId(); fml::TaskQueueId qid2 = loop2->GetTaskRunner()->GetTaskQueueId(); const auto raster_thread_merger = fml::MakeRefCounted<fml::RasterThreadMerger>(qid1, qid2); const size_t kNumFramesMerged = 5;
raster_thread_merger->MergeWithLease(kNumFramesMerged);
loop2_task_start_latch.Signal(); loop2_task_finish_latch.Wait();
for (size_t i = 0; i < kNumFramesMerged; i++) { ASSERT_TRUE(raster_thread_merger->IsMerged()); raster_thread_merger->DecrementLease(); }
ASSERT_FALSE(raster_thread_merger->IsMerged()); loop2->Terminate();
term1.Signal(); term2.Signal(); thread1.join(); thread2.join();}
} // namespace} // namespace fml123456789101112131415161718192021222324252627282930313233343536// 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_FML_SYNCHRONIZATION_ATOMIC_OBJECT_H_#define FLUTTER_FML_SYNCHRONIZATION_ATOMIC_OBJECT_H_
#include <mutex>
namespace fml {
// A wrapper for an object instance that can be read or written atomically.template <typename T>class AtomicObject { public: AtomicObject() = default; explicit AtomicObject(T object) : object_(object) {}
T Load() const { std::scoped_lock lock(mutex_); return object_; }
void Store(const T& object) { std::scoped_lock lock(mutex_); object_ = object; }
private: mutable std::mutex mutex_; T object_;};
} // namespace fml
#endif // FLUTTER_FML_SYNCHRONIZATION_ATOMIC_OBJECT_H_1234567891011121314151617181920212223242526272829// 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 "flutter/fml/synchronization/count_down_latch.h"
#include "flutter/fml/logging.h"
namespace fml {
CountDownLatch::CountDownLatch(size_t count) : count_(count) { if (count_ == 0) { waitable_event_.Signal(); }}
CountDownLatch::~CountDownLatch() = default;
void CountDownLatch::Wait() { waitable_event_.Wait();}
void CountDownLatch::CountDown() { if (--count_ == 0) { waitable_event_.Signal(); }}
} // namespace fml12345678910111213141516171819202122232425262728293031323334// 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_FML_SYNCHRONIZATION_COUNT_DOWN_LATCH_H_#define FLUTTER_FML_SYNCHRONIZATION_COUNT_DOWN_LATCH_H_
#include <atomic>
#include "flutter/fml/macros.h"#include "flutter/fml/synchronization/waitable_event.h"
namespace fml {
class CountDownLatch { public: explicit CountDownLatch(size_t count);
~CountDownLatch();
void Wait();
void CountDown();
private: std::atomic_size_t count_; ManualResetWaitableEvent waitable_event_;
FML_DISALLOW_COPY_AND_ASSIGN(CountDownLatch);};
} // namespace fml
#endif // FLUTTER_FML_SYNCHRONIZATION_COUNT_DOWN_LATCH_H_1234567891011121314151617181920212223242526272829303132333435363738394041// 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 "flutter/fml/synchronization/count_down_latch.h"
#include <chrono>#include <thread>
#include "flutter/fml/build_config.h"#include "flutter/fml/thread.h"#include "flutter/testing/testing.h"
namespace fml {
TEST(CountDownLatchTest, CanWaitOnZero) { CountDownLatch latch(0); latch.Wait();}
TEST(CountDownLatchTest, CanWait) { fml::Thread thread("test_thread"); const size_t count = 100; size_t current_count = 0; CountDownLatch latch(count); auto decrement_latch_on_thread = [runner = thread.GetTaskRunner(), &latch, ¤t_count]() { runner->PostTask([&latch, ¤t_count]() { std::this_thread::sleep_for(std::chrono::microseconds(100)); current_count++; latch.CountDown(); }); }; for (size_t i = 0; i < count; ++i) { decrement_latch_on_thread(); } latch.Wait(); ASSERT_EQ(current_count, count);}
} // namespace fml123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193// 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 "flutter/fml/synchronization/semaphore.h"
#include "flutter/fml/build_config.h"#include "flutter/fml/logging.h"
#if FML_OS_MACOSX#include <dispatch/dispatch.h>
namespace fml {
class PlatformSemaphore { public: explicit PlatformSemaphore(uint32_t count) : sem_(dispatch_semaphore_create(count)), initial_(count) {}
~PlatformSemaphore() { for (uint32_t i = 0; i < initial_; ++i) { Signal(); } if (sem_ != nullptr) { dispatch_release(reinterpret_cast<dispatch_object_t>(sem_)); sem_ = nullptr; } }
bool IsValid() const { return sem_ != nullptr; }
bool Wait() { if (sem_ == nullptr) { return false; } return dispatch_semaphore_wait(sem_, DISPATCH_TIME_FOREVER) == 0; }
bool TryWait() { if (sem_ == nullptr) { return false; }
return dispatch_semaphore_wait(sem_, DISPATCH_TIME_NOW) == 0; }
void Signal() { if (sem_ != nullptr) { dispatch_semaphore_signal(sem_); } }
private: dispatch_semaphore_t sem_; const uint32_t initial_;
FML_DISALLOW_COPY_AND_ASSIGN(PlatformSemaphore);};
} // namespace fml
#elif FML_OS_WIN#include <windows.h>
namespace fml {
class PlatformSemaphore { public: explicit PlatformSemaphore(uint32_t count) : _sem(CreateSemaphore(NULL, count, LONG_MAX, NULL)) {}
~PlatformSemaphore() { if (_sem != nullptr) { CloseHandle(_sem); _sem = nullptr; } }
bool IsValid() const { return _sem != nullptr; }
bool Wait() { if (_sem == nullptr) { return false; }
return WaitForSingleObject(_sem, INFINITE) == WAIT_OBJECT_0; }
bool TryWait() { if (_sem == nullptr) { return false; }
return WaitForSingleObject(_sem, 0) == WAIT_OBJECT_0; }
void Signal() { if (_sem != nullptr) { ReleaseSemaphore(_sem, 1, NULL); } }
private: HANDLE _sem;
FML_DISALLOW_COPY_AND_ASSIGN(PlatformSemaphore);};
} // namespace fml
#else#include <semaphore.h>#include "flutter/fml/eintr_wrapper.h"
namespace fml {
class PlatformSemaphore { public: explicit PlatformSemaphore(uint32_t count) : valid_(::sem_init(&sem_, 0 /* not shared */, count) == 0) {}
~PlatformSemaphore() { if (valid_) { int result = ::sem_destroy(&sem_); (void)result; // Can only be EINVAL which should not be possible since we checked for // validity. FML_DCHECK(result == 0); } }
bool IsValid() const { return valid_; }
bool Wait() { if (!valid_) { return false; }
return FML_HANDLE_EINTR(::sem_wait(&sem_)) == 0; }
bool TryWait() { if (!valid_) { return false; }
return FML_HANDLE_EINTR(::sem_trywait(&sem_)) == 0; }
void Signal() { if (!valid_) { return; }
::sem_post(&sem_);
return; }
private: bool valid_; sem_t sem_;
FML_DISALLOW_COPY_AND_ASSIGN(PlatformSemaphore);};
} // namespace fml
#endif
namespace fml {
Semaphore::Semaphore(uint32_t count) : impl_(new PlatformSemaphore(count)) {}
Semaphore::~Semaphore() = default;
bool Semaphore::IsValid() const { return impl_->IsValid();}
bool Semaphore::Wait() { return impl_->Wait();}
bool Semaphore::TryWait() { return impl_->TryWait();}
void Semaphore::Signal() { return impl_->Signal();}
} // namespace fml1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# 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.
import("../tools/impeller.gni")
impeller_component("base") { sources = [ "allocation.cc", "allocation.h", "allocation_size.cc", "allocation_size.h", "backend_cast.h", "comparable.cc", "comparable.h", "config.h", "flags.h", "mask.h", "promise.cc", "promise.h", "strings.cc", "strings.h", "thread.cc", "thread.h", "thread_safety.cc", "thread_safety.h", "timing.h", "validation.cc", "validation.h", "version.cc", "version.h", ]
deps = [ "//flutter/fml" ]}
impeller_component("base_unittests") { testonly = true sources = [ "allocation_size_unittests.cc", "base_unittests.cc", ] deps = [ ":base", "//flutter/testing", ]}1234# The Impeller Base Library
Contains a number of utilities that should probably go in the base library inthe buildroot but whose use is not extensive enough to warrant a move yet.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118// 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 "impeller/base/allocation.h"
#include <algorithm>#include <cstring>
#include "impeller/base/validation.h"
namespace impeller {
Allocation::Allocation() = default;
Allocation::~Allocation() { ::free(buffer_);}
uint8_t* Allocation::GetBuffer() const { return buffer_;}
Bytes Allocation::GetLength() const { return length_;}
Bytes Allocation::GetReservedLength() const { return reserved_;}
bool Allocation::Truncate(Bytes length, bool npot) { const auto reserved = npot ? ReserveNPOT(length) : Reserve(length); if (!reserved) { return false; } length_ = length; return true;}
uint32_t Allocation::NextPowerOfTwoSize(uint32_t x) { if (x == 0) { return 1; }
--x;
x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16;
return x + 1;}
bool Allocation::ReserveNPOT(Bytes reserved) { // Reserve at least one page of data. reserved = std::max(Bytes{4096u}, reserved); return Reserve(Bytes{NextPowerOfTwoSize(reserved.GetByteSize())});}
bool Allocation::Reserve(Bytes reserved) { if (reserved <= reserved_) { return true; }
auto new_allocation = ::realloc(buffer_, reserved.GetByteSize()); if (!new_allocation) { // If new length is zero, a minimum non-zero sized allocation is returned. // So this check will not trip and this routine will indicate success as // expected. VALIDATION_LOG << "Allocation failed. Out of host memory."; return false; }
buffer_ = static_cast<uint8_t*>(new_allocation); reserved_ = reserved;
return true;}
std::shared_ptr<fml::Mapping> CreateMappingWithCopy(const uint8_t* contents, Bytes length) { if (contents == nullptr) { return nullptr; }
auto allocation = std::make_shared<Allocation>(); if (!allocation->Truncate(length)) { return nullptr; }
std::memmove(allocation->GetBuffer(), contents, length.GetByteSize());
return CreateMappingFromAllocation(allocation);}
std::shared_ptr<fml::Mapping> CreateMappingFromAllocation( const std::shared_ptr<Allocation>& allocation) { if (!allocation) { return nullptr; } return std::make_shared<fml::NonOwnedMapping>( reinterpret_cast<const uint8_t*>(allocation->GetBuffer()), // allocation->GetLength().GetByteSize(), // [allocation](auto, auto) {} // );}
std::shared_ptr<fml::Mapping> CreateMappingWithString(std::string string) { auto buffer = std::make_shared<std::string>(std::move(string)); return std::make_unique<fml::NonOwnedMapping>( reinterpret_cast<const uint8_t*>(buffer->c_str()), buffer->length(), [buffer](auto, auto) {});}
} // namespace impeller123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152// 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_IMPELLER_BASE_ALLOCATION_H_#define FLUTTER_IMPELLER_BASE_ALLOCATION_H_
#include <cstdint>#include <memory>
#include "flutter/fml/mapping.h"#include "impeller/base/allocation_size.h"
namespace impeller {
//------------------------------------------------------------------------------/// @brief Describes an allocation on the heap.////// Managing allocations through this utility makes it harder to/// miss allocation failures.///class Allocation { public: //---------------------------------------------------------------------------- /// @brief Constructs a new zero-sized allocation. /// Allocation();
//---------------------------------------------------------------------------- /// @brief Destroys the allocation. /// ~Allocation();
//---------------------------------------------------------------------------- /// @brief Gets the pointer to the start of the allocation. /// /// This pointer is only valid till the next call to `Truncate`. /// /// @return The pointer to the start of the allocation. /// uint8_t* GetBuffer() const;
//---------------------------------------------------------------------------- /// @brief Gets the length of the allocation. /// /// @return The length. /// Bytes GetLength() const;
//---------------------------------------------------------------------------- /// @brief Gets the reserved length of the allocation. Calls to truncate /// may be ignored till the length exceeds the reserved length. /// /// @return The reserved length. /// Bytes GetReservedLength() const;
//---------------------------------------------------------------------------- /// @brief Resize the underlying allocation to at least given number of /// bytes. /// /// In case of failure, false is returned and the underlying /// allocation remains unchanged. /// /// @warning Pointers to buffers obtained via previous calls to `GetBuffer` /// may become invalid at this point. /// /// @param[in] length The length. /// @param[in] npot Whether to round up the length to the next power of /// two. /// /// @return If the underlying allocation was resized to the new size. /// [[nodiscard]] bool Truncate(Bytes length, bool npot = true);
//---------------------------------------------------------------------------- /// @brief Gets the next power of two size. /// /// @param[in] x The size. /// /// @return The next power of two of x. /// static uint32_t NextPowerOfTwoSize(uint32_t x);
private: uint8_t* buffer_ = nullptr; Bytes length_; Bytes reserved_;
[[nodiscard]] bool Reserve(Bytes reserved);
[[nodiscard]] bool ReserveNPOT(Bytes reserved);
Allocation(const Allocation&) = delete;
Allocation& operator=(const Allocation&) = delete;};
//------------------------------------------------------------------------------/// @brief Creates a mapping with copy of the bytes.////// @param[in] contents The contents/// @param[in] length The length////// @return The new mapping or nullptr if the copy could not be performed.///std::shared_ptr<fml::Mapping> CreateMappingWithCopy(const uint8_t* contents, Bytes length);
//------------------------------------------------------------------------------/// @brief Creates a mapping from allocation.////// No data copy occurs. Only a reference to the underlying/// allocation is bumped up.////// Changes to the underlying allocation will not be reflected in/// the mapping and must not change.////// @param[in] allocation The allocation.////// @return A new mapping or nullptr if the argument allocation was invalid.///std::shared_ptr<fml::Mapping> CreateMappingFromAllocation( const std::shared_ptr<Allocation>& allocation);
//------------------------------------------------------------------------------/// @brief Creates a mapping with string data.////// Only a reference to the underlying string is bumped up and the/// string is not copied.////// @param[in] string The string////// @return A new mapping or nullptr in case of allocation failures.///std::shared_ptr<fml::Mapping> CreateMappingWithString( std::shared_ptr<const std::string> string);
//------------------------------------------------------------------------------/// @brief Creates a mapping with string data.////// The string is copied.////// @param[in] string The string////// @return A new mapping or nullptr in case of allocation failures.///std::shared_ptr<fml::Mapping> CreateMappingWithString(std::string string);
} // namespace impeller
#endif // FLUTTER_IMPELLER_BASE_ALLOCATION_H_1234567891011// 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 "impeller/base/allocation_size.h"
namespace impeller {
//
} // namespace impeller123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202// 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_IMPELLER_BASE_ALLOCATION_SIZE_H_#define FLUTTER_IMPELLER_BASE_ALLOCATION_SIZE_H_
#include <cmath>#include <cstddef>#include <cstdint>#include <type_traits>
namespace impeller {
enum class FromBytesTag { kFromBytes };
//------------------------------------------------------------------------------/// @brief Represents the size of an allocation in different units.////// Refer to the typedefs for Bytes, KiloBytes, MegaBytes,/// Gigabytes, KibiBytes, MebiBytes, and GibiBytes below when using.////// Storage and all operations are always on unsigned units of/// bytes.////// @tparam Period The number of bytes in 1 unit of the allocation size.///template <size_t Period>class AllocationSize { public: //---------------------------------------------------------------------------- /// @brief Create a zero allocation size. /// constexpr AllocationSize() = default;
//---------------------------------------------------------------------------- /// @brief Create an allocation size with the amount in the `Period` /// number of bytes. /// /// @param[in] size The size in `Period` number of bytes. /// template <class T, class = std::enable_if_t<std::is_arithmetic_v<T>>> explicit constexpr AllocationSize(T size) : bytes_(std::ceil(size) * Period) {}
//---------------------------------------------------------------------------- /// @brief Create an allocation size from another instance with a /// different period. /// /// @param[in] other The other allocation size. /// /// @tparam OtherPeriod The period of the other allocation. /// template <size_t OtherPeriod> explicit constexpr AllocationSize(const AllocationSize<OtherPeriod>& other) : bytes_(other.GetByteSize()) {}
//---------------------------------------------------------------------------- /// @brief Create an allocation size with the amount directly specified /// in bytes. /// /// @param[in] byte_size The byte size. /// @param[in] tag A tag for this constructor. /// constexpr AllocationSize(uint64_t byte_size, FromBytesTag) : bytes_(byte_size) {}
//---------------------------------------------------------------------------- /// @return The byte size. /// constexpr uint64_t GetByteSize() const { return bytes_; }
//---------------------------------------------------------------------------- /// @return The number of `Periods` of bytes. /// constexpr double GetSize() const { return GetByteSize() / static_cast<double>(Period); }
//---------------------------------------------------------------------------- /// @brief Convert the allocation size from one unit to another. /// /// Conversions are non-truncating. /// /// @tparam AllocationSize The allocation size to convert to. /// /// @return The new allocation size. /// template <class AllocationSize> constexpr AllocationSize ConvertTo() { return AllocationSize{GetByteSize(), FromBytesTag::kFromBytes}; }
// The following relational operators can be replaced with a defaulted // spaceship operator post C++20.
constexpr bool operator<(const AllocationSize& other) const { return bytes_ < other.bytes_; }
constexpr bool operator>(const AllocationSize& other) const { return bytes_ > other.bytes_; }
constexpr bool operator>=(const AllocationSize& other) const { return bytes_ >= other.bytes_; }
constexpr bool operator<=(const AllocationSize& other) const { return bytes_ <= other.bytes_; }
constexpr bool operator==(const AllocationSize& other) const { return bytes_ == other.bytes_; }
constexpr bool operator!=(const AllocationSize& other) const { return bytes_ != other.bytes_; }
// Explicit casts.
explicit constexpr operator bool() const { return bytes_ != 0u; }
// Arithmetic operators (overflows are caller error).
constexpr AllocationSize operator+(const AllocationSize& other) const { return AllocationSize(bytes_ + other.GetByteSize(), FromBytesTag::kFromBytes); }
constexpr AllocationSize operator-(const AllocationSize& other) const { return AllocationSize(bytes_ - other.GetByteSize(), FromBytesTag::kFromBytes); }
constexpr AllocationSize& operator+=(const AllocationSize& other) { bytes_ += other.GetByteSize(); return *this; }
constexpr AllocationSize& operator-=(const AllocationSize& other) { bytes_ -= other.GetByteSize(); return *this; }
private: uint64_t bytes_ = {};};
using Bytes = AllocationSize<1u>;
using KiloBytes = AllocationSize<1'000u>;using MegaBytes = AllocationSize<1'000u * 1'000u>;using GigaBytes = AllocationSize<1'000u * 1'000u * 1'000u>;
using KibiBytes = AllocationSize<1'024u>;using MebiBytes = AllocationSize<1'024u * 1'024u>;using GibiBytes = AllocationSize<1'024u * 1'024u * 1'024u>;
inline namespace allocation_size_literals {
// NOLINTNEXTLINEconstexpr Bytes operator"" _bytes(unsigned long long int size) { return Bytes{size};}
// NOLINTNEXTLINEconstexpr KiloBytes operator"" _kb(unsigned long long int size) { return KiloBytes{size};}
// NOLINTNEXTLINEconstexpr MegaBytes operator"" _mb(unsigned long long int size) { return MegaBytes{size};}
// NOLINTNEXTLINEconstexpr GigaBytes operator"" _gb(unsigned long long int size) { return GigaBytes{size};}
// NOLINTNEXTLINEconstexpr KibiBytes operator"" _kib(unsigned long long int size) { return KibiBytes{size};}
// NOLINTNEXTLINEconstexpr MebiBytes operator"" _mib(unsigned long long int size) { return MebiBytes{size};}
// NOLINTNEXTLINEconstexpr GibiBytes operator"" _gib(unsigned long long int size) { return GibiBytes{size};}
} // namespace allocation_size_literals
} // namespace impeller
#endif // FLUTTER_IMPELLER_BASE_ALLOCATION_SIZE_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125// 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 "flutter/testing/testing.h"#include "impeller/base/allocation_size.h"
namespace impeller::testing {
TEST(AllocationSizeTest, CanCreateTypedAllocations) { auto bytes = Bytes{1024}; ASSERT_EQ(bytes.GetByteSize(), 1024u);
auto kilobytes = KiloBytes{5}; ASSERT_EQ(kilobytes.GetByteSize(), 5u * 1e3);
auto megabytes = MegaBytes{5}; ASSERT_EQ(megabytes.GetByteSize(), 5u * 1e6);
auto gigabytes = GigaBytes{5}; ASSERT_EQ(gigabytes.GetByteSize(), 5u * 1e9);
auto kibibytes = KibiBytes{1}; ASSERT_EQ(kibibytes.GetByteSize(), 1024u);
auto mebibytes = MebiBytes{1}; ASSERT_EQ(mebibytes.GetByteSize(), 1048576u);
auto gigibytes = GibiBytes{1}; ASSERT_EQ(gigibytes.GetByteSize(), 1073741824u);}
TEST(AllocationSizeTest, CanCreateTypedAllocationsWithLiterals) { using namespace allocation_size_literals; ASSERT_EQ((1024_bytes).GetByteSize(), 1024u); ASSERT_EQ((5_kb).GetByteSize(), 5u * 1e3); ASSERT_EQ((5_mb).GetByteSize(), 5u * 1e6); ASSERT_EQ((5_gb).GetByteSize(), 5u * 1e9); ASSERT_EQ((1_kib).GetByteSize(), 1024u); ASSERT_EQ((1_mib).GetByteSize(), 1048576u); ASSERT_EQ((1_gib).GetByteSize(), 1073741824u);}
TEST(AllocationSizeTest, CanConvert) { using namespace allocation_size_literals; ASSERT_EQ((5_gb).ConvertTo<MegaBytes>().GetSize(), 5000u);}
TEST(AllocationSizeTest, ConversionsAreNonTruncating) { using namespace allocation_size_literals; ASSERT_DOUBLE_EQ((1500_bytes).ConvertTo<KiloBytes>().GetSize(), 1.5); ASSERT_EQ((1500_bytes).ConvertTo<KiloBytes>().GetByteSize(), 1500u);}
TEST(AllocationSizeTest, CanGetFloatValues) { using namespace allocation_size_literals; ASSERT_DOUBLE_EQ((1500_bytes).ConvertTo<KiloBytes>().GetSize(), 1.5);}
TEST(AllocationSizeTest, RelationalOperatorsAreFunctional) { using namespace allocation_size_literals;
auto a = 1500_bytes; auto b = 2500_bytes; auto c = 0_bytes;
ASSERT_TRUE(a != b); ASSERT_FALSE(a == b); ASSERT_TRUE(b > a); ASSERT_TRUE(b >= a); ASSERT_TRUE(a < b); ASSERT_TRUE(a <= b); ASSERT_TRUE(a); ASSERT_FALSE(c);}
TEST(AllocationSizeTest, CanCast) { using namespace allocation_size_literals; { auto a = KiloBytes{1500_bytes}; ASSERT_DOUBLE_EQ(a.GetSize(), 1.5); } { auto a = KiloBytes{Bytes{1500}}; ASSERT_DOUBLE_EQ(a.GetSize(), 1.5); }
ASSERT_DOUBLE_EQ(MebiBytes{Bytes{4194304}}.GetSize(), 4);}
TEST(AllocationSizeTest, CanPerformSimpleArithmetic) { using namespace allocation_size_literals; { auto a = 100_bytes; auto b = 200_bytes; ASSERT_EQ((a + b).GetByteSize(), 300u); } { auto a = 100_bytes; a += 200_bytes; ASSERT_EQ(a.GetByteSize(), 300u); } { auto a = 100_bytes; a -= 50_bytes; ASSERT_EQ(a.GetByteSize(), 50u); }}
TEST(AllocationSizeTest, CanConstructWithArith) { { Bytes a(1u); ASSERT_EQ(a.GetByteSize(), 1u); } { Bytes a(1.5); ASSERT_EQ(a.GetByteSize(), 2u); } { Bytes a(1.5f); ASSERT_EQ(a.GetByteSize(), 2u); }}
} // namespace impeller::testing12345678910111213141516171819202122232425262728// 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_IMPELLER_BASE_BACKEND_CAST_H_#define FLUTTER_IMPELLER_BASE_BACKEND_CAST_H_
namespace impeller {
template <class Sub, class Base>class BackendCast { public: static Sub& Cast(Base& base) { return reinterpret_cast<Sub&>(base); }
static const Sub& Cast(const Base& base) { return reinterpret_cast<const Sub&>(base); }
static Sub* Cast(Base* base) { return reinterpret_cast<Sub*>(base); }
static const Sub* Cast(const Base* base) { return reinterpret_cast<const Sub*>(base); }};
} // namespace impeller
#endif // FLUTTER_IMPELLER_BASE_BACKEND_CAST_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449// 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 "flutter/testing/testing.h"#include "impeller/base/mask.h"#include "impeller/base/promise.h"#include "impeller/base/strings.h"#include "impeller/base/thread.h"
namespace impeller {
enum class MyMaskBits : uint32_t { kFoo = 0, kBar = 1 << 0, kBaz = 1 << 1, kBang = 1 << 2,};
using MyMask = Mask<MyMaskBits>;
IMPELLER_ENUM_IS_MASK(MyMaskBits);
namespace testing {
struct Foo { Mutex mtx; int a IPLR_GUARDED_BY(mtx);};
struct RWFoo { RWMutex mtx; int a IPLR_GUARDED_BY(mtx);};
TEST(ThreadTest, CanCreateMutex) { Foo f = {};
// f.a = 100; <--- Static analysis error. f.mtx.Lock(); f.a = 100; f.mtx.Unlock();}
TEST(ThreadTest, CanCreateMutexLock) { Foo f = {};
// f.a = 100; <--- Static analysis error. auto a = Lock(f.mtx); f.a = 100;}
TEST(ThreadTest, CanCreateRWMutex) { RWFoo f = {};
// f.a = 100; <--- Static analysis error. f.mtx.LockWriter(); f.a = 100; f.mtx.UnlockWriter(); // int b = f.a; <--- Static analysis error. f.mtx.LockReader(); [[maybe_unused]] int b = f.a; // NOLINT(clang-analyzer-deadcode.DeadStores) f.mtx.UnlockReader();}
TEST(ThreadTest, CanCreateRWMutexLock) { RWFoo f = {};
// f.a = 100; <--- Static analysis error. { auto write_lock = WriterLock{f.mtx}; f.a = 100; }
// int b = f.a; <--- Static analysis error. { auto read_lock = ReaderLock(f.mtx); [[maybe_unused]] int b = f.a; // NOLINT(clang-analyzer-deadcode.DeadStores) }
// f.mtx.UnlockReader(); <--- Static analysis error.}
TEST(StringsTest, CanSPrintF) { ASSERT_EQ(SPrintF("%sx%d", "Hello", 12), "Hellox12"); ASSERT_EQ(SPrintF(""), ""); ASSERT_EQ(SPrintF("Hello"), "Hello"); ASSERT_EQ(SPrintF("%sx%.2f", "Hello", 12.122222), "Hellox12.12");}
struct CVTest { Mutex mutex; ConditionVariable cv; uint32_t rando_ivar IPLR_GUARDED_BY(mutex) = 0;};
TEST(ConditionVariableTest, WaitUntil) { CVTest test; // test.rando_ivar = 12; // <--- Static analysis error for (size_t i = 0; i < 2; ++i) { test.mutex.Lock(); // <--- Static analysis error without this. auto result = test.cv.WaitUntil( test.mutex, std::chrono::high_resolution_clock::now() + std::chrono::milliseconds{10}, [&]() IPLR_REQUIRES(test.mutex) { test.rando_ivar = 12; // <-- Static analysics error without the // IPLR_REQUIRES on the pred. return false; }); test.mutex.Unlock(); ASSERT_FALSE(result); } Lock lock(test.mutex); // <--- Static analysis error without this. // The predicate never returns true. So return has to be due to a non-spurious // wake. ASSERT_EQ(test.rando_ivar, 12u);}
TEST(ConditionVariableTest, WaitFor) { CVTest test; // test.rando_ivar = 12; // <--- Static analysis error for (size_t i = 0; i < 2; ++i) { test.mutex.Lock(); // <--- Static analysis error without this. auto result = test.cv.WaitFor( test.mutex, std::chrono::milliseconds{10}, [&]() IPLR_REQUIRES(test.mutex) { test.rando_ivar = 12; // <-- Static analysics error without the // IPLR_REQUIRES on the pred. return false; }); test.mutex.Unlock(); ASSERT_FALSE(result); } Lock lock(test.mutex); // <--- Static analysis error without this. // The predicate never returns true. So return has to be due to a non-spurious // wake. ASSERT_EQ(test.rando_ivar, 12u);}
TEST(ConditionVariableTest, WaitForever) { CVTest test; // test.rando_ivar = 12; // <--- Static analysis error for (size_t i = 0; i < 2; ++i) { test.mutex.Lock(); // <--- Static analysis error without this. test.cv.Wait(test.mutex, [&]() IPLR_REQUIRES(test.mutex) { test.rando_ivar = 12; // <-- Static analysics error without // the IPLR_REQUIRES on the pred. return true; }); test.mutex.Unlock(); } Lock lock(test.mutex); // <--- Static analysis error without this. // The wake only happens when the predicate returns true. ASSERT_EQ(test.rando_ivar, 12u);}
TEST(ConditionVariableTest, TestsCriticalSectionAfterWaitForUntil) { std::vector<std::thread> threads; const auto kThreadCount = 10u;
Mutex mtx; ConditionVariable cv; size_t sum = 0u;
std::condition_variable start_cv; std::mutex start_mtx; bool start = false; auto start_predicate = [&start]() { return start; }; auto thread_main = [&]() { { std::unique_lock start_lock(start_mtx); start_cv.wait(start_lock, start_predicate); }
mtx.Lock(); cv.WaitFor(mtx, std::chrono::milliseconds{0u}, []() { return true; }); auto old_val = sum; std::this_thread::sleep_for(std::chrono::milliseconds{100u}); sum = old_val + 1u; mtx.Unlock(); }; // Launch all threads. They will wait for the start CV to be signaled. for (size_t i = 0; i < kThreadCount; i++) { threads.emplace_back(thread_main); } // Notify all threads that the test may start. { { std::scoped_lock start_lock(start_mtx); start = true; } start_cv.notify_all(); } // Join all threads. ASSERT_EQ(threads.size(), kThreadCount); for (size_t i = 0; i < kThreadCount; i++) { threads[i].join(); } ASSERT_EQ(sum, kThreadCount);}
TEST(ConditionVariableTest, TestsCriticalSectionAfterWait) { std::vector<std::thread> threads; const auto kThreadCount = 10u;
Mutex mtx; ConditionVariable cv; size_t sum = 0u;
std::condition_variable start_cv; std::mutex start_mtx; bool start = false; auto start_predicate = [&start]() { return start; }; auto thread_main = [&]() { { std::unique_lock start_lock(start_mtx); start_cv.wait(start_lock, start_predicate); }
mtx.Lock(); cv.Wait(mtx, []() { return true; }); auto old_val = sum; std::this_thread::sleep_for(std::chrono::milliseconds{100u}); sum = old_val + 1u; mtx.Unlock(); }; // Launch all threads. They will wait for the start CV to be signaled. for (size_t i = 0; i < kThreadCount; i++) { threads.emplace_back(thread_main); } // Notify all threads that the test may start. { { std::scoped_lock start_lock(start_mtx); start = true; } start_cv.notify_all(); } // Join all threads. ASSERT_EQ(threads.size(), kThreadCount); for (size_t i = 0; i < kThreadCount; i++) { threads[i].join(); } ASSERT_EQ(sum, kThreadCount);}
TEST(BaseTest, NoExceptionPromiseValue) { NoExceptionPromise<int> wrapper; std::future future = wrapper.get_future(); wrapper.set_value(123); ASSERT_EQ(future.get(), 123);}
TEST(BaseTest, NoExceptionPromiseEmpty) { auto wrapper = std::make_shared<NoExceptionPromise<int>>(); std::future future = wrapper->get_future();
// Destroy the empty promise with the future still pending. Verify that the // process does not abort while destructing the promise. wrapper.reset();}
TEST(BaseTest, CanUseTypedMasks) { { MyMask mask; ASSERT_EQ(static_cast<uint32_t>(mask), 0u); ASSERT_FALSE(mask); }
{ MyMask mask(MyMaskBits::kBar); ASSERT_EQ(static_cast<uint32_t>(mask), 1u); ASSERT_TRUE(mask); }
{ MyMask mask2(MyMaskBits::kBar); MyMask mask(mask2); ASSERT_EQ(static_cast<uint32_t>(mask), 1u); ASSERT_TRUE(mask); }
{ MyMask mask2(MyMaskBits::kBar); MyMask mask(std::move(mask2)); // NOLINT ASSERT_EQ(static_cast<uint32_t>(mask), 1u); ASSERT_TRUE(mask); }
ASSERT_LT(MyMaskBits::kBar, MyMaskBits::kBaz); ASSERT_LE(MyMaskBits::kBar, MyMaskBits::kBaz); ASSERT_GT(MyMaskBits::kBaz, MyMaskBits::kBar); ASSERT_GE(MyMaskBits::kBaz, MyMaskBits::kBar); ASSERT_EQ(MyMaskBits::kBaz, MyMaskBits::kBaz); ASSERT_NE(MyMaskBits::kBaz, MyMaskBits::kBang);
{ MyMask m1(MyMaskBits::kBar); MyMask m2(MyMaskBits::kBaz); ASSERT_EQ(static_cast<uint32_t>(m1 & m2), 0u); ASSERT_FALSE(m1 & m2); }
{ MyMask m1(MyMaskBits::kBar); MyMask m2(MyMaskBits::kBaz); ASSERT_EQ(static_cast<uint32_t>(m1 | m2), ((1u << 0u) | (1u << 1u))); ASSERT_TRUE(m1 | m2); }
{ MyMask m1(MyMaskBits::kBar); MyMask m2(MyMaskBits::kBaz); ASSERT_EQ(static_cast<uint32_t>(m1 ^ m2), ((1u << 0u) ^ (1u << 1u))); ASSERT_TRUE(m1 ^ m2); }
{ MyMask m1(MyMaskBits::kBar); ASSERT_EQ(static_cast<uint32_t>(~m1), (~(1u << 0u))); ASSERT_TRUE(m1); }
{ MyMask m1 = MyMaskBits::kBar; MyMask m2 = MyMaskBits::kBaz; m2 = m1; ASSERT_EQ(m2, MyMaskBits::kBar); }
{ MyMask m = MyMaskBits::kBar | MyMaskBits::kBaz; ASSERT_TRUE(m); }
{ MyMask m = MyMaskBits::kBar & MyMaskBits::kBaz; ASSERT_FALSE(m); }
{ MyMask m = MyMaskBits::kBar ^ MyMaskBits::kBaz; ASSERT_TRUE(m); }
{ MyMask m = ~MyMaskBits::kBar; ASSERT_TRUE(m); }
{ MyMask m1 = MyMaskBits::kBar; MyMask m2 = MyMaskBits::kBaz; m2 |= m1; ASSERT_EQ(m1, MyMaskBits::kBar); MyMask pred = MyMaskBits::kBar | MyMaskBits::kBaz; ASSERT_EQ(m2, pred); }
{ MyMask m1 = MyMaskBits::kBar; MyMask m2 = MyMaskBits::kBaz; m2 &= m1; ASSERT_EQ(m1, MyMaskBits::kBar); MyMask pred = MyMaskBits::kBar & MyMaskBits::kBaz; ASSERT_EQ(m2, pred); }
{ MyMask m1 = MyMaskBits::kBar; MyMask m2 = MyMaskBits::kBaz; m2 ^= m1; ASSERT_EQ(m1, MyMaskBits::kBar); MyMask pred = MyMaskBits::kBar ^ MyMaskBits::kBaz; ASSERT_EQ(m2, pred); }
{ MyMask x = MyMaskBits::kBar; MyMask m = x | MyMaskBits::kBaz; ASSERT_TRUE(m); }
{ MyMask x = MyMaskBits::kBar; MyMask m = MyMaskBits::kBaz | x; ASSERT_TRUE(m); }
{ MyMask x = MyMaskBits::kBar; MyMask m = x & MyMaskBits::kBaz; ASSERT_FALSE(m); }
{ MyMask x = MyMaskBits::kBar; MyMask m = MyMaskBits::kBaz & x; ASSERT_FALSE(m); }
{ MyMask x = MyMaskBits::kBar; MyMask m = x ^ MyMaskBits::kBaz; ASSERT_TRUE(m); }
{ MyMask x = MyMaskBits::kBar; MyMask m = MyMaskBits::kBaz ^ x; ASSERT_TRUE(m); }
{ MyMask x = MyMaskBits::kBar; MyMask m = ~x; ASSERT_TRUE(m); }
{ MyMaskBits x = MyMaskBits::kBar; MyMask m = MyMaskBits::kBaz; ASSERT_TRUE(x < m); ASSERT_TRUE(x <= m); }
{ MyMaskBits x = MyMaskBits::kBar; MyMask m = MyMaskBits::kBaz; ASSERT_FALSE(x == m); }
{ MyMaskBits x = MyMaskBits::kBar; MyMask m = MyMaskBits::kBaz; ASSERT_TRUE(x != m); }
{ MyMaskBits x = MyMaskBits::kBar; MyMask m = MyMaskBits::kBaz; ASSERT_FALSE(x > m); ASSERT_FALSE(x >= m); }}
} // namespace testing} // namespace impeller1234567891011121314// 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 "impeller/base/comparable.h"
#include <atomic>
namespace impeller {
static std::atomic_size_t sLastID;UniqueID::UniqueID() : id(++sLastID) {}
} // namespace impeller123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114// 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_IMPELLER_BASE_COMPARABLE_H_#define FLUTTER_IMPELLER_BASE_COMPARABLE_H_
#include <cstddef>#include <functional>#include <map>#include <memory>#include <type_traits>
namespace impeller {
struct UniqueID { size_t id;
UniqueID();
constexpr bool operator==(const UniqueID& other) const { return id == other.id; }};
class ComparableBase {};
template <class Type>class Comparable : ComparableBase { public: virtual std::size_t GetHash() const = 0;
virtual bool IsEqual(const Type& other) const = 0;};
template < class ComparableType, class = std::enable_if_t<std::is_base_of_v<ComparableBase, ComparableType>>>struct ComparableHash { std::size_t operator()(const ComparableType& object) const { return object.GetHash(); }};
template < class ComparableType, class = std::enable_if_t<std::is_base_of_v<ComparableBase, ComparableType>>>struct ComparableEqual { bool operator()(const ComparableType& lhs, const ComparableType& rhs) const { return lhs.IsEqual(rhs); }};
template < class ComparableType, class = std::enable_if_t<std::is_base_of_v<ComparableBase, ComparableType>>>bool DeepComparePointer(const std::shared_ptr<ComparableType>& lhs, const std::shared_ptr<ComparableType>& rhs) { if (lhs == rhs) { return true; }
if (lhs && rhs) { return lhs->IsEqual(*rhs); }
return false;}
template < class Key, class ComparableType, class = std::enable_if_t<std::is_base_of_v<ComparableBase, ComparableType>>>bool DeepCompareMap(const std::map<Key, std::shared_ptr<ComparableType>>& lhs, const std::map<Key, std::shared_ptr<ComparableType>>& rhs) { if (lhs.size() != rhs.size()) { return false; }
for (auto i = lhs.begin(), j = rhs.begin(); i != lhs.end(); i++, j++) { if (i->first != j->first) { return false; }
if (!DeepComparePointer(i->second, j->second)) { return false; } }
return true;}
} // namespace impeller
namespace std {
template <>struct hash<impeller::UniqueID> { constexpr std::size_t operator()(const impeller::UniqueID& id) { return id.id; }};
template <>struct less<impeller::UniqueID> { constexpr bool operator()(const impeller::UniqueID& lhs, const impeller::UniqueID& rhs) const { return lhs.id < rhs.id; }};
} // namespace std
#endif // FLUTTER_IMPELLER_BASE_COMPARABLE_H_12345678910111213141516171819202122232425262728293031323334353637383940// 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_IMPELLER_BASE_CONFIG_H_#define FLUTTER_IMPELLER_BASE_CONFIG_H_
#include <cstdlib>
#include "flutter/fml/logging.h"
#if defined(__GNUC__) || defined(__clang__)#define IMPELLER_COMPILER_CLANG 1#else // defined(__GNUC__) || defined(__clang__)#define IMPELLER_COMPILER_CLANG 0#endif // defined(__GNUC__) || defined(__clang__)
#if IMPELLER_COMPILER_CLANG#define IMPELLER_PRINTF_FORMAT(format_number, args_number) \ __attribute__((format(printf, format_number, args_number)))#else // IMPELLER_COMPILER_CLANG#define IMPELLER_PRINTF_FORMAT(format_number, args_number)#endif // IMPELLER_COMPILER_CLANG
#define IMPELLER_UNIMPLEMENTED \ impeller::ImpellerUnimplemented(__FUNCTION__, __FILE__, __LINE__);
namespace impeller {
[[noreturn]] inline void ImpellerUnimplemented(const char* method, const char* file, int line) { FML_CHECK(false) << "Unimplemented: " << method << " in " << file << ":" << line; std::abort();}
} // namespace impeller
#endif // FLUTTER_IMPELLER_BASE_CONFIG_H_123456789101112131415161718// 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_IMPELLER_BASE_FLAGS_H_#define FLUTTER_IMPELLER_BASE_FLAGS_H_
namespace impeller {struct Flags { /// Whether to defer PSO construction until first use. Usage Will introduce /// raster jank. bool lazy_shader_mode = false; /// When turned on DrawLine will use the experimental antialiased path. bool antialiased_lines = false;};} // namespace impeller
#endif // FLUTTER_IMPELLER_BASE_FLAGS_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230// 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_IMPELLER_BASE_MASK_H_#define FLUTTER_IMPELLER_BASE_MASK_H_
#include <type_traits>
namespace impeller {
template <typename EnumType_>struct MaskTraits { static constexpr bool kIsMask = false;};
//------------------------------------------------------------------------------/// @brief Declare this in the "impeller" namespace to make the enum/// maskable.///#define IMPELLER_ENUM_IS_MASK(enum_name) \ template <> \ struct MaskTraits<enum_name> { \ static constexpr bool kIsMask = true; \ };
//------------------------------------------------------------------------------/// @brief A mask of typed enums.////// @tparam EnumType_ The type of the enum. Must be an enum class.///template <typename EnumType_>struct Mask { using EnumType = EnumType_; using MaskType = typename std::underlying_type<EnumType>::type;
constexpr Mask() = default;
constexpr Mask(const Mask<EnumType>& other) = default;
constexpr Mask(Mask<EnumType>&& other) = default;
constexpr Mask(EnumType type) // NOLINT(google-explicit-constructor) : mask_(static_cast<MaskType>(type)) {}
explicit constexpr Mask(MaskType mask) : mask_(static_cast<MaskType>(mask)) {}
// All casts must be explicit.
explicit constexpr operator MaskType() const { return mask_; }
explicit constexpr operator bool() const { return !!mask_; }
// The following relational operators can be replaced with a defaulted // spaceship operator post C++20.
constexpr bool operator<(const Mask<EnumType>& other) const { return mask_ < other.mask_; }
constexpr bool operator>(const Mask<EnumType>& other) const { return mask_ > other.mask_; }
constexpr bool operator>=(const Mask<EnumType>& other) const { return mask_ >= other.mask_; }
constexpr bool operator<=(const Mask<EnumType>& other) const { return mask_ <= other.mask_; }
constexpr bool operator==(const Mask<EnumType>& other) const { return mask_ == other.mask_; }
constexpr bool operator!=(const Mask<EnumType>& other) const { return mask_ != other.mask_; }
// Logical operators.
constexpr bool operator!() const { return !mask_; }
// Bitwise operators.
constexpr Mask<EnumType> operator&(const Mask<EnumType>& other) const { return Mask<EnumType>{mask_ & other.mask_}; }
constexpr Mask<EnumType> operator|(const Mask<EnumType>& other) const { return Mask<EnumType>{mask_ | other.mask_}; }
constexpr Mask<EnumType> operator^(const Mask<EnumType>& other) const { return Mask<EnumType>{mask_ ^ other.mask_}; }
constexpr Mask<EnumType> operator~() const { return Mask<EnumType>{~mask_}; }
// Assignment operators.
constexpr Mask<EnumType>& operator=(const Mask<EnumType>&) = default;
constexpr Mask<EnumType>& operator=(Mask<EnumType>&&) = default;
constexpr Mask<EnumType>& operator|=(const Mask<EnumType>& other) { mask_ |= other.mask_; return *this; }
constexpr Mask<EnumType>& operator&=(const Mask<EnumType>& other) { mask_ &= other.mask_; return *this; }
constexpr Mask<EnumType>& operator^=(const Mask<EnumType>& other) { mask_ ^= other.mask_; return *this; }
private: MaskType mask_ = {};};
// Construction from Enum Types
template < typename EnumType, typename std::enable_if<MaskTraits<EnumType>::kIsMask, bool>::type = true>inline constexpr Mask<EnumType> operator|(const EnumType& lhs, const EnumType& rhs) { return Mask<EnumType>{lhs} | rhs;}
template < typename EnumType, typename std::enable_if<MaskTraits<EnumType>::kIsMask, bool>::type = true>inline constexpr Mask<EnumType> operator&(const EnumType& lhs, const EnumType& rhs) { return Mask<EnumType>{lhs} & rhs;}
template < typename EnumType, typename std::enable_if<MaskTraits<EnumType>::kIsMask, bool>::type = true>inline constexpr Mask<EnumType> operator^(const EnumType& lhs, const EnumType& rhs) { return Mask<EnumType>{lhs} ^ rhs;}
template < typename EnumType, typename std::enable_if<MaskTraits<EnumType>::kIsMask, bool>::type = true>inline constexpr Mask<EnumType> operator~(const EnumType& other) { return ~Mask<EnumType>{other};}
template < typename EnumType, typename std::enable_if<MaskTraits<EnumType>::kIsMask, bool>::type = true>inline constexpr Mask<EnumType> operator|(const EnumType& lhs, const Mask<EnumType>& rhs) { return Mask<EnumType>{lhs} | rhs;}
template < typename EnumType, typename std::enable_if<MaskTraits<EnumType>::kIsMask, bool>::type = true>inline constexpr Mask<EnumType> operator&(const EnumType& lhs, const Mask<EnumType>& rhs) { return Mask<EnumType>{lhs} & rhs;}
template < typename EnumType, typename std::enable_if<MaskTraits<EnumType>::kIsMask, bool>::type = true>inline constexpr Mask<EnumType> operator^(const EnumType& lhs, const Mask<EnumType>& rhs) { return Mask<EnumType>{lhs} ^ rhs;}
// Relational operators with EnumType promotion. These can be replaced by a// defaulted spaceship operator post C++20.
template <typename EnumType, typename std::enable_if_t<MaskTraits<EnumType>::kIsMask, bool> = true>inline constexpr bool operator<(const EnumType& lhs, const Mask<EnumType>& rhs) { return Mask<EnumType>{lhs} < rhs;}
template <typename EnumType, typename std::enable_if_t<MaskTraits<EnumType>::kIsMask, bool> = true>inline constexpr bool operator>(const EnumType& lhs, const Mask<EnumType>& rhs) { return Mask<EnumType>{lhs} > rhs;}
template <typename EnumType, typename std::enable_if_t<MaskTraits<EnumType>::kIsMask, bool> = true>inline constexpr bool operator<=(const EnumType& lhs, const Mask<EnumType>& rhs) { return Mask<EnumType>{lhs} <= rhs;}
template <typename EnumType, typename std::enable_if_t<MaskTraits<EnumType>::kIsMask, bool> = true>inline constexpr bool operator>=(const EnumType& lhs, const Mask<EnumType>& rhs) { return Mask<EnumType>{lhs} >= rhs;}
template <typename EnumType, typename std::enable_if_t<MaskTraits<EnumType>::kIsMask, bool> = true>inline constexpr bool operator==(const EnumType& lhs, const Mask<EnumType>& rhs) { return Mask<EnumType>{lhs} == rhs;}
template <typename EnumType, typename std::enable_if_t<MaskTraits<EnumType>::kIsMask, bool> = true>inline constexpr bool operator!=(const EnumType& lhs, const Mask<EnumType>& rhs) { return Mask<EnumType>{lhs} != rhs;}
} // namespace impeller
#endif // FLUTTER_IMPELLER_BASE_MASK_H_1234567891011// 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 "impeller/base/promise.h"
namespace impeller {
//
} // namespace impeller1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950// 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_IMPELLER_BASE_PROMISE_H_#define FLUTTER_IMPELLER_BASE_PROMISE_H_
#include <future>
namespace impeller {
template <class T>std::future<T> RealizedFuture(T t) { std::promise<T> promise; auto future = promise.get_future(); promise.set_value(std::move(t)); return future;}
// Wraps a std::promise and completes the promise with a value during// destruction if the promise does not already have a value.//// By default the std::promise destructor will complete an empty promise with an// exception. This will fail because Flutter is built without exception support.template <typename T>class NoExceptionPromise { public: NoExceptionPromise() = default;
~NoExceptionPromise() { if (!value_set_) { promise_.set_value({}); } }
std::future<T> get_future() { return promise_.get_future(); }
void set_value(const T& value) { promise_.set_value(value); value_set_ = true; }
private: std::promise<T> promise_; bool value_set_ = false;};
} // namespace impeller
#endif // FLUTTER_IMPELLER_BASE_PROMISE_H_1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950// 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 "impeller/base/strings.h"
#include <cstdarg>
namespace impeller {
IMPELLER_PRINTF_FORMAT(1, 2)std::string SPrintF(const char* format, ...) { std::string ret_val; va_list list; va_list list2; va_start(list, format); va_copy(list2, list); if (auto string_length = ::vsnprintf(nullptr, 0, format, list); string_length >= 0) { auto buffer = reinterpret_cast<char*>(::malloc(string_length + 1)); ::vsnprintf(buffer, string_length + 1, format, list2); ret_val = std::string{buffer, static_cast<size_t>(string_length)}; ::free(buffer); } va_end(list2); va_end(list); return ret_val;}
bool HasPrefix(const std::string& string, const std::string& prefix) { return string.find(prefix) == 0u;}
bool HasSuffix(const std::string& string, const std::string& suffix) { auto position = string.rfind(suffix); if (position == std::string::npos) { return false; } return position == string.size() - suffix.size();}
std::string StripPrefix(const std::string& string, const std::string& to_strip) { if (!HasPrefix(string, to_strip)) { return string; } return string.substr(to_strip.length());}
} // namespace impeller12345678910111213141516171819202122232425// 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_IMPELLER_BASE_STRINGS_H_#define FLUTTER_IMPELLER_BASE_STRINGS_H_
#include <string>
#include "impeller/base/config.h"
namespace impeller {
IMPELLER_PRINTF_FORMAT(1, 2)std::string SPrintF(const char* format, ...);
bool HasPrefix(const std::string& string, const std::string& prefix);
bool HasSuffix(const std::string& string, const std::string& suffix);
std::string StripPrefix(const std::string& string, const std::string& to_strip);
} // namespace impeller
#endif // FLUTTER_IMPELLER_BASE_STRINGS_H_1234567891011// 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 "impeller/base/thread.h"
namespace impeller {
//
} // namespace impeller123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270// 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_IMPELLER_BASE_THREAD_H_#define FLUTTER_IMPELLER_BASE_THREAD_H_
#include <chrono>#include <condition_variable>#include <functional>#include <memory>#include <mutex>#include <shared_mutex>#include <thread>
#include "impeller/base/thread_safety.h"
namespace impeller {
class ConditionVariable;
class IPLR_CAPABILITY("mutex") Mutex { public: Mutex() = default;
~Mutex() = default;
void Lock() IPLR_ACQUIRE() { mutex_.lock(); }
void Unlock() IPLR_RELEASE() { mutex_.unlock(); }
private: friend class ConditionVariable;
std::mutex mutex_;
Mutex(const Mutex&) = delete;
Mutex(Mutex&&) = delete;
Mutex& operator=(const Mutex&) = delete;
Mutex& operator=(Mutex&&) = delete;};
class IPLR_CAPABILITY("mutex") RWMutex { public: RWMutex() = default;
~RWMutex() = default;
void LockWriter() IPLR_ACQUIRE() { mutex_.lock(); }
void UnlockWriter() IPLR_RELEASE() { mutex_.unlock(); }
void LockReader() IPLR_ACQUIRE_SHARED() { mutex_.lock_shared(); }
void UnlockReader() IPLR_RELEASE_SHARED() { mutex_.unlock_shared(); }
private: std::shared_mutex mutex_;
RWMutex(const RWMutex&) = delete;
RWMutex(RWMutex&&) = delete;
RWMutex& operator=(const RWMutex&) = delete;
RWMutex& operator=(RWMutex&&) = delete;};
class IPLR_SCOPED_CAPABILITY Lock { public: explicit Lock(Mutex& mutex) IPLR_ACQUIRE(mutex) : mutex_(mutex) { mutex_.Lock(); }
~Lock() IPLR_RELEASE() { mutex_.Unlock(); }
private: Mutex& mutex_;
Lock(const Lock&) = delete;
Lock(Lock&&) = delete;
Lock& operator=(const Lock&) = delete;
Lock& operator=(Lock&&) = delete;};
class IPLR_SCOPED_CAPABILITY ReaderLock { public: explicit ReaderLock(RWMutex& mutex) IPLR_ACQUIRE_SHARED(mutex) : mutex_(mutex) { mutex_.LockReader(); }
~ReaderLock() IPLR_RELEASE() { mutex_.UnlockReader(); }
private: RWMutex& mutex_;
ReaderLock(const ReaderLock&) = delete;
ReaderLock(ReaderLock&&) = delete;
ReaderLock& operator=(const ReaderLock&) = delete;
ReaderLock& operator=(ReaderLock&&) = delete;};
class IPLR_SCOPED_CAPABILITY WriterLock { public: explicit WriterLock(RWMutex& mutex) IPLR_ACQUIRE(mutex) : mutex_(mutex) { mutex_.LockWriter(); }
~WriterLock() IPLR_RELEASE() { mutex_.UnlockWriter(); }
private: RWMutex& mutex_;
WriterLock(const WriterLock&) = delete;
WriterLock(WriterLock&&) = delete;
WriterLock& operator=(const WriterLock&) = delete;
WriterLock& operator=(WriterLock&&) = delete;};
//------------------------------------------------------------------------------/// @brief A condition variable exactly similar to the one in libcxx with/// two major differences:////// * On the Wait, WaitFor, and WaitUntil calls, static analysis/// annotation are respected./// * There is no ability to wait on a condition variable and also/// be susceptible to spurious wakes. This is because the/// predicate is mandatory.///class ConditionVariable { public: ConditionVariable() = default;
~ConditionVariable() = default;
ConditionVariable(const ConditionVariable&) = delete;
ConditionVariable& operator=(const ConditionVariable&) = delete;
void NotifyOne() { cv_.notify_one(); }
void NotifyAll() { cv_.notify_all(); }
using Predicate = std::function<bool()>;
//---------------------------------------------------------------------------- /// @brief Atomically unlocks the mutex and waits on the condition /// variable up to a specified time point. Lock will be reacquired /// when the wait exits. Spurious wakes may happen before the time /// point is reached. In such cases the predicate is invoked and /// it must return `false` for the wait to continue. The predicate /// will be invoked with the mutex locked. /// /// @note Since the predicate is invoked with the mutex locked, if it /// accesses other guarded resources, the predicate itself must be /// decorated with the IPLR_REQUIRES directive. For instance, /// /// ```c++ /// [] () IPLR_REQUIRES(mutex) { /// return my_guarded_resource.should_stop_waiting; /// } /// ``` /// /// @param mutex The mutex. /// @param[in] time_point The time point to wait to. /// @param[in] should_stop_waiting The predicate invoked on spurious wakes. /// Must return false for the wait to /// continue. /// /// @tparam Clock The clock type. /// @tparam Duration The duration type. /// /// @return The value of the predicate at the end of the wait. /// template <class Clock, class Duration> bool WaitUntil(Mutex& mutex, const std::chrono::time_point<Clock, Duration>& time_point, const Predicate& should_stop_waiting) IPLR_REQUIRES(mutex) { std::unique_lock lock(mutex.mutex_, std::adopt_lock); const auto result = cv_.wait_until(lock, time_point, should_stop_waiting); lock.release(); return result; }
//---------------------------------------------------------------------------- /// @brief Atomically unlocks the mutex and waits on the condition /// variable for a designated duration. Lock will be reacquired /// when the wait exits. Spurious wakes may happen before the time /// point is reached. In such cases the predicate is invoked and /// it must return `false` for the wait to continue. The predicate /// will be invoked with the mutex locked. /// /// @note Since the predicate is invoked with the mutex locked, if it /// accesses other guarded resources, the predicate itself must be /// decorated with the IPLR_REQUIRES directive. For instance, /// /// ```c++ /// [] () IPLR_REQUIRES(mutex) { /// return my_guarded_resource.should_stop_waiting; /// } /// ``` /// /// @param mutex The mutex. /// @param[in] duration The duration to wait for. /// @param[in] should_stop_waiting The predicate invoked on spurious wakes. /// Must return false for the wait to /// continue. /// /// @tparam Representation The duration representation type. /// @tparam Period The duration period type. /// /// @return The value of the predicate at the end of the wait. /// template <class Representation, class Period> bool WaitFor(Mutex& mutex, const std::chrono::duration<Representation, Period>& duration, const Predicate& should_stop_waiting) IPLR_REQUIRES(mutex) { return WaitUntil(mutex, std::chrono::steady_clock::now() + duration, should_stop_waiting); }
//---------------------------------------------------------------------------- /// @brief Atomically unlocks the mutex and waits on the condition /// variable indefinitely till the predicate determines that the /// wait must end. Lock will be reacquired when the wait exits. /// Spurious wakes may happen before the time point is reached. In /// such cases the predicate is invoked and it must return `false` /// for the wait to continue. The predicate will be invoked with /// the mutex locked. /// /// @note Since the predicate is invoked with the mutex locked, if it /// accesses other guarded resources, the predicate itself must be /// decorated with the IPLR_REQUIRES directive. For instance, /// /// ```c++ /// [] () IPLR_REQUIRES(mutex) { /// return my_guarded_resource.should_stop_waiting; /// } /// ``` /// /// @param mutex The mutex /// @param[in] should_stop_waiting The should stop waiting /// void Wait(Mutex& mutex, const Predicate& should_stop_waiting) IPLR_REQUIRES(mutex) { std::unique_lock lock(mutex.mutex_, std::adopt_lock); cv_.wait(lock, should_stop_waiting); lock.release(); }
private: std::condition_variable cv_;};
} // namespace impeller
#endif // FLUTTER_IMPELLER_BASE_THREAD_H_1234567891011// 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 "impeller/base/thread_safety.h"
namespace impeller {
//
} // namespace impeller123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172// 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_IMPELLER_BASE_THREAD_SAFETY_H_#define FLUTTER_IMPELLER_BASE_THREAD_SAFETY_H_
#if defined(__clang__)#define IPLR_THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x))#else#define IPLR_THREAD_ANNOTATION_ATTRIBUTE__(x) // no-op#endif
#define IPLR_CAPABILITY(x) IPLR_THREAD_ANNOTATION_ATTRIBUTE__(capability(x))
#define IPLR_SCOPED_CAPABILITY \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
#define IPLR_GUARDED_BY(x) IPLR_THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x))
#define IPLR_PT_GUARDED_BY(x) \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x))
#define IPLR_ACQUIRED_BEFORE(...) \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__))
#define IPLR_ACQUIRED_AFTER(...) \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__))
#define IPLR_REQUIRES(...) \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__))
#define IPLR_REQUIRES_SHARED(...) \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__))
#define IPLR_ACQUIRE(...) \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__))
#define IPLR_ACQUIRE_SHARED(...) \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(__VA_ARGS__))
#define IPLR_RELEASE(...) \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__))
#define IPLR_RELEASE_SHARED(...) \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(__VA_ARGS__))
#define IPLR_RELEASE_GENERIC(...) \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(release_generic_capability(__VA_ARGS__))
#define IPLR_TRY_ACQUIRE(...) \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__))
#define IPLR_TRY_ACQUIRE_SHARED(...) \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(__VA_ARGS__))
#define IPLR_EXCLUDES(...) \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__))
#define IPLR_ASSERT_CAPABILITY(x) \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x))
#define IPLR_ASSERT_SHARED_CAPABILITY(x) \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x))
#define IPLR_RETURN_CAPABILITY(x) \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x))
#define IPLR_NO_THREAD_SAFETY_ANALYSIS \ IPLR_THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis)
#endif // FLUTTER_IMPELLER_BASE_THREAD_SAFETY_H_12345678910111213141516171819// 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_IMPELLER_BASE_TIMING_H_#define FLUTTER_IMPELLER_BASE_TIMING_H_
#include <chrono>
namespace impeller {
using MillisecondsF = std::chrono::duration<float, std::milli>;using SecondsF = std::chrono::duration<float>;using Clock = std::chrono::high_resolution_clock;using TimePoint = std::chrono::time_point<std::chrono::high_resolution_clock>;
} // namespace impeller
#endif // FLUTTER_IMPELLER_BASE_TIMING_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475// 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 "impeller/base/validation.h"
#include <atomic>
#include "flutter/fml/logging.h"
namespace impeller {
static std::atomic_int32_t sValidationLogsDisabledCount = 0;static std::atomic_int32_t sValidationLogsAreFatal = 0;static ValidationFailureCallback sValidationFailureCallback;
void ImpellerValidationErrorsSetFatal(bool fatal) { sValidationLogsAreFatal = fatal;}
void ImpellerValidationErrorsSetCallback(ValidationFailureCallback callback) { sValidationFailureCallback = std::move(callback);}
ScopedValidationDisable::ScopedValidationDisable() { sValidationLogsDisabledCount++;}
ScopedValidationDisable::~ScopedValidationDisable() { sValidationLogsDisabledCount--;}
ScopedValidationFatal::ScopedValidationFatal() { sValidationLogsAreFatal++;}
ScopedValidationFatal::~ScopedValidationFatal() { sValidationLogsAreFatal--;}
ValidationLog::ValidationLog(const char* file, int line) : file_(file), line_(line) {}
ValidationLog::~ValidationLog() { if (sValidationLogsDisabledCount <= 0) { ImpellerValidationBreak(stream_.str().c_str(), file_, line_); }}
std::ostream& ValidationLog::GetStream() { return stream_;}
void ImpellerValidationBreak(const char* message, const char* file, int line) { if (sValidationFailureCallback && sValidationFailureCallback(message, file, line)) { return; } const auto severity = ImpellerValidationErrorsAreFatal() ? fml::LOG_FATAL : fml::LOG_ERROR; auto fml_log = fml::LogMessage{severity, file, line, nullptr}; fml_log.stream() <<#if FLUTTER_RELEASE "Impeller validation: " << message;#else // FLUTTER_RELEASE "Break on '" << __FUNCTION__ << "' to inspect point of failure: " << message;#endif // FLUTTER_RELEASE}
bool ImpellerValidationErrorsAreFatal() { return sValidationLogsAreFatal;}
} // namespace impeller123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293// 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_IMPELLER_BASE_VALIDATION_H_#define FLUTTER_IMPELLER_BASE_VALIDATION_H_
#include <functional>#include <sstream>
namespace impeller {
class ValidationLog { public: ValidationLog(const char* file, int line);
~ValidationLog();
std::ostream& GetStream();
private: const char* file_ = nullptr; int line_ = 0; std::ostringstream stream_;
ValidationLog(const ValidationLog&) = delete;
ValidationLog(ValidationLog&&) = delete;
ValidationLog& operator=(const ValidationLog&) = delete;
ValidationLog& operator=(ValidationLog&&) = delete;};
void ImpellerValidationBreak(const char* message, const char* file, int line);
void ImpellerValidationErrorsSetFatal(bool fatal);
bool ImpellerValidationErrorsAreFatal();
using ValidationFailureCallback = std::function<bool(const char* message, const char* file, int line)>;
//------------------------------------------------------------------------------/// @brief Sets a callback that callers (usually tests) can set to/// intercept validation failures.////// Returning true from the callback indicates that Impeller can/// continue and avoid any default behavior on tripping validation/// (which could include process termination).////// @param[in] callback The callback///void ImpellerValidationErrorsSetCallback(ValidationFailureCallback callback);
struct ScopedValidationDisable { ScopedValidationDisable();
~ScopedValidationDisable();
ScopedValidationDisable(const ScopedValidationDisable&) = delete;
ScopedValidationDisable& operator=(const ScopedValidationDisable&) = delete;};
struct ScopedValidationFatal { ScopedValidationFatal();
~ScopedValidationFatal();
ScopedValidationFatal(const ScopedValidationFatal&) = delete;
ScopedValidationFatal& operator=(const ScopedValidationFatal&) = delete;};
} // namespace impeller
//------------------------------------------------------------------------------/// Get a stream to the log Impeller uses for all validation errors. The/// behavior of these logs is as follows:////// * Validation error are completely ignored in the Flutter release/// runtime-mode./// * In non-release runtime-modes, validation logs are redirected to the/// Flutter `INFO` log. These logs typically show up when verbose logging is/// enabled./// * If `ImpellerValidationErrorsSetFatal` is set to `true`, validation logs/// are fatal. The runtime-mode restriction still applies. This usually/// happens in test environments.///#define VALIDATION_LOG ::impeller::ValidationLog{__FILE__, __LINE__}.GetStream()
#endif // FLUTTER_IMPELLER_BASE_VALIDATION_H_123456789101112131415161718192021222324252627282930313233// 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 "impeller/base/version.h"
#include <sstream>
namespace impeller {
std::optional<Version> Version::FromVector(const std::vector<size_t>& version) { if (version.size() == 0) { return Version{0, 0, 0}; } if (version.size() == 1) { return Version{version[0], 0, 0}; } if (version.size() == 2) { return Version{version[0], version[1], 0}; } if (version.size() == 3) { return Version{version[0], version[1], version[2]}; } return std::nullopt;}
std::string Version::ToString() const { std::stringstream stream; stream << major_version << "." << minor_version << "." << patch_version; return stream.str();}
} // namespace impeller123456789101112131415161718192021222324252627282930313233343536373839404142// 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_IMPELLER_BASE_VERSION_H_#define FLUTTER_IMPELLER_BASE_VERSION_H_
#include <cstddef>#include <optional>#include <string>#include <tuple>#include <vector>
namespace impeller {
struct Version { public: size_t major_version; size_t minor_version; size_t patch_version;
constexpr explicit Version(size_t p_major = 0, size_t p_minor = 0, size_t p_patch = 0) : major_version(p_major), minor_version(p_minor), patch_version(p_patch) {}
static std::optional<Version> FromVector(const std::vector<size_t>& version);
constexpr bool IsAtLeast(const Version& other) const { return std::tie(major_version, minor_version, patch_version) >= std::tie(other.major_version, other.minor_version, other.patch_version); }
std::string ToString() const;};
} // namespace impeller
#endif // FLUTTER_IMPELLER_BASE_VERSION_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118# 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.
import("//flutter/impeller/tools/impeller.gni")import("//flutter/shell/version/version.gni")
impeller_component("utilities") { # Current versions of libcxx have deprecated some of the UTF-16 string # conversion APIs. defines = [ "_LIBCPP_DISABLE_DEPRECATION_WARNINGS" ]
sources = [ "utilities.cc", "utilities.h", ]
public_deps = [ "../base", "../geometry", "../runtime_stage", "//flutter/fml", ]}
impeller_component("compiler_lib") { include_dirs = [ "//flutter/third_party/vulkan-deps/spirv-cross/src/" ]
# Current versions of libcxx have deprecated some of the UTF-16 string # conversion APIs. defines = [ "_LIBCPP_DISABLE_DEPRECATION_WARNINGS" ]
sources = [ "code_gen_template.h", "compiler.cc", "compiler.h", "compiler_backend.cc", "compiler_backend.h", "constants.cc", "constants.h", "include_dir.h", "includer.cc", "includer.h", "logger.h", "reflector.cc", "reflector.h", "runtime_stage_data.cc", "runtime_stage_data.h", "shader_bundle.cc", "shader_bundle.h", "shader_bundle_data.cc", "shader_bundle_data.h", "source_options.cc", "source_options.h", "spirv_compiler.cc", "spirv_compiler.h", "spirv_sksl.cc", "spirv_sksl.h", "switches.cc", "switches.h", "types.cc", "types.h", "uniform_sorter.cc", "uniform_sorter.h", ]
public_deps = [ ":utilities", "../base", "../geometry", "../runtime_stage", "//flutter/fml", "//flutter/impeller/shader_bundle:shader_bundle_flatbuffers",
# All third_party deps must be included by the global license script. "//third_party/inja", "//third_party/shaderc_flutter", "//third_party/spirv_cross_flutter", ]}
impeller_component("impellerc") { target_type = "executable"
sources = [ "impellerc_main.cc" ]
deps = [ ":compiler_lib", "shader_lib", ]
metadata = { entitlement_file_path = [ "impellerc" ] }}
group("compiler") { deps = [ ":impellerc" ]}
impeller_component("compiler_unittests") { testonly = true
output_name = "impellerc_unittests"
sources = [ "compiler_test.cc", "compiler_test.h", "compiler_unittests.cc", "shader_bundle_unittests.cc", "switches_unittests.cc", ]
deps = [ ":compiler_lib", "//flutter/testing:testing_lib", ]}1234567# The Impeller Shader Compiler & Reflector
Host side tooling that consumes [GLSL 4.60 (CoreProfile)](https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.60.pdf)shaders and generates libraries suitable for consumption by an Impeller backend.Along with said libraries, the reflector generates code and meta-data toconstruct rendering and compute pipelines at runtime.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259// 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 <string_view>
namespace impeller {namespace compiler {
constexpr std::string_view kReflectionHeaderTemplate = R"~~(// THIS FILE IS GENERATED BY impellerc.// DO NOT EDIT OR CHECK THIS INTO SOURCE CONTROL
#pragma once
{# Note: The nogncheck decorations are only to make GN not mad at the template#}{# this file is generated from. There are no GN rule violations in the generated#}{# file itself and the no-check declarations will be stripped in generated files.#}#include "impeller/core/buffer_view.h" {# // nogncheck #}
#include "impeller/core/sampler.h" {# // nogncheck #}
#include "impeller/core/shader_types.h" {# // nogncheck #}
#include "impeller/core/resource_binder.h" {# // nogncheck #}
#include "impeller/core/texture.h" {# // nogncheck #}
namespace impeller {
struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Shader { // =========================================================================== // Stage Info ================================================================ // =========================================================================== static constexpr std::string_view kLabel = "{{camel_case(shader_name)}}"; static constexpr std::string_view kEntrypointName = "{{entrypoint}}"; static constexpr ShaderStage kShaderStage = {{to_shader_stage(shader_stage)}}; // The generator used to prepare these bindings. Metal generators may be used // by GLES backends but GLES generators are unsuitable for the metal backend. static constexpr std::string_view kGeneratorName = "{{get_generator_name()}}";{% if length(struct_definitions) > 0 %} // =========================================================================== // Struct Definitions ======================================================== // ==========================================================================={% for def in struct_definitions %}
{% if last(def.members).array_elements == 0 %} template <size_t FlexCount>{% endif %} struct {{def.name}} {{% for member in def.members %}{{" "}}{% if member.element_padding > 0 %}Padded<{{member.type}}, {{member.element_padding}}>{% else %}{{member.type}}{% endif %}{{" " + member.name}}{% if member.array_elements != "std::nullopt" %}[{% if member.array_elements == 0 %}FlexCount{% else %}{{member.array_elements}}{% endif %}]{% endif %}; // (offset {{member.offset}}, size {{member.byte_length}}){% endfor %} }; // struct {{def.name}} (size {{def.byte_length}}){% endfor %}{% endif %}{% if length(buffers) > 0 %}
// =========================================================================== // Stage Uniform & Storage Buffers =========================================== // ==========================================================================={% for buffer in buffers %}
static constexpr auto kResource{{camel_case(buffer.name)}} = ShaderUniformSlot { // {{buffer.name}} "{{buffer.name}}", // name {{buffer.ext_res_0}}u, // ext_res_0 {{buffer.set}}u, // set {{buffer.binding}}u, // binding }; static ShaderMetadata kMetadata{{camel_case(buffer.name)}};{% endfor %}{% endif %}
// =========================================================================== // Stage Inputs ============================================================== // ==========================================================================={% for stage_input in stage_inputs %} static constexpr auto kInput{{camel_case(stage_input.name)}} = ShaderStageIOSlot { // {{stage_input.name}} "{{stage_input.name}}", // name {{stage_input.location}}u, // attribute location {{stage_input.descriptor_set}}u, // attribute set {{stage_input.binding}}u, // attribute binding {{stage_input.type.type_name}}, // type {{stage_input.type.bit_width}}u, // bit width of type {{stage_input.type.vec_size}}u, // vec size {{stage_input.type.columns}}u, // number of columns {{stage_input.offset}}u, // offset for interleaved layout {{stage_input.relaxed_precision}}, // relaxed precision };{% endfor %}
static constexpr std::array<const ShaderStageIOSlot*, {{length(stage_inputs)}}> kAllShaderStageInputs = {{% for stage_input in stage_inputs %} &kInput{{camel_case(stage_input.name)}}, // {{stage_input.name}}{% endfor %} };
{% if shader_stage == "vertex" %} static constexpr auto kInterleavedLayout = ShaderStageBufferLayout {{% if length(stage_inputs) > 0 %} sizeof(PerVertexData), // stride for interleaved layout{% else %} 0u,{% endif %} 0u, // attribute binding }; static constexpr std::array<const ShaderStageBufferLayout*, 1> kInterleavedBufferLayout = { &kInterleavedLayout };{% endif %}
{% if length(sampled_images) > 0 %} // =========================================================================== // Sampled Images ============================================================ // ==========================================================================={% for sampled_image in sampled_images %}
static constexpr auto kResource{{camel_case(sampled_image.name)}} = SampledImageSlot { // {{sampled_image.name}} "{{sampled_image.name}}", // name {{sampled_image.ext_res_0}}u, // ext_res_0 {{sampled_image.set}}u, // set {{sampled_image.binding}}u, // binding }; static ShaderMetadata kMetadata{{camel_case(sampled_image.name)}};{% endfor %}{% endif %} // =========================================================================== // Stage Outputs ============================================================= // ==========================================================================={% for stage_output in stage_outputs %} static constexpr auto kOutput{{camel_case(stage_output.name)}} = ShaderStageIOSlot { // {{stage_output.name}} "{{stage_output.name}}", // name {{stage_output.location}}u, // attribute location {{stage_output.descriptor_set}}u, // attribute set {{stage_output.binding}}u, // attribute binding {{stage_output.type.type_name}}, // type {{stage_output.type.bit_width}}u, // bit width of type {{stage_output.type.vec_size}}u, // vec size {{stage_output.type.columns}}u, // number of columns {{stage_output.offset}}u, // offset for interleaved layout {{stage_output.relaxed_precision}}, // relaxed precision };{% endfor %} static constexpr std::array<const ShaderStageIOSlot*, {{length(stage_outputs)}}> kAllShaderStageOutputs = {{% for stage_output in stage_outputs %} &kOutput{{camel_case(stage_output.name)}}, // {{stage_output.name}}{% endfor %} };
// =========================================================================== // Resource Binding Utilities ================================================ // ===========================================================================
{% for proto in bind_prototypes %} /// {{proto.docstring}} static {{proto.return_type}} Bind{{proto.name}}({% for arg in proto.args %}{{arg.type_name}} {{arg.argument_name}}{% if not loop.is_last %}, {% endif %}{% endfor %}) { return {{ proto.args.0.argument_name }}.BindResource({% for arg in proto.args %} {% if loop.is_first %}{{to_shader_stage(shader_stage)}}, {{ proto.descriptor_type }}, kResource{{ proto.name }}, &kMetadata{{ proto.name }}, {% else %}std::move({{ arg.argument_name }}){% if not loop.is_last %}, {% endif %} {% endif %} {% endfor %}); }
{% endfor %}
// =========================================================================== // Metadata for Vulkan ======================================================= // =========================================================================== static constexpr std::array<DescriptorSetLayout,{{length(buffers)+length(sampled_images)+length(subpass_inputs)}}> kDescriptorSetLayouts{{% for subpass_input in subpass_inputs %} DescriptorSetLayout{ {{subpass_input.binding}}, // binding = {{subpass_input.binding}} {{subpass_input.descriptor_type}}, // descriptor_type = {{subpass_input.descriptor_type}} {{to_shader_stage(shader_stage)}}, // shader_stage = {{to_shader_stage(shader_stage)}} },{% endfor %}{% for buffer in buffers %} DescriptorSetLayout{ {{buffer.binding}}, // binding = {{buffer.binding}} {{buffer.descriptor_type}}, // descriptor_type = {{buffer.descriptor_type}} {{to_shader_stage(shader_stage)}}, // shader_stage = {{to_shader_stage(shader_stage)}} },{% endfor %}{% for sampled_image in sampled_images %} DescriptorSetLayout{ {{sampled_image.binding}}, // binding = {{sampled_image.binding}} {{sampled_image.descriptor_type}}, // descriptor_type = {{sampled_image.descriptor_type}} {{to_shader_stage(shader_stage)}}, // shader_stage = {{to_shader_stage(shader_stage)}} },{% endfor %} };
}; // struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Shader
} // namespace impeller)~~";
constexpr std::string_view kReflectionCCTemplate = R"~~(// THIS FILE IS GENERATED BY impellerc.// DO NOT EDIT OR CHECK THIS INTO SOURCE CONTROL
#include "{{header_file_name}}"
#include <type_traits>
namespace impeller {
using Shader = {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Shader;
{% for def in struct_definitions %}// Sanity checks for {{def.name}}{% if last(def.members).array_elements == 0 %}static_assert(std::is_standard_layout_v<Shader::{{def.name}}<0>>);{% for member in def.members %}static_assert(offsetof(Shader::{{def.name}}<0>, {{member.name}}) == {{member.offset}});{% endfor %}{% else %}static_assert(std::is_standard_layout_v<Shader::{{def.name}}>);static_assert(sizeof(Shader::{{def.name}}) == {{def.byte_length}});{% for member in def.members %}static_assert(offsetof(Shader::{{def.name}}, {{member.name}}) == {{member.offset}});{% endfor %}{% endif %}{% endfor %}
{% for buffer in buffers %}ShaderMetadata Shader::kMetadata{{camel_case(buffer.name)}} = { "{{buffer.name}}", // name std::vector<ShaderStructMemberMetadata> { {% for member in buffer.type.members %} ShaderStructMemberMetadata { {{ member.base_type }}, // type "{{ member.name }}", // name {{ member.offset }}, // offset {{ member.size }}, // size {{ member.byte_length }}, // byte_length {{ member.array_elements }}, // array_elements }, {% endfor %} } // members};{% endfor %}
{% for sampled_image in sampled_images %}ShaderMetadata Shader::kMetadata{{camel_case(sampled_image.name)}} = { "{{sampled_image.name}}", // name std::vector<ShaderStructMemberMetadata> {}, // 0 members};{% endfor %}
} // namespace impeller)~~";
} // namespace compiler} // namespace impeller123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547// 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 "impeller/compiler/compiler.h"
#include <cstdint>#include <filesystem>#include <memory>#include <optional>#include <sstream>#include <string>#include <utility>
#include "flutter/fml/paths.h"#include "impeller/base/allocation.h"#include "impeller/compiler/compiler_backend.h"#include "impeller/compiler/constants.h"#include "impeller/compiler/includer.h"#include "impeller/compiler/logger.h"#include "impeller/compiler/spirv_compiler.h"#include "impeller/compiler/types.h"#include "impeller/compiler/uniform_sorter.h"#include "impeller/compiler/utilities.h"
namespace impeller {namespace compiler {
namespace {constexpr const char* kEGLImageExternalExtension = "GL_OES_EGL_image_external";constexpr const char* kEGLImageExternalExtension300 = "GL_OES_EGL_image_external_essl3";} // namespace
// This value should be <= 7372. UBOs can be larger on some devices but a// performance cost will be paid.// https://docs.qualcomm.com/bundle/publicresource/topics/80-78185-2/best_practices.html?product=1601111740035277#buffer-best-practicesstatic const uint32_t kMaxUniformBufferSize = 6208;
static uint32_t ParseMSLVersion(const std::string& msl_version) { std::stringstream sstream(msl_version); std::string version_part; uint32_t major = 1; uint32_t minor = 2; uint32_t patch = 0; if (std::getline(sstream, version_part, '.')) { major = std::stoi(version_part); if (std::getline(sstream, version_part, '.')) { minor = std::stoi(version_part); if (std::getline(sstream, version_part, '.')) { patch = std::stoi(version_part); } } } if (major < 1 || (major == 1 && minor < 2)) { std::cerr << "--metal-version version must be at least 1.2. Have " << msl_version << std::endl; } return spirv_cross::CompilerMSL::Options::make_msl_version(major, minor, patch);}
static CompilerBackend CreateMSLCompiler( const spirv_cross::ParsedIR& ir, const SourceOptions& source_options, std::optional<uint32_t> msl_version_override = {}) { auto sl_compiler = std::make_shared<spirv_cross::CompilerMSL>(ir); spirv_cross::CompilerMSL::Options sl_options; sl_options.platform = TargetPlatformToMSLPlatform(source_options.target_platform); sl_options.msl_version = msl_version_override.value_or( ParseMSLVersion(source_options.metal_version)); sl_options.ios_use_simdgroup_functions = sl_options.is_ios() && sl_options.msl_version >= spirv_cross::CompilerMSL::Options::make_msl_version(2, 4, 0); sl_options.use_framebuffer_fetch_subpasses = true; sl_compiler->set_msl_options(sl_options);
// Sort the float and sampler uniforms according to their declared/decorated // order. For user authored fragment shaders, the API for setting uniform // values uses the index of the uniform in the declared order. By default, the // metal backend of spirv-cross will order uniforms according to usage. To fix // this, we use the sorted order and the add_msl_resource_binding API to force // the ordering to match the declared order. Note that while this code runs // for all compiled shaders, it will only affect vertex and fragment shaders // due to the specified stage. auto floats = SortUniforms(&ir, sl_compiler.get(), spirv_cross::SPIRType::Float); auto images = SortUniforms(&ir, sl_compiler.get(), spirv_cross::SPIRType::SampledImage);
spv::ExecutionModel execution_model = spv::ExecutionModel::ExecutionModelFragment; if (source_options.type == SourceType::kVertexShader) { execution_model = spv::ExecutionModel::ExecutionModelVertex; }
uint32_t buffer_offset = 0; uint32_t sampler_offset = 0; for (auto& float_id : floats) { sl_compiler->add_msl_resource_binding( {.stage = execution_model, .basetype = spirv_cross::SPIRType::BaseType::Float, .desc_set = sl_compiler->get_decoration(float_id, spv::DecorationDescriptorSet), .binding = sl_compiler->get_decoration(float_id, spv::DecorationBinding), .count = 1u, .msl_buffer = buffer_offset}); buffer_offset++; } for (auto& image_id : images) { sl_compiler->add_msl_resource_binding({ .stage = execution_model, .basetype = spirv_cross::SPIRType::BaseType::SampledImage, .desc_set = sl_compiler->get_decoration(image_id, spv::DecorationDescriptorSet), .binding = sl_compiler->get_decoration(image_id, spv::DecorationBinding), .count = 1u, // A sampled image is both an image and a sampler, so both // offsets need to be set or depending on the partiular shader // the bindings may be incorrect. .msl_texture = sampler_offset, .msl_sampler = sampler_offset, }); sampler_offset++; }
return CompilerBackend(sl_compiler);}
static CompilerBackend CreateVulkanCompiler( const spirv_cross::ParsedIR& ir, const SourceOptions& source_options) { auto gl_compiler = std::make_shared<spirv_cross::CompilerGLSL>(ir); spirv_cross::CompilerGLSL::Options sl_options; sl_options.force_zero_initialized_variables = true; sl_options.vertex.fixup_clipspace = true; sl_options.vulkan_semantics = true; gl_compiler->set_common_options(sl_options); return CompilerBackend(gl_compiler);}
static CompilerBackend CreateGLSLCompiler(const spirv_cross::ParsedIR& ir, const SourceOptions& source_options) { auto gl_compiler = std::make_shared<spirv_cross::CompilerGLSL>(ir);
// Walk the variables and insert the external image extension if any of them // begins with the external texture prefix. Unfortunately, we can't walk // `gl_compiler->get_shader_resources().separate_samplers` until the compiler // is further along. // // Unfortunately, we can't just let the shader author add this extension and // use `samplerExternalOES` directly because compiling to spirv requires the // source language profile to be at least 310 ES, but this extension is // incompatible with ES 310+. for (auto& id : ir.ids_for_constant_or_variable) { if (StringStartsWith(ir.get_name(id), kExternalTexturePrefix)) { if (source_options.gles_language_version >= 300) { gl_compiler->require_extension(kEGLImageExternalExtension300); } else { gl_compiler->require_extension(kEGLImageExternalExtension); } break; } }
spirv_cross::CompilerGLSL::Options sl_options; sl_options.force_zero_initialized_variables = true; sl_options.vertex.fixup_clipspace = true; if (source_options.target_platform == TargetPlatform::kOpenGLES || source_options.target_platform == TargetPlatform::kRuntimeStageGLES || source_options.target_platform == TargetPlatform::kRuntimeStageGLES3) { sl_options.version = source_options.gles_language_version > 0 ? source_options.gles_language_version : 100; sl_options.es = true; if (source_options.target_platform == TargetPlatform::kRuntimeStageGLES3) { sl_options.version = 300; } if (source_options.require_framebuffer_fetch && source_options.type == SourceType::kFragmentShader) { gl_compiler->remap_ext_framebuffer_fetch(0, 0, true); } gl_compiler->set_variable_type_remap_callback( [&](const spirv_cross::SPIRType& type, const std::string& var_name, std::string& name_of_type) { if (StringStartsWith(var_name, kExternalTexturePrefix)) { name_of_type = "samplerExternalOES"; } }); } else { sl_options.version = source_options.gles_language_version > 0 ? source_options.gles_language_version : 120; sl_options.es = false; } gl_compiler->set_common_options(sl_options); return CompilerBackend(gl_compiler);}
static CompilerBackend CreateSkSLCompiler(const spirv_cross::ParsedIR& ir, const SourceOptions& source_options) { auto sksl_compiler = std::make_shared<CompilerSkSL>(ir); return CompilerBackend(sksl_compiler);}
static bool EntryPointMustBeNamedMain(TargetPlatform platform) { switch (platform) { case TargetPlatform::kUnknown: FML_UNREACHABLE(); case TargetPlatform::kMetalDesktop: case TargetPlatform::kMetalIOS: case TargetPlatform::kVulkan: case TargetPlatform::kRuntimeStageMetal: case TargetPlatform::kRuntimeStageVulkan: return false; case TargetPlatform::kSkSL: case TargetPlatform::kOpenGLES: case TargetPlatform::kOpenGLDesktop: case TargetPlatform::kRuntimeStageGLES: case TargetPlatform::kRuntimeStageGLES3: return true; } FML_UNREACHABLE();}
static CompilerBackend CreateCompiler(const spirv_cross::ParsedIR& ir, const SourceOptions& source_options) { CompilerBackend compiler; switch (source_options.target_platform) { case TargetPlatform::kMetalDesktop: case TargetPlatform::kMetalIOS: case TargetPlatform::kRuntimeStageMetal: compiler = CreateMSLCompiler(ir, source_options); break; case TargetPlatform::kVulkan: case TargetPlatform::kRuntimeStageVulkan: compiler = CreateVulkanCompiler(ir, source_options); break; case TargetPlatform::kUnknown: case TargetPlatform::kOpenGLES: case TargetPlatform::kOpenGLDesktop: case TargetPlatform::kRuntimeStageGLES: case TargetPlatform::kRuntimeStageGLES3: compiler = CreateGLSLCompiler(ir, source_options); break; case TargetPlatform::kSkSL: compiler = CreateSkSLCompiler(ir, source_options); } if (!compiler) { return {}; } auto* backend = compiler.GetCompiler(); if (!EntryPointMustBeNamedMain(source_options.target_platform) && source_options.source_language == SourceLanguage::kGLSL) { backend->rename_entry_point("main", source_options.entry_point_name, ToExecutionModel(source_options.type)); } return compiler;}
namespace {uint32_t CalculateUBOSize(const spirv_cross::Compiler* compiler) { spirv_cross::ShaderResources resources = compiler->get_shader_resources(); uint32_t result = 0; for (const spirv_cross::Resource& ubo : resources.uniform_buffers) { const spirv_cross::SPIRType& ubo_type = compiler->get_type(ubo.base_type_id); uint32_t size = compiler->get_declared_struct_size(ubo_type); result += size; } return result;}
} // namespace
Compiler::Compiler(const std::shared_ptr<const fml::Mapping>& source_mapping, const SourceOptions& source_options, Reflector::Options reflector_options) : options_(source_options) { if (!source_mapping || source_mapping->GetMapping() == nullptr) { COMPILER_ERROR(error_stream_) << "Could not read shader source or shader source was empty."; return; }
if (source_options.target_platform == TargetPlatform::kUnknown) { COMPILER_ERROR(error_stream_) << "Target platform not specified."; return; }
SPIRVCompilerOptions spirv_options;
// Make sure reflection is as effective as possible. The generated shaders // will be processed later by backend specific compilers. spirv_options.generate_debug_info = true;
switch (options_.source_language) { case SourceLanguage::kGLSL: // Expects GLSL 4.60 (Core Profile). // https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.60.pdf spirv_options.source_langauge = shaderc_source_language::shaderc_source_language_glsl; spirv_options.source_profile = SPIRVCompilerSourceProfile{ shaderc_profile::shaderc_profile_core, // 460, // }; break; case SourceLanguage::kHLSL: spirv_options.source_langauge = shaderc_source_language::shaderc_source_language_hlsl; break; case SourceLanguage::kUnknown: COMPILER_ERROR(error_stream_) << "Source language invalid."; return; }
switch (source_options.target_platform) { case TargetPlatform::kMetalDesktop: case TargetPlatform::kMetalIOS: { SPIRVCompilerTargetEnv target;
if (source_options.use_half_textures) { target.env = shaderc_target_env::shaderc_target_env_opengl; target.version = shaderc_env_version::shaderc_env_version_opengl_4_5; target.spirv_version = shaderc_spirv_version::shaderc_spirv_version_1_0; } else { target.env = shaderc_target_env::shaderc_target_env_vulkan; target.version = shaderc_env_version::shaderc_env_version_vulkan_1_1; target.spirv_version = shaderc_spirv_version::shaderc_spirv_version_1_3; }
spirv_options.target = target; } break; case TargetPlatform::kOpenGLES: case TargetPlatform::kOpenGLDesktop: case TargetPlatform::kVulkan: case TargetPlatform::kRuntimeStageVulkan: { SPIRVCompilerTargetEnv target;
target.env = shaderc_target_env::shaderc_target_env_vulkan; target.version = shaderc_env_version::shaderc_env_version_vulkan_1_1; target.spirv_version = shaderc_spirv_version::shaderc_spirv_version_1_3;
if (source_options.target_platform == TargetPlatform::kRuntimeStageVulkan) { spirv_options.macro_definitions.push_back("IMPELLER_GRAPHICS_BACKEND"); spirv_options.relaxed_vulkan_rules = true; } spirv_options.target = target; } break; case TargetPlatform::kRuntimeStageMetal: case TargetPlatform::kRuntimeStageGLES: case TargetPlatform::kRuntimeStageGLES3: { SPIRVCompilerTargetEnv target;
target.env = shaderc_target_env::shaderc_target_env_opengl; target.version = shaderc_env_version::shaderc_env_version_opengl_4_5; target.spirv_version = shaderc_spirv_version::shaderc_spirv_version_1_0;
spirv_options.target = target; spirv_options.macro_definitions.push_back("IMPELLER_GRAPHICS_BACKEND"); } break; case TargetPlatform::kSkSL: { SPIRVCompilerTargetEnv target;
target.env = shaderc_target_env::shaderc_target_env_opengl; target.version = shaderc_env_version::shaderc_env_version_opengl_4_5; target.spirv_version = shaderc_spirv_version::shaderc_spirv_version_1_0;
// When any optimization level above 'zero' is enabled, the phi merges at // loop continue blocks are rendered using syntax that is supported in // GLSL, but not in SkSL. // https://bugs.chromium.org/p/skia/issues/detail?id=13518. spirv_options.optimization_level = shaderc_optimization_level::shaderc_optimization_level_zero; spirv_options.target = target; spirv_options.macro_definitions.push_back("SKIA_GRAPHICS_BACKEND"); } break; case TargetPlatform::kUnknown: COMPILER_ERROR(error_stream_) << "Target platform invalid."; return; }
// Implicit definition that indicates that this compilation is for the device // (instead of the host). spirv_options.macro_definitions.push_back("IMPELLER_DEVICE"); for (const auto& define : source_options.defines) { spirv_options.macro_definitions.push_back(define); }
std::vector<std::string> included_file_names; spirv_options.includer = std::make_shared<Includer>( options_.working_directory, options_.include_dirs, [&included_file_names](auto included_name) { included_file_names.emplace_back(std::move(included_name)); });
// SPIRV Generation. SPIRVCompiler spv_compiler(source_options, source_mapping);
spirv_assembly_ = spv_compiler.CompileToSPV( error_stream_, spirv_options.BuildShadercOptions());
if (!spirv_assembly_) { return; } else { included_file_names_ = std::move(included_file_names); }
// SL Generation. spirv_cross::Parser parser( reinterpret_cast<const uint32_t*>(spirv_assembly_->GetMapping()), spirv_assembly_->GetSize() / sizeof(uint32_t)); // The parser and compiler must be run separately because the parser contains // meta information (like type member names) that are useful for reflection. parser.parse();
const auto parsed_ir = std::make_shared<spirv_cross::ParsedIR>(parser.get_parsed_ir());
auto sl_compiler = CreateCompiler(*parsed_ir, options_);
if (!sl_compiler) { COMPILER_ERROR(error_stream_) << "Could not create compiler for target platform."; return; }
uint32_t ubo_size = CalculateUBOSize(sl_compiler.GetCompiler()); if (ubo_size > kMaxUniformBufferSize) { COMPILER_ERROR(error_stream_) << "Uniform buffer size exceeds max (" << kMaxUniformBufferSize << "): " << ubo_size; return; }
// We need to invoke the compiler even if we don't use the SL mapping later // for Vulkan. The reflector needs information that is only valid after a // successful compilation call. auto sl_compilation_result = CreateMappingWithString(sl_compiler.GetCompiler()->compile());
// If the target is Vulkan, our shading language is SPIRV which we already // have. We just need to strip it of debug information. If it isn't, we need // to invoke the appropriate compiler to compile the SPIRV to the target SL. if (source_options.target_platform == TargetPlatform::kVulkan || source_options.target_platform == TargetPlatform::kRuntimeStageVulkan) { auto stripped_spirv_options = spirv_options; stripped_spirv_options.generate_debug_info = false; sl_mapping_ = spv_compiler.CompileToSPV( error_stream_, stripped_spirv_options.BuildShadercOptions()); } else { sl_mapping_ = sl_compilation_result; }
if (!sl_mapping_) { COMPILER_ERROR(error_stream_) << "Could not generate SL from SPIRV"; return; }
reflector_ = std::make_unique<Reflector>(std::move(reflector_options), // parsed_ir, // GetSLShaderSource(), // sl_compiler // );
if (!reflector_->IsValid()) { COMPILER_ERROR(error_stream_) << "Could not complete reflection on generated shader."; return; }
is_valid_ = true;}
Compiler::~Compiler() = default;
std::shared_ptr<fml::Mapping> Compiler::GetSPIRVAssembly() const { return spirv_assembly_;}
std::shared_ptr<fml::Mapping> Compiler::GetSLShaderSource() const { return sl_mapping_;}
bool Compiler::IsValid() const { return is_valid_;}
std::string Compiler::GetSourcePrefix() const { std::stringstream stream; stream << options_.file_name << ": "; return stream.str();}
std::string Compiler::GetErrorMessages() const { return error_stream_.str();}
const std::vector<std::string>& Compiler::GetIncludedFileNames() const { return included_file_names_;}
static std::string JoinStrings(std::vector<std::string> items, const std::string& separator) { std::stringstream stream; for (size_t i = 0, count = items.size(); i < count; i++) { const auto is_last = (i == count - 1);
stream << items[i]; if (!is_last) { stream << separator; } } return stream.str();}
std::string Compiler::GetDependencyNames(const std::string& separator) const { std::vector<std::string> dependencies = included_file_names_; dependencies.push_back(options_.file_name); return JoinStrings(dependencies, separator);}
std::unique_ptr<fml::Mapping> Compiler::CreateDepfileContents( std::initializer_list<std::string> targets_names) const { // https://github.com/ninja-build/ninja/blob/master/src/depfile_parser.cc#L28 const auto targets = JoinStrings(targets_names, " "); const auto dependencies = GetDependencyNames(" ");
std::stringstream stream; stream << targets << ": " << dependencies << "\n";
auto contents = std::make_shared<std::string>(stream.str()); return std::make_unique<fml::NonOwnedMapping>( reinterpret_cast<const uint8_t*>(contents->data()), contents->size(), [contents](auto, auto) {});}
const Reflector* Compiler::GetReflector() const { return reflector_.get();}
} // namespace compiler} // namespace impellerflutter/engine/src/flutter/fml/memory/ref_counted.hAdded+137
flutter/engine/src/flutter/fml/memory/ref_counted_internal.hAdded+106
flutter/engine/src/flutter/fml/memory/ref_counted_unittest.ccAdded+647
flutter/engine/src/flutter/fml/memory/ref_ptr.hAdded+272
flutter/engine/src/flutter/fml/memory/ref_ptr_internal.hAdded+38
flutter/engine/src/flutter/fml/memory/task_runner_checker.ccAdded+52
flutter/engine/src/flutter/fml/memory/task_runner_checker.hAdded+41
flutter/engine/src/flutter/fml/memory/task_runner_checker_unittest.ccAdded+173
flutter/engine/src/flutter/fml/memory/thread_checker.ccAdded+11
flutter/engine/src/flutter/fml/memory/thread_checker.hAdded+104
flutter/engine/src/flutter/fml/memory/weak_ptr.hAdded+328
flutter/engine/src/flutter/fml/memory/weak_ptr_internal.ccAdded+26
flutter/engine/src/flutter/fml/memory/weak_ptr_internal.hAdded+41
flutter/engine/src/flutter/fml/memory/weak_ptr_unittest.ccAdded+241
flutter/engine/src/flutter/fml/synchronization/atomic_object.hAdded+36
flutter/engine/src/flutter/fml/synchronization/count_down_latch.ccAdded+29
flutter/engine/src/flutter/fml/synchronization/count_down_latch.hAdded+34
flutter/engine/src/flutter/fml/synchronization/count_down_latch_unittests.ccAdded+41
flutter/engine/src/flutter/fml/synchronization/semaphore.ccAdded+193
flutter/engine/src/flutter/impeller/base/BUILD.gnAdded+47
flutter/engine/src/flutter/impeller/base/README.mdAdded+4
flutter/engine/src/flutter/impeller/base/allocation.ccAdded+118
flutter/engine/src/flutter/impeller/base/allocation.hAdded+152
flutter/engine/src/flutter/impeller/base/allocation_size.ccAdded+11
flutter/engine/src/flutter/impeller/base/allocation_size.hAdded+202
flutter/engine/src/flutter/impeller/base/allocation_size_unittests.ccAdded+125
flutter/engine/src/flutter/impeller/base/backend_cast.hAdded+28
flutter/engine/src/flutter/impeller/base/base_unittests.ccAdded+449
flutter/engine/src/flutter/impeller/base/comparable.ccAdded+14
flutter/engine/src/flutter/impeller/base/comparable.hAdded+114
flutter/engine/src/flutter/impeller/base/config.hAdded+40
flutter/engine/src/flutter/impeller/base/flags.hAdded+18
flutter/engine/src/flutter/impeller/base/mask.hAdded+230
flutter/engine/src/flutter/impeller/base/promise.ccAdded+11
flutter/engine/src/flutter/impeller/base/promise.hAdded+50
flutter/engine/src/flutter/impeller/base/strings.ccAdded+50
flutter/engine/src/flutter/impeller/base/strings.hAdded+25
flutter/engine/src/flutter/impeller/base/thread.ccAdded+11
flutter/engine/src/flutter/impeller/base/thread.hAdded+270
flutter/engine/src/flutter/impeller/base/thread_safety.ccAdded+11
flutter/engine/src/flutter/impeller/base/thread_safety.hAdded+72
flutter/engine/src/flutter/impeller/base/timing.hAdded+19
flutter/engine/src/flutter/impeller/base/validation.ccAdded+75
flutter/engine/src/flutter/impeller/base/validation.hAdded+93
flutter/engine/src/flutter/impeller/base/version.ccAdded+33
flutter/engine/src/flutter/impeller/base/version.hAdded+42
flutter/engine/src/flutter/impeller/compiler/BUILD.gnAdded+118
flutter/engine/src/flutter/impeller/compiler/README.mdAdded+7
flutter/engine/src/flutter/impeller/compiler/code_gen_template.hAdded+259
flutter/engine/src/flutter/impeller/compiler/compiler.ccAdded+547